diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 63d34f8951b..1a97c148b57 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -93,7 +93,7 @@ 1 test-no-polling-loop:src/main/daemon/daemon-stream-backpressure-socket.test.ts 1 test-no-polling-loop:src/main/daemon/headless-emulator-snapshot-cost.bench.test.ts 1 test-no-polling-loop:src/main/daemon/node-pty-conout-worker-errors.test.ts -2 test-no-polling-loop:src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts +1 test-no-polling-loop:src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts 2 test-no-polling-loop:src/main/git/repo-ref-maintenance-real-git.test.ts 1 test-no-polling-loop:src/main/git/worktree-removal-large-tree.bench.test.ts 1 test-no-polling-loop:src/main/ipc/folder-repo-git-upgrade.test.ts @@ -312,7 +312,7 @@ 4 test-no-real-time-wait:src/main/daemon/node-pty-windows-input-error.win32.test.ts 1 test-no-real-time-wait:src/main/daemon/node-pty-windows-output-error.win32.test.ts 11 test-no-real-time-wait:src/main/daemon/reattach-snapshot.test.ts -2 test-no-real-time-wait:src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts +1 test-no-real-time-wait:src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts 6 test-no-real-time-wait:src/main/daemon/repro-13767-shell-ready-marker-lost-to-exec.test.ts 4 test-no-real-time-wait:src/main/daemon/session-shell-recovery.test.ts 1 test-no-real-time-wait:src/main/daemon/session.test.ts @@ -1102,7 +1102,6 @@ 4 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeCard.compact-hover.test.tsx 13 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeCard.pr-display.test.tsx 2 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeCard.single-reference-details.test.tsx -3 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeCardAgents.send-target.test.tsx 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 @@ -1125,7 +1124,6 @@ 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 2 test-no-wall-clock:src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-removal.agent-stop.test.tsx -6 test-no-wall-clock:src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.test.tsx 2 test-no-wall-clock:src/renderer/src/hooks/ipc-events/agent-status-terminal-title-tab-write.test.ts 3 test-no-wall-clock:src/renderer/src/hooks/useAutomationDispatchEvents.test.ts 1 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-agent-status-hook-titles.test.ts @@ -1362,7 +1360,6 @@ 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 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 1 test-timeout-needs-reason:src/renderer/src/components/sidebar/WorktreeCardAgents.test.tsx 1 test-timeout-needs-reason:src/renderer/src/components/tab-bar/BrowserTab.test.tsx 1 test-timeout-needs-reason:src/renderer/src/components/tab-bar/TabBar.windows-shell-launch.test.ts diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index e7443228c83..d08728a5c62 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -4852,7 +4852,6 @@ "src/main/runtime/mobile-pairing-qr.test.ts": 694, "src/main/runtime/mobile-pairing-userdata-path.test.ts": 1791, "src/main/runtime/mobile-presence-lock.test.ts": 16606, - "src/main/runtime/mobile-rpc-allowlist.test.ts": 2610, "src/main/runtime/mobile-session-chat-tab-order.test.ts": 96, "src/main/runtime/mobile-session-editor-projection.test.ts": 42, "src/main/runtime/mobile-session-resume-identity.test.ts": 4735, @@ -6506,7 +6505,6 @@ "src/main/window/dragged-temp-file-copy.test.ts": 137, "src/main/window/dropped-path-preparation-ipc.test.ts": 106, "src/main/window/dropped-path-preparation.test.ts": 586, - "src/main/window/editable-context-menu.test.ts": 39, "src/main/window/focus-existing-window.test.ts": 49, "src/main/window/foreground-activation-policy.test.ts": 39, "src/main/window/history-gc-worktree-ids.test.ts": 228, @@ -8087,7 +8085,6 @@ "src/renderer/src/components/right-sidebar/SourceControl.resolve-conflicts-prompt.test.ts": 96, "src/renderer/src/components/right-sidebar/SourceControl.virtual-file-list.test.tsx": 3910, "src/renderer/src/components/right-sidebar/SourceControlAgentActionDialog.test.tsx": 7135, - "src/renderer/src/components/right-sidebar/SourceControlAgentActionDialogForm.test.tsx": 191, "src/renderer/src/components/right-sidebar/SourceControlTextGenerationDialog.test.ts": 495, "src/renderer/src/components/right-sidebar/active-checks-status.test.ts": 1264, "src/renderer/src/components/right-sidebar/activity-bar-buttons.test.tsx": 190, @@ -8361,7 +8358,6 @@ "src/renderer/src/components/settings/HostAccountSignInPrompt.test.tsx": 158, "src/renderer/src/components/settings/HostAgentLaunchSettings.test.tsx": 4184, "src/renderer/src/components/settings/KagiSessionLinkForm.test.ts": 193, - "src/renderer/src/components/settings/LinearAgentSkillPane.test.tsx": 675, "src/renderer/src/components/settings/LocalNetworkConnectionTest.test.tsx": 556, "src/renderer/src/components/settings/MachineNameField.test.tsx": 481, "src/renderer/src/components/settings/McpConfigSection.host-owner.test.tsx": 2450, @@ -8510,7 +8506,6 @@ "src/renderer/src/components/sidebar/AddRepoCreateStep.test.tsx": 532, "src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts": 42, "src/renderer/src/components/sidebar/AddRepoDialogChrome.test.tsx": 495, - "src/renderer/src/components/sidebar/AddRepoHostSelector.test.tsx": 390, "src/renderer/src/components/sidebar/AddRepoNestedImportStep.test.tsx": 817, "src/renderer/src/components/sidebar/AddRepoStartSteps.test.tsx": 681, "src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts": 170, @@ -8566,10 +8561,8 @@ "src/renderer/src/components/sidebar/WorkspaceKanbanSearchField.test.tsx": 658, "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.host-badge-toggle.test.tsx": 1253, "src/renderer/src/components/sidebar/WorktreeCard.hosted-review-refresh.test.tsx": 1647, - "src/renderer/src/components/sidebar/WorktreeCard.merged-pr-display.test.tsx": 1682, "src/renderer/src/components/sidebar/WorktreeCard.pr-display.test.tsx": 1246, "src/renderer/src/components/sidebar/WorktreeCard.quick-actions.test.tsx": 1827, "src/renderer/src/components/sidebar/WorktreeCard.single-reference-details.test.tsx": 1662, @@ -8577,7 +8570,6 @@ "src/renderer/src/components/sidebar/WorktreeCardAgents.acknowledgement-emphasis.test.tsx": 944, "src/renderer/src/components/sidebar/WorktreeCardAgents.activation.test.tsx": 766, "src/renderer/src/components/sidebar/WorktreeCardAgents.expansion-remount.test.tsx": 958, - "src/renderer/src/components/sidebar/WorktreeCardAgents.send-target.test.tsx": 1228, "src/renderer/src/components/sidebar/WorktreeCardAgents.test.tsx": 846, "src/renderer/src/components/sidebar/WorktreeCardLinkedItemsSection.test.tsx": 3296, "src/renderer/src/components/sidebar/WorktreeCardMeta.interaction.test.tsx": 1658, @@ -9733,7 +9725,6 @@ "src/renderer/src/components/workspace-cleanup/workspace-cleanup-background-removal.test.ts": 176, "src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-row-data.test.ts": 279, "src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-row.test.tsx": 2141, - "src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.test.tsx": 658, "src/renderer/src/components/workspace-cleanup/workspace-cleanup-facet-controls.test.tsx": 601, "src/renderer/src/components/workspace-cleanup/workspace-cleanup-facet-filter.test.ts": 107, "src/renderer/src/components/workspace-cleanup/workspace-cleanup-facet-sort.test.ts": 127, diff --git a/src/main/claude/claude-structured-queued-stop.test.ts b/src/main/claude/claude-structured-queued-stop.test.ts index d038026deca..ae1d661b280 100644 --- a/src/main/claude/claude-structured-queued-stop.test.ts +++ b/src/main/claude/claude-structured-queued-stop.test.ts @@ -192,15 +192,6 @@ describe('Stop with a follow-up Claude queued behind the running turn', () => { expect(bySessionStart).toEqual(byInit) }) - it('settles the swept follow-up without proof it never reached Claude', async () => { - const { settlements } = await stopWithQueuedFollowUp( - claudeCli({ initProof: 'init', capabilities: CAPABILITIES }), - () => {} - ) - expect(settlements[0]).toMatchObject({ state: 'rejected' }) - expect(JSON.stringify(settlements[0])).not.toContain('neverReachedAgent') - }) - it('keeps what a turn advertised when a later frame names nothing', async () => { const result = await stopWithQueuedFollowUp( claudeCli({ initProof: 'session-start' }), diff --git a/src/main/codex/codex-provider-retry-row.test.ts b/src/main/codex/codex-provider-retry-row.test.ts index b01d8eeee4b..b117f8dc1f1 100644 --- a/src/main/codex/codex-provider-retry-row.test.ts +++ b/src/main/codex/codex-provider-retry-row.test.ts @@ -111,56 +111,6 @@ describe('a Codex stream error it is about to retry', () => { ).toEqual([]) }) - it('is one line when Codex gives no detail, or only repeats its message', () => { - const { translator, rows } = harness() - translator.handle(retrying('Reconnecting... 1/5')) - translator.handle(retrying('Reconnecting... 2/5', 'Reconnecting... 2/5')) - - expect(retryRows(rows).map((row) => row.body.kind === 'status' && row.body.text)).toEqual([ - 'Codex is retrying: Reconnecting... 1/5.', - 'Codex is retrying: Reconnecting... 2/5.' - ]) - }) - - it('publishes every attempt, so each one renews the idle clock', () => { - const { translator, publishes } = harness() - - const before = publishes() - translator.handle(retrying('Reconnecting... 1/5')) - translator.handle(retrying('Reconnecting... 2/5')) - translator.handle(retrying('Reconnecting... 3/5')) - - expect(publishes() - before).toBe(3) - }) - - it('keeps every earlier row when a new connection in the same session retries', () => { - const rows: Row[] = [] - const connect = (acquisitionId: string) => { - const translator = createCodexJournalTranslator({ - sink: { - appendItem: (identity, body) => rows.push({ key: agentJournalItemKey(identity), body }), - appendTombstone: () => undefined, - publish: () => undefined - }, - primaryThreadId: () => THREAD_ID, - acquisitionId - }) - translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) - return translator - } - const first = connect('generation-1') - first.handle(retrying('Reconnecting... 1/5')) - first.handle(retrying('Reconnecting... 2/5')) - const second = connect('generation-2') - second.handle(retrying('Reconnecting... 1/5')) - - expect(retryRows(rows).map((row) => row.body.kind === 'status' && row.body.text)).toEqual([ - 'Codex is retrying: Reconnecting... 1/5.', - 'Codex is retrying: Reconnecting... 2/5.', - 'Codex is retrying: Reconnecting... 1/5.' - ]) - }) - it('is named for the acquisition that received it, so a reconnect writes new rows', async () => { const codex = fakeCodex() const adapter = adapterFor(codex) diff --git a/src/main/codex/codex-structured-visuals.test.ts b/src/main/codex/codex-structured-visuals.test.ts index 506a96e577b..84a0ebd9bf8 100644 --- a/src/main/codex/codex-structured-visuals.test.ts +++ b/src/main/codex/codex-structured-visuals.test.ts @@ -15,10 +15,8 @@ import { import { createCodexStructuredLaunchResolver } from '../runtime/structured-agent-launch-composition.test-support' import { agentSessionRecordFixture } from '../native-chat/agent-session-record-test-fixture' import { codexProviderHandle } from '../../shared/agent-session-provider-handle-encoding' -import { - CODEX_VISUALS_SETUP_BUDGET_MS, - prepareCodexThreadForVisuals -} from './codex-structured-visuals' +import { prepareCodexThreadForVisuals } from './codex-structured-visuals' + import { codexStructuredPermissionPolicy } from '../../shared/codex-permission-policy' const VISUALS: NativeChatVisualsLaunch = { @@ -51,34 +49,6 @@ const configWithRoots = (roots: unknown) => () => ({ }) describe('setting up a Codex app-server for a chat with visuals', () => { - it("names the skill root and adds the chat folder to the user's writable roots", async () => { - const { calls, connection } = connectionAnswering({ - 'config/read': configWithRoots(['/home/me/scratch']) - }) - const config = await prepareCodexThreadForVisuals(connection, { - cwd: '/work/repo', - visuals: VISUALS, - permissionPolicy: MANUAL - }) - expect(config).toEqual({ - 'sandbox_workspace_write.writable_roots': ['/home/me/scratch', VISUALS.folder] - }) - expect(calls).toEqual( - expect.arrayContaining([ - { - method: 'skills/extraRoots/set', - params: { extraRoots: [VISUALS.skill.skillsRoot] }, - timeoutMs: CODEX_VISUALS_SETUP_BUDGET_MS - }, - { - method: 'config/read', - params: { cwd: '/work/repo' }, - timeoutMs: CODEX_VISUALS_SETUP_BUDGET_MS - } - ]) - ) - }) - it('grants just the folder when the user has no writable roots of their own', async () => { for (const answer of [() => ({ config: {} }), configWithRoots([])]) { const { connection } = connectionAnswering({ 'config/read': answer }) @@ -153,12 +123,6 @@ describe('setting up a Codex app-server for a chat with visuals', () => { ) } }) - - it('sends nothing for a chat without visuals', async () => { - const { calls, connection } = connectionAnswering({}) - await expect(prepareCodexThreadForVisuals(connection, { cwd: '/w' })).resolves.toBeNull() - expect(calls).toEqual([]) - }) }) async function acquired( diff --git a/src/main/computer/desktop-script-provider-action-errors.test.ts b/src/main/computer/desktop-script-provider-action-errors.test.ts index 318729f8031..3977857bda6 100644 --- a/src/main/computer/desktop-script-provider-action-errors.test.ts +++ b/src/main/computer/desktop-script-provider-action-errors.test.ts @@ -8,57 +8,12 @@ import { expectDesktopProviderSubprocessStartCount, mockBridgeResponse, resetDesktopScriptProviderTestHarness, - sampleBridgeSnapshot, sampleCapabilities } from './desktop-script-provider-test-harness' describe('DesktopScriptProviderClient action errors', () => { afterEach(resetDesktopScriptProviderTestHarness) - it('maps action-specific bridge errors to actionable codes', async () => { - mockBridgeResponse({ ok: false, error: 'element value is not settable' }) - mockBridgeResponse({ ok: false, error: 'Raise is not a valid secondary action' }) - mockBridgeResponse({ ok: false, error: 'text_input_incomplete: inspect state before retrying' }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'value_not_settable' - }) - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'action_not_supported' - }) - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'action_timeout' - }) - }) - - it('maps native validation bridge errors to invalid arguments', async () => { - mockBridgeResponse({ ok: false, error: 'unsupported scroll direction: diagonal' }) - mockBridgeResponse({ ok: false, error: 'x is required' }) - mockBridgeResponse({ ok: false, error: 'text is required' }) - mockBridgeResponse({ ok: false, error: 'click_count must be a positive integer' }) - mockBridgeResponse({ ok: false, error: 'Unsupported key: Nope' }) - - const client = await createDesktopScriptProviderClient('windows', '/tmp/runtime.ps1') - - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'invalid_argument' - }) - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'invalid_argument' - }) - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'invalid_argument' - }) - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'invalid_argument' - }) - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'invalid_argument' - }) - }) - it('does not confuse permission setup errors with invalid arguments', async () => { mockBridgeResponse({ ok: false, error: 'Accessibility permission is required' }) @@ -83,46 +38,6 @@ describe('DesktopScriptProviderClient action errors', () => { }) }) - it('maps keyboard focus bridge errors to window_not_focused', async () => { - mockBridgeResponse({ - ok: false, - error: - 'window_not_focused: keyboard input requires the target window to be focused; retry with --restore-window' - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'window_not_focused' - }) - }) - - it('maps bridge screenshot capture errors to screenshot_failed', async () => { - mockBridgeResponse({ - ok: false, - error: 'screenshot_failed: Screen Recording permission is required' - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'screenshot_failed' - }) - }) - - it('maps missing Linux keyboard dependencies to unsupported capability', async () => { - mockBridgeResponse({ - ok: false, - error: 'GDK is required for non-character key synthesis' - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'unsupported_capability' - }) - }) - it('rejects actions that the provider does not advertise', async () => { mockBridgeResponse({ ok: true, @@ -216,79 +131,4 @@ describe('DesktopScriptProviderClient action errors', () => { }) expectDesktopProviderSubprocessStartCount(0) }) - - it('rejects non-keyboard actions that the provider does not advertise', async () => { - mockBridgeResponse({ - ok: true, - snapshot: sampleBridgeSnapshot('Text Editor', 'initial') - }) - mockBridgeResponse({ - ok: true, - capabilities: sampleCapabilities({ - setValue: false - }) - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await client.snapshot({ app: 'Text Editor' }) - await expect( - client.action('setValue', { - app: 'Text Editor', - elementIndex: 0, - value: 'changed', - noScreenshot: true - }) - ).rejects.toMatchObject({ - code: 'unsupported_capability', - message: expect.stringContaining('actions.setValue') - }) - }) - - it('uses provider action metadata when bridge reports the actual path', async () => { - mockBridgeResponse({ - ok: true, - snapshot: sampleBridgeSnapshot('Text Editor', 'initial') - }) - mockBridgeResponse({ - ok: true, - capabilities: sampleCapabilities() - }) - mockBridgeResponse({ - ok: true, - action: { - path: 'accessibility', - actionName: 'Press', - fallbackReason: null - }, - snapshot: sampleBridgeSnapshot('Text Editor', 'changed') - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await client.snapshot({ app: 'Text Editor' }) - await expect( - client.action('click', { - app: 'Text Editor', - elementIndex: 0, - noScreenshot: true - }) - ).resolves.toMatchObject({ - action: { - path: 'accessibility', - actionName: 'Press' - } - }) - }) - - it('explains that missing element indexes require a fresh snapshot', async () => { - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect( - client.action('click', { app: 'Text Editor', elementIndex: 4 }) - ).rejects.toMatchObject({ - code: 'element_not_found', - message: expect.stringContaining('run get-app-state again') - }) - }) }) diff --git a/src/main/daemon/daemon-audit-eligibility-event.test.ts b/src/main/daemon/daemon-audit-eligibility-event.test.ts index 68fd21af8dd..87834994a0e 100644 --- a/src/main/daemon/daemon-audit-eligibility-event.test.ts +++ b/src/main/daemon/daemon-audit-eligibility-event.test.ts @@ -43,26 +43,6 @@ beforeEach(() => { }) describe('daemon audit eligibility telemetry', () => { - it('uses a dedicated validator-accepted event family', () => { - trackDaemonAuditEligibility(recordAuthenticatedInventory(context, null)) - - expect(trackMock).toHaveBeenCalledOnce() - const [name, props] = trackMock.mock.calls[0] - expect(name).toBe('daemon_audit_eligibility') - expect(name).not.toBe('daemon_lifecycle') - expect(props).toMatchObject({ - state: 'present', - reason: 'authenticated_inventory', - evidence_sources: ['authenticated_inventory'], - protocol_generation: 23, - generation_role: 'legacy', - exact_incarnation: 'unavailable', - process_reason: null - }) - expect(props).not.toHaveProperty('exact_incarnation_correlation') - expect(validate('daemon_audit_eligibility', props).ok).toBe(true) - }) - it('correlates an exact incarnation across app trackers without raw identity fields', () => { const currentContext = { ...context, protocolGeneration: PROTOCOL_VERSION } const firstAppTracker = createDaemonAuditEligibilityTracker() @@ -105,20 +85,6 @@ describe('daemon audit eligibility telemetry', () => { } }) - it('does not mislabel a future protocol generation as legacy', () => { - const trackEligibility = createDaemonAuditEligibilityTracker() - - expect(() => - trackEligibility( - recordAuthenticatedInventory( - { ...context, protocolGeneration: PROTOCOL_VERSION + 1 }, - exactIncarnation - ) - ) - ).not.toThrow() - expect(trackMock).not.toHaveBeenCalled() - }) - it('cannot affect callers when telemetry throws', () => { trackMock.mockImplementation(() => { throw new Error('transport failed') diff --git a/src/main/daemon/daemon-init-child-readiness.test.ts b/src/main/daemon/daemon-init-child-readiness.test.ts index e3bc3dd767d..f88389231dd 100644 --- a/src/main/daemon/daemon-init-child-readiness.test.ts +++ b/src/main/daemon/daemon-init-child-readiness.test.ts @@ -6,8 +6,7 @@ const { writeFileSyncMock, forkMock, checkDaemonHealthMock, - getProcessStartedAtMsMock, - launchedStartedAtMs, + spawnerInstances, importFresh, installDefaultNetConnectStub, @@ -118,46 +117,6 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { expect(launchArgs[launchNonceIndex + 1]).toMatch(/^[0-9a-f-]{36}$/) }) - it('leaves exclusive PID publication to the daemon child', async () => { - const mod = await importFresh() - checkDaemonHealthMock.mockResolvedValue('unreachable') - await mod.initDaemonPtyProvider() - - const launcher = spawnerInstances[0].launcher as ( - socketPath: string, - tokenPath: string - ) => Promise<{ shutdown(): Promise }> - const child = { - pid: 12345, - on(event: string, cb: (arg?: unknown) => void) { - if (event === 'message') { - queueMicrotask(() => cb({ type: 'ready', pid: 12345, startedAtMs: 1_000_000 })) - } - return this - }, - off: vi.fn(), - disconnect: vi.fn(), - unref: vi.fn() - } - forkMock.mockReturnValueOnce(child) - - await launcher('/fake/socket', '/fake/token') - - expect(writeFileSyncMock).not.toHaveBeenCalled() - expect(forkMock.mock.calls.at(-1)?.[1]).toEqual( - expect.arrayContaining([ - '--pid-record', - `/fake/daemon/daemon-v${PROTOCOL_VERSION}.pid`, - '--entry-path', - FAKE_DAEMON_ENTRY_PATH, - '--app-version', - '1.2.3', - '--spawner-exec-path', - process.execPath - ]) - ) - }) - it('destroys the daemon stderr pipe once the daemon signals ready', async () => { const mod = await importFresh() checkDaemonHealthMock.mockResolvedValue('unreachable') @@ -208,35 +167,4 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { expect(child.disconnect).toHaveBeenCalledOnce() expect(child.unref).toHaveBeenCalledOnce() }) - - it('accepts the daemon self-reported start time when the OS query returns null', async () => { - const mod = await importFresh() - await mod.initDaemonPtyProvider() - - const launcher = spawnerInstances[0].launcher as ( - socketPath: string, - tokenPath: string - ) => Promise<{ shutdown(): Promise }> - checkDaemonHealthMock.mockResolvedValueOnce('unreachable') - getProcessStartedAtMsMock.mockReturnValue(null) - launchedStartedAtMs.current = 1_700_000_123_456 - forkMock.mockImplementationOnce(() => ({ - pid: 12345, - on(event: string, cb: (arg?: unknown) => void) { - if (event === 'message') { - queueMicrotask(() => cb({ type: 'ready', pid: 12345, startedAtMs: 1_700_000_123_456 })) - } - return this - }, - off() { - return this - }, - disconnect: vi.fn(), - unref: vi.fn() - })) - - await launcher('/fake/socket', '/fake/token') - - expect(writeFileSyncMock).not.toHaveBeenCalled() - }) }) diff --git a/src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts b/src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts index 1d962cff90a..dd181577da5 100644 --- a/src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts +++ b/src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts @@ -21,8 +21,6 @@ import { POST_REPLAY_LIVE_AGENT_REATTACH_RESET } from '../../shared/terminal-mod const ANY_MOTION_TRACKING_ON = '\x1b[?1003h' const SGR_ENCODING_ON = '\x1b[?1006h' -const ANY_MOTION_TRACKING_OFF = '\x1b[?1003l' -const SGR_ENCODING_OFF = '\x1b[?1006l' function createFakeSubprocess(foregroundProcess: string) { let onData: ((data: string) => void) | null = null @@ -76,72 +74,6 @@ describe('#12101 mouse tracking survives the death of the process that armed it' vi.useRealTimers() }) - it('re-arms mouse reporting in the fresh shell that replaces a force-killed agent', async () => { - const manager = new HistoryManager(dir) - const reader = new HistoryReader(dir) - - const agentPty = createFakeSubprocess('claude') - const agent = new Session({ - sessionId, - cols: 80, - rows: 24, - subprocess: agentPty, - launchAgent: 'claude', - shellReadySupported: false - }) - agentPty.emit(`${ANY_MOTION_TRACKING_ON}${SGR_ENCODING_ON}`) - agentPty.emit('user@host ~ % claude\r\nclaude> analyzing...\r\nuser@host ~ $ ') - await waitForEmulatorParse(agent) - - const armed = agent.getSnapshot() - expect(armed?.modes.mouseTracking).toBe(true) - expect(armed?.modes.mouseTrackingMode).toBe('any') - expect(armed?.rehydrateSequences).toContain(ANY_MOTION_TRACKING_ON) - - // Persist the still-armed checkpoint before simulating agent death. - await manager.openSession(sessionId, { cwd: '/Users/dev/feature-branch', cols: 80, rows: 24 }) - await manager.checkpoint(sessionId, armed!) - - void new TerminalSessionTeardown(new Map([[sessionId, agent]])).killSession( - sessionId, - agent, - false - ) - agentPty.simulateKilledExit() - agent.dispose() - expect(killWithDescendantSweepMock).toHaveBeenCalled() - const teardownBytes = agentPty.written.join('') - expect(teardownBytes).not.toContain(ANY_MOTION_TRACKING_OFF) - expect(teardownBytes).not.toContain(SGR_ENCODING_OFF) - - // This fixture leaves history eligible and seeds a replacement shell from it. - const restoreInfo = await reader.detectColdRestore(sessionId) - expect(restoreInfo).not.toBeNull() - const seedChunks = [ - ...iterateTerminalHistorySeedChunks(getRecoveredHistorySeedSegments(restoreInfo!)) - ] - - const shellPty = createFakeSubprocess('zsh') - const shell = new Session({ - sessionId, - cols: 80, - rows: 24, - subprocess: shellPty, - shellReadySupported: false, - historySeedChunks: seedChunks - }) - const revived = shell.getSnapshot() - try { - expect.soft(revived?.modes.mouseTracking).toBe(false) - expect.soft(revived?.modes.mouseTrackingMode).toBe('none') - expect.soft(revived?.rehydrateSequences).toBe('') - // The serializer trailer must also be disarmed; clearing rehydrateSequences alone is insufficient. - expect.soft(revived?.snapshotAnsi).not.toContain(ANY_MOTION_TRACKING_ON) - } finally { - shell.dispose() - } - }) - it('leaves the reattached renderer xterm armed against a dead agent (SGR reports into the prompt)', async () => { const manager = new HistoryManager(dir) const reader = new HistoryReader(dir) @@ -199,54 +131,4 @@ describe('#12101 mouse tracking survives the death of the process that armed it' shell.dispose() } }) - - it('control: a TUI that DID emit DECRST before exiting restores a clean shell', async () => { - const manager = new HistoryManager(dir) - const reader = new HistoryReader(dir) - - const agentPty = createFakeSubprocess('vim') - const agent = new Session({ - sessionId, - cols: 80, - rows: 24, - subprocess: agentPty, - shellReadySupported: false - }) - agentPty.emit(`${ANY_MOTION_TRACKING_ON}${SGR_ENCODING_ON}`) - agentPty.emit('user@host ~ $ ') - await waitForEmulatorParse(agent) - agentPty.emit(`${ANY_MOTION_TRACKING_OFF}${SGR_ENCODING_OFF}`) - for (let i = 0; i < 50 && agent.getSnapshot()?.modes.mouseTracking !== false; i += 1) { - await new Promise((resolve) => setTimeout(resolve, 1)) - } - - await manager.openSession(sessionId, { cwd: '/Users/dev/feature-branch', cols: 80, rows: 24 }) - await manager.checkpoint(sessionId, agent.getSnapshot()!) - void new TerminalSessionTeardown(new Map([[sessionId, agent]])).killSession( - sessionId, - agent, - false - ) - agentPty.simulateKilledExit() - agent.dispose() - - const restoreInfo = await reader.detectColdRestore(sessionId) - const shellPty = createFakeSubprocess('zsh') - const shell = new Session({ - sessionId, - cols: 80, - rows: 24, - subprocess: shellPty, - shellReadySupported: false, - historySeedChunks: [ - ...iterateTerminalHistorySeedChunks(getRecoveredHistorySeedSegments(restoreInfo!)) - ] - }) - try { - expect(shell.getSnapshot()?.modes.mouseTracking).toBe(false) - expect(shell.getSnapshot()?.rehydrateSequences).toBe('') - } finally { - shell.dispose() - } - }) }) diff --git a/src/main/emulator/serve-sim-runtime-materializer.test.ts b/src/main/emulator/serve-sim-runtime-materializer.test.ts index 0554d248f8d..079f4d13294 100644 --- a/src/main/emulator/serve-sim-runtime-materializer.test.ts +++ b/src/main/emulator/serve-sim-runtime-materializer.test.ts @@ -162,19 +162,6 @@ describe('materializeServeSimRuntime', () => { expect(leftovers).toEqual([]) }) - it('returns null when the bundled package is missing', async () => { - const root = await createRoot() - - const materialized = materializeServeSimRuntime({ - bundledPackageDir: join(root, 'does-not-exist'), - targetRootDir: join(root, 'runtime'), - version: '1.2.3', - clearQuarantine: () => {} - }) - - expect(materialized).toBeNull() - }) - it('links each bundled dependency next to the copy and skips ones the bundle lacks', async () => { const root = await createRoot() const bundledPackageDir = await createBundledServeSimPackage(root) diff --git a/src/main/gitlab/client-work-items.test.ts b/src/main/gitlab/client-work-items.test.ts index ca1f16f9442..21b89adb0d4 100644 --- a/src/main/gitlab/client-work-items.test.ts +++ b/src/main/gitlab/client-work-items.test.ts @@ -111,23 +111,6 @@ describe('gitlab client — combined listWorkItems', () => { }) }) - it("skips the issues fetch when state === 'merged'", async () => { - glabApiWithHeadersMock.mockResolvedValueOnce({ body: '[]', headers: {} }) - - await listWorkItems('/repo', 'merged', 1, 20) - expect(glabExecFileAsyncMock).not.toHaveBeenCalled() - }) - - it('passes the closed state through to the issues fetch', async () => { - glabExecFileAsyncMock.mockImplementation(async () => { - return { stdout: '[]' } - }) - - await listWorkItems('/repo', 'closed', 1, 20) - const issuesCallPath = glabExecFileAsyncMock.mock.calls[0][0] as string[] - expect(issuesCallPath.at(-1)).toContain('state=closed') - }) - it('passes search queries through to merge request and issue fetches', async () => { glabApiWithHeadersMock.mockResolvedValueOnce({ body: '[]', headers: {} }) glabExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' }) @@ -152,30 +135,6 @@ describe('gitlab client — combined listWorkItems', () => { expect(issueParams.has('search')).toBe(false) }) - it('passes the requested page through to merge request and issue fetches', async () => { - glabApiWithHeadersMock.mockResolvedValueOnce({ body: '[]', headers: {} }) - glabExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' }) - - await listWorkItems('/repo', 'opened', 2, 20) - - const mergeRequestCallPath = glabApiWithHeadersMock.mock.calls[0][0] as string[] - const issuesCallPath = glabExecFileAsyncMock.mock.calls[0][0] as string[] - const mergeRequestParams = new URLSearchParams(mergeRequestCallPath[0].split('?')[1]) - const issueParams = new URLSearchParams(issuesCallPath.at(-1)?.split('?')[1]) - expect(mergeRequestParams.get('page')).toBe('2') - expect(issueParams.get('page')).toBe('2') - }) - - it("omits the state param when 'all'", async () => { - glabExecFileAsyncMock.mockImplementation(async () => { - return { stdout: '[]' } - }) - - await listWorkItems('/repo', 'all', 1, 20) - const issuesCallPath = glabExecFileAsyncMock.mock.calls[0][0] as string[] - expect(issuesCallPath.at(-1)).not.toContain('state=') - }) - it('routes issue list fetches through the selected SSH GitLab host', async () => { resolveIssueSourceMock.mockResolvedValueOnce({ source: { host: 'git.internal', path: 'g/p' }, @@ -203,14 +162,6 @@ describe('gitlab client — combined listWorkItems', () => { expect(glabExecFileAsyncMock).not.toHaveBeenCalled() }) - it('surfaces the MR error envelope into the combined result', async () => { - glabApiWithHeadersMock.mockRejectedValueOnce(new Error('HTTP 403 Forbidden')) - glabExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' }) - - const result = await listWorkItems('/repo', 'opened', 1, 20) - expect(result.error?.type).toBe('permission_denied') - }) - it('still returns issues when MRs error out', async () => { glabApiWithHeadersMock.mockRejectedValueOnce(new Error('HTTP 500')) glabExecFileAsyncMock.mockResolvedValueOnce({ diff --git a/src/main/gitlab/merge-request-creation.test.ts b/src/main/gitlab/merge-request-creation.test.ts index 6acb317068e..71caf8cbf53 100644 --- a/src/main/gitlab/merge-request-creation.test.ts +++ b/src/main/gitlab/merge-request-creation.test.ts @@ -137,53 +137,6 @@ describe('createGitLabMergeRequest', () => { }) }) - it('creates SSH-backed merge requests without using the remote path as a local cwd', async () => { - glabExecFileAsyncMock.mockResolvedValueOnce({ - stdout: JSON.stringify({ - iid: 45, - web_url: 'https://gitlab.com/acme/widgets/-/merge_requests/45' - }), - stderr: '' - }) - - await expect( - createGitLabMergeRequest( - '/remote/repo-root', - { - provider: 'gitlab', - base: 'main', - head: 'feature/ssh-create-mr', - title: 'SSH Create MR' - }, - 'ssh:ssh-1' - ) - ).resolves.toEqual({ - ok: true, - number: 45, - url: 'https://gitlab.com/acme/widgets/-/merge_requests/45' - }) - - expect(getProjectSlugMock).toHaveBeenCalledWith('/remote/repo-root', 'ssh-1') - const [args, options] = glabExecFileAsyncMock.mock.calls[0] - expect(args).toEqual( - expect.arrayContaining([ - 'mr', - 'create', - '-R', - 'acme/widgets', - '--target-branch', - 'main', - '--source-branch', - 'feature/ssh-create-mr' - ]) - ) - expect(options).toMatchObject({ - timeout: 60_000, - idempotent: false - }) - expect(options).not.toHaveProperty('cwd') - }) - it('returns an existing merge request when GitLab reports a duplicate', async () => { glabExecFileAsyncMock .mockRejectedValueOnce(new Error('merge request already exists')) diff --git a/src/main/ipc/worktrees-ssh-pr-head-fetch.test.ts b/src/main/ipc/worktrees-ssh-pr-head-fetch.test.ts index 1289bc7a83c..8d4be2a08f2 100644 --- a/src/main/ipc/worktrees-ssh-pr-head-fetch.test.ts +++ b/src/main/ipc/worktrees-ssh-pr-head-fetch.test.ts @@ -1,9 +1,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { REVIEW_HEAD_FETCH_TIMEOUT_MS } from '../../shared/review-head-tracking-ref' -import { getPullRequestPushTargetMock, gitExecFileAsyncMock } from './worktrees-test-module-mocks' +import { gitExecFileAsyncMock } from './worktrees-test-module-mocks' + import { handlers, harnessRepo, setupWorktreeHandlers, store } from './worktrees-test-harness' import { ORIGIN_HEAD_COMPONENT, ORIGIN_REMOTE_URL } from './worktrees-test-fixtures' -import type { WorktreeRuntimeStub } from './worktrees-test-runtime-stub' vi.mock('electron', async () => (await import('./worktrees-test-module-mocks')).electronModuleMock() @@ -83,45 +83,8 @@ vi.mock('./pty/provider/state-cleanup', async () => ) describe('registerWorktreeHandlers', () => { - let runtimeStub: WorktreeRuntimeStub - beforeEach(() => { - runtimeStub = setupWorktreeHandlers() - }) - - it('resolves a fork PR base even when push-target discovery fails', async () => { - getPullRequestPushTargetMock.mockRejectedValueOnce(new Error('lookup failed')) - gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { - if (args[0] === 'remote' && args[1] === 'get-url') { - return { stdout: `${ORIGIN_REMOTE_URL}\n`, stderr: '' } - } - if (args[0] === 'rev-parse') { - return { stdout: 'abc123\n', stderr: '' } - } - return { stdout: '', stderr: '' } - }) - - const result = await handlers['worktrees:resolvePrBase'](null, { - repoId: 'repo-1', - prNumber: 1849, - headRefName: 'feat/onboarding-model-choice-782', - isCrossRepository: true - }) - - expect(gitExecFileAsyncMock).toHaveBeenCalledWith( - [ - 'fetch', - '--no-tags', - 'origin', - `+refs/pull/1849/head:refs/orca/pull/${ORIGIN_HEAD_COMPONENT}/1849` - ], - { cwd: '/workspace/repo', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } - ) - expect(result).toEqual({ - baseBranch: 'abc123', - headSha: 'abc123', - branchNameOverride: 'feat/onboarding-model-choice-782' - }) + setupWorktreeHandlers() }) it('refuses local git for a PR base on an executionHostId-only SSH repo', async () => { @@ -217,29 +180,4 @@ describe('registerWorktreeHandlers', () => { 'Failed to fetch origin/feat/onboarding-model-choice-782: fatal: unable to access repo: Could not resolve host: github.com' }) }) - - it('delegates GitLab MR base resolution through the runtime implementation', async () => { - runtimeStub.resolveManagedMrBase.mockResolvedValueOnce({ - baseBranch: 'fork-mr-sha', - pushTarget: { remoteName: 'origin', branchName: 'feature/mr' } - }) - - const result = await handlers['worktrees:resolveMrBase'](null, { - repoId: 'repo-1', - mrIid: 42, - sourceBranch: 'feature/mr', - isCrossRepository: true - }) - - expect(runtimeStub.resolveManagedMrBase).toHaveBeenCalledWith({ - repoSelector: 'id:repo-1', - mrIid: 42, - sourceBranch: 'feature/mr', - isCrossRepository: true - }) - expect(result).toMatchObject({ - baseBranch: 'fork-mr-sha', - pushTarget: { remoteName: 'origin', branchName: 'feature/mr' } - }) - }) }) diff --git a/src/main/ipc/worktrees/listing/wsl-stopped-worktree-listing.test.ts b/src/main/ipc/worktrees/listing/wsl-stopped-worktree-listing.test.ts index 6812728c857..6a8e5634652 100644 --- a/src/main/ipc/worktrees/listing/wsl-stopped-worktree-listing.test.ts +++ b/src/main/ipc/worktrees/listing/wsl-stopped-worktree-listing.test.ts @@ -249,13 +249,4 @@ describe('Retry on a stopped WSL distro (E9)', () => { expect(insideAct).toEqual([true]) expect(isWslUserActFor('Ubuntu')).toBe(false) }) - - it('does nothing for a folder workspace or a repo outside WSL', async () => { - for (const repo of [makeRepo({ kind: 'folder' }), makeRepo({ path: 'C:\\work\\repo' })]) { - await scanWorktreesStartingWslDistro(createStore(repo), repo.id) - } - await scanWorktreesStartingWslDistro(createStore(makeRepo()), 'unknown-repo') - - expect(mocks.listDetectedGitWorktrees).not.toHaveBeenCalled() - }) }) diff --git a/src/main/managed-server/install/remote-node-runtime-store-windows.test.ts b/src/main/managed-server/install/remote-node-runtime-store-windows.test.ts index 82e23e99c69..ec9a65065c2 100644 --- a/src/main/managed-server/install/remote-node-runtime-store-windows.test.ts +++ b/src/main/managed-server/install/remote-node-runtime-store-windows.test.ts @@ -27,8 +27,6 @@ const conn = unusedSshConnection() const host = getRemoteHostPlatform('win32-x64') const mockExec = vi.mocked(execCommand) const sha = (c: string): string => c.repeat(64) -const root = 'C:/Users/ada/.orca-remote' -const store = `${root}/runtimes` const powerShell = [ process.env.ORCA_POWERSHELL_EXECUTABLE, @@ -41,49 +39,6 @@ const powerShell = [ }).status === 0 ) -describe('Windows runtime store commands', () => { - it('stay inside the EDR posture: one encoded powershell.exe line, no policy switch, no compilation', () => { - for (const command of [ - windowsRuntimeStoreInventoryCommand(root), - windowsSweepStaleRuntimeStagesCommand(store, 20, 'SWEPT') - ]) { - expect(command).toMatch(/^powershell\.exe -NoProfile -NonInteractive -EncodedCommand \S+$/) - expect(decodeRemotePowerShellScript(command)).not.toMatch( - /ExecutionPolicy|Add-Type|\.ps1|Import-Module/ - ) - } - }) - - it('finds process holds by image path under runtimes\\, never by image name', () => { - const script = decodeRemotePowerShellScript(windowsRuntimeStoreInventoryCommand(root)) - expect(script).toContain( - `Get-CimInstance -ClassName Win32_Process -Filter "ExecutablePath LIKE '%\\\\runtimes\\\\%'" -Property ExecutablePath -ErrorAction Stop` - ) - expect(script).not.toMatch(/Name\s*=|node\.exe|ProcessName/) - expect(script.indexOf("Write-Output 'PROCESS_CHECK cim'")).toBeGreaterThan( - script.indexOf('Get-CimInstance') - ) - }) - - it('falls back to Get-Process image paths when WMI refuses a standard user', () => { - const script = decodeRemotePowerShellScript(windowsRuntimeStoreInventoryCommand(root)) - const fallback = script.slice(script.indexOf("Write-Output 'PROCESS_CHECK cim'")) - expect(fallback).toContain( - "Get-Process -ErrorAction Stop | Where-Object { $_.Path -and $_.Path.IndexOf('\\runtimes\\', [StringComparison]::OrdinalIgnoreCase) -ge 0 }" - ) - expect(fallback.indexOf("Write-Output 'PROCESS_CHECK process'")).toBeGreaterThan( - fallback.indexOf('Get-Process') - ) - }) - - it('reads both ref shapes from every sibling of runtimes\\', () => { - const script = decodeRemotePowerShellScript(windowsRuntimeStoreInventoryCommand(root)) - expect(script).toContain("Join-Path $d.FullName '.runtime-node'") - expect(script).toContain("$_.Name.StartsWith('.runtime-ref-node-')") - expect(script).toContain("$_.Name -ne 'runtimes'") - }) -}) - describe('parseRuntimeStoreInventory with Windows output', () => { it('takes holds from backslash image paths in any case, tombstones included', () => { const inventory = parseRuntimeStoreInventory( diff --git a/src/main/native-chat/agent-session-wire/provider-turn-activity-routing.test.ts b/src/main/native-chat/agent-session-wire/provider-turn-activity-routing.test.ts index 5ff023fb236..0d56726c167 100644 --- a/src/main/native-chat/agent-session-wire/provider-turn-activity-routing.test.ts +++ b/src/main/native-chat/agent-session-wire/provider-turn-activity-routing.test.ts @@ -191,32 +191,6 @@ describe('provider turn activity routing', () => { translator.dispose() }) - it('keeps Codex tool rows singular and the activity free of tool labels', () => { - const state = recordingSink() - const translator = createCodexJournalTranslator({ - sink: state.sink, - primaryThreadId: () => THREAD_ID - }) - translator.handle(codexNotification('turn/started', { turn: { id: TURN_ID } })) - const lifecycleRows = state.rows.length - translator.handle( - codexNotification('item/started', { - turnId: TURN_ID, - item: { - type: 'commandExecution', - id: 'command-1', - command: 'pnpm test', - status: 'inProgress' - } - }) - ) - - expect(state.rows).toHaveLength(lifecycleRows + 1) - expect(state.rows.at(-1)).toMatchObject({ kind: 'tool-call', name: 'shell' }) - expect(state.activities.at(-1)).toEqual({ turnId: TURN_ID, text: 'Running a command' }) - expect(state.activities.at(-1)?.text).not.toContain('pnpm test') - }) - it('routes Claude status frames without creating timeline rows and clears on settlement', () => { const state = recordingSink() const translator = createClaudeJournalTranslator({ sink: state.sink }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-logger.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-logger.test.ts index 365381c36d0..ae28498a909 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-logger.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-logger.test.ts @@ -215,15 +215,6 @@ describe('what an Error leaves in the trace file', () => { expect(sqlite?.attributes).toMatchObject({ errorCode: 'ERR_SQLITE_ERROR', errorErrcode: 5 }) expect(sqlite?.exit).toMatchObject({ cause: expect.stringContaining('database is locked') }) }) - - it('names the code of a cause whose message does not', () => { - const logger = createStructuredAgentSessionLogger({ now: () => clock }) - logger.warn('x failed', { - scope: 'x', - error: new Error('x', { cause: Object.assign(new Error('no space'), { code: 'ENOSPC' }) }) - }) - expect(written()[0]?.attributes['errorCause']).toEqual(['Error: no space [ENOSPC]']) - }) }) describe('a logger that throws', () => { diff --git a/src/main/notebook/notebook-kernel.test.ts b/src/main/notebook/notebook-kernel.test.ts index ea3894b4c42..5933fd0c0d8 100644 --- a/src/main/notebook/notebook-kernel.test.ts +++ b/src/main/notebook/notebook-kernel.test.ts @@ -18,28 +18,6 @@ function collect(chunks: string[]): unknown[] { } describe('createFrameReader', () => { - it('reassembles frames split across chunks and skips stray lines', () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - try { - expect( - collect([ - 'warning: something printed\n{"type": "rea', - 'dy"}\n{"type": "stream", "content": {"name": "stdout", "text": "hi"}}\n[1, 2]\n', - '{"type": "missing", "externallyManaged": true}\n{"type": "missing"}\n', - '{"type": "unknown"}\n{"type": "done", "status": "ok", "execution_count": 3}\n{"partial' - ]) - ).toEqual([ - { type: 'ready' }, - { type: 'stream', content: { name: 'stdout', text: 'hi' } }, - { type: 'missing', externallyManaged: true }, - { type: 'missing', externallyManaged: false }, - { type: 'done', status: 'ok', execution_count: 3 } - ]) - } finally { - warn.mockRestore() - } - }) - it('avoids repeatedly scanning an incomplete image record for newlines', () => { const frame = { type: 'display_data', content: { data: { 'image/png': 'x'.repeat(524_288) } } } const wire = `${JSON.stringify(frame)}\n` @@ -83,21 +61,6 @@ describe('createFrameReader', () => { expect(scannedCharacters).toBeLessThanOrEqual(wire.length * 2) }) - it('does not measure record bytes when no size limit applies', () => { - const frame = { type: 'display_data', content: { data: { 'image/png': 'x'.repeat(65_536) } } } - const byteLength = vi.spyOn(Buffer, 'byteLength') - let frames: unknown[] - let measurements: number - try { - frames = collect([`${JSON.stringify(frame)}\n`]) - measurements = byteLength.mock.calls.length - } finally { - byteLength.mockRestore() - } - expect(frames).toEqual([frame]) - expect(measurements).toBe(0) - }) - it('preserves code units at every split boundary', () => { const frames = [ { type: 'stream', content: { text: 'café 漢字 🐋\n\u0000' } }, diff --git a/src/main/opencode/hook-plugin-background-child-completion.test.ts b/src/main/opencode/hook-plugin-background-child-completion.test.ts index 8849cbc8032..40eb27b0cbf 100644 --- a/src/main/opencode/hook-plugin-background-child-completion.test.ts +++ b/src/main/opencode/hook-plugin-background-child-completion.test.ts @@ -177,23 +177,6 @@ describe('OpenCode plugin background child completion', () => { expect(posts.at(-1)?.sessionID).toBe('root') }) - it('retires a background child through an Idle whose ancestry cannot be resolved', async () => { - let resolvable = true - const hooks = await createHooks([], async () => - resolvable ? { data: TASK_TREE } : Promise.reject(new Error('sdk outage')) - ) - - await hooks.event({ event: status('busy', 'root') }) - await hooks.event({ event: status('busy', 'child') }) - await hooks.event({ event: status('idle', 'root') }) - expect(names()).not.toContain('SessionIdle') - - resolvable = false - await hooks.event({ event: status('idle', 'child') }) - - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - }) - it('drops a disposed factory background child instead of pinning the pane', async () => { const first = await createHooks(TASK_TREE) const second = await createHooks(TASK_TREE) diff --git a/src/main/orca-profiles/profile-cloud-session-refresh.test.ts b/src/main/orca-profiles/profile-cloud-session-refresh.test.ts index 6aa1723d375..b934697a178 100644 --- a/src/main/orca-profiles/profile-cloud-session-refresh.test.ts +++ b/src/main/orca-profiles/profile-cloud-session-refresh.test.ts @@ -275,16 +275,4 @@ describe('refresh-token replay after an ambiguous attempt', () => { expect(invalidated).toHaveBeenCalledTimes(1) unsubscribe() }) - - it('does not mark a 401 that follows no ambiguous attempt', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - refreshMock.mockRejectedValue(new OrcaCloudRequestError(401)) - - await expect(readFreshOrcaCloudSession(config, active, '/data')).resolves.toEqual({ - status: 'reconnect-required' - }) - - expect(warn.mock.calls.flat().join(' ')).not.toContain('orca_cloud_refresh_possible_replay') - expect(clearMock).toHaveBeenCalledTimes(1) - }) }) diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-orchestration-history-rewrite.test.ts b/src/main/persistence/moving-wsl-projects/wsl-move-orchestration-history-rewrite.test.ts index f906573bff3..121f41a35df 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-orchestration-history-rewrite.test.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-orchestration-history-rewrite.test.ts @@ -1,4 +1,5 @@ -import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { existsSync, mkdtempSync, rmSync } from 'node:fs' + import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -11,10 +12,8 @@ import { wslMoveCutoverFixture } from '../__fixtures__/wsl-mover/wsl-move-cutove import { seedWslMoveCutover } from '../__fixtures__/wsl-mover/wsl-move-journal-seeding' import { listWslMoveCutovers, wslMoveJournalDirectory } from './wsl-move-cutover-journal' import { runWslMoveDesktopRewritePass } from './wsl-move-desktop-rewrite' -import { - listWslMoveDesktopRewriteStores, - resetWslMoveDesktopRewriteStoresForTests -} from './wsl-move-desktop-rewrite-stores' +import { resetWslMoveDesktopRewriteStoresForTests } from './wsl-move-desktop-rewrite-stores' + import { registerWslMoveOrchestrationHistoryStore, rewriteWslMoveOrchestrationHistory, @@ -121,12 +120,6 @@ afterEach(() => { }) describe('WSL move orchestration history rewrite', () => { - it('registers one main-side store', () => { - expect(listWslMoveDesktopRewriteStores().map((store) => [store.id, store.side])).toEqual([ - [WSL_MOVE_ORCHESTRATION_HISTORY_STORE_ID, 'main'] - ]) - }) - it("gives a moved project's settled local dispatches the host's worktree id", async () => { seedOrchestrationHistory() seedWslMoveCutover(userDataPath, committedMove()) @@ -155,21 +148,6 @@ describe('WSL move orchestration history rewrite', () => { expect(attachmentIds()).toEqual({ 'd-remote': MOVED }) }) - it('leaves timestamps and JSON receipts as written', async () => { - seedOrchestrationHistory() - const before = withDb((db) => - db.prepare(`SELECT updated_at, effects, start_options FROM worker_dispatches`).all() - ) - seedWslMoveCutover(userDataPath, committedMove()) - - await runWslMoveDesktopRewritePass({ userDataPath }) - - const after = withDb((db) => - db.prepare(`SELECT updated_at, effects, start_options FROM worker_dispatches`).all() - ) - expect(after).toEqual(before) - }) - it('changes nothing when a crash lost its ledger entry and it runs again', async () => { seedOrchestrationHistory() seedWslMoveCutover(userDataPath, committedMove()) @@ -195,17 +173,6 @@ describe('WSL move orchestration history rewrite', () => { expect(withDb((db) => rewriteWslMoveOrchestrationHistory(db, scope))).toBe(0) }) - it('touches nothing with no move journal', async () => { - seedOrchestrationHistory() - const bytes = readFileSync(databasePath) - const dispatches = dispatchIds() - - await runWslMoveDesktopRewritePass({ userDataPath }) - - expect(readFileSync(databasePath).equals(bytes)).toBe(true) - expect(dispatchIds()).toEqual(dispatches) - }) - it('touches nothing for a move that has not committed', async () => { seedOrchestrationHistory() const dispatches = dispatchIds() diff --git a/src/main/rate-limits/gemini-usage-fetcher.test.ts b/src/main/rate-limits/gemini-usage-fetcher.test.ts index ee76d26fb56..609c815dd2d 100644 --- a/src/main/rate-limits/gemini-usage-fetcher.test.ts +++ b/src/main/rate-limits/gemini-usage-fetcher.test.ts @@ -1,11 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { setMainHttpClient } from '../network/http-client' -import { - authJsonGoogle, - authJsonGoogleExpired, - makeResponse, - quotaResponse -} from './gemini-usage-fetcher.test-fixtures' +import { authJsonGoogle, makeResponse, quotaResponse } from './gemini-usage-fetcher.test-fixtures' const { readFileMock, extractCredsMock } = vi.hoisted(() => ({ readFileMock: vi.fn(), @@ -59,35 +54,6 @@ describe('fetchGeminiRateLimits', () => { throw { code: 'ENOENT' } }) } - const setupAuthJsonExpired = () => { - readFileMock.mockImplementation(async (p: string) => { - if (p.includes('auth.json')) { - return JSON.stringify(authJsonGoogleExpired) - } - throw { code: 'ENOENT' } - }) - } - - it('returns unavailable when no credentials exist', async () => { - const result = await fetchGeminiRateLimits(true) - expect(result.status).toBe('unavailable') - }) - - it('returns quota via auth.json', async () => { - setupAuthJsonValid() - fetchMock.mockImplementation((url: string) => { - if (url.includes('retrieveUserQuota')) { - return Promise.resolve(makeResponse(quotaResponse)) - } - if (url.includes('loadCodeAssist')) { - return Promise.resolve(makeResponse({ cloudaicompanionProject: 'proj-123' })) - } - return Promise.resolve(makeResponse({}, 404)) - }) - const result = await fetchGeminiRateLimits(true) - expect(result.status).toBe('ok') - expect(result.buckets).toHaveLength(2) - }) it('tags a quota request that throws as a network failure', async () => { setupAuthJsonValid() @@ -136,31 +102,6 @@ describe('fetchGeminiRateLimits', () => { expect(result.buckets![0].name).toBe('1.5 Flash') }) - it('handles empty bucket list', async () => { - setupAuthJsonValid() - fetchMock.mockImplementation((url: string) => { - if (url.includes('retrieveUserQuota')) { - return Promise.resolve(makeResponse([])) - } - if (url.includes('loadCodeAssist')) { - return Promise.resolve(makeResponse({ cloudaicompanionProject: 'proj-123' })) - } - return Promise.resolve(makeResponse({}, 404)) - }) - const result = await fetchGeminiRateLimits(true) - expect(result.status).toBe('ok') - expect(result.buckets).toEqual([]) - }) - - it('returns error when token refresh fails', async () => { - vi.useRealTimers() - setupAuthJsonExpired() - const result = await fetchGeminiRateLimits(true) - expect(result.status).toBe('error') - expect(result.error).toContain('Token refresh failed') - vi.useFakeTimers() - }) - it('handles wrapped buckets response', async () => { setupAuthJsonValid() fetchMock.mockImplementation((url: string) => { diff --git a/src/main/runtime/managed-worktree-create-telemetry.test.ts b/src/main/runtime/managed-worktree-create-telemetry.test.ts index d79a6148124..e01918e6743 100644 --- a/src/main/runtime/managed-worktree-create-telemetry.test.ts +++ b/src/main/runtime/managed-worktree-create-telemetry.test.ts @@ -139,33 +139,6 @@ describe('runtime create events', () => { _resetWorktreeCreateConcurrencyForTests() }) - it('sends one workspace_created with the runtime entry point and the timing fields', async () => { - await makeRuntime().createManagedWorktree({ - repoSelector: 'repo-1', - name: 'app', - baseBranch: 'origin/main', - telemetrySource: 'sidebar' - }) - await vi.waitFor(() => expect(events('workspace_created')).toHaveLength(1)) - - expect(events('workspace_created')[0]).toMatchObject({ - source: 'sidebar', - from_existing_branch: true, - create_entry_point: 'runtime', - execution_host: 'local', - prepared_checkout: 'hit', - prepared_checkout_reset: 'none', - prepared_checkout_origin: 'prefetch', - concurrent_creates: 0, - concurrent_preparations: 0, - repo_file_count_bucket: '1k-10k', - post_checkout_hook: 'absent' - }) - expect(typeof events('workspace_created')[0].git_worktree_add_ms).toBe('number') - expect(mocks.probe).toHaveBeenCalledWith('/repo') - expect(events('workspace_create_failed')).toHaveLength(0) - }) - it('sends one workspace_create_failed naming the phase the create died in', async () => { mocks.createLocal.mockImplementation(async ({ timing }: LocalCreateArgs) => timing.time('git_worktree_add', async () => { @@ -251,15 +224,6 @@ describe('runtime create events', () => { expect(mocks.probe).not.toHaveBeenCalled() }) - it('sends nothing for a folder workspace, as before', async () => { - await makeRuntime({ id: 'folder', path: '/notes', kind: 'folder' }).createManagedWorktree({ - repoSelector: 'folder', - name: 'notes' - }) - await new Promise((resolve) => setImmediate(resolve)) - expect(mocks.track).not.toHaveBeenCalled() - }) - it('sends nothing when the request is rejected before any create starts', async () => { await expect( makeRuntime().createManagedWorktree({ diff --git a/src/main/runtime/mobile-rpc-allowlist.test.ts b/src/main/runtime/mobile-rpc-allowlist.test.ts deleted file mode 100644 index 50ecb917bcf..00000000000 --- a/src/main/runtime/mobile-rpc-allowlist.test.ts +++ /dev/null @@ -1,244 +0,0 @@ -import { readdirSync, readFileSync, statSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import { ALL_RPC_METHODS } from './rpc/methods' -import { MOBILE_RPC_METHOD_ALLOWLIST } from './runtime-rpc/runtime-rpc-mobile-method-allowlist' - -const MOBILE_DYNAMIC_RPC_METHODS = [ - // Computed sendRequest names evade the literal source scan. - 'accounts.selectClaude', - 'accounts.selectCodex', - 'accounts.selectCodexForTarget', - 'terminal.createAgentSession', - 'terminal.ensureAgentSession', - 'github.updateIssue', - 'github.updatePRState', - 'gitlab.updateIssue', - 'gitlab.updateMR', - // GitHub wrappers pass names positionally, outside the literal sendRequest scan. - 'github.repoSlug', - 'github.prForBranch', - 'github.workItemDetails', - 'github.prChecks', - 'github.prCheckDetails', - 'github.listAssignableUsers', - 'github.markPRReadyForReview', - 'github.mergePR', - 'github.setPRAutoMerge', - 'github.requestPRReviewers', - 'github.removePRReviewers', - 'github.rerunPRChecks', - 'github.updatePRTitle', - 'github.addPRReviewCommentReply', - 'github.addIssueComment', - 'github.resolveReviewThread', - 'github.project.updateIssueCommentBySlug', - 'github.project.deleteIssueCommentBySlug', - 'hostedReview.forBranch', - 'runtime.clientCapabilities.update', - 'agentSession.send', - 'agentSession.cancel', - 'agentSession.history', - 'agentSession.hold', - 'agentSession.release' -] - -// These methods require both client and host built with ORCA_SIDEBAR_INPUTS=main. -const MOBILE_SIDEBAR_INPUTS_RPC_METHODS = [ - 'sidebarInputs.read', - 'sidebarInputs.repoIcons', - 'ui.setCollapsed' -] - -const MOBILE_STREAMING_CLEANUP_RPC_METHODS = [ - // Generated cleanup paths evade the literal source scan. - 'accounts.unsubscribe', - 'browser.screencast.unsubscribe', - 'notifications.unsubscribe', - 'runtime.clientEvents.unsubscribe', - 'session.tabs.unsubscribe', - 'session.tabs.unsubscribeAll', - 'terminal.unsubscribe' -] - -function listSourceFiles(root: string): string[] { - const entries = readdirSync(root) - const files: string[] = [] - for (const entry of entries) { - const path = join(root, entry) - const stat = statSync(path) - if (stat.isDirectory()) { - files.push(...listSourceFiles(path)) - continue - } - if (!/\.[cm]?[jt]sx?$/.test(entry) || /\.test\.[cm]?[jt]sx?$/.test(entry)) { - continue - } - files.push(path) - } - return files -} - -function mobileLiteralRpcMethods(): string[] { - const roots = [join(process.cwd(), 'mobile/app'), join(process.cwd(), 'mobile/src')] - const methods = new Set() - for (const file of roots.flatMap(listSourceFiles)) { - const source = readFileSync(file, 'utf8') - for (const match of source.matchAll(/sendRequest\(\s*['"]([^'"]+)/g)) { - methods.add(match[1]!) - } - for (const match of source.matchAll(/subscribe\(\s*['"]([^'"]+)/g)) { - methods.add(match[1]!) - } - for (const match of source.matchAll(/method:\s*['"]([^'"]+)/g)) { - const method = match[1]! - if (method.includes('.')) { - methods.add(method) - } - } - } - return [...methods].sort() -} - -function mobileRpcMethods(): string[] { - return [...new Set([...mobileLiteralRpcMethods(), ...MOBILE_DYNAMIC_RPC_METHODS])] - .filter((method) => !MOBILE_SIDEBAR_INPUTS_RPC_METHODS.includes(method)) - .sort() -} - -function mobileRpcAllowlist(): ReadonlySet { - return MOBILE_RPC_METHOD_ALLOWLIST -} - -function registeredRuntimeMethods(): Set { - return new Set(ALL_RPC_METHODS.map((method) => method.name)) -} - -describe('mobile RPC allowlist', () => { - it('grants Jira reads while keeping credentials, writes, and desktop site selection private', () => { - const allowed = mobileRpcAllowlist() - for (const method of [ - 'jira.status', - 'jira.listIssues', - 'jira.searchIssues', - 'jira.getIssue', - 'jira.issueComments' - ]) { - expect(allowed.has(method), method).toBe(true) - } - for (const method of [ - 'jira.connect', - 'jira.disconnect', - 'jira.selectSite', - 'jira.createIssue', - 'jira.updateIssue', - 'jira.addIssueComment' - ]) { - expect(allowed.has(method), method).toBe(false) - } - }) - - it('allows every RPC method used by the mobile app', () => { - const allowed = mobileRpcAllowlist() - const missing = mobileRpcMethods().filter((method) => !allowed.has(method)) - - expect(missing).toEqual([]) - }) - - it('registers every RPC method used by the mobile app', () => { - const registered = registeredRuntimeMethods() - const missing = mobileRpcMethods().filter((method) => !registered.has(method)) - - expect(missing).toEqual([]) - }) - - it('allows and registers the sidebar feed the phone reads only in a switched-on build', async () => { - expect(mobileLiteralRpcMethods()).toEqual( - expect.arrayContaining(MOBILE_SIDEBAR_INPUTS_RPC_METHODS) - ) - for (const method of MOBILE_SIDEBAR_INPUTS_RPC_METHODS) { - expect(mobileRpcAllowlist().has(method)).toBe(false) - } - vi.resetModules() - vi.doMock('../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) - try { - const { MOBILE_RPC_METHOD_ALLOWLIST: switchedOn } = - await import('./runtime-rpc/runtime-rpc-mobile-method-allowlist') - const { ALL_RPC_METHODS: switchedOnMethods } = await import('./rpc/methods') - const registered = new Set(switchedOnMethods.map((method) => method.name)) - for (const method of MOBILE_SIDEBAR_INPUTS_RPC_METHODS) { - expect(switchedOn.has(method)).toBe(true) - expect(registered.has(method)).toBe(true) - } - } finally { - vi.doUnmock('../../shared/sidebar-inputs-switch') - vi.resetModules() - } - }) - - it('allows every cleanup RPC for mobile streaming subscriptions', () => { - const allowed = mobileRpcAllowlist() - const missing = MOBILE_STREAMING_CLEANUP_RPC_METHODS.filter((method) => !allowed.has(method)) - - expect(missing).toEqual([]) - }) - - it('does not grant mobile credentials control over host updates', () => { - const allowed = mobileRpcAllowlist() - expect( - ['updater.getStatus', 'updater.check', 'updater.download', 'updater.install'].filter( - (method) => allowed.has(method) - ) - ).toEqual([]) - }) - - it('exposes only the mobile structured agent-session surface', () => { - expect( - [...mobileRpcAllowlist()].filter((method) => method.startsWith('agentSession.')) - ).toEqual([ - 'agentSession.createSupport', - 'agentSession.create', - 'agentSession.ensure', - 'agentSession.reveal', - 'agentSession.send', - 'agentSession.cancel', - 'agentSession.queuedMessageSend', - 'agentSession.queuedMessageDelete', - 'agentSession.queuedMessageMove', - 'agentSession.queuedMessageUpdate', - 'agentSession.queuedMessageEditHold', - 'agentSession.queuedMessagesResume', - 'agentSession.close', - 'agentSession.respondToApproval', - 'agentSession.respondToQuestion', - 'agentSession.setOption', - 'agentSession.handoffStatus', - 'agentSession.options', - 'agentSession.modelCatalog', - 'agentSession.conversationCommand', - 'agentSession.commands', - 'agentSession.history', - 'agentSession.currentRequests', - 'agentSession.subscribe', - 'agentSession.unsubscribe', - 'agentSession.subscribeStatus', - 'agentSession.readVisual', - 'agentSession.item', - 'agentSession.hold', - 'agentSession.release' - ]) - expect(mobileRpcAllowlist().has('agentSession.attach')).toBe(false) - }) - - it('lets a phone upload chat attachments and read stored images back', () => { - expect( - [...mobileRpcAllowlist()].filter((method) => method.startsWith('agentSessionAttachment.')) - ).toEqual([ - 'agentSessionAttachment.uploadStart', - 'agentSessionAttachment.uploadAppend', - 'agentSessionAttachment.uploadCommit', - 'agentSessionAttachment.uploadAbort', - 'agentSessionAttachment.read' - ]) - }) -}) diff --git a/src/main/runtime/orchestration/mailbox-pointer-stage.test.ts b/src/main/runtime/orchestration/mailbox-pointer-stage.test.ts index ea929606c42..23d4fe37951 100644 --- a/src/main/runtime/orchestration/mailbox-pointer-stage.test.ts +++ b/src/main/runtime/orchestration/mailbox-pointer-stage.test.ts @@ -110,26 +110,6 @@ describe('mailbox pointer staging watermark', () => { db.close() }) - it('keeps the watermark for the flight that owns the reservation', () => { - const db = new OrchestrationDb(':memory:') - const message = db.insertMessage({ - runId: 'run_legacy_local', - from: 'a', - to: 'run:run-1', - subject: 's' - }) - const state = new OrchestrationMailboxPointerState() - const args = stageArgs(db, state) - stageOrchestrationMailboxPointer({ - ...args, - deps: { ...args.deps, writePty: () => WRITE_ACCEPTED }, - messages: [{ id: message.id, type: 'status', sequence: 1 }] - } as never) - - expect(state.hasActiveWatermark('run:run-1')).toBe(true) - db.close() - }) - it('drains a delivery parked behind the watermark when the write is refused', () => { const db = new OrchestrationDb(':memory:') const message = db.insertMessage({ 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 2aa4eec1c76..e5a40219293 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 @@ -433,14 +433,3 @@ it('refuses a damaged journal as unloadable at subscribe and send, and keeps its .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-precommit-refusal.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts index 600bcaa5605..4c163f86b61 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts @@ -179,16 +179,6 @@ describe('a create refused before it commits', () => { expect(refusal?.message).toContain('could not open the session store') }) - it('answers a missing host as a definitive envelope rather than a thrown code', async () => { - setStructuredAgentSessionHost(null) - - const response = await create() - - const refusal = refusalOf(response) - expect(refusal?.code).toBe('structured_agent_session_unsupported') - expect(isDefinitiveAgentSessionCreateRefusal(refusal?.code)).toBe(true) - }) - it('still refuses a fingerprint conflict with its own code, not a pre-commit one', async () => { const response = await create( {}, diff --git a/src/main/runtime/runtime-rpc-metadata-lifecycle.test.ts b/src/main/runtime/runtime-rpc-metadata-lifecycle.test.ts index 7c5fcbe784d..6d53872ff5c 100644 --- a/src/main/runtime/runtime-rpc-metadata-lifecycle.test.ts +++ b/src/main/runtime/runtime-rpc-metadata-lifecycle.test.ts @@ -209,27 +209,6 @@ describe('OrcaRuntimeRpcServer', () => { expect(pending).toBe(false) }) - it('leaves the last published metadata in place when a runtime stops', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const runtime = new OrcaRuntimeService() - const server = new OrcaRuntimeRpcServer({ - methods: [], - runtime, - userDataPath, - pid: 1001 - }) - - await server.start() - const metadata = readRuntimeMetadata(userDataPath) - expect(metadata?.pid).toBe(1001) - - await server.stop() - expect(readRuntimeMetadata(userDataPath)).toMatchObject({ - pid: 1001, - runtimeId: runtime.getRuntimeId() - }) - }) - it('closes the socket if metadata publication fails during startup', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) const runtime = new OrcaRuntimeService() diff --git a/src/main/runtime/session-tabs/session-tabs-windowed-main-change.test.ts b/src/main/runtime/session-tabs/session-tabs-windowed-main-change.test.ts index 33b00fa1c28..a5ccf92c568 100644 --- a/src/main/runtime/session-tabs/session-tabs-windowed-main-change.test.ts +++ b/src/main/runtime/session-tabs/session-tabs-windowed-main-change.test.ts @@ -146,25 +146,6 @@ describe('session.tabs on a windowed server follow main without a window publish expect(parentTabsOf(await listed(runtime))).toEqual([SURFACE_TAB_ID, SECOND_TAB_ID]) }) - // Stale until W4's dropped-leaf hook (its close PR, ledger L255) drops the row; remove .fails then. - it.fails("a CLI close reaches the rows, which then agree with main's layout", async () => { - const { runtime, store } = threeTabSurfaceRuntime() - const seen = await windowedPhone(runtime) - expect(parentTabsOf(await listed(runtime))).toContain(SECOND_TAB_ID) - - await runtime.applyLayoutCommand({ - type: 'closeTabs', - workspace: TEST_WORKTREE_ID, - tabIds: [SECOND_TAB_ID], - force: true - }) - await vi.runAllTimersAsync() - - expect(layoutTabIds(store)).not.toContain(SECOND_TAB_ID) - expect(parentTabsOf(seen.at(-1))).toEqual(layoutTabIds(store)) - expect(parentTabsOf(await listed(runtime))).toEqual(layoutTabIds(store)) - }) - it("a later commit, or the window's older snapshot, never re-adds a row main's layout lacks", async () => { const { runtime } = threeTabSurfaceRuntime() await windowedPhone(runtime) diff --git a/src/main/runtime/windows-mobile-firewall.test.ts b/src/main/runtime/windows-mobile-firewall.test.ts index f00b8cd10a0..d5a0e24db6b 100644 --- a/src/main/runtime/windows-mobile-firewall.test.ts +++ b/src/main/runtime/windows-mobile-firewall.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { execFile } from 'node:child_process' import { - getWebSocketPort, inspectWindowsMobileFirewall, repairWindowsMobileFirewall, type WindowsMobileFirewallEnvironment @@ -25,48 +24,6 @@ function environment( } describe('windows mobile firewall', () => { - it('inspects the exact executable, port, and selected interface profile', async () => { - const runPowerShell = vi.fn().mockResolvedValue( - JSON.stringify({ - matchingRuleScopes: [{ remoteAddresses: ['192.168.0.0/24'] }], - blockingRuleDetected: false, - localAddress: '192.168.0.108', - localPrefixLength: 24, - privateFirewallEnabled: true, - networkCategory: 'Private' - }) - ) - - await expect( - inspectWindowsMobileFirewall(6768, '192.168.0.108', environment(runPowerShell)) - ).resolves.toEqual({ - supported: true, - port: 6768, - ruleAllowed: true, - blockingRuleDetected: false, - privateFirewallEnabled: true, - networkCategory: 'private', - inspectionAvailable: true - }) - - const script = runPowerShell.mock.calls[0]![0] as string - // Why: without ActiveStore, GPO-applied Block rules are invisible and the - // post-repair re-inspection could report a false success on managed hosts. - expect(script).toContain( - "Get-NetFirewallApplicationFilter -PolicyStore ActiveStore -Program 'C:\\Users\\O''Brien\\Orca\\Orca.exe'" - ) - expect(script).toContain('Get-NetFirewallProfile -PolicyStore ActiveStore -Name Private') - expect(script).toContain("LocalPort | Where-Object { [string]$_ -eq 'Any'") - expect(script).toContain("[string]$_ -eq '6768'") - expect(script).toContain("C:\\Users\\O''Brien\\Orca\\Orca.exe") - expect(script).toContain("$profile -match 'Private'") - expect(script).toContain("Get-NetIPAddress -IPAddress '192.168.0.108'") - expect(script).toContain('Get-NetFirewallAddressFilter') - expect(script).toContain("[string]$rule.Action -eq 'Block'") - expect(script).toContain('remoteAddresses = @($addressFilter.RemoteAddress') - expect(script).toContain('$localPrefixLength = [int]$ip.PrefixLength') - }) - it('doubles typographic single quotes in the executable literal', async () => { const runPowerShell = vi.fn().mockResolvedValue('not json') await inspectWindowsMobileFirewall( @@ -79,31 +36,6 @@ describe('windows mobile firewall', () => { ) }) - it('treats an overlapping inbound Block rule as overriding a matching Allow rule', async () => { - const runPowerShell = vi.fn().mockResolvedValue( - JSON.stringify({ - matchingRuleScopes: [{ remoteAddresses: ['Any'] }], - blockingRuleDetected: true, - localAddress: '192.168.0.108', - localPrefixLength: 24, - privateFirewallEnabled: true, - networkCategory: 'Private' - }) - ) - - await expect( - inspectWindowsMobileFirewall(6768, '192.168.0.108', environment(runPowerShell)) - ).resolves.toEqual({ - supported: true, - port: 6768, - ruleAllowed: false, - blockingRuleDetected: true, - privateFirewallEnabled: true, - networkCategory: 'private', - inspectionAvailable: true - }) - }) - it('does not accept a qualifying rule whose remote-address scope excludes the phone subnet', async () => { const runPowerShell = vi.fn().mockResolvedValue( JSON.stringify({ @@ -139,24 +71,6 @@ describe('windows mobile firewall', () => { expect(runPowerShell).not.toHaveBeenCalled() }) - it('returns an actionable status when inspection is unavailable', async () => { - await expect( - inspectWindowsMobileFirewall( - 6768, - undefined, - environment(vi.fn().mockRejectedValue(new Error('managed policy'))) - ) - ).resolves.toEqual({ - supported: true, - port: 6768, - ruleAllowed: false, - blockingRuleDetected: false, - privateFirewallEnabled: true, - networkCategory: 'unknown', - inspectionAvailable: false - }) - }) - it('returns an actionable status for malformed or empty PowerShell output', async () => { for (const stdout of ['', 'not json']) { await expect( @@ -173,28 +87,6 @@ describe('windows mobile firewall', () => { } }) - it('repairs only Orca mobile pairing on private networks after elevation', async () => { - const runPowerShell = vi.fn().mockResolvedValue('{"launched":true,"exitCode":0}') - await expect(repairWindowsMobileFirewall(6769, environment(runPowerShell))).resolves.toEqual({ - ok: true - }) - - const outerScript = runPowerShell.mock.calls[0]![0] as string - const encoded = outerScript.match(/'-EncodedCommand', '([^']+)'/)?.[1] - expect(encoded).toBeTruthy() - const repairScript = Buffer.from(encoded!, 'base64').toString('utf16le') - expect(repairScript).toContain("-Name 'Orca.MobilePairing'") - expect(repairScript).toContain( - "Where-Object { $_.Enabled -eq 'True' -and $_.Direction -eq 'Inbound' -and $_.Action -eq 'Block' }" - ) - expect(repairScript).toContain('$rule | Remove-NetFirewallRule') - expect(repairScript).toContain('-Profile Private') - expect(repairScript).toContain('-Protocol TCP') - expect(repairScript).toContain('-LocalPort 6769') - expect(repairScript).toContain("-Program 'C:\\Users\\O''Brien\\Orca\\Orca.exe'") - expect(repairScript).toContain('-EdgeTraversalPolicy Block') - }) - it('keeps the elevated child encoded because Start-Process re-splits its ArgumentList', async () => { // Elevated Start-Process joins/re-splits argv and collapses spaces in executable paths; only this hop needs base64. const runPowerShell = vi.fn().mockResolvedValue('{"launched":true,"exitCode":0}') @@ -247,10 +139,4 @@ describe('windows mobile firewall', () => { ) ).resolves.toEqual({ ok: false, reason: 'cancelled' }) }) - - it('extracts only explicit valid websocket ports', () => { - expect(getWebSocketPort('ws://0.0.0.0:6768')).toBe(6768) - expect(getWebSocketPort('ws://0.0.0.0')).toBeNull() - expect(getWebSocketPort('not a url')).toBeNull() - }) }) diff --git a/src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts b/src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts index f0d7782de69..2f4358bc073 100644 --- a/src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts +++ b/src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts @@ -12,7 +12,6 @@ import { import { OrcaRuntimeService } from '../../orca-runtime' import type { ResolvedWorktree } from '../../runtime-worktree-path-identity' import { TERMINAL_QUERY_METHODS } from '../../rpc/methods/terminal/terminal-query-methods' -import { FIRST_SURFACE_PLACEMENT_WAIT_MS } from './restored-terminal-placement' vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) @@ -183,59 +182,3 @@ describe('a terminal created by the CLI, across a restart, layout-owner build', expect(boundPtyIds(relaunched, SWEPT)).toEqual(['pty-cli']) }) }) - -describe('a workspace’s first surface beside a sweep’s pass, layout-owner build', () => { - async function hostReadingASweepCensus() { - const directory = mkdtempSync(join(tmpdir(), 'orca-sweep-first-surface-')) - directories.push(directory) - const store = await openTopologyStore(directory, emptyTerminalSessionProfile()) - let answerCensus = (): void => {} - const census = new Promise((resolve) => { - answerCensus = () => resolve([session('pty-other', OTHER)]) - }) - const listProcesses = vi.fn(() => census) - const runtime = new SweepRuntime(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses - }) - const sweeping = runtime.placeUnshownLiveTerminalsOf(`id:${OTHER}`) - await vi.waitFor(() => expect(listProcesses).toHaveBeenCalled()) - const firstSurfaceOf = (workspace: string) => - runtime.applyLayoutCommand({ - type: 'createTerminalTab', - workspace, - tabId: '33333333-3333-4333-8333-333333333333', - leafId: '44444444-4444-4444-8444-444444444444', - initial: 'activation' - }) - return { answerCensus, sweeping, firstSurfaceOf } - } - - it('does not wait for a sweep of another workspace, which cannot place its terminals', async () => { - const { answerCensus, sweeping, firstSurfaceOf } = await hostReadingASweepCensus() - - const startedAt = performance.now() - const reply = await firstSurfaceOf(SWEPT) - - expect(performance.now() - startedAt).toBeLessThan(FIRST_SURFACE_PLACEMENT_WAIT_MS - 100) - expect(reply.ok).toBe(true) - answerCensus() - await sweeping - }) - - it('waits, up to the cap, for a sweep of its own workspace', async () => { - const { answerCensus, sweeping, firstSurfaceOf } = await hostReadingASweepCensus() - - const startedAt = performance.now() - await firstSurfaceOf(OTHER) - - expect(performance.now() - startedAt).toBeGreaterThanOrEqual( - FIRST_SURFACE_PLACEMENT_WAIT_MS - 20 - ) - answerCensus() - await sweeping - }) -}) diff --git a/src/main/skills/skill-bundle-install-service.test.ts b/src/main/skills/skill-bundle-install-service.test.ts index f5de4faf7eb..8761205904f 100644 --- a/src/main/skills/skill-bundle-install-service.test.ts +++ b/src/main/skills/skill-bundle-install-service.test.ts @@ -33,40 +33,6 @@ afterEach(async () => { }) describe('skill bundle installation', () => { - it('cancels before extracting bundle bytes and removes staging', async () => { - const root = await temporaryDirectory() - const source = await createSkill(join(root, 'sources'), 'alpha-skill') - const bundle = await createSkillBundleArchive({ - sources: [{ sourceDirectory: source }], - archivePath: join(root, 'bundle.tar.gz'), - packageId: 'package_cancel', - versionId: 'version_cancel', - bundleName: 'team-skills' - }) - const controller = new AbortController() - controller.abort() - - await expect( - installSkillBundle({ - operationId: 'operation_cancel', - archivePath: bundle.archivePath, - packageId: bundle.manifest.packageId, - versionId: bundle.manifest.versionId, - bundleDigest: bundle.manifest.bundleDigest, - selectedSkillIds: ['alpha-skill'], - expectedArchiveSha256: bundle.archiveSha256, - scope: 'global', - homeDirectory: join(root, 'home'), - orcaStateDirectory: join(root, 'state'), - detectedProviders: [], - destinationIdentity: 'local-global', - hostIdentity: 'host_1', - signal: controller.signal - }) - ).rejects.toMatchObject({ data: SKILL_INSTALL_CANCELLED_FAILURE }) - await expect(readdir(join(root, 'home', '.agents', 'skills'))).resolves.toEqual([]) - }) - it('cancels during bundle extraction and removes its journal and partial bytes', async () => { const root = await temporaryDirectory() const source = await createSkill(join(root, 'sources'), 'alpha-skill') diff --git a/src/main/skills/skill-share-preparation-service.test.ts b/src/main/skills/skill-share-preparation-service.test.ts index 8a316d1f886..f8c8f5afcf5 100644 --- a/src/main/skills/skill-share-preparation-service.test.ts +++ b/src/main/skills/skill-share-preparation-service.test.ts @@ -55,38 +55,6 @@ afterEach(async () => { }) describe('SkillSharePreparationService', () => { - it('preserves executable modes from a managed Windows install receipt', async () => { - const { root, source } = await createSource() - await writeFile(join(source, 'run.sh'), 'echo without shebang\n') - const stateDirectory = join(root, 'state') - await writeSkillInstallReceipt(stateDirectory, { - schemaVersion: 1, - packageId: 'package_1', - versionId: 'version_1', - packageDigest: 'a'.repeat(64), - archiveSha256: 'b'.repeat(64), - scope: 'global', - destinationIdentity: 'global:windows', - canonicalPath: source, - placements: [], - installedAt: '2026-08-16T12:00:00.000Z', - hostIdentity: 'windows', - fileModes: [ - { path: 'SKILL.md', executable: false }, - { path: 'run.sh', executable: true } - ] - }) - const service = new SkillSharePreparationService( - join(root, 'preparations'), - { findOwnedPackageId: nameIsFree, publishVersion: vi.fn(), createShare: vi.fn() }, - { installStateDirectory: stateDirectory, platform: 'win32' } - ) - - const prepared = await service.prepare({ sourceDirectory: source }) - - expect(prepared.skills?.[0]?.executablePaths).toEqual(['run.sh']) - }) - it('finds Windows install receipts through a provider junction', async () => { const { root, source } = await createSource() await writeFile(join(source, 'run.sh'), 'echo without shebang\n') diff --git a/src/main/ssh/system-transport/system-ssh-sftp-path.test.ts b/src/main/ssh/system-transport/system-ssh-sftp-path.test.ts index 21442b78f5d..c0cb84358c0 100644 --- a/src/main/ssh/system-transport/system-ssh-sftp-path.test.ts +++ b/src/main/ssh/system-transport/system-ssh-sftp-path.test.ts @@ -12,10 +12,6 @@ describe('toSftpRemotePath', () => { expect(toSftpRemotePath('C:/Users/dev/f.bin')).toBe('/C:/Users/dev/f.bin') }) - it('accepts a path already in that namespace unchanged', () => { - expect(toSftpRemotePath('/C:/Users/dev/f.bin')).toBe('/C:/Users/dev/f.bin') - }) - it('converts the separators Orca stores paths with', () => { expect(toSftpRemotePath('C:\\Users\\dev\\f.bin')).toBe('/C:/Users/dev/f.bin') }) diff --git a/src/main/window/editable-context-menu.test.ts b/src/main/window/editable-context-menu.test.ts deleted file mode 100644 index b057803d774..00000000000 --- a/src/main/window/editable-context-menu.test.ts +++ /dev/null @@ -1,300 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - buildEditableContextMenuTemplate, - matchingRichMarkdownContextMenuTableTarget, - parseRichMarkdownContextMenuTableTarget -} from './editable-context-menu' -import { richMarkdownContextMenuCommandChannel } from '../../shared/rich-markdown-context-menu' - -function contextParams( - overrides: Partial = {} -): Electron.ContextMenuParams { - return { - x: 0, - y: 0, - frame: null, - linkURL: '', - linkText: '', - pageURL: '', - frameURL: '', - srcURL: '', - mediaType: 'none', - hasImageContents: false, - isEditable: true, - selectionText: '', - titleText: '', - altText: '', - suggestedFilename: '', - selectionRect: { x: 0, y: 0, width: 0, height: 0 }, - selectionStartOffset: 0, - referrerPolicy: {} as Electron.Referrer, - misspelledWord: 'refrence', - dictionarySuggestions: ['reference', 'reverence'], - frameCharset: 'utf-8', - formControlType: 'none', - spellcheckEnabled: true, - menuSourceType: 'mouse', - mediaFlags: {} as Electron.MediaFlags, - editFlags: {} as Electron.EditFlags, - ...overrides - } -} - -describe('buildEditableContextMenuTemplate', () => { - it('builds spelling suggestion actions for editable markdown text', () => { - const replaceMisspelling = vi.fn() - const addWordToSpellCheckerDictionary = vi.fn() - const send = vi.fn() - const template = buildEditableContextMenuTemplate(contextParams(), { - replaceMisspelling, - send, - session: { addWordToSpellCheckerDictionary } as unknown as Electron.Session - }) - - expect(template.slice(0, 5).map((item) => item.label ?? item.type)).toEqual([ - 'reference', - 'reverence', - 'separator', - 'Add to dictionary', - 'separator' - ]) - - template[0].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - template[3].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - - expect(replaceMisspelling).toHaveBeenCalledWith('reference') - expect(addWordToSpellCheckerDictionary).toHaveBeenCalledWith('refrence') - }) - - it('builds a menu when Chromium reports suggestions even if spellcheckEnabled is false', () => { - const template = buildEditableContextMenuTemplate(contextParams({ spellcheckEnabled: false }), { - replaceMisspelling: vi.fn(), - send: vi.fn(), - session: { addWordToSpellCheckerDictionary: vi.fn() } as unknown as Electron.Session - }) - - expect(template.map((item) => item.label ?? item.type)).toContain('reference') - }) - - it('adds useful markdown and native edit actions for rich markdown text', () => { - const send = vi.fn() - const template = buildEditableContextMenuTemplate( - contextParams({ x: 12, y: 34, misspelledWord: '', dictionarySuggestions: [] }), - { - replaceMisspelling: vi.fn(), - send, - session: { addWordToSpellCheckerDictionary: vi.fn() } as unknown as Electron.Session - }, - { tableTarget: { cellType: 'body', targetId: 'table-target-1', x: 12, y: 34 } } - ) - - expect(template.map((item) => item.label ?? item.role ?? item.type)).toEqual([ - 'Add link', - 'separator', - 'Format', - 'Paragraph', - 'Insert', - 'Table', - 'separator', - 'cut', - 'copy', - 'Paste', - 'Paste as plain text', - 'selectAll' - ]) - - template[0].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - expect(send).toHaveBeenCalledWith(richMarkdownContextMenuCommandChannel, { - command: 'add-link', - x: 12, - y: 34 - }) - - const formatMenu = template[2].submenu as Electron.MenuItemConstructorOptions[] - formatMenu[0].click?.( - {} as Electron.MenuItem, - {} as Electron.BrowserWindow, - {} as KeyboardEvent - ) - expect(send).toHaveBeenLastCalledWith(richMarkdownContextMenuCommandChannel, { - command: 'bold', - x: 12, - y: 34 - }) - - const paragraphMenu = template[3].submenu as Electron.MenuItemConstructorOptions[] - expect(paragraphMenu.map((item) => item.label ?? item.type)).toEqual([ - 'Body text', - 'Heading 1', - 'Heading 2', - 'Heading 3', - 'Heading 4', - 'Heading 5', - 'separator', - 'Bullet list', - 'Numbered list', - 'Checklist' - ]) - paragraphMenu[5].click?.( - {} as Electron.MenuItem, - {} as Electron.BrowserWindow, - {} as KeyboardEvent - ) - expect(send).toHaveBeenLastCalledWith(richMarkdownContextMenuCommandChannel, { - command: 'heading-5', - x: 12, - y: 34 - }) - - const tableMenu = template[5].submenu as Electron.MenuItemConstructorOptions[] - expect(tableMenu.map((item) => item.label ?? item.type)).toEqual([ - 'Insert row above', - 'Insert row below', - 'Delete row', - 'separator', - 'Insert column left', - 'Insert column right', - 'Delete column', - 'separator', - 'Delete table' - ]) - tableMenu[0].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - expect(send).toHaveBeenLastCalledWith(richMarkdownContextMenuCommandChannel, { - command: 'insert-row-above', - tableTargetId: 'table-target-1', - x: 12, - y: 34 - }) - - template[9].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - template[10].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - expect(send).toHaveBeenCalledWith('ui:editableContextPaste', { plainTextOnly: false }) - expect(send).toHaveBeenCalledWith('ui:editableContextPaste', { plainTextOnly: true }) - }) - - it('omits table actions when the context target is outside a table', () => { - const template = buildEditableContextMenuTemplate( - contextParams({ misspelledWord: '', dictionarySuggestions: [] }), - { - replaceMisspelling: vi.fn(), - send: vi.fn(), - session: { addWordToSpellCheckerDictionary: vi.fn() } as unknown as Electron.Session - } - ) - - expect(template.map((item) => item.label ?? item.role ?? item.type)).not.toContain('Table') - }) - - it('disables native row actions that cannot cross the Markdown header boundary', () => { - const template = buildEditableContextMenuTemplate( - contextParams({ x: 12, y: 34, misspelledWord: '', dictionarySuggestions: [] }), - { - replaceMisspelling: vi.fn(), - send: vi.fn(), - session: { addWordToSpellCheckerDictionary: vi.fn() } as unknown as Electron.Session - }, - { tableTarget: { cellType: 'header', targetId: 'header-target', x: 12, y: 34 } } - ) - const tableMenu = template[5].submenu as Electron.MenuItemConstructorOptions[] - - expect(tableMenu[0]).toMatchObject({ label: 'Insert row above', enabled: false }) - expect(tableMenu[1]).toMatchObject({ label: 'Insert row below' }) - expect(tableMenu[2]).toMatchObject({ label: 'Delete row', enabled: false }) - }) - - it('does not build a menu outside editable text', () => { - const webContents = { - replaceMisspelling: vi.fn(), - send: vi.fn(), - session: { addWordToSpellCheckerDictionary: vi.fn() } as unknown as Electron.Session - } - - expect( - buildEditableContextMenuTemplate(contextParams({ isEditable: false }), webContents) - ).toEqual([]) - }) - - it('keeps coordinated paste available for regular editable text without spelling actions', () => { - const send = vi.fn() - const template = buildEditableContextMenuTemplate( - contextParams({ - formControlType: 'input-text', - misspelledWord: '', - dictionarySuggestions: [] - }), - { - replaceMisspelling: vi.fn(), - send, - session: { addWordToSpellCheckerDictionary: vi.fn() } as unknown as Electron.Session - } - ) - - expect(template.map((item) => item.label ?? item.role ?? item.type)).toEqual([ - 'cut', - 'copy', - 'Paste', - 'Paste as plain text', - 'selectAll' - ]) - - template[2].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - template[3].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - expect(send).toHaveBeenCalledWith('ui:editableContextPaste', { plainTextOnly: false }) - expect(send).toHaveBeenCalledWith('ui:editableContextPaste', { plainTextOnly: true }) - }) - - it('keeps regular text inputs to spelling and native edit actions', () => { - const send = vi.fn() - const template = buildEditableContextMenuTemplate( - contextParams({ formControlType: 'input-text' }), - { - replaceMisspelling: vi.fn(), - send, - session: { addWordToSpellCheckerDictionary: vi.fn() } as unknown as Electron.Session - } - ) - - expect(template.map((item) => item.label ?? item.role ?? item.type)).toEqual([ - 'reference', - 'reverence', - 'separator', - 'Add to dictionary', - 'separator', - 'cut', - 'copy', - 'Paste', - 'Paste as plain text', - 'selectAll' - ]) - - template[7].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - template[8].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - expect(send).toHaveBeenCalledWith('ui:editableContextPaste', { plainTextOnly: false }) - expect(send).toHaveBeenCalledWith('ui:editableContextPaste', { plainTextOnly: true }) - }) -}) - -describe('rich markdown context-menu table targets', () => { - const target = { cellType: 'body' as const, targetId: 'table-target', x: 12, y: 34 } - - it('accepts a valid renderer-reported table target', () => { - expect(parseRichMarkdownContextMenuTableTarget(target)).toEqual(target) - expect( - matchingRichMarkdownContextMenuTableTarget(contextParams({ x: 12, y: 34 }), target) - ).toEqual(target) - }) - - it('rejects malformed, stale, and non-rich targets', () => { - expect(parseRichMarkdownContextMenuTableTarget({ ...target, x: Number.NaN })).toBeNull() - expect(parseRichMarkdownContextMenuTableTarget({ ...target, cellType: 'footer' })).toBeNull() - expect( - matchingRichMarkdownContextMenuTableTarget(contextParams({ x: 13, y: 34 }), target) - ).toBeNull() - expect( - matchingRichMarkdownContextMenuTableTarget( - contextParams({ x: 12, y: 34, formControlType: 'input-text' }), - target - ) - ).toBeNull() - }) -}) diff --git a/src/main/wsl/wsl-orcad-held-context.test.ts b/src/main/wsl/wsl-orcad-held-context.test.ts index a722d11a642..0f9df9e349d 100644 --- a/src/main/wsl/wsl-orcad-held-context.test.ts +++ b/src/main/wsl/wsl-orcad-held-context.test.ts @@ -63,7 +63,6 @@ vi.mock('../managed-server/install/orcad-remote-context', async () => { import { runProcess } from '@orca/process-host' import { holdWslDistroWithContext, - isWsl1KernelRelease, readWslHostFacts, WSL_HOST_FACTS_COMMAND } from './wsl-orcad-held-context' @@ -274,13 +273,3 @@ describe.skipIf(process.platform === 'win32')('WSL_HOST_FACTS_COMMAND under a re }) }) }) - -describe('isWsl1KernelRelease', () => { - it('tells the WSL 1 syscall layer from a WSL 2 kernel, stock or custom', () => { - expect(isWsl1KernelRelease('4.4.0-19041-Microsoft')).toBe(true) - expect(isWsl1KernelRelease('4.4.0-22621-Microsoft\n')).toBe(true) - expect(isWsl1KernelRelease('5.15.167.4-microsoft-standard-WSL2')).toBe(false) - expect(isWsl1KernelRelease('6.6.36.6-microsoft-standard-WSL2+')).toBe(false) - expect(isWsl1KernelRelease('6.10.0-custom')).toBe(false) - }) -}) diff --git a/src/main/wsl/wsl-orcad-incumbent.test.ts b/src/main/wsl/wsl-orcad-incumbent.test.ts index 7c0c9fda43c..87de5c5a236 100644 --- a/src/main/wsl/wsl-orcad-incumbent.test.ts +++ b/src/main/wsl/wsl-orcad-incumbent.test.ts @@ -138,26 +138,6 @@ describe('readWslOrcadIncumbent', () => { expect(vi.mocked(deps.census).mock.calls[2]?.[3]).toEqual({ closeAdmissionForMs: 0 }) }) - // After a reboot the woken incumbent's daemon starts empty, so the census proves zero. - it('wakes an incumbent a reboot stopped and reads it without probing again', async () => { - const { deps } = dependencies({ - wake: vi.fn(async () => ({ - outcome: 'started' as const, - readiness: READINESS - })), - census: vi.fn(async () => ({ - liveSessions: 0, - startedSinceActivation: 0, - daemonProtocolVersion: 3 - })) - }) - await expect(readWslOrcadIncumbent({ context: context(), slot }, deps)).resolves.toMatchObject({ - census: { liveSessions: 0 }, - readiness: READINESS - }) - expect(deps.probe).not.toHaveBeenCalled() - }) - it('is unverifiable, without a bridge, when the incumbent cannot be proven running', async () => { const { deps } = dependencies({ wake: vi.fn(async () => ({ outcome: 'unverifiable' as const })) @@ -181,14 +161,6 @@ describe('readWslOrcadIncumbent', () => { }) expect(close).toHaveBeenCalledTimes(1) }) - - it('touches nothing when no version is active', async () => { - const { deps } = dependencies() - await expect( - readWslOrcadIncumbent({ context: context(null), slot }, deps) - ).resolves.toMatchObject({ census: UNVERIFIABLE, readiness: null }) - expect(deps.wake).not.toHaveBeenCalled() - }) }) describe('the incumbent terminal count across restarts', () => { diff --git a/src/renderer/src/components/editor/check-run-details-fix-with-ai.test.ts b/src/renderer/src/components/editor/check-run-details-fix-with-ai.test.ts index 01c63aa6c52..f9fff1d0421 100644 --- a/src/renderer/src/components/editor/check-run-details-fix-with-ai.test.ts +++ b/src/renderer/src/components/editor/check-run-details-fix-with-ai.test.ts @@ -11,7 +11,6 @@ import type { PRInfo } from '../../../../shared/github/pull-request-types' import type { Repo } from '../../../../shared/repo-types' import type { Worktree } from '../../../../shared/worktree/types' import { - getCheckRunDetailsFixDisabledReason, isCheckRunDetailsFixCandidate, resolveCheckRunDetailsFixCheck, resolveHostedReviewForCheckRunDetailsFix, @@ -183,16 +182,6 @@ describe('check-run-details-fix-with-ai', () => { expect(runtimeCall).not.toHaveBeenCalled() }) - it('detects failing checks as fix candidates', () => { - expect(isCheckRunDetailsFixCandidate(fixtures.failingCheck)).toBe(true) - expect( - isCheckRunDetailsFixCandidate({ - ...fixtures.failingCheck, - conclusion: 'success' - }) - ).toBe(false) - }) - it('prefers loaded details conclusion over the list-level check', () => { const listFailure = fixtures.failingCheck const passingDetails: PRCheckRunDetails = { @@ -215,14 +204,6 @@ describe('check-run-details-fix-with-ai', () => { ).toBe(true) }) - it('resolves hosted review metadata from the worktree PR cache', () => { - expect(resolveHostedReviewForCheckRunDetailsFix(fixtures.worktree.id)).toMatchObject({ - number: 42, - title: 'Fix CI', - url: 'https://github.com/acme/widgets/pull/42' - }) - }) - it('does not resolve a matching suppressed GitHub PR', () => { storeState.worktreesByRepo = { 'repo-1': [ @@ -237,11 +218,6 @@ describe('check-run-details-fix-with-ai', () => { expect(resolveHostedReviewForCheckRunDetailsFix(fixtures.worktree.id)).toBeNull() }) - it('requires a hosted review before launching an AI fix', () => { - storeState.prCache = {} - expect(getCheckRunDetailsFixDisabledReason(fixtures.worktree.id)).toContain('PR or MR') - }) - it('starts a single-check AI fix prompt for the owning worktree', async () => { await startCheckRunDetailsFixWithAI({ worktreeId: fixtures.worktree.id, diff --git a/src/renderer/src/components/github-project/ProjectBoard.test.tsx b/src/renderer/src/components/github-project/ProjectBoard.test.tsx index 6dd326a7db0..86a2634addd 100644 --- a/src/renderer/src/components/github-project/ProjectBoard.test.tsx +++ b/src/renderer/src/components/github-project/ProjectBoard.test.tsx @@ -113,22 +113,6 @@ function dragData(rowId: string): { dataTransfer: Partial } { afterEach(cleanup) describe('ProjectBoard', () => { - it('renders one column per option (empty included) plus the no-value column', () => { - render( - list} - /> - ) - expect(screen.getByTestId('board-column-opt_todo')).toBeTruthy() - expect(screen.getByTestId('board-column-opt_done')).toBeTruthy() - expect(screen.getByTestId('board-column-__empty__').textContent).toContain('Loose end') - expect(screen.queryByText('list')).toBeNull() - }) - it('moves a card on drop via onEditField and skips no-op drops', () => { const onEditField = vi.fn() const boardTable = table( @@ -229,16 +213,6 @@ describe('ProjectBoard', () => { expect(screen.getByText('list')).toBeTruthy() }) - it('uses the shared empty-state copy for unfiltered and filtered boards', () => { - const empty = table([TITLE_FIELD, STATUS_FIELD], []) - const { rerender } = render(list} />) - expect(screen.getByText('This view has no items yet.')).toBeTruthy() - expect(screen.queryByText("No items match this view's filter.")).toBeNull() - empty.selectedView.filter = 'status:Done' - rerender(list} />) - expect(screen.getByText("No items match this view's filter.")).toBeTruthy() - }) - it('ignores restricted and unknown payloads and deleted-option drops', () => { const onEditField = vi.fn() render( 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 ae50bc1a42a..ef35927ccfd 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 @@ -25,15 +25,9 @@ vi.mock('@/runtime/structured-agent-session-client', async (importOriginal) => ( import type { AgentJournalCursor } from '../../../../shared/agent-session-journal-types' import type { AgentSessionHistoryPage } from '../../../../shared/agent-session-wire' -import { - AGENT_SESSION_CONVERSATION_STOP_RUNTIME_CAPABILITY, - AGENT_SESSION_PROMPT_CANCEL_RUNTIME_CAPABILITY, - AGENT_SESSION_REPEATED_STOP_RUNTIME_CAPABILITY -} from '../../../../shared/agent-session-stop-capabilities' -import { - AGENT_SESSION_QUESTION_ANSWERS_RUNTIME_CAPABILITY, - RUNTIME_CAPABILITIES -} from '../../../../shared/protocol-version' + +import { RUNTIME_CAPABILITIES } from '../../../../shared/protocol-version' + import { setLocalRuntimeCapabilitiesForTests } from '@/runtime/local-runtime-capabilities' import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' import { resetStructuredAgentSessionReadOwnersForTests } from './structured-agent-session-read-owner' @@ -142,17 +136,6 @@ describe('a structured chat on a paired server', () => { mocks.subscribe.mockResolvedValue({ unsubscribe: vi.fn() }) }) - it('advertises every capability these actions ask about', () => { - expect(RUNTIME_CAPABILITIES).toEqual( - expect.arrayContaining([ - AGENT_SESSION_CONVERSATION_STOP_RUNTIME_CAPABILITY, - AGENT_SESSION_PROMPT_CANCEL_RUNTIME_CAPABILITY, - AGENT_SESSION_QUESTION_ANSWERS_RUNTIME_CAPABILITY, - AGENT_SESSION_REPEATED_STOP_RUNTIME_CAPABILITY - ]) - ) - }) - it('reads, sends, stops, answers, and releases through the server', async () => { const unsubscribe = vi.fn() mocks.subscribe.mockResolvedValue({ unsubscribe }) @@ -223,17 +206,6 @@ describe('a structured chat on a paired server', () => { ) }) - it("reads the rail's conversation outline from the server", async () => { - olderHistoryUnloaded = true - render(PAIRED_TARGET) - - await waitFor(() => - expect(calls('agentSession.conversationOutline')).toEqual([ - { target: PAIRED_TARGET, params: { sessionId: 'session-a' } } - ]) - ) - }) - it('keeps a local session apart from a paired session with the same id', async () => { const paired = render(PAIRED_TARGET) const local = render(LOCAL_TARGET) diff --git a/src/renderer/src/components/plugins/list/PluginManager.test.tsx b/src/renderer/src/components/plugins/list/PluginManager.test.tsx index b3e0d3064f3..e1dd650bb18 100644 --- a/src/renderer/src/components/plugins/list/PluginManager.test.tsx +++ b/src/renderer/src/components/plugins/list/PluginManager.test.tsx @@ -248,25 +248,6 @@ describe('PluginManager', () => { expect(container.querySelectorAll('[data-plugin-key]').length).toBeGreaterThan(1) }) - it('labels cards by category with an icon, keeping a chip only for full access', async () => { - const worker: PluginHostListEntry = { - ...installedPlugin, - pluginKey: 'local.watcher', - name: 'Watcher', - execution: 'trusted-worker', - hasWorker: true, - types: ['worker'], - source: undefined - } - const container = await render([installedPlugin, worker]) - const nord = container.querySelector('[data-plugin-key="stablyai.orca-nord-theme"]') - const watcher = container.querySelector('[data-plugin-key="local.watcher"]') - expect(nord?.textContent).toContain('Themes') - expect(nord?.textContent).not.toContain('Content only') - expect(watcher?.textContent).toContain('Commands & panels') - expect(watcher?.textContent).toContain('Full access') - }) - it('keeps installed plugins when the catalog never loads', async () => { installApi({ listMarketplaces: vi.fn().mockRejectedValue(new Error('offline')) }) const container = await render() diff --git a/src/renderer/src/components/right-sidebar/AiVaultPanel.legacy-filter.test.tsx b/src/renderer/src/components/right-sidebar/AiVaultPanel.legacy-filter.test.tsx index 4ba56f3072e..fb1ab85ea16 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultPanel.legacy-filter.test.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultPanel.legacy-filter.test.tsx @@ -161,95 +161,3 @@ it('switches to index search with the same query once indexing is enabled', asyn expect(screen.queryByRole('button', { name: 'Enable' })).toBeNull() await waitFor(() => expect(screen.queryByText('Fix the foo pipeline')).toBeNull()) }) - -it('shows the whole history and no offer while the box is empty', async () => { - await typeQuery('') - - expect(screen.queryByRole('status')).toBeNull() - expect(screen.queryByRole('button', { name: 'Enable' })).toBeNull() - expect(screen.getByText('Fix the foo pipeline')).toBeTruthy() - expect(screen.getByText('Rename the bar widget')).toBeTruthy() - expect(searchSessions).not.toHaveBeenCalled() - expect(screen.getByText('2 sessions')).toBeTruthy() - expect(screen.getByRole('button', { name: 'Sort sessions: Last updated' })).toBeTruthy() - expect(screen.queryByText('2 results')).toBeNull() - expect(screen.queryByRole('button', { name: /^Sort results:/ })).toBeNull() -}) - -it('keeps sort off the filter menu, which is filters only', async () => { - await typeQuery('') - - await userEvent.click(screen.getByRole('button', { name: 'Session History view options' })) - - expect(await screen.findByRole('menuitem', { name: 'Select all' })).toBeTruthy() - expect(screen.queryByText('Sort')).toBeNull() - expect(screen.queryByRole('menuitemradio', { name: 'Last updated' })).toBeNull() - expect(screen.queryByRole('menuitemradio', { name: 'Created' })).toBeNull() -}) - -it('puts the hit count and the search sort on the same bar once the index answers', async () => { - mockState.settings = { aiVaultSearch: { enabled: true } } - searchSessions.mockResolvedValue({ - kind: 'results', - hits: [ - { - agent: 'claude', - sessionId: 'claude:1', - title: 'Fix the foo pipeline', - cwd: '/Users/ada/repo', - branch: null, - updatedAt: '2026-05-01T10:10:00.000Z', - messageCount: 4, - score: 1, - source: { presence: 'present', filePath: '/Users/ada/.claude/claude:1.jsonl' }, - evidence: null - } - ], - page: { cursor: null, hasMore: false }, - generation: 1, - durationMs: 1, - truncated: { candidates: false, snippets: 0, query: false, freshness: false } - }) - - await typeQuery('foo') - - await waitFor(() => expect(screen.getByText('1 result')).toBeTruthy()) - expect(screen.getByRole('button', { name: 'Sort results: Most relevant' })).toBeTruthy() - expect(screen.queryByRole('button', { name: /^Sort sessions:/ })).toBeNull() -}) - -it('hands the list one untitled group while searching, and titled groups while browsing', async () => { - mockState.settings = { aiVaultSearch: { enabled: true } } - searchSessions.mockResolvedValue({ - kind: 'results', - hits: [ - { - agent: 'claude', - sessionId: 'claude:1', - title: 'Fix the foo pipeline', - cwd: '/Users/ada/repo', - branch: null, - updatedAt: '2026-05-01T10:10:00.000Z', - messageCount: 4, - score: 1, - source: { presence: 'present', filePath: '/Users/ada/.claude/claude:1.jsonl' }, - evidence: null - } - ], - page: { cursor: null, hasMore: false }, - generation: 1, - durationMs: 1, - truncated: { candidates: false, snippets: 0, query: false, freshness: false } - }) - - await typeQuery('') - const browsing = screen.getByRole('list').getAttribute('data-group-labels') - expect(browsing).not.toContain('(untitled)') - expect(browsing).toBeTruthy() - - await userEvent.type(screen.getByLabelText('Search sessions'), 'foo') - - await waitFor(() => - expect(screen.getByRole('list').getAttribute('data-group-labels')).toBe('(untitled)') - ) -}) diff --git a/src/renderer/src/components/right-sidebar/SourceControlAgentActionDialogForm.test.tsx b/src/renderer/src/components/right-sidebar/SourceControlAgentActionDialogForm.test.tsx deleted file mode 100644 index 63c0f869f9c..00000000000 --- a/src/renderer/src/components/right-sidebar/SourceControlAgentActionDialogForm.test.tsx +++ /dev/null @@ -1,266 +0,0 @@ -import { sourceControlActionRecipeEntry } from '../../../../shared/source-control-action-selection' -import type { SourceControlActionRecipe } from '../../../../shared/source-control-ai-actions' -import React, { type ReactNode } from 'react' -import { renderToStaticMarkup } from 'react-dom/server' -import { describe, expect, it, vi } from 'vitest' -import { SourceControlAgentActionDialogForm } from './SourceControlAgentActionDialogForm' -import type { GlobalSettings } from '../../../../shared/global-settings-types' -import type { Repo } from '../../../../shared/repo-types' - -vi.mock('@/components/agent/AgentCombobox', () => ({ - default: ({ - value, - allowBlankTerminal - }: { - value: string | null - allowBlankTerminal?: boolean - }) => - React.createElement('div', { - 'data-agent-value': value ?? '', - 'data-allow-blank': String(allowBlankTerminal === true) - }) -})) - -vi.mock('@/components/ui/dialog', () => ({ - DialogFooter: ({ children }: { children?: ReactNode }) => - React.createElement('div', null, children) -})) - -vi.mock('@/components/ui/select', () => ({ - Select: ({ children }: { children?: ReactNode }) => React.createElement('div', null, children), - SelectContent: ({ children }: { children?: ReactNode }) => - React.createElement('div', null, children), - SelectItem: ({ children, value }: { children?: ReactNode; value: string }) => - React.createElement('div', { 'data-select-item': value }, children), - SelectTrigger: ({ children }: { children?: ReactNode }) => - React.createElement('button', null, children), - SelectValue: () => React.createElement('span') -})) - -vi.mock('../source-control/SourceControlActionVariableChips', () => ({ - SourceControlActionVariableChips: ({ - variablePreviews - }: { - variablePreviews?: Partial> - }) => - React.createElement('div', { - 'data-variable-previews': JSON.stringify(variablePreviews ?? {}) - }) -})) - -function renderForm( - overrides: Partial< - Omit, 'recipe'> - > & { recipe?: SourceControlActionRecipe } = {} -): string { - return renderToStaticMarkup( - React.createElement(SourceControlAgentActionDialogForm, { - actionId: 'resolveConflicts', - baseCommandInput: 'Resolve the merge conflicts reported for this pull request.', - agentScopeNote: null, - agentOptions: [], - selectedAgent: 'codex', - hasEnabledAgents: true, - detecting: false, - surfaceRows: { - model: { state: 'loading', placeholderCount: 0 }, - selection: { ready: true, cli: false }, - onPick: () => {} - }, - statusCopy: null, - agentArgs: '', - agentArgsApply: true, - commandTemplate: '{basePrompt}', - savedCommandInputTemplate: '{basePrompt}', - saveLaunchRecipe: true, - saveTargetValue: 'global', - saveTargets: [ - { value: 'none', label: "Don't save" }, - { value: 'global', label: 'All repositories' } - ], - settings: null, - repo: null, - canSaveAgentDefault: true, - deliveryPlan: { status: 'idle' }, - canStart: true, - isStarting: false, - startLabel: 'Start agent', - onAgentPick: () => {}, - onAgentArgsChange: () => {}, - onCommandTemplateChange: () => {}, - onSaveLaunchRecipeChange: () => {}, - onSaveAgentDefaultChange: () => {}, - onCancel: () => {}, - onStart: () => {}, - ...overrides, - recipe: sourceControlActionRecipeEntry( - overrides.recipe ?? { - agentId: overrides.selectedAgent ?? 'codex', - commandInputTemplate: overrides.commandTemplate ?? '{basePrompt}', - ...(overrides.agentArgs !== undefined ? { agentArgs: overrides.agentArgs } : {}) - } - ) - }) - ) -} - -function settingsWithSavedGlobalRecipe(): GlobalSettings { - return { - sourceControlAi: { - enabled: true, - agentId: 'codex', - selectedModelByAgent: {}, - selectedThinkingByModel: {}, - customAgentCommand: '', - instructionsByOperation: {}, - actions: { - resolveConflicts: { - agentId: 'codex', - commandInputTemplate: '{basePrompt}' - } - } - } - } as unknown as GlobalSettings -} - -const repoWithoutSavedRecipe = { - id: 'repo-1', - sourceControlAi: { enabled: true } -} satisfies Pick - -describe('SourceControlAgentActionDialogForm', () => { - it('passes the base prompt preview to the variable chip hover content', () => { - const markup = renderForm() - - expect(markup).toContain('Resolve the merge conflicts reported for this pull request.') - }) - - it('names the saved choice on chat and terminal launches alike', () => { - const recipe = { - agentId: 'codex' as const, - launchPreferences: { - agentId: 'codex' as const, - model: 'saved', - permissionMode: 'ask' as const - } - } - expect(renderForm({ recipe, agentArgsApply: true })).toContain( - 'Older servers use their own permission settings.' - ) - expect( - renderForm({ - recipe: { - ...recipe, - launchPreferences: { - agentId: 'claude', - permissionMode: 'ask', - modelSelection: { - base: 'inherit', - model: { agentId: 'codex', value: 'saved' } - } - } - }, - agentArgsApply: false - }) - ).toContain('Model from Settings: saved') - expect( - renderForm({ - recipe: { - agentId: 'codex', - launchPreferences: { - agentId: 'codex', - modelSelection: { - base: 'default', - options: { effort: { agentId: 'codex', value: 'high' } } - } - } - } - }) - ).toContain('Model from Settings: High') - expect( - renderForm({ - selectedAgent: 'antigravity', - recipe: { - agentId: 'antigravity', - launchPreferences: { agentId: 'antigravity', permissionMode: 'ask' } - } - }) - ).toContain('Applies to chats only') - }) - - it('offers agents only, since an action cannot start without one', () => { - expect(renderForm()).toContain('data-allow-blank="false"') - }) - - it('checks already-saved copy against the selected save target', () => { - const settings = settingsWithSavedGlobalRecipe() - const saveTargets = [ - { value: 'none', label: "Don't save" }, - { value: 'repo', label: 'This repository' }, - { value: 'global', label: 'All repositories' } - ] - - const globalMarkup = renderForm({ - settings, - recipe: { agentId: 'codex', commandInputTemplate: '{basePrompt}' }, - repo: repoWithoutSavedRecipe, - saveTargets, - saveTargetValue: 'global' - }) - const repoMarkup = renderForm({ - settings, - repo: repoWithoutSavedRecipe, - saveTargets, - saveTargetValue: 'repo' - }) - const clearedArgsMarkup = renderForm({ settings, agentArgs: '' }) - - expect(globalMarkup).toContain('Launch recipe already saved') - expect(globalMarkup).not.toContain('Save & start agent') - expect(repoMarkup).not.toContain('Launch recipe already saved') - expect(repoMarkup).toContain('Save & start agent') - expect(clearedArgsMarkup).not.toContain('Launch recipe already saved') - expect(clearedArgsMarkup).toContain('Save & start agent') - }) - - it('surfaces a diverging repo override alongside the save controls', () => { - const markup = renderForm({ - agentScopeNote: { effectiveAgentLabel: 'Codex', globalAgentLabel: 'Claude' } - }) - - expect(markup).toContain('overrides your global default (Claude)') - expect(markup).toContain('currently runs Codex') - }) - - it('omits the scope note when there is no diverging repo override', () => { - const markup = renderForm({ agentScopeNote: null }) - - expect(markup).not.toContain('overrides your global default') - }) - - it('omits the scope note when the save controls are hidden', () => { - const markup = renderForm({ - agentScopeNote: { effectiveAgentLabel: 'Codex', globalAgentLabel: 'Claude' }, - canSaveAgentDefault: false - }) - - expect(markup).not.toContain('overrides your global default') - }) -}) - -describe('CLI arguments field applicability', () => { - it('offers the field when the launch would apply the arguments', () => { - const markup = renderForm({ agentArgsApply: true }) - - expect(markup).toContain('source-control-agent-cli-args') - expect(markup).toContain('CLI arguments') - }) - - // Native chat launches ignore CLI arguments, so omit the field. - it('leaves the field out entirely when they would not apply', () => { - const markup = renderForm({ agentArgsApply: false }) - - expect(markup).not.toContain('source-control-agent-cli-args') - expect(markup).not.toContain('CLI arguments') - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control-action-recipe-match.test.ts b/src/renderer/src/components/right-sidebar/source-control-action-recipe-match.test.ts index 334642807ed..3baf909db78 100644 --- a/src/renderer/src/components/right-sidebar/source-control-action-recipe-match.test.ts +++ b/src/renderer/src/components/right-sidebar/source-control-action-recipe-match.test.ts @@ -47,37 +47,6 @@ describe('sourceControlActionRecipeMatchesTarget', () => { ).toBe(true) }) - it('returns true when the launch recipe matches the global saved recipe', () => { - expect( - sourceControlActionRecipeMatchesTarget({ - actionId: 'resolveConflicts', - target: { type: 'global' }, - recipe: { - agentId: 'codex', - commandInputTemplate: '{basePrompt}', - agentArgs: '--model sonnet' - }, - settings: settings() - }) - ).toBe(true) - }) - - it('returns false when the repo target has no saved override yet', () => { - expect( - sourceControlActionRecipeMatchesTarget({ - actionId: 'resolveConflicts', - target: { type: 'repo', repoId: 'repo-1' }, - recipe: { - agentId: 'codex', - commandInputTemplate: '{basePrompt}', - agentArgs: '--model sonnet' - }, - settings: settings(), - repo: { sourceControlAi: { enabled: true } } satisfies Pick - }) - ).toBe(false) - }) - it('returns true when the launch recipe matches the repo saved recipe', () => { expect( sourceControlActionRecipeMatchesTarget({ @@ -103,33 +72,6 @@ describe('sourceControlActionRecipeMatchesTarget', () => { ).toBe(true) }) - it('returns true when the resolve conflicts recipe matches the repo saved recipe', () => { - expect( - sourceControlActionRecipeMatchesTarget({ - actionId: 'resolveConflicts', - target: { type: 'repo', repoId: 'repo-1' }, - recipe: { - agentId: 'codex', - commandInputTemplate: '{basePrompt}', - agentArgs: '' - }, - settings: settings(), - repo: { - sourceControlAi: { - enabled: true, - actionOverrides: { - resolveConflicts: { - agentId: 'codex', - commandInputTemplate: '{basePrompt}', - agentArgs: '' - } - } - } - } satisfies Pick - }) - ).toBe(true) - }) - it('returns true when a repo recipe inherits the global command template', () => { const currentSettings = settings() currentSettings.sourceControlAi = { diff --git a/src/renderer/src/components/settings/EphemeralVmsPane.test.tsx b/src/renderer/src/components/settings/EphemeralVmsPane.test.tsx index 543db2dc88e..92e9f585a77 100644 --- a/src/renderer/src/components/settings/EphemeralVmsPane.test.tsx +++ b/src/renderer/src/components/settings/EphemeralVmsPane.test.tsx @@ -169,48 +169,6 @@ describe('EphemeralVmsPane', () => { } }) - it('shows copied feedback while mounted and releases its reset on unmount', async () => { - const container = await renderPane() - const setTimeout = vi.spyOn(window, 'setTimeout') - const clearTimeout = vi.spyOn(window, 'clearTimeout') - try { - await act(async () => { - container.querySelector('button[aria-label="Copy"]')?.click() - }) - expect(container.querySelector('button[aria-label="Copy"]')?.textContent).toBe('Copied') - const timerIndex = setTimeout.mock.calls.findIndex(([, delay]) => delay === 1500) - expect(timerIndex).toBeGreaterThanOrEqual(0) - const timer = setTimeout.mock.results[timerIndex].value - await act(async () => roots.pop()?.unmount()) - expect(clearTimeout).toHaveBeenCalledWith(timer) - } finally { - setTimeout.mockRestore() - clearTimeout.mockRestore() - } - }) - - it('refreshes the catalog when plugin content changes', async () => { - const listRecipeCatalog = window.api.ephemeralVm.listRecipeCatalog as ReturnType - const container = await renderPane() - await vi.waitFor(() => expect(container.textContent).toContain('Cloud Sandbox')) - listRecipeCatalog.mockResolvedValueOnce([ - { - repoId: 'repo-1', - repoName: 'Repo', - repoPath: '/repo', - diagnostics: [], - recipes: [{ id: 'plugin-recipe', name: 'Plugin Recipe', create: 'create' }] - } - ]) - - await act(async () => { - ;(window.api.plugins as never as { emitContentChanged: () => void }).emitContentChanged() - }) - - await vi.waitFor(() => expect(container.textContent).toContain('Plugin Recipe')) - expect(listRecipeCatalog).toHaveBeenCalledTimes(2) - }) - it('ignores an older refresh that finishes after a plugin-content refresh', async () => { const listRecipeCatalog = window.api.ephemeralVm.listRecipeCatalog as ReturnType let resolveInitial!: (catalog: unknown[]) => void diff --git a/src/renderer/src/components/settings/LinearAgentSkillPane.test.tsx b/src/renderer/src/components/settings/LinearAgentSkillPane.test.tsx deleted file mode 100644 index 984ed2fd2bf..00000000000 --- a/src/renderer/src/components/settings/LinearAgentSkillPane.test.tsx +++ /dev/null @@ -1,246 +0,0 @@ -// @vitest-environment happy-dom - -import { act, type ReactNode } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { renderToStaticMarkup } from 'react-dom/server' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { ORCA_LINEAR_SKILL_NAME } from '@/lib/agent-feature-skill-names' -import { getLinearUsageExamples } from '@/lib/linear-usage-examples' -import { LinearAgentSkillPane } from './LinearAgentSkillPane' - -const mocks = vi.hoisted(() => ({ - panelProps: [] as Record[], - runtime: 'native' as 'native' | 'wsl', - skillInstalled: true, - skillUnverifiable: false, - updateSkillName: 'orca-linear', - linearConnected: true, - visibleTaskProviders: ['github', 'linear'] as string[], - openSettingsPage: vi.fn(), - openSettingsTarget: vi.fn() -})) - -vi.mock('./AgentSkillSetupPanel', () => ({ - AgentSkillSetupPanel: (props: Record & { footer?: ReactNode }) => { - mocks.panelProps.push(props) - return ( -
- {!props.hideHeader &&

{String(props.title)}

} - {props.description != null &&

{String(props.description)}

} - {props.installed ? 'Installed' : 'Not installed'} - {String(props.skillNames)} - {String(props.installedSkillNames)} - {String(props.freshnessSkillName)} -
- ) - } -})) - -vi.mock('@/lib/linear-agent-skill-update-target', () => ({ - getLinearAgentSkillUpdateTarget: () => ({ skillName: mocks.updateSkillName }) -})) - -vi.mock('@/hooks/useInstalledAgentSkills', () => ({ - GLOBAL_AGENT_SKILL_SOURCE_KINDS: ['home'], - useInstalledAgentSkillNames: () => ({ - installed: mocks.skillInstalled, - loading: false, - settled: true, - installedUnverifiable: mocks.skillUnverifiable, - error: null, - skills: [], - sources: [], - refresh: vi.fn() - }) -})) - -vi.mock('@/hooks/useActiveProjectSkillRuntime', () => ({ - useActiveProjectSkillRuntime: () => ({ - discoveryTarget: undefined, - agentRuntime: { runtime: mocks.runtime }, - installDisabledReason: null, - canUseSkillFreshness: mocks.runtime !== 'wsl' - }) -})) - -vi.mock('@/hooks/useLinearProviderConnected', () => ({ - useLinearProviderConnected: () => mocks.linearConnected -})) - -vi.mock('@/lib/provider-runtime-context', () => ({ - getProviderRuntimeContextKey: () => 'runtime-key' -})) - -vi.mock('@/components/linear-api-key-dialog', () => ({ - LinearApiKeyDialog: () => null -})) - -vi.mock('@/store', () => ({ - useAppStore: ( - selector: (state: { - openSettingsPage: () => void - openSettingsTarget: (target: unknown) => void - settings: { visibleTaskProviders: string[] } - linearStatusChecked: boolean - linearStatusContextKey: string - checkLinearConnection: () => void - settingsSearchQuery: string - }) => unknown - ) => - selector({ - openSettingsPage: mocks.openSettingsPage, - openSettingsTarget: mocks.openSettingsTarget, - settings: { visibleTaskProviders: mocks.visibleTaskProviders }, - linearStatusChecked: true, - linearStatusContextKey: 'runtime-key', - checkLinearConnection: vi.fn(), - settingsSearchQuery: '' - }) -})) - -let root: Root | null = null -let container: HTMLDivElement | null = null - -async function renderPane(): Promise { - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - await act(async () => { - root?.render() - }) - return container -} - -describe('LinearAgentSkillPane', () => { - afterEach(async () => { - if (root) { - await act(async () => { - root?.unmount() - }) - } - root = null - container?.remove() - container = null - mocks.panelProps.length = 0 - mocks.runtime = 'native' - mocks.skillInstalled = true - mocks.skillUnverifiable = false - mocks.updateSkillName = 'orca-linear' - mocks.linearConnected = true - mocks.visibleTaskProviders = ['github', 'linear'] - mocks.openSettingsPage.mockClear() - mocks.openSettingsTarget.mockClear() - }) - - it('keeps a clickable route to the Integrations credentials pane', async () => { - const rendered = await renderPane() - const link = [...rendered.querySelectorAll('button')].find( - (button) => button.textContent === 'Integrations' - ) - - expect(link).toBeDefined() - await act(async () => { - link?.click() - }) - - expect(mocks.openSettingsPage).toHaveBeenCalled() - expect(mocks.openSettingsTarget).toHaveBeenCalledWith({ - pane: 'integrations', - repoId: null, - sectionId: 'integrations-linear' - }) - }) - - it('routes the connected checklist credential action to Integrations', async () => { - const rendered = await renderPane() - const manageKeys = [...rendered.querySelectorAll('button')].find( - (button) => button.textContent === 'Manage keys' - ) - - expect(manageKeys).toBeDefined() - await act(async () => { - manageKeys?.click() - }) - - expect(mocks.openSettingsTarget).toHaveBeenCalledWith({ - pane: 'integrations', - repoId: null, - sectionId: 'integrations-linear' - }) - }) - - it('does not pass an icon the hideHeader layout would drop', () => { - renderToStaticMarkup() - - expect(mocks.panelProps.at(-1)).not.toHaveProperty('icon') - }) - - it('renders checklist with inlined skill panel and usage examples', () => { - const markup = renderToStaticMarkup() - - expect(markup).toContain('Setup checklist') - expect(markup).toContain('2. Install the agent skill') - expect(mocks.panelProps.at(-1)).toEqual( - expect.objectContaining({ hideHeader: true, description: null }) - ) - expect(markup).not.toContain('Agent skill') - expect(markup).not.toContain('Ready below') - expect(markup).toContain('Example prompts') - expect(markup).toContain('Good to know') - expect(markup).toContain('Start from a Linear issue') - expect(markup).toContain('All set') - expect(markup.indexOf('Example prompts')).toBeLessThan(markup.indexOf('Good to know')) - const examples = getLinearUsageExamples() - expect(examples).toHaveLength(5) - for (const example of examples) { - expect(markup).toContain(example.title) - expect(example.prompt).toContain('/orca-linear') - expect(example.prompt).not.toContain('{{value0}}') - } - }) - - it('reports an unverifiable skill scan as unknown instead of an unfinished step', () => { - mocks.skillInstalled = false - mocks.skillUnverifiable = true - const markup = renderToStaticMarkup() - - expect(markup).toContain('Cannot verify') - expect(markup).not.toContain('2 of 3 ready') - }) - - it('shows incomplete checklist when the skill is missing', () => { - mocks.skillInstalled = false - const markup = renderToStaticMarkup() - - expect(markup).toContain('2 of 3 ready') - expect(mocks.panelProps.at(-1)).toEqual( - expect.objectContaining({ hideHeader: true, description: null }) - ) - }) - - it('passes the orca-linear install/update skills and freshness on a local runtime', async () => { - await renderPane() - - expect(mocks.panelProps.at(-1)).toEqual( - expect.objectContaining({ - skillNames: [ORCA_LINEAR_SKILL_NAME], - installedSkillNames: [ORCA_LINEAR_SKILL_NAME], - freshnessSkillName: ORCA_LINEAR_SKILL_NAME - }) - ) - }) - - it('drops freshness on a WSL runtime the local scan cannot vouch for', async () => { - mocks.runtime = 'wsl' - await renderPane() - - expect(mocks.panelProps.at(-1)?.freshnessSkillName).toBeUndefined() - }) - - it('checks freshness under the legacy name when that is the installed update target', async () => { - mocks.updateSkillName = 'linear-tickets' - await renderPane() - - expect(mocks.panelProps.at(-1)?.freshnessSkillName).toBe('linear-tickets') - }) -}) diff --git a/src/renderer/src/components/settings/NotificationsPane.test.tsx b/src/renderer/src/components/settings/NotificationsPane.test.tsx index 98f712a6937..c32bd3e8f13 100644 --- a/src/renderer/src/components/settings/NotificationsPane.test.tsx +++ b/src/renderer/src/components/settings/NotificationsPane.test.tsx @@ -1,15 +1,10 @@ import { createGlobalSettingsFixture } from '../../../../shared/global-settings-test-fixture' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { renderToStaticMarkup } from 'react-dom/server' + import type { GlobalSettings } from '../../../../shared/global-settings-types' import type { NotificationDispatchRequest } from '../../../../shared/notification-settings-types' -import { getNotificationSoundOptions } from '@/components/notification-sound-options' -import { - createNotificationVolumeDraftState, - NotificationsPane, - resolveNotificationVolumeDraftState, - sendNotificationSettingsTestNotification -} from './NotificationsPane' + +import { sendNotificationSettingsTestNotification } from './NotificationsPane' const { toastError, toastMessage, toastSuccess } = vi.hoisted(() => ({ toastError: vi.fn(), @@ -52,28 +47,6 @@ describe('NotificationsPane', () => { vi.unstubAllGlobals() }) - it('renders built-in notification sound choices in settings', () => { - const html = renderToStaticMarkup( - - ) - - expect(html).toContain('Notification Sound') - expect(getNotificationSoundOptions(null).map((option) => option.title)).toEqual( - expect.arrayContaining(['System Default', 'Two Tone', 'Bong', 'Ding']) - ) - }) - - it('resets the volume draft only when the persisted volume changes', () => { - const state = createNotificationVolumeDraftState(50) - state.draft = 75 - - expect(resolveNotificationVolumeDraftState(state, 50)).toBe(state) - expect(resolveNotificationVolumeDraftState(state, 25)).toEqual({ - sourceVolume: 25, - draft: 25 - }) - }) - it('uses native main-process delivery even when renderer permission is stale denied on macOS', async () => { const notifications = { getPermissionStatus: vi.fn(async () => ({ @@ -117,141 +90,4 @@ describe('NotificationsPane', () => { toastOptions?.action?.onClick?.() expect(notifications.openSystemSettings).toHaveBeenCalledTimes(1) }) - - it('confirms delivered test notifications on platforms where show means displayed', async () => { - const notifications = { - getPermissionStatus: vi.fn(async () => ({ - supported: true, - platform: 'win32' as NodeJS.Platform, - requested: true - })), - dispatch: vi.fn(async (_args: NotificationDispatchRequest) => ({ delivered: true })), - playSound: vi.fn(), - openSystemSettings: vi.fn(), - requestPermission: vi.fn() - } - vi.stubGlobal('window', { - Notification: { permission: 'granted' }, - api: { - notifications, - shell: { pickAudio: vi.fn() } - } - }) - - await sendNotificationSettingsTestNotification(createSettings().notifications, 50) - - expect(toastMessage).not.toHaveBeenCalled() - expect(toastError).not.toHaveBeenCalled() - expect(toastSuccess).toHaveBeenCalledWith('Test notification sent') - }) - - it('opens macOS notification settings when the native test notification is not shown', async () => { - const notifications = { - getPermissionStatus: vi.fn(async () => ({ - supported: true, - platform: 'darwin' as NodeJS.Platform, - requested: true - })), - dispatch: vi.fn(async (_args: NotificationDispatchRequest) => ({ - delivered: false, - reason: 'not-displayed' as const - })), - playSound: vi.fn(), - openSystemSettings: vi.fn(), - requestPermission: vi.fn() - } - vi.stubGlobal('window', { - Notification: { permission: 'granted' }, - api: { - notifications, - shell: { pickAudio: vi.fn() } - } - }) - - await sendNotificationSettingsTestNotification(createSettings().notifications, 50) - - expect(toastSuccess).not.toHaveBeenCalled() - expect(toastError).toHaveBeenCalledWith( - 'macOS did not show the notification', - expect.objectContaining({ - action: expect.objectContaining({ label: 'Open Settings' }) - }) - ) - - const toastOptions = toastError.mock.calls[0]?.[1] as - | { action?: { onClick?: () => void } } - | undefined - toastOptions?.action?.onClick?.() - expect(notifications.openSystemSettings).toHaveBeenCalledTimes(1) - }) - - it('uses Windows notification settings copy when the native test notification is not shown', async () => { - const notifications = { - getPermissionStatus: vi.fn(async () => ({ - supported: true, - platform: 'win32' as NodeJS.Platform, - requested: true - })), - dispatch: vi.fn(async (_args: NotificationDispatchRequest) => ({ - delivered: false, - reason: 'not-displayed' as const - })), - playSound: vi.fn(), - openSystemSettings: vi.fn(), - requestPermission: vi.fn() - } - vi.stubGlobal('window', { - Notification: { permission: 'granted' }, - api: { - notifications, - shell: { pickAudio: vi.fn() } - } - }) - - await sendNotificationSettingsTestNotification(createSettings().notifications, 50) - - expect(toastSuccess).not.toHaveBeenCalled() - expect(toastError).toHaveBeenCalledWith( - 'Windows did not show the notification', - expect.objectContaining({ - description: 'Enable notifications for Orca in Windows Settings.', - action: expect.objectContaining({ label: 'Open Settings' }) - }) - ) - }) - - it('does not show an inert settings action on platforms without a settings shortcut', async () => { - const notifications = { - getPermissionStatus: vi.fn(async () => ({ - supported: true, - platform: 'linux' as NodeJS.Platform, - requested: true - })), - dispatch: vi.fn(async (_args: NotificationDispatchRequest) => ({ - delivered: false, - reason: 'not-displayed' as const - })), - playSound: vi.fn(), - openSystemSettings: vi.fn(), - requestPermission: vi.fn() - } - vi.stubGlobal('window', { - Notification: { permission: 'granted' }, - api: { - notifications, - shell: { pickAudio: vi.fn() } - } - }) - - await sendNotificationSettingsTestNotification(createSettings().notifications, 50) - - expect(toastSuccess).not.toHaveBeenCalled() - expect(toastError).toHaveBeenCalledWith( - 'System did not show the notification', - expect.not.objectContaining({ - action: expect.anything() - }) - ) - expect(notifications.openSystemSettings).not.toHaveBeenCalled() - }) }) diff --git a/src/renderer/src/components/settings/OrchestrationPane.test.tsx b/src/renderer/src/components/settings/OrchestrationPane.test.tsx index a64d1c2da03..0a76c8790b2 100644 --- a/src/renderer/src/components/settings/OrchestrationPane.test.tsx +++ b/src/renderer/src/components/settings/OrchestrationPane.test.tsx @@ -6,7 +6,7 @@ import { planEntry, planOf, planOp } from '../skills/bundled-skill-plan-fixtures import { createRoot, type Root } from 'react-dom/client' import { renderToStaticMarkup } from 'react-dom/server' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getOrchestrationUsageExamples } from '@/lib/orchestration-usage-examples' + import { getDefaultSettings } from '../../../../shared/constants' import type { GlobalSettings } from '../../../../shared/global-settings-types' import { useAppStore } from '../../store' @@ -161,46 +161,6 @@ describe('OrchestrationPane', () => { delete (globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ }) - it('keeps skill setup visible after install and shows agent coverage plus examples', () => { - const markup = renderToStaticMarkup() - - expect(markup).toContain('Orchestration skill') - expect(markup).toContain('Installed') - expect(markup).toContain('Agent coverage') - expect(markup).not.toContain('Prefer your own terminal?') - expect(markup).not.toContain('Copy update command') - expect(markup).toContain('detected agents') - expect(markup).toContain('Gemini') - expect(markup).toContain('Ready') - expect(markup).toContain('How to use it') - expect(markup).not.toContain('See examples') - const examples = getOrchestrationUsageExamples() - expect(examples).toHaveLength(5) - for (const example of examples) { - expect(markup).toContain(example.title) - } - expect(markup).toMatch(/]*>[\s\S]*?Update[\s\S]*?<\/button>/) - expect(markup).toContain('Re-check') - }) - - it('renders nested worker depth as an unbounded positive whole-number input', () => { - const markup = renderToStaticMarkup() - - expect(markup).toContain('Nested worker depth') - expect(markup).toContain('type="number"') - expect(markup).toContain('aria-label="Nested worker depth"') - const container = document.createElement('div') - container.innerHTML = markup - const depth = container.querySelector('input[aria-label="Nested worker depth"]') - expect(depth?.getAttribute('min')).toBe('1') - expect(depth?.hasAttribute('max')).toBe(false) - expect(markup).not.toContain('Default:') - expect(markup.indexOf('Nested worker depth')).toBeGreaterThan( - markup.indexOf('Orchestration skill') - ) - expect(matchesSettingsSearch('nested worker', getOrchestrationPaneSearchEntries())).toBe(true) - }) - it('keeps the nested depth row visible when settings search routes to Orchestration', () => { useAppStore.setState({ settingsSearchQuery: 'Nested worker' }) @@ -255,16 +215,4 @@ describe('OrchestrationPane', () => { ) ).toBe(false) }) - - it('installs the orchestration skill, which also updates, with no manual-copy path', async () => { - mocks.skillInstalled = false - const rendered = await renderPane() - - expect(mocks.panelProps.at(-1)).toEqual( - expect.objectContaining({ skillNames: ['orchestration'] }) - ) - expect(mocks.panelProps.at(-1)?.installedSkillNames).toBeUndefined() - expect(rendered.textContent).not.toContain('Prefer your own terminal?') - expect(rendered.textContent).not.toContain('Copy install command') - }) }) diff --git a/src/renderer/src/components/settings/ProjectWindowsRuntimeSetting.test.tsx b/src/renderer/src/components/settings/ProjectWindowsRuntimeSetting.test.tsx index 6caa188c9d1..605a812169b 100644 --- a/src/renderer/src/components/settings/ProjectWindowsRuntimeSetting.test.tsx +++ b/src/renderer/src/components/settings/ProjectWindowsRuntimeSetting.test.tsx @@ -2,7 +2,7 @@ import React, { act } from 'react' import { createRoot } from 'react-dom/client' -import { renderToStaticMarkup } from 'react-dom/server' + import { describe, expect, it, vi } from 'vitest' import { getDefaultSettings } from '../../../../shared/constants' import type { Project } from '../../../../shared/project-types' @@ -48,30 +48,6 @@ function cleanupClient(container: HTMLElement, root: ReturnType { - it('describes the inherited global WSL runtime for a local Windows project', () => { - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('Project runtime') - expect(markup).toContain('No project override. General settings select Ubuntu-24.04 via WSL.') - expect(markup).toContain('Existing terminals keep their current runtime.') - expect(markup).toContain('Default (WSL)') - expect(markup).toContain('Windows') - expect(markup).toContain('WSL') - }) - it('persists runtime override changes through the project update path', () => { const updateProject = vi.fn() const { container, root } = renderClient({ @@ -120,28 +96,6 @@ describe('ProjectWindowsRuntimeSetting', () => { } }) - it('shows the selected distro for explicit WSL project overrides', () => { - const updateProject = vi.fn() - const { container, root } = renderClient({ - project: { - ...project, - localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu-24.04' } - }, - settings: getDefaultSettings('/tmp'), - isLocalWindowsProject: true, - wslAvailable: true, - wslDistros: ['Ubuntu-24.04', 'Debian'], - wslCapabilitiesLoading: false, - updateProject - }) - - try { - expect(container.textContent).toContain('Ubuntu-24.04') - } finally { - cleanupClient(container, root) - } - }) - it('requires apply before switching runtime when live project sessions exist', () => { const updateProject = vi.fn() const container = document.createElement('div') @@ -195,40 +149,4 @@ describe('ProjectWindowsRuntimeSetting', () => { container.remove() } }) - - it('shows repair copy instead of silently falling back when a selected WSL distro is missing', () => { - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('Ubuntu-24.04 is not installed in WSL.') - expect(markup).toContain('Choose an installed distro or switch this project to Windows.') - }) - - it('does not render for remote or non-Windows-owned projects', () => { - const markup = renderToStaticMarkup( - - ) - - expect(markup).toBe('') - }) }) diff --git a/src/renderer/src/components/settings/managed-server-row-parts.test.tsx b/src/renderer/src/components/settings/managed-server-row-parts.test.tsx index fb8168a687e..072878087aa 100644 --- a/src/renderer/src/components/settings/managed-server-row-parts.test.tsx +++ b/src/renderer/src/components/settings/managed-server-row-parts.test.tsx @@ -126,17 +126,6 @@ const button = (container: HTMLElement, label: string) => [...container.querySelectorAll('button')].find((entry) => entry.textContent?.trim() === label) describe('managed server row', () => { - it('reports unknown terminals, the running migration and the deferred update', async () => { - const { container } = await render() - expect(container.textContent).toContain('Builder') - expect(container.textContent).toContain('Running terminals: unknown') - expect(container.textContent).toContain('Migration: Copy staged') - expect(container.textContent).toContain('Update to 1.3.0 deferred.') - expect(container.textContent).toContain('couldn’t confirm what is running') - expect(container.textContent).not.toContain('the daemon did not answer') - expect(button(container, 'Roll back')).toBeUndefined() - }) - it('stops only after a second, explicit confirmation', async () => { const { container, stop } = await render() await act(async () => button(container, 'Stop…')?.click()) diff --git a/src/renderer/src/components/sidebar/AddRepoHostSelector.test.tsx b/src/renderer/src/components/sidebar/AddRepoHostSelector.test.tsx deleted file mode 100644 index eb214877f3b..00000000000 --- a/src/renderer/src/components/sidebar/AddRepoHostSelector.test.tsx +++ /dev/null @@ -1,272 +0,0 @@ -import { renderToStaticMarkup } from 'react-dom/server' -import { describe, expect, it, vi } from 'vitest' -import { AddRepoHostSelector } from './AddRepoHostSelector' - -vi.mock('@/components/ui/popover', () => ({ - Popover: ({ children }: { children: React.ReactNode }) =>
{children}
, - PopoverTrigger: ({ children }: { children: React.ReactNode }) => <>{children}, - PopoverContent: ({ children }: { children: React.ReactNode }) =>
{children}
-})) - -vi.mock('@/components/ui/command', () => ({ - Command: ({ children }: { children: React.ReactNode }) =>
{children}
, - CommandList: ({ children }: { children: React.ReactNode }) =>
{children}
, - CommandItem: ({ - children, - disabled, - className, - 'aria-disabled': ariaDisabled - }: { - children: React.ReactNode - disabled?: boolean - className?: string - 'aria-disabled'?: React.AriaAttributes['aria-disabled'] - }) => ( -
- {children} -
- ) -})) - -describe('AddRepoHostSelector', () => { - it('shows a remote host setup menu when Local Mac is the only host', () => { - const html = renderToStaticMarkup( - - ) - - expect(html).toContain('Add remote host') - expect(html).toContain('Add SSH host') - expect(html).toContain('Use an existing machine over SSH.') - expect(html).toContain('Add remote server') - expect(html).toContain('Pair with Orca running on another computer.') - }) - - it('shows disconnected SSH hosts with a connect action in Add Project', () => { - const html = renderToStaticMarkup( - - ) - - expect(html).toContain('Builder') - expect(html).toContain('Disconnected') - expect(html).toContain('Connect') - expect(html).toContain('aria-disabled="true"') - expect(html).not.toContain('cursor-not-allowed') - expect(html).not.toContain('opacity-55') - }) - - it('says why a failed SSH host needs attention (#29648)', () => { - const html = renderToStaticMarkup( - - ) - - expect(html).toContain('Needs attention - All configured authentication methods failed') - }) - - it('shows exact update guidance for incompatible runtime hosts', () => { - const html = renderToStaticMarkup( - - ) - - expect(html).toContain('Update needed') - expect(html).toContain('The selected Orca server is too old for this client.') - expect(html).toContain('Update Orca on the server.') - expect(html).toContain('aria-disabled="true"') - }) - - it('offers Add WSL distro only when given, and a connect action on a stopped WSL host', () => { - const hosts = [ - { - id: 'local' as const, - label: 'Local PC', - detail: 'This computer', - kind: 'local' as const, - health: 'local' as const, - presence: 'local' as const - }, - { - id: 'runtime:wsl%3Aubuntu' as const, - label: 'Ubuntu (WSL)', - detail: 'WSL distro · Distro stopped', - kind: 'runtime' as const, - health: 'disconnected' as const, - presence: 'project' as const, - wslDistro: 'Ubuntu' - } - ] - const withWsl = renderToStaticMarkup( - - ) - expect(withWsl).toContain('Add WSL distro') - expect(withWsl).toContain('Ubuntu (WSL)') - expect(withWsl).toContain('Distro stopped') - expect(withWsl).toContain('Connect') - - const withoutWsl = renderToStaticMarkup( - - ) - expect(withoutWsl).not.toContain('Add WSL distro') - }) - - it('says adding WSL distros is paused where the Add entry would be, only when told', () => { - const props = { - hosts: [ - { - id: 'local' as const, - label: 'Local Mac', - detail: 'This computer', - kind: 'local' as const, - health: 'local' as const, - presence: 'local' as const - } - ], - selectedHostId: 'local' as const, - open: true, - onOpenChange: vi.fn(), - onSelectHost: vi.fn(), - onAddSshHost: vi.fn() - } - const paused = renderToStaticMarkup( - - ) - expect(paused).toContain('Adding WSL distros is paused') - expect(paused).not.toContain('Add WSL distro<') - expect(renderToStaticMarkup()).not.toContain('paused') - }) - - it('offers Turn on instead of Connect for a WSL host whose experiment is off', () => { - const html = renderToStaticMarkup( - - ) - expect(html).toContain('Turned off in Settings → Experimental') - expect(html).not.toContain('Disconnected') - expect(html).toContain('Turn on') - expect(html).not.toContain('>Connect<') - }) -}) diff --git a/src/renderer/src/components/sidebar/AddRepoWslHostOffer.test.tsx b/src/renderer/src/components/sidebar/AddRepoWslHostOffer.test.tsx deleted file mode 100644 index 84f9ed204ad..00000000000 --- a/src/renderer/src/components/sidebar/AddRepoWslHostOffer.test.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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/Sidebar.test.tsx b/src/renderer/src/components/sidebar/Sidebar.test.tsx index 262b924dee5..99158d86344 100644 --- a/src/renderer/src/components/sidebar/Sidebar.test.tsx +++ b/src/renderer/src/components/sidebar/Sidebar.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import type { CSSProperties, ReactNode } from 'react' -import { renderToStaticMarkup } from 'react-dom/server' + import { tmpdir } from 'node:os' import { act, cleanup, render, waitFor } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -121,12 +121,6 @@ function setSidebarState(settings: GlobalSettings, statusBarVisible = true): voi } } -function renderSidebar(): string { - return renderToStaticMarkup( - - ) -} - function sidebarElement(): ReactNode { return ( @@ -164,46 +158,6 @@ describe('Sidebar', () => { } }) - it('anchors the setup script popup to the bottom toolbar', () => { - setSidebarState(getDefaultSettings(tmpdir())) - const view = render(sidebarElement()) - const prompt = view.getByTestId('setup-script-prompt-card') - const toolbar = view.getByTestId('sidebar-toolbar') - - expect(prompt.parentElement).toBe(toolbar.parentElement) - expect(prompt.parentElement?.classList.contains('relative')).toBe(true) - expect(prompt.parentElement?.classList.contains('shrink-0')).toBe(true) - }) - - it('applies left sidebar appearance variables to the workspace sidebar surface', () => { - setSidebarState({ - ...getDefaultSettings(tmpdir()), - leftSidebarAppearanceMode: 'match-terminal', - terminalColorOverrides: { - background: '#101820', - foreground: '#f0f4f8' - } - }) - - const markup = renderSidebar() - const sidebarRootTag = markup.slice(0, markup.indexOf('>')) - - expect(sidebarRootTag).toContain('--worktree-sidebar:#101820') - expect(sidebarRootTag).toContain('--worktree-sidebar-foreground:#f0f4f8') - expect(sidebarRootTag).toMatch(/[;"]color:#f0f4f8/) - expect(markup).toContain('data-testid="workspace-kanban-drawer"') - expect(markup.match(/--worktree-sidebar:#101820/g)).toHaveLength(2) - }) - - it('passes status bar visibility into the workspace board drawer', () => { - setSidebarState(getDefaultSettings(tmpdir()), false) - - const markup = renderSidebar() - - expect(markup).toContain('data-testid="workspace-kanban-drawer"') - expect(markup).toContain('data-status-bar-visible="false"') - }) - it('does not start a full worktree scan while the startup session is hydrating', () => { setSidebarState(getDefaultSettings(tmpdir())) const fetchAllWorktrees = vi.fn().mockResolvedValue(undefined) diff --git a/src/renderer/src/components/sidebar/WorktreeCard.compact-ports-hover-independence.test.tsx b/src/renderer/src/components/sidebar/WorktreeCard.compact-ports-hover-independence.test.tsx deleted file mode 100644 index 27b8c527a89..00000000000 --- a/src/renderer/src/components/sidebar/WorktreeCard.compact-ports-hover-independence.test.tsx +++ /dev/null @@ -1,283 +0,0 @@ -// @vitest-environment happy-dom - -import React, { act, type ReactNode } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { DashboardAgentRow as DashboardAgentRowData } from '@/components/dashboard/useDashboardData' -import type { GlobalSettings } from '../../../../shared/global-settings-types' -import type { Repo } from '../../../../shared/repo-types' -import type { WorktreeCardProperty } from '../../../../shared/ui-chrome-types' -import type { Worktree } from '../../../../shared/worktree/types' -import type { WorkspacePortScanResult } from '../../../../shared/workspace-ports' - -const fetchHostedReviewForBranch = vi.fn() -const fetchIssue = vi.fn() -const fetchLinearIssue = vi.fn() -const replaceWorkspacePortScans = vi.fn() -const setWorkspacePortScanRefreshing = vi.fn() -const cacheTimerMocks = vi.hoisted(() => ({ - usePromptCacheCountdownStartedAt: vi.fn() -})) - -let worktreeCardProperties: WorktreeCardProperty[] = ['status', 'ports'] -let settings: Partial | null = { compactWorktreeCards: true } - -vi.mock('@/store', () => { - const getState = () => ({ - browserTabsByWorktree: {}, - agentActivityDisplayMode: undefined, - createBrowserTab: vi.fn(), - deleteStateByWorktreeId: {}, - fetchHostedReviewForBranch, - fetchIssue, - fetchLinearIssue, - gitConflictOperationByWorktree: {}, - hostedReviewCache: {}, - issueCache: {}, - linearIssueCache: {}, - openModal: vi.fn(), - openTaskPage: vi.fn(), - projectGroups: [], - ptyIdsByTabId: {}, - recordFeatureInteraction: vi.fn(), - remoteBranchConflictByWorktreeId: {}, - setRemoteBrowserPageHandle: vi.fn(), - replaceWorkspacePortScans, - setWorkspacePortScanRefreshing, - settings, - sshConnectionStates: new Map(), - sshTargetLabels: new Map(), - tabsByWorktree: {}, - updateWorktreeMeta: vi.fn(), - workspacePortScan, - worktreeCardProperties - }) - return { - useAppStore: Object.assign((selector: (state: unknown) => unknown) => selector(getState()), { - getState - }) - } -}) - -const openChangeByRoot = new Map void>() -vi.mock('@/components/ui/hover-card', () => ({ - HoverCard: ({ - children, - open, - onOpenChange, - openDelay - }: { - children: ReactNode - open?: boolean - onOpenChange?: (open: boolean) => void - openDelay?: number - }) => ( -
{ - if (el && onOpenChange) { - openChangeByRoot.set(el, onOpenChange) - } - }} - > - {children} -
- ), - HoverCardContent: ({ children }: { children: ReactNode }) => ( -
{children}
- ), - HoverCardTrigger: ({ children }: { children: ReactNode }) => - React.isValidElement(children) ? ( - React.cloneElement(children as React.ReactElement>, { - 'data-hover-card-trigger': '' - }) - ) : ( - <>{children} - ) -})) - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: ReactNode }) => <>{children}, - TooltipContent: ({ children }: { children: ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children} -})) - -vi.mock('@/lib/sidebar-worktree-activation', () => ({ - activateWorktreeFromSidebar: vi.fn() -})) - -vi.mock('./use-worktree-activity-status', () => ({ - useWorktreeActivityStatus: () => 'active' -})) - -vi.mock('./use-worktree-sleep-state', () => ({ - useIsSleepingWorktree: () => false -})) - -vi.mock('./CacheTimer', () => ({ - default: () => null, - usePromptCacheCountdownStartedAt: cacheTimerMocks.usePromptCacheCountdownStartedAt -})) - -vi.mock('./useWorktreeAgentRows', () => ({ - useWorktreeAgentRows: vi.fn(() => [] as DashboardAgentRowData[]) -})) - -vi.mock('./WorktreeCardAgents', () => ({ - default: () =>
-})) - -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' -})) - -let workspacePortScan: { key: string; result: WorkspacePortScanResult } | null = null - -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/pr-456', - repoId: 'repo-1', - path: '/repo/worktrees/pr-456', - displayName: 'Fix stale GH PR', - branch: 'feature/local-branch', - 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 makePortScan(worktree: Worktree): { key: string; result: WorkspacePortScanResult } { - return { - key: 'repo-1', - result: { - platform: 'darwin', - scannedAt: 1, - ports: [ - { - id: '127.0.0.1:58941:1234', - bindHost: '127.0.0.1', - connectHost: '127.0.0.1', - port: 58941, - pid: 1234, - processName: 'node', - protocol: 'http', - kind: 'workspace', - owner: { - worktreeId: worktree.id, - repoId: worktree.repoId, - displayName: worktree.displayName, - path: worktree.path, - confidence: 'cwd' - } - } - ] - } - } -} - -function rootContaining(selector: string): HTMLElement { - const el = document.querySelector(selector) - if (!el) { - throw new Error(`No element matched ${selector}`) - } - const root = el.closest('[data-hovercard-root]') - if (!(root instanceof HTMLElement)) { - throw new Error(`No hover-card root ancestor for ${selector}`) - } - return root -} - -describe('WorktreeCard compact hover ownership', () => { - let container: HTMLDivElement - let root: Root - - beforeEach(() => { - vi.clearAllMocks() - openChangeByRoot.clear() - worktreeCardProperties = ['status', 'ports'] - settings = { compactWorktreeCards: true } - cacheTimerMocks.usePromptCacheCountdownStartedAt.mockReturnValue(null) - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - }) - - afterEach(() => { - act(() => { - root.unmount() - }) - container.remove() - }) - - it('uses one full identity anchor for compact title, metadata, and live ports', async () => { - const worktree = makeWorktree({ - linkedItems: [ - { - provider: 'github', - type: 'pr', - number: 57, - title: 'Review', - url: 'https://github.com/acme/orca/pull/57' - }, - { - provider: 'linear', - type: 'issue', - number: 0, - identifier: 'ENG-2', - title: 'Task', - url: 'https://linear.app/acme/issue/ENG-2/task' - } - ] - }) - workspacePortScan = makePortScan(worktree) - const { default: WorktreeCard } = await import('./WorktreeCard') - - act(() => { - root.render() - }) - - const titleRoot = rootContaining('[data-worktree-title-inline-rename]') - const portsRoot = rootContaining('[aria-label="1 live port"]') - const metadataRoot = rootContaining('[aria-label="Workspace metadata"]') - expect(titleRoot).toBe(portsRoot) - expect(titleRoot).toBe(metadataRoot) - expect(container.querySelectorAll('[data-hovercard-root]')).toHaveLength(1) - expect(container.querySelectorAll('[data-hover-card-content]')).toHaveLength(1) - expect( - container - .querySelector('[data-worktree-card-hover-trigger]') - ?.hasAttribute('data-hover-card-trigger') - ).toBe(true) - const open = openChangeByRoot.get(titleRoot) - act(() => { - open?.(true) - }) - expect(container.querySelectorAll('[data-open="true"]')).toHaveLength(1) - act(() => { - open?.(false) - open?.(true) - }) - expect(container.querySelectorAll('[data-open="true"]')).toHaveLength(1) - expect(titleRoot.textContent).toContain('Reviews · 1') - expect(titleRoot.textContent).toContain('Issues & tasks · 1') - expect(titleRoot.textContent).toContain('58941') - }) -}) diff --git a/src/renderer/src/components/sidebar/WorktreeCard.merged-pr-display.test.tsx b/src/renderer/src/components/sidebar/WorktreeCard.merged-pr-display.test.tsx deleted file mode 100644 index b5d65858ba4..00000000000 --- a/src/renderer/src/components/sidebar/WorktreeCard.merged-pr-display.test.tsx +++ /dev/null @@ -1,257 +0,0 @@ -import { renderToStaticMarkup } from 'react-dom/server' -import type { ReactNode } from 'react' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { HostedReviewInfo } from '../../../../shared/hosted-review' -import type { PRInfo } from '../../../../shared/github/pull-request-types' -import type { GlobalSettings } from '../../../../shared/global-settings-types' -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[] = ['pr'] -let hostedReviewCache: Record = {} -let prCache: Record = {} -let settings: Partial | null = null - -vi.mock('@/store', () => { - const getState = () => ({ - deleteStateByWorktreeId: {}, - fetchHostedReviewForBranch, - fetchIssue, - fetchLinearIssue, - gitConflictOperationByWorktree: {}, - hostedReviewCache, - issueCache: {}, - linearIssueCache: {}, - openModal, - prCache, - projectGroups: [], - remoteBranchConflictByWorktreeId: {}, - settings, - sshConnectionStates: new Map(), - sshTargetLabels: new Map(), - updateWorktreeMeta, - workspacePortScan: null, - 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-activity-status', () => ({ - useWorktreeActivityStatus: () => 'active' -})) - -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_NATIVE_CONTEXT_MENU_ATTR: 'data-worktree-native-context-menu', - WORKTREE_CONTEXT_MENU_SCOPE_ATTR: 'data-orca-context-menu-scope' -})) - -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/pr-456', - repoId: 'repo-1', - path: '/repo/worktrees/pr-456', - displayName: 'Fix stale GH PR', - branch: 'feature/local-branch', - 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 makePRInfo(overrides: Partial = {}): PRInfo { - return { - number: 6340, - title: 'Merged PR still checked out', - state: 'merged', - url: 'https://github.com/acme/orca/pull/6340', - checksStatus: 'success', - updatedAt: '2026-05-17T00:00:00.000Z', - mergeable: 'MERGEABLE', - headSha: 'abc123', - ...overrides - } -} - -function makeHostedReviewInfo(overrides: Partial = {}): HostedReviewInfo { - return { - provider: 'github', - number: 6340, - title: 'Merged PR still checked out', - state: 'merged', - url: 'https://github.com/acme/orca/pull/6340', - status: 'success', - updatedAt: '2026-05-17T00:00:00.000Z', - mergeable: 'MERGEABLE', - headSha: 'abc123', - ...overrides - } -} - -function renderWorktreeCardMarkup(element: ReactNode): string { - return renderToStaticMarkup(<>{element}) -} - -describe('WorktreeCard merged PR fallback display', () => { - beforeEach(() => { - vi.clearAllMocks() - settings = { compactWorktreeCards: false, experimentalNewWorktreeCardStyle: false } - worktreeCardProperties = ['pr'] - hostedReviewCache = { - 'local::repo-1::feature/local-branch': { - data: null, - fetchedAt: 200 - } - } - prCache = {} - }) - - it('shows cached merged PR when a newer hosted-review miss still matches the worktree head', async () => { - prCache = { - 'repo-1::feature/local-branch': { - data: makePRInfo(), - fetchedAt: 100 - } - } - const { default: WorktreeCard } = await import('./WorktreeCard') - - const markup = renderWorktreeCardMarkup( - - ) - - expect(markup).toContain('Linked PR #6340') - expect(markup).not.toContain('Branch') - }) - - it('suppresses cached merged PR after a newer hosted-review miss when the worktree head moved', async () => { - prCache = { - 'repo-1::feature/local-branch': { - data: makePRInfo({ - title: 'Merged PR no longer checked out', - headSha: 'old-head' - }), - fetchedAt: 100 - } - } - const { default: WorktreeCard } = await import('./WorktreeCard') - - const markup = renderWorktreeCardMarkup( - - ) - - expect(markup).not.toContain('Linked PR #6340') - expect(markup).not.toContain('Merged PR no longer checked out') - }) - - it('does not let branch provenance resurrect a merged review after the worktree head moved', async () => { - hostedReviewCache = { - 'local::repo-1::feature/local-branch': { - data: makeHostedReviewInfo({ title: 'Stale proven merged PR', headSha: 'old-head' }), - fetchedAt: 200, - linkedReviewHintKey: 'github:6340', - branchLookupGitHubPRNumber: 6340 - } - } - const { default: WorktreeCard } = await import('./WorktreeCard') - - const markup = renderWorktreeCardMarkup( - - ) - - expect(markup).not.toContain('Linked PR #6340') - expect(markup).not.toContain('Stale proven merged PR') - }) - - it('keeps proven merged review visible when the worktree head is a confirmed PR commit', async () => { - hostedReviewCache = { - 'local::repo-1::feature/local-branch': { - data: makeHostedReviewInfo({ - title: 'Confirmed proven merged PR', - headSha: 'final-head', - confirmedContainedHeadOid: 'behind-head' - }), - fetchedAt: 200, - linkedReviewHintKey: 'github:6340', - branchLookupGitHubPRNumber: 6340 - } - } - const { default: WorktreeCard } = await import('./WorktreeCard') - - const markup = renderWorktreeCardMarkup( - - ) - - expect(markup).toContain('Linked PR #6340') - }) -}) diff --git a/src/renderer/src/components/sidebar/WorktreeCardAgents.send-target.test.tsx b/src/renderer/src/components/sidebar/WorktreeCardAgents.send-target.test.tsx deleted file mode 100644 index 32403ded3f4..00000000000 --- a/src/renderer/src/components/sidebar/WorktreeCardAgents.send-target.test.tsx +++ /dev/null @@ -1,241 +0,0 @@ -import { renderToStaticMarkup } from 'react-dom/server' -import type { ReactNode } from 'react' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const READY_PANE_KEY = 'tab-1:11111111-1111-4111-8111-111111111111' -const WORKING_PANE_KEY = 'tab-1:22222222-2222-4222-8222-222222222222' - -let mockAgents: unknown[] = [] -let mockStoreState: Record = {} -const mockSendPromptToSidebarAgentTarget = vi.fn() - -function agentRow(paneKey: string, state: string, now: number): unknown { - return { - paneKey, - tab: { id: 'tab-1', title: 'Terminal' }, - state, - startedAt: now, - agentType: 'codex', - entry: { - prompt: state === 'working' ? 'Busy' : 'Ready', - state, - stateStartedAt: now, - stateHistory: [], - lastAssistantMessage: '', - orchestration: undefined - } - } -} - -function storeAgent(paneKey: string, state: string, prompt: string, now: number): unknown { - return { - state, - prompt, - updatedAt: now, - stateStartedAt: now, - agentType: 'codex', - paneKey, - stateHistory: [] - } -} - -function activeTargetMode(extra: Record = {}): Record { - return { - id: 'send-1', - worktreeId: 'wt-1', - source: 'diff-notes', - prompt: 'Review this', - label: 'Send', - launchSource: 'diff-notes', - eligiblePaneKeys: [], - disabledPaneKeys: {}, - status: 'open', - ...extra - } -} - -function targetStoreState(now: number): Record { - return { - agentStatusByPaneKey: { - [READY_PANE_KEY]: storeAgent(READY_PANE_KEY, 'done', 'Ready', now), - [WORKING_PANE_KEY]: storeAgent(WORKING_PANE_KEY, 'working', 'Busy', now) - }, - tabsByWorktree: { - 'wt-1': [{ id: 'tab-1' }] - }, - unifiedTabsByWorktree: {}, - terminalLayoutsByTabId: { - 'tab-1': { - root: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', leafId: '11111111-1111-4111-8111-111111111111' }, - second: { type: 'leaf', leafId: '22222222-2222-4222-8222-222222222222' } - }, - activeLeafId: '11111111-1111-4111-8111-111111111111', - expandedLeafId: null, - ptyIdsByLeafId: { - '11111111-1111-4111-8111-111111111111': 'pty-1', - '22222222-2222-4222-8222-222222222222': 'pty-2' - } - } - }, - ptyIdsByTabId: { - 'tab-1': ['pty-1', 'pty-2'] - }, - runtimePaneTitlesByTabId: {} - } -} - -vi.mock('@/store', () => ({ - useAppStore: (selector: (state: unknown) => unknown) => - selector({ - agentActivityDisplayMode: 'full', - acknowledgedAgentsByPaneKey: {}, - retainedAgentsByPaneKey: {}, - dropAgentStatus: vi.fn(), - dismissRetainedAgent: vi.fn(), - acknowledgeAgents: vi.fn(), - agentSendPopoverTargetMode: null, - agentStatusByPaneKey: {}, - agentStatusEpoch: 0, - tabsByWorktree: {}, - unifiedTabsByWorktree: {}, - terminalLayoutsByTabId: {}, - ptyIdsByTabId: {}, - runtimePaneTitlesByTabId: {}, - sendPromptToSidebarAgentTarget: mockSendPromptToSidebarAgentTarget, - ...mockStoreState - }) -})) - -vi.mock('./useWorktreeAgentRows', () => ({ - useWorktreeAgentRows: vi.fn(() => mockAgents) -})) - -vi.mock('@/hooks/use-now', () => ({ - useNow: vi.fn(() => 2000) -})) - -vi.mock('@/components/dashboard/DashboardAgentRow', () => ({ - default: ({ - agent, - sendTargetStatus, - sendTargetDisabledReason, - onSendTargetClick - }: { - agent: { paneKey: string } - sendTargetStatus?: 'eligible' | 'disabled' | 'sending' - sendTargetDisabledReason?: string - onSendTargetClick?: (paneKey: string) => void - }) => ( -
- ) -})) - -vi.mock('./focused-agent-row-highlight', () => ({ - useFocusedAgentPaneKey: vi.fn(() => null) -})) - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: ReactNode }) => <>{children}, - TooltipContent: ({ children }: { children: ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children} -})) - -describe('WorktreeCardAgents send targets', () => { - beforeEach(() => { - vi.clearAllMocks() - const now = Date.now() - mockAgents = [agentRow(READY_PANE_KEY, 'done', now), agentRow(WORKING_PANE_KEY, 'working', now)] - mockStoreState = { - ...targetStoreState(now), - agentSendPopoverTargetMode: activeTargetMode() - } - }) - - it('marks eligible active-worktree rows including working send targets', async () => { - const { default: WorktreeCardAgents } = await import('./WorktreeCardAgents') - - const markup = renderToStaticMarkup() - - expect(markup).toContain('data-agent-send-target="eligible"') - expect(markup).toContain(`data-pane-key="${READY_PANE_KEY}"`) - expect(markup).toContain(`data-pane-key="${WORKING_PANE_KEY}"`) - expect(markup).toContain('data-has-send-handler="true"') - }, 30_000) - - it('disables rows whose live pane title needs permission', async () => { - const now = Date.now() - mockAgents = [agentRow(WORKING_PANE_KEY, 'working', now)] - mockStoreState = { - ...targetStoreState(now), - runtimePaneTitlesByTabId: { - 'tab-1': { - 2: 'Codex - action required' - } - }, - agentSendPopoverTargetMode: activeTargetMode() - } - const { default: WorktreeCardAgents } = await import('./WorktreeCardAgents') - - const markup = renderToStaticMarkup() - - expect(markup).toContain('data-agent-send-target="disabled"') - expect(markup).toContain('data-disabled-reason="Agent needs permission"') - expect(markup).toContain(`data-pane-key="${WORKING_PANE_KEY}"`) - }) - - it('leaves other worktree rows in ordinary mode during target selection', async () => { - mockStoreState = { - agentSendPopoverTargetMode: activeTargetMode({ worktreeId: 'wt-other' }) - } - const { default: WorktreeCardAgents } = await import('./WorktreeCardAgents') - - const markup = renderToStaticMarkup() - - expect(markup).toContain(`data-pane-key="${READY_PANE_KEY}"`) - expect(markup).not.toContain('data-agent-send-target="eligible"') - expect(markup).not.toContain('data-agent-send-target="disabled"') - expect(markup).toContain('data-has-send-handler="false"') - }) - - it('marks the currently sending row', async () => { - const now = Date.now() - mockAgents = [agentRow(READY_PANE_KEY, 'done', now)] - mockStoreState = { - ...targetStoreState(now), - agentSendPopoverTargetMode: activeTargetMode({ - eligiblePaneKeys: [READY_PANE_KEY], - status: 'sending', - sendingPaneKey: READY_PANE_KEY - }) - } - const { default: WorktreeCardAgents } = await import('./WorktreeCardAgents') - - const markup = renderToStaticMarkup() - - expect(markup).toContain('data-agent-send-target="sending"') - expect(markup).toContain('data-disabled-reason="Sending..."') - expect(markup).toContain(`data-pane-key="${READY_PANE_KEY}"`) - }) - - it('marks compact active-worktree rows as send targets in the default row UI', async () => { - mockStoreState = { - ...mockStoreState, - agentActivityDisplayMode: 'compact' - } - const { default: WorktreeCardAgents } = await import('./WorktreeCardAgents') - - const markup = renderToStaticMarkup() - - expect(markup).toContain('data-agent-send-target="eligible"') - expect(markup).not.toContain('data-agent-send-target="disabled"') - expect(markup).not.toContain('title="Agent is working"') - }) -}) diff --git a/src/renderer/src/components/sidebar/WorktreeCardLinkedItemsSection.test.tsx b/src/renderer/src/components/sidebar/WorktreeCardLinkedItemsSection.test.tsx index ed185b8cba4..c52b8259662 100644 --- a/src/renderer/src/components/sidebar/WorktreeCardLinkedItemsSection.test.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCardLinkedItemsSection.test.tsx @@ -149,30 +149,6 @@ describe('workspace linked references in hover details', () => { expect(icon?.classList.contains('lucide-git-merge')).toBe(true) expect(icon?.classList.contains('dark:text-purple-400/70')).toBe(true) }) - it('shows grouped peers and only each review’s own known checks', () => { - const { container } = render() - expect(screen.getByText('Reviews · 2')).toBeTruthy() - expect(screen.getByText('Issues & tasks · 2')).toBeTruthy() - expect(screen.getAllByText('Active review')).toHaveLength(1) - expect(screen.getByText('MR !42')).toBeTruthy() - expect(screen.getByText('· GitLab · gitlab.example.com/team/orca')).toBeTruthy() - expect(screen.getByText('ENG-215')).toBeTruthy() - expect(screen.getByText('· Linear · acme')).toBeTruthy() - const checks = screen.getByLabelText('Checks: Passing') - expect(checks.previousElementSibling?.textContent).toBe('PR #57') - expect(checks.previousElementSibling?.previousElementSibling?.getAttribute('aria-label')).toBe( - 'GitHub' - ) - expect(checks.nextElementSibling?.textContent).not.toContain('GitHub') - const key = getWorkspaceAttachmentKey(attachments[0]) - expect( - Array.from(container.querySelectorAll('[data-workspace-hover-reference]')) - .find((node) => node.getAttribute('data-workspace-hover-reference') === key) - ?.querySelector('[aria-label="Checks: Passing"]') - ).toBeTruthy() - expect(screen.queryByText('Used for checks')).toBeNull() - expect(screen.getAllByLabelText('Checks: Passing')).toHaveLength(1) - }) it('offers Orca link destinations without activating the parent or dismissing hover', () => { const openUrl = vi.fn() Object.defineProperty(window, 'api', { configurable: true, value: { shell: { openUrl } } }) diff --git a/src/renderer/src/components/skills/SkillFreshnessNudge.test.tsx b/src/renderer/src/components/skills/SkillFreshnessNudge.test.tsx index 626fbf0dd06..d1a40468828 100644 --- a/src/renderer/src/components/skills/SkillFreshnessNudge.test.tsx +++ b/src/renderer/src/components/skills/SkillFreshnessNudge.test.tsx @@ -109,32 +109,6 @@ describe('SkillFreshnessNudge', () => { container = null }) - it('lingers without an auto-close timer or auto-close dismissal write', async () => { - await renderNudge() - - expect(mocks.toastInfo).toHaveBeenCalledTimes(1) - const options = mocks.toastInfo.mock.calls[0]?.[1] - expect(options.duration).toBe(Number.POSITIVE_INFINITY) - expect(options.onAutoClose).toBeUndefined() - expect(mocks.updateSettings).not.toHaveBeenCalled() - }) - - it('counts only skills the plan would update', async () => { - mocks.plan = planOf([ - sharedEntry('orca-cli', 'update'), - sharedEntry('computer-use', 'keep'), - planEntry('orchestration', [ - planOp('keep', '/home/u/.agents/skills/orchestration'), - planOp('leave', '/home/u/.claude/skills/orchestration', { reason: 'edited' }) - ]) - ]) - await renderNudge() - - expect(mocks.toastInfo).toHaveBeenCalledTimes(1) - expect(mocks.toastInfo.mock.calls[0]?.[0]).toBe('An installed Orca skill is out of date') - expect(mocks.toastInfo.mock.calls[0]?.[1].description).toContain('Update orca-cli so') - }) - it('raises no nudge when the plan only links a newly detected agent', async () => { mocks.plan = planOf([ planEntry('orca-cli', [ @@ -235,12 +209,4 @@ describe('SkillFreshnessNudge', () => { expect(mocks.toastInfo).toHaveBeenCalledTimes(1) }) - - it('waits for persisted settings before deciding whether to nudge', async () => { - mocks.settingsLoaded = false - - await renderNudge() - - expect(mocks.toastInfo).not.toHaveBeenCalled() - }) }) diff --git a/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.test.tsx b/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.test.tsx index ab3f187c5fe..6935e374507 100644 --- a/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.test.tsx +++ b/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.test.tsx @@ -149,14 +149,6 @@ describe('NativeChatResumeStatusSegment', () => { expect(screen.queryByText(/failed to resume/)).toBeNull() }) - it('names a single chat in the singular', async () => { - rpc.mockResolvedValue({ sessions: candidates.slice(0, 1) }) - await mount() - - expect(screen.getByRole('button', { name: '1 chat available to resume' })).toBeTruthy() - expect(screen.getByText('1 chat to resume')).toBeTruthy() - }) - // The count can lag the host — another window may have dismissed the offer. The re-read decides. it('does not reopen the dialog when the host no longer offers anything', async () => { rpc.mockResolvedValueOnce({ sessions: candidates }).mockResolvedValue({ sessions: [] }) @@ -244,14 +236,6 @@ describe('NativeChatResumeStatusSegment', () => { expect(screen.queryByRole('button')).toBeNull() }) - it('renders a compact count in icon-only mode', async () => { - rpc.mockResolvedValue({ sessions: candidates }) - await mount(true) - - expect(screen.getByRole('button').textContent).toContain('2') - expect(screen.queryByText('2 chats to resume')).toBeNull() - }) - it('keeps run-only uncertainty reachable until its viewed summary is closed', async () => { rpc.mockResolvedValue({ sessions: [candidates[0]], failed: [] }) await mount() diff --git a/src/renderer/src/components/status-bar/UsagePercentageDisplayChangeNotice.test.tsx b/src/renderer/src/components/status-bar/UsagePercentageDisplayChangeNotice.test.tsx index 22ae3f98bcb..4be8fdd6f3c 100644 --- a/src/renderer/src/components/status-bar/UsagePercentageDisplayChangeNotice.test.tsx +++ b/src/renderer/src/components/status-bar/UsagePercentageDisplayChangeNotice.test.tsx @@ -4,7 +4,6 @@ import { act, Profiler } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { UsagePercentageDisplayChangeNotice } from './UsagePercentageDisplayChangeNotice' -import { USAGE_PERCENTAGE_DISPLAY_SETTING_ID } from '../settings/appearance-usage-percentage-search' type ResizeObserverStub = { cb: ResizeObserverCallback; targets: Element[] } const resizeObservers: ResizeObserverStub[] = [] @@ -97,145 +96,6 @@ describe('UsagePercentageDisplayChangeNotice', () => { vi.restoreAllMocks() }) - it('portals the callout above the usage-meter anchor after a short delay', () => { - act(() => { - root.render( - - usage-meters - - ) - }) - - expect(document.querySelector('.status-bar-change-notice-card')).toBeNull() - act(() => { - vi.advanceTimersByTime(1_800) - }) - const card = document.querySelector('.status-bar-change-notice-card') as HTMLElement | null - expect(card).not.toBeNull() - expect(card?.parentElement).toBe(document.body) - expect(card?.style.left).toBe('24px') - expect(card?.style.bottom).toBeTruthy() - expect(document.body.textContent).toContain('Usage now shows % used') - expect(container.textContent).toContain('usage-meters') - }) - - it('does not open when no usage meters are visible', () => { - act(() => { - root.render( - - usage-meters - - ) - }) - act(() => { - vi.advanceTimersByTime(2_000) - }) - expect(document.querySelector('.status-bar-change-notice-card')).toBeNull() - }) - - it('does not open when the notice was already dismissed', () => { - storeState.usagePercentageDisplayChangeNoticeDismissed = true - act(() => { - root.render( - - usage-meters - - ) - }) - act(() => { - vi.advanceTimersByTime(2_000) - }) - expect(document.querySelector('.status-bar-change-notice-card')).toBeNull() - }) - - it('does not open while another modal is open', () => { - storeState.activeModal = 'feature-tips' - act(() => { - root.render( - - usage-meters - - ) - }) - act(() => { - vi.advanceTimersByTime(2_000) - }) - expect(document.querySelector('.status-bar-change-notice-card')).toBeNull() - }) - - it('deep-links to the Usage percentages setting without a search filter', () => { - const callOrder: string[] = [] - storeState.openSettingsPage = vi.fn(() => { - callOrder.push('openSettingsPage') - }) - storeState.openSettingsTarget = vi.fn(() => { - callOrder.push('openSettingsTarget') - }) - storeState.dismissUsagePercentageDisplayChangeNotice = vi.fn() - - act(() => { - root.render( - - usage-meters - - ) - }) - act(() => { - vi.advanceTimersByTime(1_800) - }) - - const openSettingsButton = Array.from( - document.querySelectorAll('.status-bar-change-notice-card button') - ).find((button) => button.textContent === 'Open Settings') - expect(openSettingsButton).toBeTruthy() - act(() => { - openSettingsButton?.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - - expect(callOrder).toEqual(['openSettingsPage', 'openSettingsTarget']) - expect(storeState.openSettingsTarget).toHaveBeenCalledWith({ - pane: 'appearance', - repoId: null, - sectionId: USAGE_PERCENTAGE_DISPLAY_SETTING_ID - }) - expect(storeState.dismissUsagePercentageDisplayChangeNotice).toHaveBeenCalled() - }) - - it('dismisses from the X button', () => { - openNotice() - - const dismissButton = document.querySelector( - '.status-bar-change-notice-card button[aria-label="Dismiss"]' - ) - expect(dismissButton).toBeTruthy() - act(() => { - dismissButton?.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - expect(storeState.dismissUsagePercentageDisplayChangeNotice).toHaveBeenCalledTimes(1) - }) - - it('dismisses from Got it', () => { - openNotice() - - const gotItButton = Array.from( - document.querySelectorAll('.status-bar-change-notice-card button') - ).find((button) => button.textContent === 'Got it') - expect(gotItButton).toBeTruthy() - act(() => { - gotItButton?.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - expect(storeState.dismissUsagePercentageDisplayChangeNotice).toHaveBeenCalledTimes(1) - }) - - it('dismisses on Escape', () => { - openNotice() - - act(() => { - window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })) - }) - expect(storeState.dismissUsagePercentageDisplayChangeNotice).toHaveBeenCalledTimes(1) - }) - it('does not re-render on ResizeObserver deliveries with unchanged geometry', () => { let commits = 0 act(() => { @@ -266,18 +126,4 @@ describe('UsagePercentageDisplayChangeNotice', () => { // Equal-geometry deliveries must reuse state instead of adding a render per observer callback. expect(commits - commitsAfterOpen).toBeLessThanOrEqual(1) }) - - function openNotice(): void { - act(() => { - root.render( - - usage-meters - - ) - }) - act(() => { - vi.advanceTimersByTime(1_800) - }) - expect(document.querySelector('.status-bar-change-notice-card')).not.toBeNull() - } }) diff --git a/src/renderer/src/components/status-bar/claude-status-sign-in.test.tsx b/src/renderer/src/components/status-bar/claude-status-sign-in.test.tsx index a7ac003d48c..536b5241662 100644 --- a/src/renderer/src/components/status-bar/claude-status-sign-in.test.tsx +++ b/src/renderer/src/components/status-bar/claude-status-sign-in.test.tsx @@ -164,20 +164,6 @@ describe('status bar Claude account that needs a sign-in', () => { expect(toastError).not.toHaveBeenCalled() }) - it('does not repeat its sign-in note with a usage sign-in line', async () => { - const unavailable = (accountId: string): unknown => ({ - accountId, - isFetching: false, - rateLimits: { ...claudeProvider, status: 'error', error: 'Not signed in' } - }) - inactiveClaudeAccounts = [unavailable('old'), unavailable('new')] - await openAccounts() - expect(screen.getByText('Sign in again to use this account')).toBeTruthy() - expect(screen.getAllByText('Sign in to see usage')).toHaveLength(1) - const newRow = screen.getAllByText('new@example.com').at(-1)!.closest('[role="menuitem"]') - expect(newRow?.textContent).toContain('Sign in to see usage') - }) - it('does not ask an idle account whose usage token expired overnight to sign in', async () => { inactiveClaudeAccounts = [ { @@ -201,13 +187,6 @@ describe('status bar Claude account that needs a sign-in', () => { expect(newRow?.textContent).toContain('Updates when Claude runs') }) - it('says why a failed sign-in failed', async () => { - reauthenticate.mockRejectedValueOnce(new Error('Claude login exited with code 1.')) - await openAccounts() - fireEvent.click(screen.getByRole('button', { name: /Sign in/ })) - await waitFor(() => expect(toastError).toHaveBeenCalledTimes(1)) - }) - it('keeps the account list in the usage roster when the selected account needs a sign-in', async () => { const { ClaudeSwitcherMenu } = await import('./ClaudeSwitcherMenu') const { UsageRosterPanel } = await import('./UsageRosterPanel') diff --git a/src/renderer/src/components/terminal-pane/terminal-link-worktree-root-activation.test.ts b/src/renderer/src/components/terminal-pane/terminal-link-worktree-root-activation.test.ts index cae99de8cbd..8e567394ea0 100644 --- a/src/renderer/src/components/terminal-pane/terminal-link-worktree-root-activation.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-link-worktree-root-activation.test.ts @@ -45,21 +45,6 @@ installTerminalLinkTestEnvironment(doubles) const SOURCE_WORKTREE = { id: 'wt-1', path: '/tmp' } describe('handleOscLink', () => { - it('switches to an exact known worktree root without local auth or stat', async () => { - setPlatform('Macintosh') - storeState.worktreesByRepo = { - repo: [SOURCE_WORKTREE, { id: 'wt-2', path: '/tmp/other-worktree' }] - } - - openDetectedFilePath('/tmp/other-worktree', null, null, deps) - await flushAsyncWork() - - expect(activateAndRevealWorktree).toHaveBeenCalledWith('wt-2', { executionHostId: 'local' }) - expect(statMock).not.toHaveBeenCalled() - expect(openFilePathMock).not.toHaveBeenCalled() - expect(openFileMock).not.toHaveBeenCalled() - }) - it('coalesces duplicate known-root activation from provider and mouseup fallback', async () => { setPlatform('Macintosh') storeState.worktreesByRepo = { @@ -150,24 +135,6 @@ describe('handleOscLink', () => { }) describe('createFilePathLinkProvider range bounds', () => { - it('shows switch and external-open hint for known worktree root hover', async () => { - setPlatform('Macintosh') - storeState.worktreesByRepo = { - repo: [{ id: 'wt-1', path: '/repo' }] - } - const { provider, linkTooltip } = createProviderSetup([makeBufferLine('/repo')]) - - const links = await new Promise((resolve) => { - provider.provideLinks(1, (provided) => resolve(provided ?? [])) - }) - expect(links[0]).toBeDefined() - links[0]!.hover?.({} as MouseEvent, links[0]!.text) - - expect(linkTooltip.textContent).toBe( - '/repo (Click for actions, ⌘+click to switch workspace, or ⇧⌘+click to open in Finder)' - ) - }) - it('shows a known worktree root link even when the exists cache says missing', async () => { setPlatform('Macintosh') storeState.worktreesByRepo = { @@ -208,25 +175,6 @@ describe('createFilePathLinkProvider range bounds', () => { ) }) - it('does not advertise external open for SSH worktree root hover', async () => { - setPlatform('Windows') - vi.mocked(getConnectionId).mockReturnValue('ssh-1') - storeState.worktreesByRepo = { - repo: [{ id: 'wt-1', repoId: 'repo', path: '/repo', hostId: 'ssh:ssh-1' }] - } - const { provider, linkTooltip } = createProviderSetup([makeBufferLine('/repo')]) - - const links = await new Promise((resolve) => { - provider.provideLinks(1, (provided) => resolve(provided ?? [])) - }) - expect(links[0]).toBeDefined() - links[0]!.hover?.({} as MouseEvent, links[0]!.text) - - expect(linkTooltip.textContent).toBe( - '/repo (Click for actions or Ctrl+click to switch workspace)' - ) - }) - it('switches to a known worktree root from direct fallback even when cache says missing', async () => { setPlatform('Macintosh') storeState.worktreesByRepo = { diff --git a/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-removal.agent-stop.test.tsx b/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-removal.agent-stop.test.tsx index 5be1d79a8d8..43f56c45bfe 100644 --- a/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-removal.agent-stop.test.tsx +++ b/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-removal.agent-stop.test.tsx @@ -179,16 +179,6 @@ describe('workspace cleanup removal of workspaces with a running agent', () => { expect(calls).toEqual([]) }) - it('adds no step when no agent is running', async () => { - const calls = installRemoval() - const { result } = renderAtConfirm([candidateFor('a')]) - - act(() => result.current.confirmRemove()) - - expect(result.current.agentStopRequest).toBeNull() - await waitFor(() => expect(calls).toHaveLength(1)) - }) - it('asks before "Delete anyway" stops a running agent', async () => { const calls = installRemoval() startAgent('b') diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.test.tsx b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.test.tsx deleted file mode 100644 index 379a9d60d10..00000000000 --- a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.test.tsx +++ /dev/null @@ -1,260 +0,0 @@ -// @vitest-environment happy-dom -import { act, type ReactNode } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { makeFacetCandidate } from './workspace-cleanup-facet.test.fixture' -import { WorkspaceCleanupConfirmRemove } from './workspace-cleanup-confirm-remove' -import { - getWorkspaceCleanupCandidateAccessibleName, - getWorkspaceCleanupCandidateHostLabel -} from './workspace-cleanup-host-label' - -const listProbe = vi.hoisted(() => vi.fn()) - -vi.mock('./workspace-cleanup-candidate-list', () => ({ - WorkspaceCleanupCandidateList: ({ - rows, - renderRow - }: { - rows: readonly Row[] - renderRow: (row: Row, index: number) => ReactNode - }) => { - listProbe(rows.length) - return <>{rows.slice(0, 5).map(renderRow)} - } -})) - -vi.mock('@/components/ui/dialog', () => ({ - DialogDescription: ({ children }: { children: ReactNode }) =>
{children}
, - DialogFooter: ({ children }: { children: ReactNode }) =>
{children}
, - DialogHeader: ({ children }: { children: ReactNode }) =>
{children}
, - DialogTitle: ({ children }: { children: ReactNode }) =>
{children}
-})) - -vi.mock('@/components/ui/scroll-area', () => ({ - ScrollArea: ({ children }: { children: ReactNode }) =>
{children}
-})) - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: ReactNode }) => <>{children}, - TooltipContent: ({ children }: { children: ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children} -})) - -let container: HTMLDivElement -let root: Root - -describe('WorkspaceCleanupConfirmRemove', () => { - beforeEach(() => { - listProbe.mockClear() - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - }) - - afterEach(() => { - act(() => root.unmount()) - document.body.replaceChildren() - }) - - it('routes fleet-sized confirmations through the bounded row list', () => { - const candidates = Array.from({ length: 2_727 }, (_, index) => - makeFacetCandidate({ - worktreeId: `repo-1::/repo/worktree-${index}`, - displayName: `Workspace ${index}`, - path: `/repo/worktree-${index}` - }) - ) - - act(() => { - root.render( - - ) - }) - - expect(listProbe).toHaveBeenCalledWith(candidates.length) - expect(container.querySelectorAll('span.truncate.text-sm.font-medium')).toHaveLength(5) - }) - - it('names each local context type separately instead of totalling them', () => { - const candidate = makeFacetCandidate({ - worktreeId: 'repo-1::/repo/with-context', - displayName: 'Has context', - localContext: { - terminalTabCount: 1, - cleanEditorTabCount: 2, - browserTabCount: 3, - diffCommentCount: 4, - newestDiffCommentAt: null, - retainedDoneAgentCount: 5 - } - }) - - act(() => { - root.render( - - ) - }) - - const labels = [ - 'Terminal tabs: 1', - 'Editor tabs: 2', - 'Browser tabs: 3', - 'Diff notes: 4', - 'Completed agents: 5' - ] - const renderedLabels = Array.from(container.querySelectorAll('span')) - .map((element) => element.textContent) - .filter((label): label is string => labels.includes(label ?? '')) - - expect(renderedLabels).toEqual(labels) - expect(container.textContent).not.toContain('Context: ') - }) - - it('visibly and accessibly identifies each host for colliding confirmations', () => { - const local = makeFacetCandidate({ executionHostId: 'local' }) - const remote = makeFacetCandidate({ - connectionId: 'builder', - executionHostId: 'ssh:builder' - }) - - act(() => { - root.render( - - ) - }) - - expect(getWorkspaceCleanupCandidateAccessibleName(local)).not.toBe( - getWorkspaceCleanupCandidateAccessibleName(remote) - ) - for (const candidate of [local, remote]) { - const name = getWorkspaceCleanupCandidateAccessibleName(candidate) - const hostLabel = getWorkspaceCleanupCandidateHostLabel(candidate) - expect(container.querySelector(`[role="group"][aria-label="${name}"]`)).not.toBeNull() - expect(container.querySelector(`[aria-label="Host: ${hostLabel}"]`)).not.toBeNull() - } - }) - - it('shows every destructive git risk and the fleet-level force projection', () => { - const failed = makeFacetCandidate({ - worktreeId: 'repo-1::/failed', - blockers: ['pinned', 'git-status-error'], - git: { - clean: null, - upstreamAhead: null, - upstreamBehind: null, - checkedAt: null - } - }) - const unknownBase = makeFacetCandidate({ - worktreeId: 'repo-1::/unknown-base', - blockers: ['unknown-base'] - }) - - act(() => { - root.render( - - ) - }) - - expect(container.textContent).toContain('Pinned') - expect(container.textContent).toContain('Git status unavailable') - expect(container.textContent).toContain('Could not verify unpushed commits') - expect(container.textContent).toContain( - '2 workspaces currently show risk and may need a force delete' - ) - expect( - [...container.querySelectorAll('.text-destructive')].map((node) => node.textContent) - ).toEqual( - expect.arrayContaining(['Git status unavailable', 'Could not verify unpushed commits']) - ) - - act(() => { - root.render( - - ) - }) - expect(container.textContent).toContain( - '1 workspace currently shows risk and may need a force delete' - ) - }) - - it('gives the review pill a text equivalent for its state color without repeating the number', () => { - const candidate = makeFacetCandidate({ - worktreeId: 'repo-1::/repo/merged-review', - displayName: 'Merged review', - path: '/repo/merged-review' - }) - - act(() => { - root.render( - - ) - }) - - const srText = container.querySelector('span.sr-only')?.textContent ?? '' - expect(srText).toContain('Merged') - expect(srText).not.toContain('PR #15716') - }) -}) diff --git a/src/renderer/src/lib/pane-manager/pane-cursor-blink-suspension.test.ts b/src/renderer/src/lib/pane-manager/pane-cursor-blink-suspension.test.ts index fbd4da81a47..7a3fb517dac 100644 --- a/src/renderer/src/lib/pane-manager/pane-cursor-blink-suspension.test.ts +++ b/src/renderer/src/lib/pane-manager/pane-cursor-blink-suspension.test.ts @@ -216,58 +216,4 @@ describe('hidden-pane cursor blink suspension', () => { await nextFrame() expect(rendersBlinkingCursor(pane), 'the new setting applies on reveal').toBe(true) }) - - it('resume is a no-op for a pane that was never suspended', async () => { - const pane = createTestPane() - await flushRender() - await reveal([pane]) - await nextFrame() - expect(rendersBlinkingCursor(pane)).toBe(true) - }) -}) - -/** Model addon-webgl 0.20’s 600ms document-focused timer, which redraws a full row per tick; DEC cursor mode overrides cursorBlink options. Read effective state from the real Terminal. */ -const BLINK_INTERVAL_MS = 600 - -function blinkCellsRedrawnPerWindow(terminal: Terminal, windowMs: number): number { - const decPrivateBlink = ( - terminal as unknown as { - _core: { coreService: { decPrivateModes: { cursorBlink?: boolean } } } - } - )._core.coreService.decPrivateModes.cursorBlink - const blinking = decPrivateBlink ?? terminal.options.cursorBlink === true - if (!blinking) { - return 0 - } - return Math.floor(windowMs / BLINK_INTERVAL_MS) * terminal.cols -} - -describe('hidden-pane cursor blink redraw cost', () => { - beforeEach(() => { - resetHiddenWebglRetentionForTest() - vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({ - measureText: () => ({ width: 10 }) - } as unknown as CanvasRenderingContext2D) - }) - - afterEach(() => { - vi.restoreAllMocks() - document.body.replaceChildren() - }) - - it('drops retained hidden panes to zero blink redraws and restores them on reveal', async () => { - const owner = {} - const panes = Array.from({ length: 6 }, () => createTestPane({ webglAddon: true })) - const windowMs = 30_000 - const cells = () => - panes.reduce((sum, pane) => sum + blinkCellsRedrawnPerWindow(pane.terminal, windowMs), 0) - - expect(cells()).toBe(6 * 50 * COLS) - - suspendPaneRendering(panes, { owner, livePanes: () => panes }) - expect(cells(), 'hidden panes must cost nothing while the window is visible').toBe(0) - - await reveal(panes, owner) - expect(cells()).toBe(6 * 50 * COLS) - }) }) diff --git a/src/renderer/src/lib/text-control-paste.test.ts b/src/renderer/src/lib/text-control-paste.test.ts index 942bd92c69b..ced5926c597 100644 --- a/src/renderer/src/lib/text-control-paste.test.ts +++ b/src/renderer/src/lib/text-control-paste.test.ts @@ -2,11 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { PASTE_PAYLOAD_CORPUS } from './paste-payload-corpus' -import { - measureTextControlPasteByteLength, - pasteTextIntoTextControl, - shouldHandleTextControlPaste -} from './text-control-paste' +import { measureTextControlPasteByteLength, pasteTextIntoTextControl } from './text-control-paste' function appendTextarea(value = ''): HTMLTextAreaElement { const textarea = document.createElement('textarea') @@ -107,20 +103,6 @@ describe('text control paste', () => { expect(textarea.value).toBe(text) }) - it('does not split surrogate pairs across chunks', async () => { - const textarea = appendTextarea() - const text = 'a😀b😀c' - - const result = await pasteTextIntoTextControl(textarea, text, { - directMaxBytes: 2, - chunkMaxBytes: 5, - yieldToEventLoop: async () => {} - }) - - expect(result.status).toBe('pasted') - expect(textarea.value).toBe(text) - }) - it('rejects unavailable text controls without mutating them', async () => { const textarea = appendTextarea('unchanged') const disabled = appendTextarea('disabled') @@ -249,13 +231,6 @@ describe('text control paste', () => { expect(events).toHaveLength(0) }) - it('uses utf-8 byte thresholds for non-ascii text', () => { - expect(measureTextControlPasteByteLength('a😀é').byteLength).toBe(7) - expect(shouldHandleTextControlPaste('😀😀', { directMaxBytes: 7 })).toBe(true) - expect(shouldHandleTextControlPaste('abc', { directMaxBytes: 7 })).toBe(false) - expect(shouldHandleTextControlPaste('', { directMaxBytes: 0 })).toBe(false) - }) - it('can stop measuring text-control paste once the limit is exceeded', () => { const measurement = measureTextControlPasteByteLength('😀'.repeat(100), { stopAfterBytes: 5 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 8de275af20a..b14e42caae9 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,38 +216,4 @@ 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/wsl-move-renderer-store-rewrites.test.ts b/src/renderer/src/lib/wsl-move-renderer-store-rewrites.test.ts index c4da57c490b..b1e4f60227d 100644 --- a/src/renderer/src/lib/wsl-move-renderer-store-rewrites.test.ts +++ b/src/renderer/src/lib/wsl-move-renderer-store-rewrites.test.ts @@ -96,16 +96,6 @@ afterEach(() => { }) describe('WSL move renderer store rewrites', () => { - it('changes nothing without a committed move', async () => { - seedStorage() - const before = { ...localStorage } - client.list.mockResolvedValue([]) - await (await loadRunner()).runWslMoveRendererStoreRewrites() - expect({ ...localStorage }).toEqual(before) - expect(localStorage.getItem(APPLIED)).toBeNull() - expect(client.record).not.toHaveBeenCalled() - }) - it('never throws when the move list is unavailable, and asks again later', async () => { vi.useFakeTimers() try { diff --git a/src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts b/src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts index 35cf9daaa11..ceb066373e2 100644 --- a/src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts +++ b/src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts @@ -156,13 +156,6 @@ describe('syncRuntimeGraph cold-parked tabs', () => { expect(reportedTabIds(graph)).toContain(TAB_ID) }) - it('drops the leaf once the watcher is disposed (reveal, close, PTY exit, teardown)', async () => { - const graph = await captureGraph() - - expect(reportedPanes(graph)).not.toContainEqual(expect.objectContaining({ tabId: TAB_ID })) - expect(reportedTabIds(graph)).not.toContain(TAB_ID) - }) - // Stale paneIdByPtyId/tabPtyId survive these cases; tests must reject those false liveness proofs. it('drops the leaf when per-PTY disposal leaves only the pane-id slot behind', async () => { // PTY exit removes disposer but retains pane-ID slot and tabPtyId. diff --git a/src/renderer/src/store/slices/project-removal-unreachable-server.test.ts b/src/renderer/src/store/slices/project-removal-unreachable-server.test.ts index 72b42b57cce..d029806d582 100644 --- a/src/renderer/src/store/slices/project-removal-unreachable-server.test.ts +++ b/src/renderer/src/store/slices/project-removal-unreachable-server.test.ts @@ -229,18 +229,6 @@ describe('removing a project while its paired server is unreachable', () => { expect(rmAttempts).toBe(2) }) - it('keeps the record when the server is still unreachable at replay time', async () => { - seedPendingRuntimeRepoRemovals([{ environmentId: 'env-1', repoId: 'app', requestedAt: 1 }]) - - await replayPendingRuntimeRepoRemovals( - 'env-1', - () => Promise.reject(new Error(UNREACHABLE)), - vi.fn() - ) - - expect(listPendingRuntimeRepoRemovals('env-1')).toHaveLength(1) - }) - it('never lets a replayed repo.rm undo a re-add of the same project', async () => { seedPendingRuntimeRepoRemovals([{ environmentId: 'env-1', repoId: 'app', requestedAt: 1 }]) reachable = true diff --git a/src/renderer/src/store/slices/worktrees/listing/stale-listing-purges-created-worktree.test.ts b/src/renderer/src/store/slices/worktrees/listing/stale-listing-purges-created-worktree.test.ts index f40e5aef6a1..742b13db860 100644 --- a/src/renderer/src/store/slices/worktrees/listing/stale-listing-purges-created-worktree.test.ts +++ b/src/renderer/src/store/slices/worktrees/listing/stale-listing-purges-created-worktree.test.ts @@ -188,20 +188,6 @@ describe('an authoritative listing that omits a just-created worktree', () => { expect(state.activeWorktreeId).toBeNull() expect(state.unifiedTabsByWorktree[CREATED_ID]).toBeUndefined() }) - - it('control: a listing that includes the created worktree leaves everything intact', () => { - const store = createTestStore() - seedCreatedWorkspaceWithPendingLaunch(store, true) - const rows = store.getState().worktreesByRepo[REPO_ID]! - - expect(applyListing(store, [...rows])).toBe('applied') - - const state = store.getState() - expect(readStructuredAgentLaunchRecord(SESSION_ID)).toBeDefined() - expect(launchWasCancelled()).toBe(false) - expect(state.activeWorktreeId).toBe(CREATED_ID) - expect(state.unifiedTabsByWorktree[CREATED_ID]).toHaveLength(2) - }) }) // Catalog versions fence delayed listings before merge/teardown so scans predating applied create cannot purge new tabs or replace current rows.