test: remove 48 low-value suites (#42951)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-15 20:30:40 -08:00
committed by GitHub
co-authored by OrcaWin
parent 6d2e6337b9
commit e9b1aabe73
52 changed files with 19 additions and 4076 deletions
File diff suppressed because one or more lines are too long
@@ -1,23 +0,0 @@
import { expect, it } from 'vitest'
import { runProcess } from '@orca/process-host'
it('publishes conservative hints for malformed evidence and refuses a malformed consumer list', async () => {
const program = 'config/scripts/ci/e2e-selection/ci-e2e-job-selection.mjs'
const consumer = await runProcess({
program: process.execPath,
args: [program],
input: 'malformed',
timeoutMs: 10000
})
expect(consumer.code).not.toBe(0)
const hints = await runProcess({
program: process.execPath,
args: [program, '--job-outputs'],
input: 'malformed',
timeoutMs: 10000
})
expect(hints.code, hints.stderr).toBe(0)
expect(hints.stdout).toBe(
'e2e_run_changed=true\ne2e_needs_build=true\ne2e_ssh_shards=["1/2","2/2"]\n'
)
})
@@ -37,7 +37,6 @@
"config/scripts/ci/unit-selection/check-test-file-runners.test.mjs": 267,
"config/scripts/ci/workflow-contracts/ci-closed-pr-cancellation.test.mjs": 112,
"config/scripts/ci/workflow-contracts/ci-draft-pr-admission.test.mjs": 546,
"config/scripts/ci/e2e-selection/ci-e2e-job-selection.test.mjs": 273,
"config/scripts/ci/e2e-selection/ci-e2e-shard-selection.test.mjs": 2772,
"config/scripts/ci/workflow-contracts/ci-managed-ssh-execution.test.mjs": 844,
"config/scripts/ci/workflow-contracts/ci-native-toolchain.test.mjs": 109,
@@ -384,7 +383,6 @@
"src/main/acp/history/acp-history-scaling.test.ts": 24879,
"src/main/persistence/preferences/active-view-persistence-boundary.test.ts": 2119,
"src/main/persistence/preferences/active-view-preference-sync-flush-veto.test.ts": 781,
"src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.test.ts": 202,
"src/main/agent-hooks/installation/scripts/cursor-replay-guard.test.ts": 403,
"src/main/agent-hooks/server/testing/reconciliation/ended-process-reconciliation.test.ts": 775,
"src/main/agent-hooks/first-work/first-work-branch-rename-wsl-move.test.ts": 831,
@@ -1047,14 +1045,12 @@
"src/main/computer/macos-permissions/macos-computer-use-permission-status-cleanup.integration.test.ts": 65,
"src/main/computer/macos-native/macos-native-provider-client.test.ts": 1210,
"src/main/computer/sidecar-transport/sidecar-client.test.ts": 121,
"src/main/computer/desktop-script/runtime-host/windows-powershell-execution-policy.test.ts": 46,
"src/main/connector-cloud/connector-hello.test.ts": 126,
"src/main/connector-cloud/connector-places.test.ts": 345,
"src/main/connector-cloud/connector-poll-client.test.ts": 874,
"src/main/connector-cloud/connector-snapshot.test.ts": 126,
"src/main/connector-cloud/connector-turn-events.test.ts": 411,
"src/main/copilot/hook-service.test.ts": 180,
"src/main/crash-reporting/breadcrumbs/crash-breadcrumb-store-orphan-cleanup.test.ts": 81,
"src/main/crash-reporting/reports/crash-report-store.test.ts": 438,
"src/main/crash-reporting/minidumps/minidump-crash-signature.test.ts": 87,
"src/main/crash-reporting/memory/renderer-heap-allocation-sites.test.ts": 62,
@@ -1192,7 +1188,6 @@
"src/main/daemon/emulation/testing/serialize-grid.differential.fuzz.test.ts": 586,
"src/main/daemon/sessions/testing/session-conpty-resize-history.test.ts": 270,
"src/main/daemon/sessions/testing/session-conpty-resize-transcript.test.ts": 241,
"src/main/daemon/sessions/testing/session-pending-output.test.ts": 326,
"src/main/daemon/sessions/testing/session-reset-input-modes.test.ts": 200,
"src/main/daemon/sessions/testing/session-shell-ready-interactive-rc.node-pty.test.ts": 643,
"src/main/daemon/sessions/testing/session-shell-recovery.test.ts": 288,
@@ -1450,9 +1445,7 @@
"src/main/host/deferred-secret-protection-report.test.ts": 81,
"src/main/host/electron-manual-redirect-fetch.test.ts": 52,
"src/main/host/secret-protection-report.test.ts": 59,
"src/main/i18n/main-i18n-lazy-locale.test.ts": 518,
"src/shared/image-file-signature.test.ts": 47,
"src/main/credentials/integration-state-file-cache.test.ts": 47,
"src/main/credentials/integration-token-file-cache.test.ts": 152,
"src/main/ipc/account-sign-in-link-opener.test.ts": 128,
"src/main/ipc/agent-hooks.test.ts": 736,
@@ -1603,7 +1596,6 @@
"src/main/ipc/ssh/ssh-connect-decision-cancellation.test.ts": 6414,
"src/main/ipc/ssh/ssh-credential-cancel.test.ts": 4604,
"src/main/ipc/ssh/ssh-host-user-disconnect.test.ts": 4734,
"src/main/ipc/ssh/ssh-passphrase.test.ts": 135,
"src/main/ipc/terminal-render-desync-evidence.test.ts": 78,
"src/main/workspaces/removal/watcher-removal-gate.test.ts": 384,
"src/main/ipc/workspace-cleanup/workspace-cleanup-activity.test.ts": 76,
@@ -1738,7 +1730,6 @@
"src/main/native-chat/agent-session-journal/outcomes/journal-outcome-sweeper.test.ts": 503,
"src/main/native-chat/agent-session-journal/replay/journal-outcome-wire.test.ts": 543,
"src/main/native-chat/agent-session-journal/store-lifecycle/journal-queued-message-contracts.test.ts": 3279,
"src/main/native-chat/agent-session-journal/projection/journal-reducer-rejection-fact.test.ts": 278,
"src/main/native-chat/agent-session-journal/projection/journal-rejected-message-placement.test.ts": 369,
"src/main/native-chat/agent-session-journal/store-lifecycle/journal-settlement-contracts.test.ts": 3953,
"src/main/native-chat/agent-session-journal/durable-rows/journal-storage-admission.test.ts": 1276,
@@ -2310,7 +2301,6 @@
"src/main/runtime/terminal/surface/orca-runtime-terminal-close-no-widening-layout-owner.test.ts": 4997,
"src/main/runtime/terminal/surface/orca-runtime-terminal-close-no-widening.test.ts": 4509,
"src/main/runtime/terminal/surface/orca-runtime-terminal-close-records.test.ts": 7575,
"src/main/runtime/terminal/launch/orca-runtime-terminal-create-replay-after-close.test.ts": 4654,
"src/main/runtime/terminal/identity/orca-runtime-terminal-handle-incarnation.test.ts": 4449,
"src/main/runtime/terminal/title/orca-runtime-terminal-rename-retention.test.ts": 5757,
"src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts": 3714,
@@ -2962,7 +2952,6 @@
"src/main/ssh/host-keys/ssh-host-key-store.test.ts": 238,
"src/main/ssh/host-keys/ssh-host-key-verifier.test.ts": 97,
"src/main/ssh/host-server/ssh-host-server-on-connect-held-move.test.ts": 510,
"src/main/ssh/host-server/ssh-host-server-on-connect-node-download.test.ts": 455,
"src/main/ssh/host-server/ssh-host-server-on-connect.test.ts": 536,
"src/main/ssh/host-server/ssh-host-server-telemetry.test.ts": 194,
"src/main/ssh/authentication/ssh-identity-file-read.test.ts": 111,
@@ -3134,9 +3123,7 @@
"src/main/persistence/moving-wsl-projects/quiescence/wsl-approved-root-race.wsl.test.ts": 102,
"src/main/wsl/discovery/wsl-background-distro-gate.test.ts": 674,
"src/main/wsl/discovery/wsl-console-running-distros.test.ts": 57,
"src/main/wsl/history/wsl-fish-history-cleanup.test.ts": 158,
"src/main/wsl/execution/wsl-interop-spawn-directory.test.ts": 52,
"src/main/wsl/execution/wsl-managed-cli-path-restore.test.ts": 68,
"src/main/wsl/discovery/wsl-running-distro-stop.test.ts": 42,
"src/main/wsl/discovery/wsl-running-distros.test.ts": 201,
"src/main/wsl/filesystem/wsl-running-path-filter.test.ts": 57,
@@ -3437,7 +3424,6 @@
"src/renderer/src/components/editor/rich-markdown/schema/rich-markdown-trailing-paragraph.test.ts": 2437,
"src/renderer/src/components/editor/use-custom-editor-outside-merge.test.tsx": 2069,
"src/renderer/src/components/editor/model-lifetime/buffer-text/use-editor-content-change-handler.test.tsx": 2031,
"src/renderer/src/components/editor/markdown-preview/search/use-markdown-preview-search-reveal.test.tsx": 390,
"src/renderer/src/components/editor/use-monaco-editor-mount.cursor-owner.test.tsx": 1332,
"src/renderer/src/components/editor/use-monaco-editor-mount.stale-cache.test.tsx": 877,
"src/renderer/src/components/editor/rich-markdown/tables/use-rich-markdown-table-context-menu.test.tsx": 2238,
@@ -3480,7 +3466,6 @@
"src/renderer/src/components/linear-issue-text-draft-state.test.ts": 49,
"src/renderer/src/components/link-actions/LinkActionPopover.test.tsx": 628,
"src/renderer/src/components/mobile/WindowsFirewallNotice.test.tsx": 691,
"src/renderer/src/components/mobile/use-mobile-page-paired-devices.test.ts": 475,
"src/renderer/src/components/native-chat/markdown/code/NativeChatCodeBlock.test.tsx": 2775,
"src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx": 2881,
"src/renderer/src/components/native-chat/viewport/scroll/NativeChatJumpToLatest.test.tsx": 477,
@@ -3737,7 +3722,6 @@
"src/renderer/src/components/terminal-pane/links/http/edge-wrapped-terminal-http-links.test.ts": 529,
"src/renderer/src/components/terminal-pane/links/http/framed-overlay-terminal-http-links.test.ts": 508,
"src/renderer/src/components/terminal-pane/pty-connection/output-restore/hidden-query-carry-osc-introducer-leak.repro.test.ts": 1154,
"src/renderer/src/components/terminal-pane/emulation/issue-12112-agent-pane-startup-color-reply-leak.repro.test.ts": 564,
"src/renderer/src/components/terminal-pane/input/keyboard-handlers-ime-composing-chord.test.tsx": 2223,
"src/renderer/src/components/terminal-pane/input/keyboard-handlers-ime-enter-keyup.test.tsx": 2120,
"src/renderer/src/components/terminal-pane/input/keyboard-handlers-ime.test.tsx": 2239,
@@ -3755,7 +3739,6 @@
"src/renderer/src/components/terminal-pane/pty-connection/lifecycle/pty-connection-hibernation-kill-shell-foreground.test.ts": 2205,
"src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-restore-marker-handoff.test.ts": 2170,
"src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-restore-unhide-coverage.test.ts": 4612,
"src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-restore-unhide-retired-task.test.ts": 1947,
"src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-hook-idle-arbitration.test.ts": 2228,
"src/renderer/src/components/terminal-pane/pty-connection/spawn/pty-connection-main-pane-restore-start.test.ts": 2430,
"src/renderer/src/components/terminal-pane/pty-connection/spawn/pty-connection-main-pane-start.test.ts": 2611,
@@ -3843,7 +3826,6 @@
"src/renderer/src/components/terminal-pane/input/file-drop/terminal-pane-element-file-drop.test.tsx": 1748,
"src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-commit.test.ts": 2090,
"src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-move.test.ts": 2147,
"src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts": 473,
"src/renderer/src/components/terminal-pane/emulation/terminal-parser-handler-guard.test.ts": 55,
"src/renderer/src/components/terminal-pane/input/paste/terminal-paste-coordinator.test.ts": 155,
"src/renderer/src/components/terminal-pane/links/files/terminal-path-exists-cache.test.ts": 47,
@@ -3882,7 +3864,6 @@
"src/renderer/src/components/window-close-request-coordinator.test.ts": 361,
"src/renderer/src/components/workspace-cleanup/dialog/WorkspaceCleanupDialog.stale-while-revalidate.test.tsx": 3269,
"src/renderer/src/components/workspace-cleanup/removal/use-workspace-cleanup-removal.agent-stop.test.tsx": 2285,
"src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-background-removal-late-settlement.test.ts": 1880,
"src/renderer/src/components/workspace-cleanup/removal/workspace-cleanup-removal-candidates.test.ts": 206,
"src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-removal-timeout-recovery.test.ts": 1817,
"src/renderer/src/components/workspace-emoji/WorkspaceEmojiPickerButton.test.tsx": 1086,
@@ -3953,7 +3934,6 @@
"src/renderer/src/hooks/clipboard/primary-selection/usePrimarySelectionPaste.test.tsx": 411,
"src/renderer/src/hooks/useReadOnScreenAttention.mixed-workspace.test.ts": 1725,
"src/renderer/src/hooks/worktree-change-refresh-queue.test.ts": 59,
"src/renderer/src/i18n/I18nProvider.test.tsx": 2101,
"src/renderer/src/i18n/language-catalog-timeout.test.tsx": 2025,
"src/renderer/src/i18n/relative-time-format.test.ts": 53,
"src/renderer/src/i18n/ui-intl-formatters.test.ts": 208,
@@ -4135,7 +4115,6 @@
"src/renderer/src/store/slices/editor/buffers/editor-buffer-reconcile-joins.test.ts": 1766,
"src/renderer/src/store/slices/editor/buffers/editor-buffer-rejoin.test.ts": 1843,
"src/renderer/src/store/slices/editor/file-ids/floating-editor-file-id-layout-owner.test.ts": 933,
"src/renderer/src/store/slices/worktrees/session/folder-workspace-activation-and-activity.test.ts": 2358,
"src/renderer/src/store/slices/diff-comments/folder-workspace-diff-comments.test.ts": 1042,
"src/renderer/src/store/folder-workspaces/folder-workspace-owner-routed-mutations.test.ts": 1844,
"src/renderer/src/store/github/issues/github-issue-state-machine.test.ts": 658,
@@ -4209,7 +4188,6 @@
"src/renderer/src/web/web-file-write-disk-precondition.test.ts": 555,
"src/renderer/src/web/web-insecure-origin-pairing.test.ts": 184,
"src/renderer/src/web/web-pairing.test.ts": 105,
"src/renderer/src/web/web-preload-api-chat-ui-launch-migration.test.ts": 10672,
"src/renderer/src/web/web-preload-api-clipboard.test.ts": 2816,
"src/renderer/src/web/web-preload-api-github.test.ts": 875,
"src/renderer/src/web/web-preload-api-keybindings.test.ts": 1519,
@@ -4275,7 +4253,6 @@
"src/shared/agent-session/lifecycle/agent-session-operation-ledger.test.ts": 169,
"src/shared/agent-session/lifecycle/agent-session-provider-handle.test.ts": 90,
"src/shared/agent-session/lifecycle/agent-session-record-stored-form.test.ts": 192,
"src/shared/agent-session/lifecycle/agent-session-sign-in.test.ts": 144,
"src/shared/agent-session/lifecycle/agent-session-stopped-history.test.ts": 164,
"src/shared/agent-session/lifecycle/agent-session-stored-agent.test.ts": 160,
"src/shared/agent-session/lifecycle/agent-session-turn-record.test.ts": 127,
@@ -4293,7 +4270,6 @@
"src/shared/agent-session/structured-agent-session-reducer.test.ts": 159,
"src/shared/agent-session/view/structured-agent-session-item-retention.test.ts": 679,
"src/shared/agent-session/view/structured-agent-session-projection-turn-verdict.test.ts": 168,
"src/shared/agent-session/view/structured-agent-session-projection.test.ts": 245,
"src/shared/agent-session/view/structured-agent-session-status-started-at.test.ts": 211,
"src/shared/agent-session/view/structured-agent-session-subagent-roster.test.ts": 63,
"src/shared/agent-session/view/structured-agent-session-turn-timing-retention.test.ts": 221,
@@ -4401,7 +4377,6 @@
"src/shared/git/status/git-uncommitted-line-stats.test.ts": 87,
"src/shared/git/worktrees/git-worktree-admin.test.ts": 161,
"src/shared/github/project-board-columns.test.ts": 64,
"src/shared/github/project-identity.test.ts": 33,
"src/shared/github/project-ref-input.test.ts": 40,
"src/shared/grok-session-paths.test.ts": 104,
"src/shared/terminal/links/hard-wrapped-terminal-http-links.test.ts": 91,
@@ -4481,7 +4456,6 @@
"src/shared/node-bounded-file-reader-sync.test.ts": 56,
"src/shared/node-bounded-file-reader-window.test.ts": 63,
"src/shared/node-bounded-file-reader.test.ts": 67,
"src/shared/node-readable-text.test.ts": 45,
"src/shared/node-source-copy-content-equality.test.ts": 52,
"src/shared/nvm-default-alias.test.ts": 81,
"src/shared/agent-launch/startup/omp-draft-launch-shell.test.ts": 382,
@@ -4523,7 +4497,6 @@
"src/shared/plugins/artifacts/plugin-theme-artifact.test.ts": 165,
"src/shared/plugins/authoring/plugin-host-typings.test.ts": 2140,
"src/shared/plugins/catalog/plugin-kill-list.test.ts": 195,
"src/shared/plugins/catalog/plugin-marketplace.test.ts": 246,
"src/shared/plugins/contributions/plugin-command-replaces.test.ts": 230,
"src/shared/plugins/contributions/plugin-content-pack-contributions.test.ts": 227,
"src/shared/plugins/contributions/plugin-custom-editor-contribution.test.ts": 238,
@@ -4601,13 +4574,11 @@
"src/shared/repro-13889-claude-quarter-circle-busy-title.test.ts": 83,
"src/shared/require-tui-agent-config.test.ts": 54,
"src/shared/resolved-worktree-lineage.test.ts": 59,
"src/shared/ripgrep-dense-match-json.test.ts": 161,
"src/shared/ripgrep-filename-decoder.test.ts": 49,
"src/shared/ripgrep-line-decoding.test.ts": 352,
"src/shared/ripgrep-process-availability.test.ts": 56,
"src/shared/ripgrep-search-diagnostics.test.ts": 72,
"src/shared/rpc-contract/automation-params-extra-agent-args.test.ts": 131,
"src/shared/rpc-contract/session-tabs/session-tabs-create-resume-session-param.test.ts": 259,
"src/shared/rpc-contract/structured-agent-session-agent-params.test.ts": 274,
"src/shared/remote-runtime/host-store/runtime-environment-managed-orcad-store.test.ts": 313,
"src/shared/remote-runtime/host-store/runtime-environment-sidecar.test.ts": 277,
@@ -4651,10 +4622,8 @@
"src/shared/structured-session-message-contracts.test.ts": 411,
"src/shared/task-query.test.ts": 55,
"src/shared/program-status/terminal-agent-status-processor.test.ts": 74,
"src/shared/terminal/output/terminal-bell-detector.test.ts": 40,
"src/shared/terminal/protocol/queries/terminal-color-scheme-protocol.test.ts": 39,
"src/shared/terminal/input/terminal-composer-draft.test.ts": 73,
"src/shared/terminal/links/terminal-file-uri-link.test.ts": 51,
"src/shared/terminal/links/terminal-github-pr-link-detector.test.ts": 61,
"src/shared/terminal/links/terminal-http-url-extraction.test.ts": 42,
"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts": 84,
@@ -4681,7 +4650,6 @@
"src/shared/terminal/protocol/queries/terminal-view-attributes.test.ts": 54,
"src/shared/text-search-dense-matches.test.ts": 559,
"src/shared/text-search-glob-patterns.test.ts": 268,
"src/shared/text-search-invalid-filename.test.ts": 60,
"src/shared/text-search-snippet-boundaries.test.ts": 77,
"src/shared/text-search-snippet-retention.test.ts": 587,
"src/shared/text-search.test.ts": 135,
@@ -218,7 +218,6 @@ const CROSS_VERSION_WIRE_PREFIXES = [
'src/shared/agent-launch/contracts/agent-launch-intent',
'src/shared/rpc-contract/agent-launch/agent-launch-params',
'src/shared/agent-session/agent-session-wire',
'src/shared/agent-session/view/structured-agent-session-projection.test.ts',
'src/shared/agent-session/view/structured-agent-session-projection.ts',
'src/shared/agent-session/lifecycle/records/agent-session-record-stored-form.test.ts',
'src/shared/agent-session/lifecycle/records/agent-session-record-stored-form.ts',
@@ -1,21 +0,0 @@
import { Buffer } from 'node:buffer'
import { describe, expect, it } from 'vitest'
import { MobileImageBase64Accumulator } from './mobile-image-base64-accumulator'
function decodeBase64(data: string): Uint8Array {
return Buffer.from(atob(data), 'latin1')
}
describe('MobileImageBase64Accumulator', () => {
it('preserves bytes across internal staging flushes', () => {
const bytes = new Uint8Array(256 * 1024 + 7)
bytes.forEach((_, index) => {
bytes[index] = index % 251
})
const accumulator = new MobileImageBase64Accumulator()
accumulator.append(bytes.subarray(0, 123_457))
accumulator.append(bytes.subarray(123_457))
expect(Buffer.compare(decodeBase64(accumulator.finish()), bytes)).toBe(0)
})
})
@@ -1,16 +0,0 @@
import { describe, expect, it } from 'vitest'
import { MobileDictationPendingAudioBudget } from './mobile-dictation-pending-audio-budget'
describe('MobileDictationPendingAudioBudget', () => {
it('keeps a replayed backlog out of the live limit while live requests settle first', () => {
const budget = new MobileDictationPendingAudioBudget(100)
budget.reserveBacklog(150)
expect(budget.takeBacklog(150)).toBe(150)
expect(budget.tryReserve(60)).toBe(true)
expect(budget.takeBacklog(60)).toBe(0)
// The live request answers before the older backlog request does.
budget.release(60, 0)
expect(budget.tryReserve(90)).toBe(true)
expect(budget.tryReserve(11)).toBe(false)
})
})
@@ -1,22 +0,0 @@
import { afterEach, expect, it } from 'vitest'
import { createFakeBridgePortPair } from '../test-support/bridge-port-pair-test-harness'
import { readBridgeHostMessage } from '../protocol/bridge-envelope'
let pair: ReturnType<typeof createFakeBridgePortPair> | null = null
afterEach(() => {
pair?.client.close()
pair?.host.dispose()
pair = null
})
it('keeps an init whose language this page does not ship', async () => {
pair = createFakeBridgePortPair()
await pair.flush()
const init = pair.readToPage().find((frame) => frame.type === 'init')
const read = readBridgeHostMessage(JSON.stringify({ ...init, uiLocale: 'it' }))
expect(read.ok).toBe(true)
expect(
read.ok && read.message.type === 'init' ? read.message.uiLocale : 'refused'
).toBeUndefined()
})
@@ -1,18 +0,0 @@
import { describe, expect, it } from 'vitest'
import { resolveHostIdForFingerprint } from './push-host-fingerprint'
const publicKey = Uint8Array.from({ length: 32 }, (_, index) => index)
const publicKeyB64 = Buffer.from(publicKey).toString('base64')
describe('resolveHostIdForFingerprint', () => {
const other = Uint8Array.from({ length: 32 }, (_, index) => index + 1)
const hosts = [
{ id: 'host-corrupt', publicKeyB64: 'not-a-key' },
{ id: 'host-other', publicKeyB64: Buffer.from(other).toString('base64') },
{ id: 'host-1', publicKeyB64 }
]
it('maps a push fingerprint back to the paired host id', () => {
expect(resolveHostIdForFingerprint('Yw3NKWbEM2aRElRI', hosts)).toBe('host-1')
})
})
@@ -1,15 +0,0 @@
import { describe, expect, it } from 'vitest'
import { fitDimensionsFromCell } from './terminal-grid-fit'
describe('fitDimensionsFromCell', () => {
it('keeps an exact fit at a fractional pixel ratio whole', () => {
// An exact device-pixel fit can divide to 49.999… after pixel-ratio conversion.
const cell = { cellWidth: 18 / 2.75, cellHeight: 40 / 2.75 }
expect(fitDimensionsFromCell(cell, 900 / 2.75, 1320 / 2.75)).toEqual({ cols: 50, rows: 33 })
})
it('still falls short of a column the frame does not hold', () => {
const cell = { cellWidth: 393 / 51, cellHeight: 15 }
expect(fitDimensionsFromCell(cell, 1080 / 2.75, 600)?.cols).toBe(50)
})
})
@@ -1,28 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
MobileRelayBackgroundGraceTimer,
RELAY_BACKGROUND_GRACE_MS
} from './mobile-relay-background-grace'
describe('MobileRelayBackgroundGraceTimer', () => {
afterEach(() => vi.useRealTimers())
it('detects expiry on resume when the background timer was suspended', () => {
vi.useFakeTimers()
let now = 1_000
const timer = new MobileRelayBackgroundGraceTimer(
{
now: () => now,
setTimer: vi.fn(() => setTimeout(() => {}, 0)),
clearTimer: vi.fn()
},
vi.fn()
)
timer.arm()
now += RELAY_BACKGROUND_GRACE_MS
expect(timer.consumeExpired()).toBe(true)
expect(timer.consumeExpired()).toBe(false)
})
})
@@ -1,57 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { PluginHookName } from '../../../shared/plugins/contributions/plugin-hook-contribution'
import type { PluginHookChainOutcome } from '../../../shared/plugins/workers/plugin-hook-chain'
import { setPluginHookRunner } from '../../plugins/hooks/plugin-hook-dispatch'
import { answerAgentToolPluginHooks } from './agent-tool-plugin-hooks'
const DECIDES = { 'x-orca-hook-decision': 'claude-pre-tool-use-v1' }
function installRunner(
decide: (payload: unknown) => PluginHookChainOutcome | Promise<PluginHookChainOutcome>
) {
const run = vi.fn(async (_event: PluginHookName, payload: unknown) => decide(payload))
setPluginHookRunner({ wants: (event) => event.startsWith('agent.tool.'), run })
return run
}
function post(payload: Record<string, unknown>) {
return { paneKey: 'tab-1:0', worktreeId: 'repo::/w', payload: JSON.stringify(payload) }
}
const PRE = post({
hook_event_name: 'PreToolUse',
tool_name: 'Bash',
tool_input: { command: 'rm -rf /' },
tool_use_id: 'toolu_1'
})
const OWNER = { paneKey: 'tab-1:0', worktreeId: 'repo::/w', hookEventName: 'PreToolUse' }
afterEach(() => {
setPluginHookRunner(null)
vi.useRealTimers()
})
describe('answerAgentToolPluginHooks', () => {
it('answers changed input without approving it, and nothing when unchanged', async () => {
installRunner((payload) => ({
kind: 'continue',
payload: { ...Object(payload), input: { command: 'ls' } }
}))
expect(
JSON.parse((await answerAgentToolPluginHooks('claude', PRE, DECIDES, OWNER)) ?? 'null')
).toEqual({
hookSpecificOutput: { hookEventName: 'PreToolUse', updatedInput: { command: 'ls' } }
})
installRunner((payload) => ({ kind: 'continue', payload }))
await expect(answerAgentToolPluginHooks('claude', PRE, DECIDES, OWNER)).resolves.toBeNull()
})
it('fails open when the plugins take longer than the script waits', async () => {
vi.useFakeTimers()
installRunner(() => new Promise(() => undefined))
const answer = answerAgentToolPluginHooks('claude', PRE, DECIDES, OWNER)
await vi.advanceTimersByTimeAsync(6_000)
await expect(answer).resolves.toBeNull()
})
})
@@ -1,40 +0,0 @@
import { describe, expect, it } from 'vitest'
import { isExecutionPolicyBlocked } from './windows-powershell-execution-policy'
/** Captured PowerShell errors, preserving console hard wrapping. */
const POLICY_BLOCKED_RESTRICTED = [
'File C:\\Temp\\runtime.ps1 cannot be loaded because running scripts is disabled on this system. For more ',
'information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.',
' + CategoryInfo : SecurityError: (:) [], ParentContainsErrorRecordException',
' + FullyQualifiedErrorId : UnauthorizedAccess'
].join('\r\n')
const POLICY_BLOCKED_REMOTE_SIGNED = [
'File C:\\Temp\\runtime.ps1 cannot be loaded. The file ',
'C:\\Temp\\runtime.ps1 is not digitally signed. You cannot run this script on the current system. For more ',
'information about running scripts and setting execution policy, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.',
' + CategoryInfo : SecurityError: (:) [], ParentContainsErrorRecordException',
' + FullyQualifiedErrorId : UnauthorizedAccess'
].join('\r\n')
/** No execution policy involved: .NET refusing a file the process may not read. */
const GENUINE_ACCESS_DENIED = [
'Exception calling "ReadAllText" with "1" argument(s): "Access to the path \'C:\\Windows\\System32\\config\\SAM\' is denied."',
'At C:\\Temp\\runtime.ps1:1 char:1',
'+ [System.IO.File]::ReadAllText("C:\\Windows\\System32\\config\\SAM")',
'+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~',
' + CategoryInfo : NotSpecified: (:) [], MethodInvocationException',
' + FullyQualifiedErrorId : UnauthorizedAccessException'
].join('\r\n')
describe('isExecutionPolicyBlocked', () => {
it('recognises a policy block under either policy', () => {
expect(isExecutionPolicyBlocked(POLICY_BLOCKED_RESTRICTED)).toBe(true)
expect(isExecutionPolicyBlocked(POLICY_BLOCKED_REMOTE_SIGNED)).toBe(true)
})
it('does not read a plain access denial as a policy block', () => {
// The word boundary distinguishes a policy ID from UnauthorizedAccessException.
expect(isExecutionPolicyBlocked(GENUINE_ACCESS_DENIED)).toBe(false)
})
})
@@ -1,76 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
clearCrashBreadcrumbsForTest,
getCrashBreadcrumbSnapshot,
recordCoalescedCrashBreadcrumb,
recordCrashBreadcrumb
} from './crash-breadcrumb-store'
const COALESCE_WINDOW_MS = 30_000
const ORPHAN_KEY = 'terminal_safe_fit_retry_exhausted'
function recordOrphanCandidate(livePanes: number): void {
recordCoalescedCrashBreadcrumb({
name: ORPHAN_KEY,
data: { livePanes },
coalesceKey: ORPHAN_KEY,
minIntervalMs: COALESCE_WINDOW_MS
})
}
function resumeOrphanCandidate(livePanes: number): { suppressedSinceLast: number } | undefined {
return recordCoalescedCrashBreadcrumb({
name: ORPHAN_KEY,
data: { livePanes },
coalesceKey: ORPHAN_KEY,
minIntervalMs: COALESCE_WINDOW_MS
})
}
function orphanFromRing(): void {
for (let index = 0; index < 30; index += 1) {
recordCrashBreadcrumb(`renderer_error_${index}`, { index })
}
getCrashBreadcrumbSnapshot()
}
function expireWithUnrelatedKey(): void {
vi.advanceTimersByTime(COALESCE_WINDOW_MS + 1)
recordCoalescedCrashBreadcrumb({
name: 'agent_state_changed',
data: { agentType: 'claude', state: 'working' },
coalesceKey: 'agent:claude:working',
minIntervalMs: COALESCE_WINDOW_MS
})
}
describe('orphaned coalesced breadcrumb cleanup', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-07-22T12:00:00.000Z'))
})
afterEach(() => {
clearCrashBreadcrumbsForTest()
vi.useRealTimers()
})
it('materializes only repeats not already claimed by an earlier snapshot', () => {
recordOrphanCandidate(1)
recordOrphanCandidate(2)
const firstSnapshot = getCrashBreadcrumbSnapshot()
recordOrphanCandidate(3)
recordOrphanCandidate(4)
orphanFromRing()
expireWithUnrelatedKey()
expect(firstSnapshot[0]?.data).toEqual({ livePanes: 2, suppressedSinceLast: 1 })
const recovered = getCrashBreadcrumbSnapshot().find(
(breadcrumb) => breadcrumb.name === ORPHAN_KEY
)
expect(recovered?.data).toEqual({ livePanes: 4, suppressedSinceLast: 2 })
expect(resumeOrphanCandidate(5)).toEqual({ suppressedSinceLast: 0 })
})
})
@@ -1,83 +0,0 @@
import {
existsSync,
mkdtempSync,
readFileSync,
renameSync,
rmSync,
statSync,
utimesSync,
writeFileSync
} from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { createIntegrationStateFileCache } from './integration-state-file-cache'
let dir = ''
function tempFile(): string {
dir = mkdtempSync(join(tmpdir(), 'orca-state-file-cache-'))
return join(dir, 'state.json')
}
afterEach(() => {
if (dir) {
rmSync(dir, { recursive: true, force: true })
dir = ''
}
})
describe('createIntegrationStateFileCache', () => {
it('notices a same-size atomic replacement with the original modification time', () => {
const path = tempFile()
writeFileSync(path, 'old')
const time = new Date('2026-01-01T00:00:00Z')
utimesSync(path, time, time)
const cache = createIntegrationStateFileCache({
filePath: () => path,
readFromDisk: () => readBody(path)
})
expect(cache.get()).toBe('old')
const replacement = join(dir, 'replacement.json')
writeFileSync(replacement, 'new')
utimesSync(replacement, time, time)
renameSync(replacement, path)
expect(statSync(path).mtime.getTime()).toBe(time.getTime())
expect(cache.get()).toBe('new')
})
it('reloads when a file appears after an absent first read', () => {
const path = tempFile()
const cache = createIntegrationStateFileCache({
filePath: () => path,
readFromDisk: () => ({ present: fileExists(path) })
})
expect(cache.get()).toEqual({ present: false })
writeFileSync(path, 'now here')
expect(cache.get()).toEqual({ present: true })
})
it('reloads when the file is removed', () => {
const path = tempFile()
writeFileSync(path, 'a')
const cache = createIntegrationStateFileCache({
filePath: () => path,
readFromDisk: () => ({ present: fileExists(path) })
})
expect(cache.get()).toEqual({ present: true })
rmSync(path)
expect(cache.get()).toEqual({ present: false })
})
})
function readBody(path: string): string {
return readFileSync(path, 'utf-8')
}
function fileExists(path: string): boolean {
return existsSync(path)
}
@@ -1,79 +0,0 @@
import { afterEach, describe, expect, it } from 'vitest'
import { Session } from '../session'
function createMockSubprocess() {
let onData: ((data: string) => void) | null = null
return {
pid: 12345,
getForegroundProcess: (): string | null => null,
write(_data: string) {},
resize(_cols: number, _rows: number) {},
kill() {},
terminateOwnedTree: () => 'unavailable' as const,
forceKill() {},
signal(_sig: string) {},
onData(cb: (data: string) => void) {
onData = cb
},
onExit(_cb: (code: number) => void) {},
dispose() {},
simulateData(data: string) {
onData?.(data)
}
}
}
let session: Session | null = null
afterEach(() => {
session?.dispose()
session = null
})
function createSession(subprocess = createMockSubprocess()): Session {
session = new Session({
sessionId: 'pending-test',
cols: 80,
rows: 24,
subprocess,
shellReadySupported: false
})
return session
}
describe('Session pending output', () => {
it('records output, resize, and clear in application order', () => {
const subprocess = createMockSubprocess()
const live = createSession(subprocess)
subprocess.simulateData('before resize')
live.resize(100, 30)
subprocess.simulateData('after resize')
live.clearScrollback()
const take = live.takePendingOutput(false)
expect(take).not.toBeNull()
expect(take!.overflowed).toBe(false)
expect(take!.snapshot).toBeNull()
expect(take!.records).toEqual([
{ kind: 'output', data: 'before resize' },
{ kind: 'resize', cols: 100, rows: 30 },
{ kind: 'output', data: 'after resize' },
{ kind: 'clear' }
])
})
it('returns the snapshot and drops records in the same take when requested', () => {
const subprocess = createMockSubprocess()
const live = createSession(subprocess)
subprocess.simulateData('snapshot content\r\n')
const take = live.takePendingOutput(true)
expect(take!.records).toEqual([])
expect(take!.snapshot?.snapshotAnsi).toContain('snapshot content')
// Snapshot-covered records must not replay again on recovery.
const next = live.takePendingOutput(false)
expect(next!.records).toEqual([])
})
})
@@ -1,40 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
// English uses fallbacks; awaited non-English catalogs must load without entering the cold-start bundle.
vi.mock('electron', () => ({
app: {
getLocale: vi.fn(() => 'en-US')
}
}))
import { UI_LANGUAGE_ENGLISH } from '../../shared/i18n/ui-language'
import { mainI18n, setMainPluginLanguagePacks, setMainUiLanguage, translateMain } from './main-i18n'
import '../../shared/plugins/artifacts/plugin-language-pack-artifact'
describe('main-i18n lazy locale loading', () => {
afterEach(() => vi.restoreAllMocks())
beforeEach(async () => {
setMainPluginLanguagePacks([])
await setMainUiLanguage(UI_LANGUAGE_ENGLISH)
})
it('keeps a newer explicit language when system fallback catalog loading finishes late', async () => {
const { getSystemLanguageDetection } = await import('./system-language')
expect(getSystemLanguageDetection(['fr-FR'])?.locale).toBe('fr')
let finishLoad: () => void = () => {}
const load = vi.spyOn(mainI18n, 'loadLanguages').mockImplementationOnce(
() =>
new Promise<void>((resolve) => {
finishLoad = resolve
})
)
const fallback = setMainUiLanguage('system')
await vi.waitFor(() => expect(load).toHaveBeenCalledWith('fr'))
await setMainUiLanguage('en')
finishLoad()
await fallback
expect(mainI18n.language).toBe('en')
expect(translateMain('menu.file', 'File')).toBe('File')
})
})
-72
View File
@@ -1,72 +0,0 @@
import { ipcMain, type BrowserWindow } from 'electron'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { registerCredentialHandler, requestCredential } from './ssh-passphrase'
import { resetSshCredentialDeclinesForTests } from '../../ssh/authentication/ssh-credential-decline'
vi.mock('electron', () => ({
ipcMain: {
handle: vi.fn(),
removeHandler: vi.fn()
}
}))
function credentialWindow() {
return {
isDestroyed: () => false,
webContents: { send: vi.fn() }
} as unknown as BrowserWindow
}
describe('SSH credential requests', () => {
beforeEach(() => {
resetSshCredentialDeclinesForTests()
})
it('closes every other open prompt for the host the user cancelled', async () => {
registerCredentialHandler()
const handler = vi.mocked(ipcMain.handle).mock.calls.at(-1)![1]
const submit = (requestId: string, value: string | null): unknown =>
handler(Object.create(null), { requestId, value })
const window = credentialWindow()
const requestIds = (): string[] =>
vi
.mocked(window.webContents.send)
.mock.calls.flatMap(([channel, request]) =>
channel === 'ssh:credential-request' &&
request &&
typeof request === 'object' &&
'requestId' in request &&
typeof request.requestId === 'string'
? [request.requestId]
: []
)
const first = requestCredential(
() => window,
'target-1',
'password',
'host',
undefined,
new AbortController().signal
)
const queued = requestCredential(
() => window,
'target-1',
'password',
'host',
undefined,
new AbortController().signal
)
const otherHost = requestCredential(() => window, 'target-2', 'password', 'other')
const [firstId, queuedId, otherId] = requestIds()
await submit(firstId, null)
await expect(first).resolves.toBeNull()
await expect(queued).resolves.toBeNull()
expect(window.webContents.send).toHaveBeenCalledWith('ssh:credential-resolved', {
requestId: queuedId
})
await submit(otherId, 'secret')
await expect(otherHost).resolves.toBe('secret')
})
})
@@ -1,70 +0,0 @@
import { afterEach, expect, it } from 'vitest'
import { agentSessionFailureFact } from '../../../shared/agent-session/failures/agent-session-failure'
import { agentSessionFailureWords } from '../../../shared/agent-session/failures/agent-session-failure-words'
import { domainLifecycleFixture } from './journal-domain-lifecycle.test-fixture'
const cleanup: (() => void)[] = []
afterEach(() => cleanup.splice(0).forEach((close) => close()))
it('claims stopped history with the handover and releases it after an unwritten refusal', async () => {
const f = domainLifecycleFixture(cleanup)
const body = (text: string) => ({
kind: 'message' as const,
role: 'user' as const,
blocks: [{ type: 'text' as const, text }]
})
const handover = (clientMessageId: string) =>
f
.run({
kind: 'handover',
input: {
clientMessageId,
fence: 1,
turnScope: { kind: 'thread' },
body: body(clientMessageId)
}
})
.then((commit) => commit.value)
const refuse = (clientMessageId: string) =>
f.run({
kind: 'dispatch',
input: {
clientMessageId,
state: 'rejected',
fence: 1,
...agentSessionFailureWords(
agentSessionFailureFact('cancelled', { neverReachedAgent: true }),
{ surface: 'rejection' }
)
}
})
for (const clientMessageId of ['owed', 'carrier-a', 'carrier-b']) {
await f.run({
kind: 'submission',
input: {
clientMessageId,
payloadFingerprint: clientMessageId,
body: body(clientMessageId),
fence: 1,
handoverRecorded: true,
origin: 'client',
source: { kind: 'user' }
}
})
}
expect(await handover('owed')).toBeNull()
await refuse('owed')
expect(await handover('carrier-a')).toEqual({
messages: [{ clientMessageId: 'owed', words: 'owed' }],
covers: ['owed']
})
expect(await handover('carrier-b')).toBeNull()
await refuse('carrier-a')
expect(await handover('carrier-b')).toEqual({
messages: [
{ clientMessageId: 'owed', words: 'owed' },
{ clientMessageId: 'carrier-a', words: 'carrier-a' }
],
covers: ['owed', 'carrier-a']
})
})
@@ -1,61 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
classifyDispatchRejection,
DISPATCH_REJECTED_QUEUE_FULL
} from '../../../../shared/agent-session/requests/structured-agent-session-dispatch-rejection'
import {
applyJournalRow,
createJournalReducerState,
type JournalReducerState
} from './journal-reducer'
import type { JournalRow } from '../durable-rows/journal-row-schema'
const EPOCH = 'epoch-1'
function base(seq: number): { v: number; epoch: string; seq: number; fence: number; ts: number } {
return { v: 1, epoch: EPOCH, seq, fence: 1, ts: 1_000 + seq }
}
function fold(rows: JournalRow[]): JournalReducerState {
const state = createJournalReducerState('session-1', EPOCH)
for (const row of rows) {
applyJournalRow(state, row)
}
return state
}
describe('a rejected dispatch', () => {
const submission: JournalRow = {
kind: 'submission',
clientMessageId: 'cm_1',
payloadFingerprint: 'fp_1',
providerHandle: { kind: 'codex', threadId: 'thread-1' },
body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hi' }] },
...base(1)
}
it('keeps only the kind of a rejection fact it cannot place, so it reads as no verdict', () => {
const rejected = (rejection: unknown): JournalRow => {
const row: JournalRow = {
kind: 'dispatch',
clientMessageId: 'cm_1',
state: 'rejected',
providerItemId: null,
reason: DISPATCH_REJECTED_QUEUE_FULL,
...base(2)
}
return Object.assign(row, { rejection })
}
// Unknown typed facts must not fall back to conflicting reason markers.
const newer = fold([submission, rejected({ kind: 'futureKind', detail: 'x' })])
const settled = newer.submissions.get('cm_1')
expect(settled).toMatchObject({ dispatchState: 'rejected', rejection: { kind: 'futureKind' } })
expect(settled && classifyDispatchRejection(settled)).toEqual({
category: 'undelivered',
verdict: null
})
const malformed = fold([submission, rejected('queueFull')]).submissions.get('cm_1')
expect(malformed).not.toHaveProperty('rejection')
expect(malformed && classifyDispatchRejection(malformed)).toMatchObject({ kind: 'queueFull' })
})
})
@@ -1,64 +0,0 @@
import { afterEach, expect, it, vi } from 'vitest'
import { createJournalReducerState } from '../projection/journal-reducer'
import '../projection/journal-reducer-transition'
import '../input-order/journal-queued-row-index'
import './journal-queue-events'
import { QueuedMessageEditLeases } from './queued-message-edit-leases'
import '../input-order/journal-input-order'
import { nextEligibleQueuedCard } from './journal-queue-mail-eligibility'
import type { AgentJournalMessageItem } from '../../../../shared/agent-session/journal/agent-session-journal-types'
import type { QueuedMessageRow } from './queued-message-table'
const body: AgentJournalMessageItem = {
kind: 'message',
role: 'user',
blocks: [{ type: 'text', text: 'follow up' }]
}
function card(index: number, state: QueuedMessageRow['state'] = 'waiting'): QueuedMessageRow {
return {
messageId: `card-${index}`,
position: index,
body,
fingerprint: 'body',
state,
holdReason: null,
returnedReason: null,
returnedRejection: null,
consumedAs: null,
queuedAt: { epoch: 'epoch', sequence: 1 },
unattended: false
}
}
afterEach(() => vi.restoreAllMocks())
it('an edit lease on a skipped row bars the tail until its deadline', () => {
const state = createJournalReducerState('session', 'epoch')
state.queue.cards.set('card-1', card(1, 'returned'))
state.queue.cards.set('card-2', card(2))
state.queue.cards.set('card-3', { ...card(3), deliveryMode: 'steer' })
state.queuePauseMarks.cleared = { sequence: 2, operationId: 'clear', messageIds: ['card-2'] }
let now = 0
const leases = new QueuedMessageEditLeases(
() => [],
() => now,
(id) => state.queue.cards.get(id)
)
leases.acquire(
{ callerKey: 'person', editId: 'edit' },
{ messageId: 'card-2', fingerprint: 'body' }
)
const claim = () =>
nextEligibleQueuedCard({
state,
floor: null,
get: (id) => state.queue.cards.get(id) ?? null,
editHeld: (id) => leases.isHeld(id),
revisions: [leases.version()],
unavailable: undefined,
steer: true
})
expect(claim()).toBeNull()
now = 120_001
expect(claim()?.messageId).toBe('card-3')
leases.dispose()
})
@@ -1,59 +0,0 @@
import { afterEach, expect, it, vi } from 'vitest'
import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload'
import type { AgentPaneChange } from '../../../agent-hooks/observations/agent-transition-detector'
import { TerminalAgentTurnNews } from './terminal-agent-turn-news'
const paneKey = 'tab:11111111-1111-4111-8111-111111111111'
const workspace = { worktreeId: 'repo::/task', sshHostId: null }
afterEach(() => {
vi.useRealTimers()
})
it.each([false, true])(
'delivers an accepted finish after departure unless a new prompt supersedes it (new prompt: %s)',
(newPrompt) => {
vi.useFakeTimers()
let row: AgentStatusIpcPayload | null = {
paneKey,
worktreeId: workspace.worktreeId,
connectionId: null,
state: 'working',
agentType: 'claude',
prompt: 'finish task',
receivedAt: 1000,
stateStartedAt: 1000
}
const delivered: string[] = []
const news = new TerminalAgentTurnNews({
readHookRow: () => row,
prepare: ({ row: completed }) => completed.lastAssistantMessage ?? '',
deliver: (message) => delivered.push(message),
setTimer: (run, delayMs) => {
const timer = setTimeout(run, delayMs)
return { cancel: () => clearTimeout(timer) }
}
})
const observe = (
from: Extract<AgentPaneChange, { kind: 'moved' }>['from'],
to: Extract<AgentPaneChange, { kind: 'moved' }>['to'],
transition: Extract<AgentPaneChange, { kind: 'moved' }>['transition']
) => news.observe({ kind: 'moved', paneKey, workspace, from, to, transition, at: 2000 })
try {
news.observe({ kind: 'observed', paneKey, workspace, phase: 'working', at: 1000 })
row = { ...row, state: 'done', stateStartedAt: 2000, lastAssistantMessage: 'Finished.' }
observe('working', 'done', 'turn-finished')
row = null
observe('done', 'rest', null)
if (newPrompt) {
observe('rest', 'working', 'prompt-submitted')
}
vi.runAllTimers()
expect(delivered).toEqual(newPrompt ? [] : ['Finished.'])
vi.runAllTimers()
expect(delivered).toEqual(newPrompt ? [] : ['Finished.'])
} finally {
news.dispose()
}
}
)
@@ -1,59 +0,0 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it, vi } from 'vitest'
import type { PtyProcessInfo } from '../../../providers/pty/process-info'
import {
setupLayoutOwnerRuntime,
WORKTREE_ID
} from '../../orca-runtime-tests/orca-runtime-layout-owner-start-fixture'
import { committingSpawn } from '../../orca-runtime-tests/bind-first-pane.test-fixture'
vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true }))
// Paired desktops replay stable tab/leaf ids; durable closed-tab records must reject late retries.
function pairedDesktopCreate() {
const fixture = setupLayoutOwnerRuntime()
const live: PtyProcessInfo[] = []
fixture.runtime.setPtyController({
spawn: committingSpawn(fixture.runtime, fixture.spawn),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null,
listProcesses: vi.fn(async () => live)
})
const pane = { tabId: randomUUID(), leafId: randomUUID() }
const create = (reconcileExisting: boolean) =>
fixture.runtime.dedupeTerminalCreate(
'paired-desktop',
`id:${WORKTREE_ID}`,
'mutation-x',
reconcileExisting,
(selector, preAllocatedHandle) =>
fixture.runtime.createTerminal(selector, {
...pane,
...(preAllocatedHandle ? { preAllocatedHandle } : {})
})
)
return { ...fixture, live, pane, create }
}
describe('a paired desktop terminal.create replayed with its pane ids', () => {
it('is refused after another client closed its tab: nothing starts and no tab comes back', async () => {
const { runtime, spawn, session, pane, create } = pairedDesktopCreate()
await create(false)
expect(session().tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([pane.tabId])
expect(spawn).toHaveBeenCalledTimes(1)
await runtime.applyLayoutCommand({
type: 'closeTabs',
workspace: WORKTREE_ID,
tabIds: [pane.tabId],
recordClose: 'user'
})
expect(session().tabsByWorktree[WORKTREE_ID] ?? []).toEqual([])
await expect(create(true)).rejects.toThrow('tab_not_found')
expect(spawn).toHaveBeenCalledTimes(1)
expect(session().tabsByWorktree[WORKTREE_ID] ?? []).toEqual([])
})
})
@@ -1,57 +0,0 @@
/** Carry structured Node-download failure for the mirror offer; never infer it from message text. */
import { describe, expect, it, vi } from 'vitest'
import type { SshTarget } from '../../../shared/remote-runtime/ssh/ssh-types'
import { resolveHostServerOnConnect } from './ssh-host-server-on-connect'
import { hostServerDepsStub } from './testing/ssh-host-server-on-connect-test-deps'
import { unservedHostServerMessage } from './ssh-host-unserved-status'
import { NodeRuntimeUnreachableError } from '../../managed-server/install/remote-node-runtime-host-download'
const target: SshTarget = { id: 'ssh-1', label: 'Box', host: 'box', port: 22, username: 'me' }
function unreachable(mirror?: 'unset' | 'tried' | 'unsupported'): NodeRuntimeUnreachableError {
return new NodeRuntimeUnreachableError(
'https://nodejs.org/dist/v24.21.0/node-v24.21.0-linux-x64.tar.gz',
'its downloads failed (curl: (7) Failed to connect)',
'/cache/node/archives/node.tar.gz',
new Error('net::ERR_CONNECTION_REFUSED'),
mirror
)
}
async function deployFailingWith(error: unknown) {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
try {
const result = await resolveHostServerOnConnect(
target,
hostServerDepsStub({
isEmptyHost: () => true,
deploy: async () => {
throw error
}
})
)
if (result.route !== 'unserved') {
throw new Error('expected unserved')
}
return result
} finally {
warn.mockRestore()
}
}
describe('a managed-server setup that could not download Node', () => {
it('reads the flag through a wrapping install error', async () => {
const wrapped = new Error('Installing the runtime failed', { cause: unreachable('unset') })
await expect(deployFailingWith(wrapped)).resolves.toMatchObject({
nodeDownloadBlocked: { mirror: 'unset' }
})
})
it('never reads the flag from message text', async () => {
const lookalike = new Error(unreachable('unset').message)
const result = await deployFailingWith(lookalike)
expect(result).not.toHaveProperty('nodeDownloadBlocked')
expect(unservedHostServerMessage(result)).toContain('Try connecting again')
})
})
@@ -1,62 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import {
CANCELED_GENERATION_RESULT,
cancelLocalGeneration,
clearLocalGenerationCancelToken,
localGenerationLaneKey,
runCancelableLocalGeneration,
setLocalGenerationCancelToken
} from './source-control-generation-lanes'
describe('runCancelableLocalGeneration', () => {
it('settles as canceled when cancel lands before the agent spawns', async () => {
const preparation = Promise.withResolvers<void>()
const spawn = vi.fn()
const run = runCancelableLocalGeneration('commit-message', '/repo', async (isCanceled) => {
await preparation.promise
if (isCanceled()) {
return 'skipped'
}
spawn()
return 'spawned'
})
cancelLocalGeneration('commit-message', '/repo')
await expect(run).resolves.toBe(CANCELED_GENERATION_RESULT)
preparation.resolve()
await preparation.promise
expect(spawn).not.toHaveBeenCalled()
})
it('hands cancel to the token a spawned agent installs over the pending one', async () => {
const laneKey = localGenerationLaneKey('commit-message', '/repo')
const killAgent = vi.fn()
const agent = Promise.withResolvers<string>()
const run = runCancelableLocalGeneration('commit-message', '/repo', () => {
setLocalGenerationCancelToken(laneKey, killAgent)
return agent.promise.finally(() => clearLocalGenerationCancelToken(laneKey, killAgent))
})
cancelLocalGeneration('commit-message', '/repo')
expect(killAgent).toHaveBeenCalledOnce()
agent.resolve('agent canceled')
await expect(run).resolves.toBe('agent canceled')
})
it('leaves a newer request cancelable after an older one on the lane finishes', async () => {
const older = runCancelableLocalGeneration('commit-message', '/repo', async () => 'older')
const newerPreparation = Promise.withResolvers<string>()
const newer = runCancelableLocalGeneration(
'commit-message',
'/repo',
() => newerPreparation.promise
)
await expect(older).resolves.toBe('older')
cancelLocalGeneration('commit-message', '/repo')
await expect(newer).resolves.toBe(CANCELED_GENERATION_RESULT)
newerPreparation.resolve('late')
})
})
@@ -1,55 +0,0 @@
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, describe, expect, it } from 'vitest'
import { runProcessSync } from '@orca/process-host'
import { WSL_MANAGED_CLI_PATH_RESTORE } from './wsl-managed-cli-path-restore'
const posix = process.platform !== 'win32'
const hasZsh = posix && runProcessSync({ program: 'sh', args: ['-c', 'command -v zsh'] }).code === 0
const root = posix ? mkdtempSync(join(tmpdir(), 'orca managed cli restore ')) : ''
if (posix) {
writeFileSync(join(root, 'orca-dev'), '#!/bin/sh\n')
chmodSync(join(root, 'orca-dev'), 0o755)
writeFileSync(join(root, 'orca-ide'), '#!/bin/sh\n')
chmodSync(join(root, 'orca-ide'), 0o644)
}
afterAll(() => {
if (root) {
rmSync(root, { recursive: true, force: true })
}
})
// Mirrors how each shell embeds the snippet: bash rcfile top level, zsh first-prompt hook.
const SHELLS = [
{ name: 'bash', enabled: posix, args: (body: string) => ['--norc', '--noprofile', '-uc', body] },
{
name: 'zsh',
enabled: hasZsh,
args: (body: string) => ['-fuc', `__orca_hook() {\n emulate -L zsh\n${body}\n}\n__orca_hook`]
}
] as const
function run(
shell: (typeof SHELLS)[number],
env: Record<string, string>
): { code: number | null; stdout: string; stderr: string } {
return runProcessSync({
program: shell.name,
args: shell.args(`${WSL_MANAGED_CLI_PATH_RESTORE}\nprintf '%s' "$PATH"`),
env: { PATH: '/usr/bin:/bin', ...env }
})
}
describe.each(SHELLS)('WSL_MANAGED_CLI_PATH_RESTORE in $name', (shell) => {
it.skipIf(!shell.enabled)('leads PATH with a directory holding an executable CLI', () => {
const result = run(shell, { ORCA_WSL_CLI_DIR: root, ORCA_CLI_COMMAND: 'orca-dev' })
expect(result).toMatchObject({ code: 0, stdout: `${root}:/usr/bin:/bin`, stderr: '' })
})
it.skipIf(!shell.enabled)('warns and keeps PATH when the CLI cannot run', () => {
const result = run(shell, { ORCA_WSL_CLI_DIR: root, ORCA_CLI_COMMAND: 'orca-ide' })
expect(result).toMatchObject({ code: 0, stdout: '/usr/bin:/bin' })
expect(result.stderr).toContain('Orca CLI unavailable')
})
})
@@ -1,69 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
__resetWslFishHistoryCleanups,
deleteWslFishHistoryFile,
flushWslFishHistoryCleanups
} from './wsl-fish-history-cleanup'
const okResult = { environmentResolved: true, code: 0, stdout: '', stderr: '', timedOut: false }
const running = async (): Promise<boolean> => true
beforeEach(() => {
__resetWslFishHistoryCleanups()
})
afterEach(async () => {
await flushWslFishHistoryCleanups()
__resetWslFishHistoryCleanups()
})
describe('deleteWslFishHistoryFile', () => {
it('rejects an unsafe session before spawning', async () => {
const run = vi.fn()
await deleteWslFishHistoryFile('Ubuntu', '../../user-history', run, running)
expect(run).not.toHaveBeenCalled()
})
it('coalesces concurrent requests for the same distro and session', async () => {
let settle!: () => void
const run = vi.fn().mockReturnValue(
new Promise((resolve) => {
settle = () => resolve(okResult)
})
)
const session = 'orca_0123456789abcdef'
const first = deleteWslFishHistoryFile('Ubuntu', session, run, running)
const second = deleteWslFishHistoryFile('Ubuntu', session, run, running)
expect(second).toBe(first)
await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1))
settle()
await Promise.all([first, second])
})
it('permits a retry once a failed cleanup settles', async () => {
const run = vi
.fn()
.mockRejectedValueOnce(new Error('distro offline'))
.mockResolvedValue(okResult)
const session = 'orca_0123456789abcdef'
await expect(deleteWslFishHistoryFile('Ubuntu', session, run, running)).rejects.toThrow(
'distro offline'
)
await expect(deleteWslFishHistoryFile('Ubuntu', session, run, running)).resolves.toBe('deleted')
expect(run).toHaveBeenCalledTimes(2)
})
it('does not spawn into a stopped distro and reports it for a later retry', async () => {
const run = vi.fn().mockResolvedValue(okResult)
await expect(
deleteWslFishHistoryFile('Ubuntu', 'orca_0123456789abcdef', run, async () => false)
).resolves.toBe('distro-stopped')
expect(run).not.toHaveBeenCalled()
})
})
@@ -1,187 +0,0 @@
// @vitest-environment happy-dom
import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import { useAppStore } from '@/store'
import { getDefaultSettings } from '../../../../shared/constants'
import { useAgentLaunchPickerInventory } from './use-agent-launch-picker-inventory'
import type { UseDetectedAgentsResult } from '@/hooks/useDetectedAgents'
import type { NewTabAgentMenuModel } from '../tab-bar/new-tab-agent-menu-model'
import {
loadHostStructuredAgents,
resetHostStructuredAgentsForTests
} from '@/runtime/native-chat/agent-catalogs/host-structured-agents'
import { STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY as REGISTERED } from '../../../../shared/agent-session/structured-agent-session-surface-capabilities'
import { TEST_REPO } from '@/store/repos/repo.test-fixture'
const transport = vi.hoisted(() => ({ call: vi.fn(), rpc: vi.fn(), defaults: vi.fn() }))
vi.mock('@/runtime/native-chat/requests/structured-agent-session-call', () => ({
callStructuredAgentSession: transport.call
}))
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc: transport.rpc }))
vi.mock('@/runtime/agent-launch-settings/agent-launch-settings-transport', () => ({
readHostAgentLaunchDefaults: transport.defaults
}))
const initial = useAppStore.getState()
const previousApi = Object.getOwnPropertyDescriptor(window, 'api')
afterEach(() => {
cleanup()
useAppStore.setState(initial, true)
resetHostStructuredAgentsForTests()
vi.resetAllMocks()
if (previousApi) {
Object.defineProperty(window, 'api', previousApi)
} else {
Reflect.deleteProperty(window, 'api')
}
})
const detection: UseDetectedAgentsResult = {
detectedIds: ['codex'],
isLoading: false,
isRefreshing: false,
detectionFailed: false,
needsServerUpdate: false,
refresh: async () => ['codex']
}
it('reads a paired unknown-platform catalog before launch defaults and keeps it after defaults fail', async () => {
useAppStore.setState({ settings: getDefaultSettings('/synthetic') })
transport.rpc.mockResolvedValue({ agents: [] })
await loadHostStructuredAgents('runtime:unknown-platform', [REGISTERED], 'server-runtime')
const defaults = Promise.withResolvers<never>()
transport.defaults.mockReturnValue(defaults.promise)
transport.call.mockResolvedValue({
origin: 'probe',
fetchedAt: 1,
models: [{ id: 'server-only', label: 'Server', isDefault: false, efforts: [] }]
})
const model: NewTabAgentMenuModel = {
state: 'settled',
rows: [{ agent: 'codex', kind: 'cli' }],
detection,
pickerContext: {
workspace: {
kind: 'git-worktree',
repoId: 'future',
executionHostId: 'runtime:unknown-platform'
},
executionHostId: 'runtime:unknown-platform',
runtimeId: 'server-runtime',
settings: null,
key: 'unknown-platform'
}
}
const hook = renderHook(() => useAgentLaunchPickerInventory(undefined, model, true))
await waitFor(() =>
expect(hook.result.current[0]).toMatchObject({
catalogRead: 'settled',
defaultsPending: true,
catalog: { models: [{ id: 'server-only' }] }
})
)
await act(async () => {
defaults.reject(new Error('defaults offline'))
})
expect(hook.result.current[0]).toMatchObject({
catalogRead: 'settled',
catalog: { models: [{ id: 'server-only' }] }
})
})
it('reads the structured host list for a local UNC workspace instead of gating on its terminal route', async () => {
Object.defineProperty(window, 'api', {
configurable: true,
value: { platform: { get: () => ({ platform: 'win32' }) } }
})
useAppStore.setState({
settings: getDefaultSettings('/synthetic'),
repos: [
{
...TEST_REPO,
id: 'unc',
path: '\\\\wsl.localhost\\Ubuntu\\home\\app',
executionHostId: 'local'
}
]
})
transport.call.mockResolvedValue({
origin: 'probe',
fetchedAt: 1,
models: [{ id: 'host-only', label: 'Host', isDefault: false, efforts: [] }]
})
const model: NewTabAgentMenuModel = {
state: 'settled',
rows: [{ agent: 'codex', kind: 'cli' }],
detection,
pickerContext: {
workspace: { kind: 'git-worktree', repoId: 'unc' },
executionHostId: 'local',
settings: {},
key: 'local-unc'
}
}
const hook = renderHook(() => useAgentLaunchPickerInventory(undefined, model, true))
await waitFor(() =>
expect(hook.result.current[0]).toMatchObject({
catalogRead: 'settled',
catalog: { models: [{ id: 'host-only' }] }
})
)
})
it('reloads paired launch defaults when reopening while the old catalog request drains', async () => {
useAppStore.setState({ settings: getDefaultSettings('/synthetic') })
const catalog = Promise.withResolvers<never>()
const admitted = Promise.withResolvers<void>()
const defaults = Promise.withResolvers<{
settings: { agentDefaultArgs: { codex: string } }
structuredKnown: boolean
}>()
transport.call.mockImplementation(() => {
admitted.resolve()
return catalog.promise
})
transport.defaults.mockReturnValueOnce(defaults.promise).mockResolvedValue({
settings: {
agentDefaultArgs: { codex: '--add-dir fresh' },
nativeChatSessionOptions: {
codex: { model: 'fresh-default', valuesByModel: { 'fresh-default': { effort: 'high' } } }
}
},
structuredKnown: true
})
const model: NewTabAgentMenuModel = {
state: 'settled',
rows: [{ agent: 'codex', kind: 'cli' }],
detection,
pickerContext: {
workspace: { kind: 'floating', executionHostId: 'runtime:defaults-reopen' },
executionHostId: 'runtime:defaults-reopen',
runtimeId: 'defaults-server',
settings: null,
key: 'defaults-reopen'
}
}
const hook = renderHook(({ open }) => useAgentLaunchPickerInventory(undefined, model, open), {
initialProps: { open: true }
})
await act(async () => admitted.promise)
hook.rerender({ open: false })
await act(async () => {
defaults.resolve({
settings: { agentDefaultArgs: { codex: '--add-dir old' } },
structuredKnown: true
})
})
hook.rerender({ open: true })
try {
await waitFor(() =>
expect(hook.result.current[0]).toMatchObject({
defaultsPending: false,
arguments: '--add-dir fresh',
structured: { model: 'fresh-default', options: { effort: 'high' } }
})
)
} finally {
hook.unmount()
await act(async () => catalog.reject(new Error('closed catalog')))
}
})
@@ -1,167 +0,0 @@
// @vitest-environment happy-dom
import { act, renderHook } from '@testing-library/react'
import { Virtualizer } from '@tanstack/react-virtual'
import { createProgrammaticScrollMarks } from '@/hooks/programmatic-scroll-marks'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { MarkdownPreviewDocumentClient } from '../document-worker/markdown-preview-document-client'
import type { MarkdownPreviewDocumentMatch } from '../document-worker/markdown-preview-document-types'
import { useMarkdownPreviewSearchReveal } from './use-markdown-preview-search-reveal'
function setup() {
const root = document.createElement('div')
const input = document.createElement('input')
root.append(input)
const client = new MarkdownPreviewDocumentClient(
{ postMessage: vi.fn(), terminate: vi.fn(), onmessage: null, onerror: null },
vi.fn()
)
const virtualizer = new Virtualizer<HTMLDivElement, HTMLDivElement>({
count: 2,
getScrollElement: () => root,
estimateSize: () => 100,
scrollToFn: () => {},
observeElementRect: () => () => {},
observeElementOffset: () => () => {},
initialRect: { width: 100, height: 100 }
})
const scroll = vi.spyOn(virtualizer, 'scrollToIndex')
const options = {
client,
blocks: null,
components: {},
viewportReady: false,
rootRef: { current: root },
bodyRef: { current: root },
virtualizer,
scrollMarks: createProgrammaticScrollMarks(),
searchInstance: {}
}
const initialProps: { activeMatch: MarkdownPreviewDocumentMatch | undefined; query: string } = {
activeMatch: undefined,
query: 'needle'
}
const hook = renderHook(
({
activeMatch,
query
}: {
activeMatch: MarkdownPreviewDocumentMatch | undefined
query: string
}) => useMarkdownPreviewSearchReveal({ ...options, activeMatch, query }),
{ initialProps }
)
return { ...hook, root, input, scroll, client }
}
afterEach(() => vi.unstubAllGlobals())
describe('virtual Find navigation ownership', () => {
it.each(['wheel', 'touchmove', 'pointerdown', 'keydown'])(
'lets %s input cancel a result before worker blocks arrive, while Next still works',
(type) => {
const { root, scroll, rerender, unmount, client } = setup()
act(() =>
root.dispatchEvent(
type === 'keydown'
? new KeyboardEvent(type, { key: 'PageDown', bubbles: true })
: new Event(type, { bubbles: true })
)
)
const first = { block: 0, occurrence: 0 }
rerender({ activeMatch: first, query: 'needle' })
expect(scroll).not.toHaveBeenCalled()
rerender({ activeMatch: { block: 1, occurrence: 0 }, query: 'needle' })
expect(scroll).toHaveBeenCalledExactlyOnceWith(1, { align: 'center' })
unmount()
client.close()
}
)
it('lets explicit Next reveal a single match after its initial result was cancelled', () => {
const { root, scroll, rerender, result, unmount, client } = setup()
act(() => root.dispatchEvent(new Event('wheel')))
rerender({ activeMatch: { block: 0, occurrence: 0 }, query: 'needle' })
expect(scroll).not.toHaveBeenCalled()
act(() => result.current())
expect(scroll).toHaveBeenCalledExactlyOnceWith(0, { align: 'center' })
unmount()
client.close()
})
it('keeps query editing independent of viewport scroll input and cleans up listeners', () => {
const { root, input, scroll, rerender, unmount, client } = setup()
const remove = vi.spyOn(root, 'removeEventListener')
act(() => input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Home', bubbles: true })))
rerender({ activeMatch: { block: 1, occurrence: 0 }, query: 'needle' })
expect(scroll).toHaveBeenCalledExactlyOnceWith(1, { align: 'center' })
unmount()
for (const type of ['wheel', 'touchmove', 'pointerdown', 'keydown']) {
expect(remove.mock.calls.some(([name]) => name === type)).toBe(true)
}
client.close()
})
})
describe('Find ranges after rendered content changes', () => {
it('repaints replaced code without taking navigation back from manual scrolling', () => {
const registry = new Map<string, Set<Range>>()
vi.stubGlobal('CSS', { highlights: registry })
vi.stubGlobal('Highlight', Set)
const root = document.createElement('div')
const block = document.createElement('div')
block.dataset.previewBlockIndex = '0'
const code = document.createElement('code')
code.textContent = 'const needle = 42'
block.append(code)
root.append(block)
const client = new MarkdownPreviewDocumentClient(
{ postMessage: vi.fn(), terminate: vi.fn(), onmessage: null, onerror: null },
vi.fn()
)
const virtualizer = new Virtualizer<HTMLDivElement, HTMLDivElement>({
count: 1,
getScrollElement: () => root,
estimateSize: () => 100,
scrollToFn: () => {},
observeElementRect: () => () => {},
observeElementOffset: () => () => {},
initialRect: { width: 100, height: 400 }
})
vi.spyOn(virtualizer, 'scrollToIndex').mockImplementation(() => {})
vi.spyOn(root, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 100, 400))
const bounds = vi.spyOn(Range.prototype, 'getBoundingClientRect')
bounds.mockReturnValue(new DOMRect(0, 120, 80, 20))
const scroll = vi.spyOn(root, 'scrollTo').mockImplementation(() => {})
const options = {
client,
activeMatch: { block: 0, occurrence: 0 },
query: 'const needle',
blocks: [],
viewportReady: true,
rootRef: { current: root },
bodyRef: { current: root },
virtualizer,
scrollMarks: createProgrammaticScrollMarks(),
searchInstance: {}
}
const { rerender, unmount } = renderHook(
({ components }) => useMarkdownPreviewSearchReveal({ ...options, components }),
{ initialProps: { components: {} } }
)
const before = [...(registry.get('markdown-preview-search-active-match') ?? [])][0]
expect(before?.toString()).toBe('const needle')
act(() => root.dispatchEvent(new Event('wheel')))
const replacement = document.createElement('code')
replacement.textContent = code.textContent
code.replaceWith(replacement)
rerender({ components: {} })
const after = [...(registry.get('markdown-preview-search-active-match') ?? [])][0]
expect(after?.toString()).toBe('const needle')
expect(after?.startContainer).toBe(replacement.firstChild)
expect(after).not.toBe(before)
expect(scroll).toHaveBeenCalledOnce()
unmount()
client.close()
bounds.mockRestore()
})
})
@@ -1,225 +0,0 @@
// @vitest-environment happy-dom
import { act, createElement, useState } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { _resetPairedMobileDevicesCacheForTests } from './paired-mobile-devices'
import type { StepIndex } from './MobileHero'
const mocks = vi.hoisted(() => ({
listDevices: vi.fn(),
revokeDevice: vi.fn(),
toastError: vi.fn(),
toastSuccess: vi.fn()
}))
vi.mock('sonner', () => ({
toast: {
error: mocks.toastError,
success: mocks.toastSuccess
}
}))
// Disable polling to isolate the listDevices calls made directly by this hook.
vi.mock('./pairing/mobile-pairing-device-polling', () => ({
useMobilePairingDevicePolling: (): void => {}
}))
import { useMobilePagePairedDevices } from './use-mobile-page-paired-devices'
type HookApi = ReturnType<typeof useMobilePagePairedDevices>
let latest: HookApi | null = null
let latestStep: StepIndex | null = null
function Probe(): null {
const [stepIdx, setStepIdx] = useState<StepIndex>(0)
latestStep = stepIdx
latest = useMobilePagePairedDevices({ stepIdx, setStepIdx })
return null
}
const mountedRoots: Root[] = []
function device(deviceId: string): {
deviceId: string
name: string
pairedAt: number
lastSeenAt: number
} {
return { deviceId, name: deviceId, pairedAt: 1, lastSeenAt: 2 }
}
async function renderProbe(): Promise<void> {
const container = document.createElement('div')
document.body.appendChild(container)
const root = createRoot(container)
mountedRoots.push(root)
await act(async () => {
root.render(createElement(Probe))
})
}
async function unmountProbes(): Promise<void> {
await act(async () => {
for (const root of mountedRoots.splice(0)) {
root.unmount()
}
})
}
describe('useMobilePagePairedDevices', () => {
beforeEach(() => {
vi.clearAllMocks()
latest = null
latestStep = null
_resetPairedMobileDevicesCacheForTests()
Object.defineProperty(window, 'api', {
configurable: true,
value: {
mobile: {
listDevices: mocks.listDevices,
revokeDevice: mocks.revokeDevice
}
}
})
})
afterEach(async () => {
await unmountProbes()
document.body.innerHTML = ''
})
it('returns to the paired summary from step 0 while devices exist', async () => {
mocks.listDevices.mockResolvedValue({ devices: [device('phone-1')] })
await renderProbe()
await vi.waitFor(() => expect(latest?.stage).toBe('paired'))
await act(async () => {
latest?.enterFlow()
})
expect(latest?.stage).toBe('flow')
await act(async () => {
latest?.handleBack()
})
expect(latest?.stage).toBe('paired')
})
it('returns to intro from step 0 when no devices exist', async () => {
mocks.listDevices.mockResolvedValue({ devices: [] })
await renderProbe()
await vi.waitFor(() => expect(latest?.stage).toBe('intro'))
await act(async () => {
latest?.enterFlow()
})
expect(latest?.stage).toBe('flow')
await act(async () => {
latest?.handleBack()
})
expect(latest?.stage).toBe('intro')
})
it('steps back to step 0 from step 1 without leaving the flow', async () => {
mocks.listDevices.mockResolvedValue({ devices: [device('phone-1')] })
await renderProbe()
await vi.waitFor(() => expect(latest?.stage).toBe('paired'))
await act(async () => {
latest?.pairAnotherDevice()
})
expect(latestStep).toBe(1)
expect(latest?.stage).toBe('flow')
await act(async () => {
latest?.handleBack()
})
expect(latestStep).toBe(0)
expect(latest?.stage).toBe('flow')
})
it('keeps the device and shows an error when revoke returns revoked:false', async () => {
mocks.listDevices.mockResolvedValue({ devices: [device('phone-1')] })
mocks.revokeDevice.mockResolvedValue({ revoked: false })
await renderProbe()
await vi.waitFor(() => expect(latest?.stage).toBe('paired'))
await act(async () => {
await latest?.revokeDevice('phone-1')
})
expect(mocks.toastError).toHaveBeenCalledTimes(1)
expect(mocks.toastSuccess).not.toHaveBeenCalled()
expect(mocks.listDevices).toHaveBeenCalledTimes(1)
expect(latest?.devices.map((d) => d.deviceId)).toEqual(['phone-1'])
})
it('routes to intro after revoking the last device', async () => {
mocks.listDevices
.mockResolvedValueOnce({ devices: [device('phone-1')] })
.mockResolvedValueOnce({ devices: [] })
mocks.revokeDevice.mockResolvedValue({ revoked: true })
await renderProbe()
await vi.waitFor(() => expect(latest?.stage).toBe('paired'))
await act(async () => {
await latest?.revokeDevice('phone-1')
})
expect(mocks.revokeDevice).toHaveBeenCalledWith({ deviceId: 'phone-1' })
expect(mocks.toastSuccess).toHaveBeenCalledTimes(1)
await vi.waitFor(() => expect(latest?.stage).toBe('intro'))
expect(latest?.devices).toEqual([])
})
it('optimistically drops the device and still succeeds when the post-revoke refresh fails', async () => {
mocks.listDevices
.mockResolvedValueOnce({ devices: [device('phone-1')] })
.mockRejectedValueOnce(new Error('refresh failed'))
mocks.revokeDevice.mockResolvedValue({ revoked: true })
await renderProbe()
await vi.waitFor(() => expect(latest?.stage).toBe('paired'))
await act(async () => {
await latest?.revokeDevice('phone-1')
})
// A failed reload cannot undo server-side revocation; report success and remove the device optimistically.
expect(mocks.toastSuccess).toHaveBeenCalledTimes(1)
expect(mocks.toastError).not.toHaveBeenCalled()
await vi.waitFor(() => expect(latest?.devices).toEqual([]))
await vi.waitFor(() => expect(latest?.stage).toBe('intro'))
})
it('issues one revoke call for a rapid double-click', async () => {
mocks.listDevices.mockResolvedValue({ devices: [device('phone-1')] })
let releaseRevoke: (() => void) | null = null
mocks.revokeDevice.mockImplementation(
() =>
new Promise((resolve) => {
releaseRevoke = () => resolve({ revoked: true })
})
)
await renderProbe()
await vi.waitFor(() => expect(latest?.stage).toBe('paired'))
await act(async () => {
void latest?.revokeDevice('phone-1')
void latest?.revokeDevice('phone-1')
})
expect(mocks.revokeDevice).toHaveBeenCalledTimes(1)
await act(async () => {
releaseRevoke?.()
})
})
})
@@ -1,169 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { Repo } from '../../../../../../shared/repository/repo-types'
import { parseGitHubIssueOrPRLink } from '../../../../../../shared/github/repositories/links'
import { clearRepoSlugCacheValues } from '@/lib/workspace/catalog/repo-slug-cache'
const mocks = await vi.hoisted(async () => {
const { createStore } = await import('zustand/vanilla')
const store = createStore<{ repos: Repo[] }>(() => ({ repos: [] }))
return {
store,
get repos() {
return store.getState().repos
},
set repos(repos: Repo[]) {
store.setState({ repos })
},
slugs: new Map<string, string | null>(),
lookup: vi.fn()
}
})
vi.mock('@/store/index', () => ({
useAppStore: mocks.store
}))
vi.mock('@/lib/workspace/catalog/repo-slug-index', async () => {
const { rememberRepoSlug, repoSlugCacheKey } =
await import('@/lib/workspace/catalog/repo-slug-cache')
return {
resolveRepoSlug: async (repo: Repo) => {
const slug = mocks.slugs.get(repo.id) ?? null
const key = repoSlugCacheKey(repo)
if (key) {
rememberRepoSlug(key, slug)
}
return slug
}
}
})
vi.mock('@/lib/work-items/github/github-work-item-source-lookup', () => ({
lookupGitHubWorkItemByOwnerRepoForSource: mocks.lookup
}))
const { githubPreviewRouteCandidates, pickGitHubPreviewRouteRepo } =
await import('./native-chat-github-route-repo')
const { loadRoutedGitHubLinkPreview, readCachedRoutedGitHubLinkPreview } =
await import('./native-chat-github-link-preview')
function repo(id: string, extra: Partial<Repo> = {}): Repo {
return { id, path: `/src/${id}`, displayName: id, badgeColor: '', addedAt: 0, ...extra }
}
const privatePr = parseGitHubIssueOrPRLink('https://github.com/stablyai/orca-private/pull/685')!
describe('GitHub preview routing for a chat without a repo of its own', () => {
beforeEach(() => {
mocks.repos = []
mocks.slugs.clear()
clearRepoSlugCacheValues()
mocks.lookup.mockReset()
})
it('keeps git repos on the chat host only', () => {
const local = repo('local')
const remote = repo('ssh', { connectionId: 'box' })
const runtime = repo('rt', { executionHostId: 'runtime:env' })
const folder = repo('folder', { kind: 'folder' })
const all = [local, remote, runtime, folder]
expect(githubPreviewRouteCandidates(all, 'local')).toEqual([local])
expect(githubPreviewRouteCandidates(all, 'runtime:env')).toEqual([runtime])
})
it('separates endpoint-local repos from each nested SSH target on the same runtime', () => {
const local = repo('local')
const endpoint = repo('endpoint', { executionHostId: 'runtime:env' })
const targetT = repo('target-t', { executionHostId: 'runtime:env', connectionId: 'T' })
const targetU = repo('target-u', { executionHostId: 'runtime:env', connectionId: 'U' })
const directT = repo('direct-t', { connectionId: 'T' })
const candidates = [local, endpoint, targetT, targetU, directT]
expect(githubPreviewRouteCandidates(candidates, 'local')).toEqual([local])
expect(githubPreviewRouteCandidates(candidates, 'runtime:env')).toEqual([endpoint])
expect(githubPreviewRouteCandidates(candidates, 'nested:env/T')).toEqual([targetT])
expect(githubPreviewRouteCandidates(candidates, 'nested:env/U')).toEqual([targetU])
expect(githubPreviewRouteCandidates(candidates, 'ssh:T')).toEqual([directT])
})
it('prefers an exact clone before a fork upstream, then any repo on the GitHub host', () => {
const orca = repo('orca')
const fork = repo('fork', { upstream: { owner: 'stablyai', repo: 'orca-private' } })
const clone = repo('clone')
const ghes = repo('ghes')
const rows = [
{ repo: ghes, originKey: 'git.corp.example/team/app' },
{ repo: orca, originKey: 'stablyai/orca' },
{ repo: fork, originKey: 'me/orca-private' },
{ repo: clone, originKey: 'stablyai/orca-private' }
]
expect(pickGitHubPreviewRouteRepo(rows, privatePr)).toBe(clone)
expect(pickGitHubPreviewRouteRepo(rows.slice(0, 3), privatePr)).toBe(fork)
expect(pickGitHubPreviewRouteRepo(rows.slice(0, 2), privatePr)).toBe(orca)
expect(pickGitHubPreviewRouteRepo(rows.slice(0, 1), privatePr)).toBeNull()
expect(pickGitHubPreviewRouteRepo([{ repo: orca, originKey: null }], privatePr)).toBeNull()
})
it('uses the remaining repo after the repo that answered is removed', async () => {
const link = parseGitHubIssueOrPRLink('https://github.com/acme/private/pull/701')!
const alice = repo('alice', { ghAccount: { host: 'github.com', user: 'alice' } })
const bob = repo('bob', { ghAccount: { host: 'github.com', user: 'bob' } })
mocks.repos = [alice, bob]
mocks.slugs.set('alice', 'acme/alice')
mocks.slugs.set('bob', 'acme/bob')
mocks.lookup.mockImplementation(async ({ repoId }) => ({ title: `${repoId}'s preview` }))
await expect(loadRoutedGitHubLinkPreview('local', link)).resolves.toEqual({
title: "alice's preview"
})
mocks.repos = [bob]
expect(readCachedRoutedGitHubLinkPreview('local', link)).toBeNull()
await expect(loadRoutedGitHubLinkPreview('local', link)).resolves.toEqual({
title: "bob's preview"
})
})
it('leaves no cached preview when the last eligible repo is removed', async () => {
const link = parseGitHubIssueOrPRLink('https://github.com/acme/private/pull/702')!
mocks.repos = [repo('alice')]
mocks.slugs.set('alice', 'acme/alice')
mocks.lookup.mockResolvedValue({ title: "alice's preview" })
await expect(loadRoutedGitHubLinkPreview('local', link)).resolves.toEqual({
title: "alice's preview"
})
mocks.repos = []
expect(readCachedRoutedGitHubLinkPreview('local', link)).toBeNull()
await expect(loadRoutedGitHubLinkPreview('local', link)).resolves.toBeNull()
})
it('reloads a preview when the answering repo changes its account binding', async () => {
const link = parseGitHubIssueOrPRLink('https://github.com/acme/private/pull/703')!
const alice = repo('bound', { ghAccount: { host: 'github.com', user: 'alice' } })
mocks.repos = [alice]
mocks.slugs.set('bound', 'acme/bound')
mocks.lookup.mockResolvedValueOnce({ title: "alice's preview" }).mockResolvedValueOnce(null)
await expect(loadRoutedGitHubLinkPreview('local', link)).resolves.toEqual({
title: "alice's preview"
})
mocks.repos = [{ ...alice, ghAccount: { host: 'github.com', user: 'bob' } }]
expect(readCachedRoutedGitHubLinkPreview('local', link)).toBeNull()
await expect(loadRoutedGitHubLinkPreview('local', link)).resolves.toBeNull()
})
it('uses a newly resolved exact clone instead of the previously cached fallback', async () => {
const link = parseGitHubIssueOrPRLink('https://github.com/acme/private/pull/704')!
mocks.repos = [repo('alice'), repo('bob')]
mocks.slugs.set('bob', 'acme/bob')
mocks.lookup.mockImplementation(async ({ repoId }) => ({ title: `${repoId}'s preview` }))
await expect(loadRoutedGitHubLinkPreview('local', link)).resolves.toEqual({
title: "bob's preview"
})
mocks.slugs.set('alice', 'acme/private')
await expect(loadRoutedGitHubLinkPreview('local', link)).resolves.toEqual({
title: "alice's preview"
})
expect(readCachedRoutedGitHubLinkPreview('local', link)).toEqual({
title: "alice's preview"
})
})
})
@@ -1,170 +0,0 @@
// @vitest-environment happy-dom
import { act, useMemo } from 'react'
import { cleanup, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { createProgrammaticScrollMarks } from '@/hooks/programmatic-scroll-marks'
import type { VirtualizedScrollAnchor } from '@/hooks/useVirtualizedScrollAnchor'
import { supersedeVirtualizedScrollAnchorRestore } from '@/hooks/requestVirtualizedScrollAnchorRecord'
import { buildLineageRowProjection } from '../listing/lineage-row-projection'
import type { RenderRow } from '../listing/render-row'
import { repo, worktree } from '../grouping/worktree-list-groups-test-fixtures'
import { revealElementInScrollContainer } from '../navigation/worktree-sidebar-reveal'
import { useWorktreeListVirtualizer } from './use-virtualizer'
import { useVirtualRowMeasurementSync } from './use-row-measurement'
import { useWorktreeSidebarScrollSuppression } from './use-scroll-suppression'
const caches = vi.hoisted(() => ({ prCache: {}, issueCache: {} }))
vi.mock('@/store', () => ({
useAppStore: (selector: (state: typeof caches) => unknown) => selector(caches)
}))
beforeEach(() => {
vi.useFakeTimers()
vi.spyOn(window, 'requestAnimationFrame').mockReturnValue(1)
vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {})
})
afterEach(() => {
cleanup()
document.body.replaceChildren()
vi.restoreAllMocks()
vi.useRealTimers()
})
function setup() {
const scroller = document.createElement('div')
document.body.append(scroller)
Object.defineProperties(scroller, {
clientHeight: { value: 300 },
offsetHeight: { value: 300 },
offsetWidth: { value: 300 },
scrollHeight: { value: 10000 }
})
scroller.getBoundingClientRect = () => new DOMRect(0, 0, 300, 300)
scroller.scrollTo = (options?: ScrollToOptions | number) => {
if (typeof options === 'object' && options.behavior !== 'smooth') {
scroller.scrollTop = options.top ?? scroller.scrollTop
}
}
const rows: RenderRow[] = Array.from({ length: 60 }, (_, index) => ({
type: 'item',
rowKey: String(index),
sectionKey: 'all',
repo,
worktree: { ...worktree, id: String(index) },
depth: 0,
groupDepth: 0,
isLastLineageChild: false,
lineageChildCount: 0
}))
const scrollRef = { current: scroller }
const scrollOffsetRef = { current: 0 }
const scrollAnchorRef: { current: VirtualizedScrollAnchor } = { current: null }
const marks = createProgrammaticScrollMarks()
const view = renderHook(() => {
const projection = useMemo(() => buildLineageRowProjection(rows, 'none', false), [])
const virtualization = useWorktreeListVirtualizer({
renderRows: rows,
projection,
firstHeaderIndex: -1,
scrollRef,
scrollOffsetRef,
programmaticScrollMarks: marks
})
const input = useWorktreeSidebarScrollSuppression(scrollRef)
useVirtualRowMeasurementSync({
renderRows: rows,
virtualization,
scrollRef,
scrollOffsetRef,
scrollAnchorRef,
shouldSkipScrollAnchorRestore: input.shouldSkipScrollAnchorRestore
})
return { ...virtualization, input }
})
const mount = (index: number, height: number) => {
const element = document.createElement('div')
element.setAttribute('data-index', String(index))
element.setAttribute('data-worktree-virtual-row', '')
element.setAttribute('data-worktree-virtual-row-key', `wt:${index}`)
Object.defineProperty(element, 'offsetHeight', { value: height })
scroller.append(element)
act(() => view.result.current.virtualizer.measureElement(element))
return element
}
return { scroller, view, mount, scrollAnchorRef }
}
it('measures skipped mounted rows and new rows after late direct takeover without rewinding a stale offset', () => {
const { scroller, view, mount } = setup()
act(() => {
view.result.current.input.markRevealScroll(3000)
view.result.current.virtualizer.scrollToOffset(3000, { behavior: 'smooth' })
})
mount(0, 93)
vi.spyOn(window.performance, 'now').mockReturnValue(10000)
expect(view.result.current.input.shouldSkipScrollAnchorRestore()).toBe(false)
scroller.scrollTop = 50
act(() => view.result.current.input.markDirectScrollInput())
expect(scroller.scrollTop).toBe(50)
expect(view.result.current.virtualizer.measurementsCache[0].size).toBe(93)
mount(1, 115)
expect(view.result.current.virtualizer.measurementsCache[2].start).toBe(208)
})
it.each(['arrival', 'idle', 'replacement', 'no-op'] as const)(
'releases measurement after %s instead of leaving the smooth target active',
(completion) => {
const { scroller, view, mount } = setup()
act(() => view.result.current.virtualizer.scrollToOffset(3000, { behavior: 'smooth' }))
mount(0, 93)
act(() => {
if (completion === 'replacement') {
view.result.current.virtualizer.scrollToIndex(0, { behavior: 'auto' })
} else if (completion === 'no-op') {
view.result.current.virtualizer.scrollToOffset(0, { behavior: 'smooth' })
} else {
scroller.scrollTop = completion === 'arrival' ? 3000 : 80
scroller.dispatchEvent(new Event('scroll'))
if (completion === 'idle') {
vi.advanceTimersByTime(250)
}
}
})
expect(view.result.current.virtualizer.measurementsCache[0].size).toBe(93)
mount(1, 115)
expect(view.result.current.virtualizer.measurementsCache[2].start).toBe(208)
view.unmount()
scroller.scrollTop = 37
supersedeVirtualizedScrollAnchorRestore(scroller)
expect(scroller.scrollTop).toBe(37)
}
)
it.each(['virtualizer', 'native'] as const)(
'records later user movement back to a completed %s reveal destination',
(writer) => {
const { scroller, view, scrollAnchorRef } = setup()
const target = document.createElement('div')
target.getBoundingClientRect = () => new DOMRect(0, 350 - scroller.scrollTop, 300, 50)
scroller.append(target)
act(() => {
revealElementInScrollContainer(
scroller,
target,
'auto',
undefined,
writer === 'virtualizer'
? (top) => view.result.current.virtualizer.scrollToOffset(top, { behavior: 'auto' })
: undefined
)
scroller.dispatchEvent(new Event('scroll'))
})
expect(scroller.scrollTop).toBe(100)
act(() => {
scroller.scrollTop = 20
scroller.dispatchEvent(new Event('scroll'))
scroller.scrollTop = 100
scroller.dispatchEvent(new Event('scroll'))
})
expect(scrollAnchorRef.current?.offset).toBe(100)
}
)
@@ -1,193 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Terminal } from '@xterm/headless'
import { PtyStartupIngress } from '../../../../../shared/terminal/pty/ingress/pty-startup-ingress'
import { installTerminalCapabilityReplyHandlers } from './terminal-capability-replies'
import { createIpcPtyTransport } from '../pty-transport/ipc/pty-transport'
import type { PtyTransport } from '../pty-transport/pty-transport-types'
// Guard agent startup color replies against cooked-mode echo leaks; plain tabs and agent ingress must deliver replies without rendering them.
// opencode/OpenTUI's unconditional startup burst (BEL-terminated, not ST).
const OPENCODE_STARTUP_QUERY_BURST = '\x1b]10;?\x07\x1b]11;?\x07\x1b]4;0;?\x07'
// Orca's One Dark terminal theme — the values that appear in the leaked text.
const ORCA_TERMINAL_THEME = { foreground: '#ffffff', background: '#282c34' }
const OSC10_REPLY = '\x1b]10;rgb:ffff/ffff/ffff\x1b\\'
const OSC11_REPLY = '\x1b]11;rgb:2828/2c2c/3434\x1b\\'
const LEAKED_COLOR_REPLY_TEXT = /\d\d;rgb:[0-9a-f]{4}\//
const PTY_ID = 'pty-12112'
let dispatchPtyData: (payload: { id: string; data: string }) => void = () => {}
/** Model measured readline echo: unbound ESC ]/ST are swallowed while the reply payload renders as literal text. */
function readlineEchoOf(reply: string): string {
return reply.replaceAll('\x1b]', '\x07').replaceAll('\x1b\\', '')
}
type StartupTty = {
/** A writer (main ingress or renderer) pushes bytes at the PTY master. */
writeToPty: (data: string) => void
/** Bytes the querying program actually read. */
programInput: () => string
onPtyOutput: (sink: (data: string) => void) => void
emitStartupBurst: () => void
}
/** Model cooked tty during startup callback and raw tty immediately after; both arms share the same echo timing. */
function createStartupTty(): StartupTty {
let raw = false
let received = ''
let sink: (data: string) => void = () => {}
return {
writeToPty: (data) => {
if (raw) {
received += data
return
}
// ECHO copies master writes without consuming slave input; TCSANOW/TCSADRAIN preserve delivery, while TCSAFLUSH discards it.
received += data
sink(readlineEchoOf(data))
},
programInput: () => received,
onPtyOutput: (next) => {
sink = next
},
emitStartupBurst: () => {
sink(OPENCODE_STARTUP_QUERY_BURST)
// Enter raw mode just after the synchronous startup writer callback.
queueMicrotask(() => {
raw = true
})
}
}
}
function stubPtyApi(tty: StartupTty): void {
vi.stubGlobal('window', {
api: {
pty: {
spawn: vi.fn(async () => ({ id: PTY_ID })),
write: vi.fn((_id: string, data: string) => tty.writeToPty(data)),
resize: vi.fn(),
kill: vi.fn(async () => {}),
claimViewport: vi.fn(),
onData: (cb: (payload: { id: string; data: string }) => void) => {
dispatchPtyData = cb
return () => {}
},
onReplay: () => () => {},
onExit: () => () => {}
}
}
})
}
type RendererPane = {
transport: PtyTransport
deliver: (data: string) => void
renderedText: () => string
dispose: () => void
}
/** Real xterm + real capability-reply handlers + the real local IPC transport. */
async function createRendererPane(): Promise<RendererPane> {
const terminal = new Terminal({ cols: 80, rows: 24, allowProposedApi: true })
terminal.options.theme = { ...ORCA_TERMINAL_THEME }
const transport = createIpcPtyTransport({ worktreeId: 'wt-1', tabId: 'tab-1', leafId: 'pane:1' })
await transport.connect({
url: '',
cols: 80,
rows: 24,
callbacks: { onData: (data) => terminal.write(data) }
})
const handlers = installTerminalCapabilityReplyHandlers({
// SAFETY: headless xterm supplies the parser and event members used by capability replies.
terminal: terminal as never,
parser: terminal.parser,
// Matches pty-connection.ts: replies go out via sendInputImmediate.
sendInput: (data) => transport.sendInputImmediate(data),
isReplaying: () => false
})
return {
transport,
deliver: (data) => dispatchPtyData({ id: PTY_ID, data }),
renderedText: () => {
const lines: string[] = []
for (let row = 0; row < terminal.rows; row += 1) {
lines.push(terminal.buffer.active.getLine(row)?.translateToString(true) ?? '')
}
return lines.join('\n').trim()
},
dispose: () => {
handlers.dispose()
terminal.dispose()
}
}
}
async function settleUntil(condition: () => boolean, timeoutMs = 500): Promise<void> {
const deadline = Date.now() + timeoutMs
while (!condition() && Date.now() < deadline) {
await vi.advanceTimersByTimeAsync(1)
}
expect(condition()).toBe(true)
}
describe('#12112 opencode startup OSC 10/11 replies on the local path', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
})
it('plain terminal tab consumes the replies and renders nothing', async () => {
const tty = createStartupTty()
stubPtyApi(tty)
const pane = await createRendererPane()
// Plain tabs have no main startup ingress; xterm alone answers their probes.
tty.onPtyOutput(pane.deliver)
try {
tty.emitStartupBurst()
await settleUntil(() => tty.programInput().includes(OSC11_REPLY))
expect(pane.renderedText()).not.toMatch(LEAKED_COLOR_REPLY_TEXT)
expect(tty.programInput()).toContain(OSC10_REPLY)
expect(tty.programInput()).toContain(OSC11_REPLY)
} finally {
pane.dispose()
}
})
it('agent pane consumes the replies and renders nothing', async () => {
const tty = createStartupTty()
stubPtyApi(tty)
const pane = await createRendererPane()
// TUI agent launches arm main startup ingress.
const ingress = new PtyStartupIngress({
intent: { colors: ORCA_TERMINAL_THEME, deadlineMs: 5_000 },
ownerBackend: 'posix-pty',
write: (data) => tty.writeToPty(data),
onEmission: (emission) => pane.deliver(emission.data)
})
tty.onPtyOutput((data) => ingress.accept(data))
try {
tty.emitStartupBurst()
await settleUntil(() => tty.programInput().includes(OSC11_REPLY))
expect(pane.renderedText()).not.toMatch(LEAKED_COLOR_REPLY_TEXT)
expect(tty.programInput()).toContain(OSC10_REPLY)
expect(tty.programInput()).toContain(OSC11_REPLY)
} finally {
ingress.drainAndClose()
pane.dispose()
}
})
})
@@ -1,184 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { ParkedTerminalByteWatcherOptions } from './parked-terminal-byte-watcher'
const WORKTREE_ID = 'repo::/worktree'
const TAB_ID = 'tab-1'
const PTY_ID = `${WORKTREE_ID}@@session-1`
const SECOND_PTY_ID = `${WORKTREE_ID}@@session-2`
const LEAF_ID = '11111111-1111-4111-8111-111111111111'
const SECOND_LEAF_ID = '22222222-2222-4222-8222-222222222222'
type StartedWatcher = {
options: ParkedTerminalByteWatcherOptions
dispose: ReturnType<typeof vi.fn>
}
const startedWatchers: StartedWatcher[] = []
const startParkedTerminalByteWatcher = vi.fn((options: ParkedTerminalByteWatcherOptions) => {
const dispose = vi.fn()
startedWatchers.push({ options, dispose })
return dispose
})
vi.mock('./parked-terminal-byte-watcher', () => ({
startParkedTerminalByteWatcher: (options: ParkedTerminalByteWatcherOptions) =>
startParkedTerminalByteWatcher(options)
}))
type ExitSubscription = {
ptyId: string
callback: (code: number, context: { hadPrimary: boolean }) => void
unsubscribe: ReturnType<typeof vi.fn>
}
const exitSubscriptions: ExitSubscription[] = []
const subscribeToPtyExit = vi.fn(
(ptyId: string, callback: (code: number, context: { hadPrimary: boolean }) => void) => {
const unsubscribe = vi.fn()
exitSubscriptions.push({ ptyId, callback, unsubscribe })
return unsubscribe
}
)
vi.mock('../../pty-transport/delivery/pty-dispatcher', () => ({
subscribeToPtyExit: (ptyId: string, callback: (code: number) => void) =>
subscribeToPtyExit(ptyId, callback)
}))
const consumePreHandlerPtyState = vi.fn()
vi.mock('../../pty-transport/delivery/pty-pre-handler-buffer', () => ({
discardPreHandlerPtyState: (ptyId: string) => consumePreHandlerPtyState(ptyId),
hasPreHandlerPtyExit: (ptyId: string) => unownedExitPtyIds.has(ptyId)
}))
/** PTYs whose exit was delivered with no owning handler — the park handoff gap. */
const unownedExitPtyIds = new Set<string>()
type CloseTerminalTabOptions = {
captureRecentlyClosed?: boolean
hostCloseReason?: string
lifecyclePtyId?: string
onClosed?: () => void
onCancel?: () => void
}
const closeTerminalTab = vi.fn()
vi.mock('../../../terminal/terminal-tab-actions', () => ({
closeTerminalTab: (tabId: string, options?: CloseTerminalTabOptions) =>
closeTerminalTab(tabId, options)
}))
type MockStoreState = {
tabsByWorktree: Record<
string,
{ id: string; launchAgent?: 'claude' | 'codex'; ptyId: string | null }[]
>
terminalLayoutsByTabId: Record<
string,
{
root: unknown
activeLeafId: string | null
expandedLeafId: string | null
ptyIdsByLeafId?: Record<string, string>
}
>
runtimePaneTitlesByTabId: Record<string, Record<number, string>>
sleepingAgentSessionsByPaneKey: Record<string, { tabId?: string }>
settings: { terminalSshViewParking?: boolean } | null
runtimeStatusByEnvironmentId: Map<
string,
{ status: { capabilities?: string[] } | null; checkedAt: number }
>
clearTabLaunchAgent: ReturnType<typeof vi.fn>
clearRuntimePaneTitle: ReturnType<typeof vi.fn>
setRuntimePaneTitle: ReturnType<typeof vi.fn>
setTabLayout: ReturnType<typeof vi.fn>
updateTabTitle: ReturnType<typeof vi.fn>
markUnverifiedPtyLoss: ReturnType<typeof vi.fn>
isPtyShutdownPending: ReturnType<typeof vi.fn>
suppressedPtyExitIds: Record<string, true>
}
let mockStoreState: MockStoreState
vi.mock('@/store/index', () => ({
useAppStore: { getState: () => mockStoreState }
}))
import {
clearTerminalProviderSnapshotCapabilities,
synchronizeTerminalProviderSnapshotCapabilities
} from '../../../terminal/terminal-provider-snapshot-capability'
import { probeTerminalProviderGoneSessions } from '../../../terminal/terminal-provider-gone-sessions'
import './terminal-parked-tab-watchers'
import { canWatcherCoverParkedTerminalTab } from './parked-terminal-tab-coverage'
import {
captureParkedTerminalPaneCandidates,
pruneParkedTerminalWatchers
} from './terminal-parked-watcher-registry'
const ptyWrite = vi.fn()
const originalWindow = (globalThis as { window?: unknown }).window
function capturePanes(
panes: { ptyId: string | null; paneId: number; leafId: string; drivesTabTitle: boolean }[],
args?: { tabId?: string; worktreeId?: string }
): void {
captureParkedTerminalPaneCandidates(args?.tabId ?? TAB_ID, args?.worktreeId ?? WORKTREE_ID, panes)
}
describe('terminal-parked-tab-watchers', () => {
beforeEach(async () => {
mockStoreState = {
tabsByWorktree: {},
terminalLayoutsByTabId: {},
runtimePaneTitlesByTabId: {},
sleepingAgentSessionsByPaneKey: {},
settings: null,
runtimeStatusByEnvironmentId: new Map(),
clearTabLaunchAgent: vi.fn(),
clearRuntimePaneTitle: vi.fn(),
setRuntimePaneTitle: vi.fn(),
setTabLayout: vi.fn(),
updateTabTitle: vi.fn(),
markUnverifiedPtyLoss: vi.fn(),
isPtyShutdownPending: vi.fn(() => false),
suppressedPtyExitIds: {}
}
;(globalThis as { window?: unknown }).window = { api: { pty: { write: ptyWrite } } }
clearTerminalProviderSnapshotCapabilities()
await synchronizeTerminalProviderSnapshotCapabilities([PTY_ID, SECOND_PTY_ID], async (ids) =>
ids.map((id) => ({ id, authoritative: true }))
)
})
afterEach(() => {
unownedExitPtyIds.clear()
// Prune persistent module registries so each suite starts without parked watchers.
pruneParkedTerminalWatchers(new Set())
startedWatchers.length = 0
exitSubscriptions.length = 0
vi.clearAllMocks()
clearTerminalProviderSnapshotCapabilities()
;(globalThis as { window?: unknown }).window = originalWindow
})
it('keeps a split tab mounted when only some pane sessions are gone', async () => {
await probeTerminalProviderGoneSessions([PTY_ID], async () => [PTY_ID])
capturePanes([
{ ptyId: PTY_ID, paneId: 1, leafId: LEAF_ID, drivesTabTitle: true },
{ ptyId: SECOND_PTY_ID, paneId: 2, leafId: SECOND_LEAF_ID, drivesTabTitle: false }
])
expect(canWatcherCoverParkedTerminalTab(WORKTREE_ID, { id: TAB_ID, ptyId: PTY_ID })).toBe(false)
})
it('keeps a gone agent tab mounted so its resume path is unchanged', async () => {
await probeTerminalProviderGoneSessions([PTY_ID], async () => [PTY_ID])
mockStoreState.tabsByWorktree[WORKTREE_ID] = [
{ id: TAB_ID, ptyId: PTY_ID, launchAgent: 'claude' }
]
capturePanes([{ ptyId: PTY_ID, paneId: 1, leafId: LEAF_ID, drivesTabTitle: true }])
expect(canWatcherCoverParkedTerminalTab(WORKTREE_ID, { id: TAB_ID, ptyId: PTY_ID })).toBe(false)
})
})
@@ -1,180 +0,0 @@
import { acceptedAgentStatuses } from '@/store/slices/agent-status/accepted-agent-statuses'
import { bindPtyConnectionTestMocks } from '../test-fixtures/pty-connection-mocks.spec'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id'
import { flushAsyncTicks, createDeferred } from '../test-fixtures/pty-connection-test-async'
import { createKeyboardEventTarget, keyEvent } from '../test-fixtures/pty-connection-test-dom'
import {
LEAF_1,
createMockTransport,
createPane,
createManager,
type ConnectCallbacks,
type MockTransport
} from '../test-fixtures/pty-connection-test-pane-fixtures'
import type { StoreState } from '../test-fixtures/pty-connection-test-store-state'
import {
buildPaneConnectionDeps,
type PtyConnectionAgentTitleMocks,
bindPaneAgentTitleMocks
} from '../test-fixtures/pty-connection-test-deps'
import { createInitialStoreState } from '../test-fixtures/pty-connection-test-store-fixtures'
import {
installTerminalTestGlobals,
restoreTerminalTestGlobals
} from '../test-fixtures/pty-connection-test-environment'
import { mockPanePtyArgs } from '../test-fixtures/pty-connection-test-connect-mock-pane'
export function registerPtyConnectionCommandFinishedInterruptArbitrationTests(): void {
let mockStoreState: StoreState
let transportFactoryQueue: MockTransport[] = []
let createdTransportOptions: Record<string, unknown>[] = []
let storeSubscribers: ((state: StoreState) => void)[] = []
function createDeps(overrides: Record<string, unknown> = {}) {
return buildPaneConnectionDeps(() => mockStoreState, overrides)
}
describe('connectPanePty', () => {
beforeEach(async () => {
vi.clearAllMocks()
transportFactoryQueue = []
createdTransportOptions = []
storeSubscribers = []
mockStoreState = createInitialStoreState(() => mockStoreState)
bindPtyConnectionTestMocks({
getState: () => mockStoreState,
getTransportQueue: () => transportFactoryQueue,
getTransportOptions: () => createdTransportOptions,
getStoreSubscribers: () => storeSubscribers,
setStoreSubscribers: (subscribers) => {
storeSubscribers = subscribers
}
})
await installTerminalTestGlobals()
})
afterEach(async () => {
await restoreTerminalTestGlobals()
})
it.each(['gemini', 'codex'] as const)(
'pins %s interrupt policy before acknowledged input and command exit cleanup',
async (agentType) => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks14 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
const transport = createMockTransport()
const writeAccepted = createDeferred<boolean>()
transport.sendInputAccepted = vi.fn(() => writeAccepted.promise)
transport.connect.mockImplementation(
async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return { id: 'tab-pty' }
}
)
transport.attach.mockImplementation(({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
})
transportFactoryQueue.push(transport)
vi.useFakeTimers()
vi.setSystemTime(1_100)
const paneKey = makePaneKey('tab-1', LEAF_1)
mockStoreState = {
...mockStoreState,
agentStatusByPaneKey: acceptedAgentStatuses(
Object.entries({
[paneKey]: {
paneKey,
state: 'working',
prompt: 'stop quickly',
updatedAt: 1_000,
stateStartedAt: 900,
agentType,
terminalTitle: agentType,
stateHistory: []
}
})
)
}
vi.mocked(window.api.agentStatus.inferInterrupt).mockImplementation(async () => {
mockStoreState.agentStatusByPaneKey = mockStoreState.agentStatusByPaneKey.replace([
[
paneKey,
{
paneKey,
state: 'done',
prompt: 'stop quickly',
updatedAt: 1_100,
stateStartedAt: 1_100,
agentType,
terminalTitle: agentType,
interrupted: true,
stateHistory: [
{
state: 'working',
prompt: 'stop quickly',
startedAt: 900
}
]
}
]
])
return true
})
const terminalTarget = createKeyboardEventTarget()
const pane = createPane(1)
;(pane.terminal as { element?: unknown }).element = terminalTarget.target
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
connectPanePty(
...mockPanePtyArgs(
pane,
createManager(1),
bindPaneAgentTitleMocks(createDeps(), agentTitleMocks14)
)
)
vi.advanceTimersByTime(1_000)
await flushAsyncTicks()
expect(capturedDataCallback.current).not.toBeNull()
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
terminalTarget.dispatch(keyEvent({ key: 'Escape' }))
;(onDataHandler as unknown as (data: string) => void)('\x1b')
capturedDataCallback.current?.('\x1b]133;D;130\x07thebr ~/repo $ ')
expect(window.api.agentStatus.inferInterrupt).not.toHaveBeenCalled()
expect(mockStoreState.dropAgentStatus).not.toHaveBeenCalled()
mockStoreState.agentStatusByPaneKey = mockStoreState.agentStatusByPaneKey.replace([
[paneKey, null]
])
writeAccepted.resolve(true)
await flushAsyncTicks()
if (agentType === 'codex') {
expect(window.api.agentStatus.inferInterrupt).not.toHaveBeenCalled()
expect(mockStoreState.dropAgentStatus).not.toHaveBeenCalled()
expect(mockStoreState.clearAgentLaunchConfig).toHaveBeenCalledWith(paneKey)
} else {
expect(window.api.agentStatus.inferInterrupt).toHaveBeenCalledWith({
paneKey,
baselineUpdatedAt: 1_000,
baselineStateStartedAt: 900,
baselinePrompt: 'stop quickly',
baselineAgentType: agentType,
intent: 'plain-escape'
})
expect(mockStoreState.dropAgentStatus).toHaveBeenCalledWith(paneKey)
}
}
)
})
}
@@ -1,143 +0,0 @@
import '../test-fixtures/pty-connection-mocks.spec'
import { describe, expect, it, vi } from 'vitest'
import { flushAsyncTicks, createDeferred } from '../test-fixtures/pty-connection-test-async'
import {
announceMainDrop,
connectVisiblePane,
installHiddenRestoreFloodSuiteHooks,
modelSnapshot,
PTY_ID,
type MainSnapshot
} from '../test-fixtures/pty-connection-test-hidden-restore-flood'
// Retired restore tasks cannot paint or consume the unhide recovery owed by their successor.
describe('hidden-output restore unhide with a retired task (STA-4869)', () => {
installHiddenRestoreFloodSuiteHooks()
it('ignores a timed-out task without consuming the next restore request', async () => {
const drive = await connectVisiblePane()
vi.useFakeTimers()
const getMainBufferSnapshot = vi.mocked(window.api.pty.getMainBufferSnapshot)
const first = createDeferred<MainSnapshot>()
const second = createDeferred<MainSnapshot>()
getMainBufferSnapshot.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise)
try {
await announceMainDrop(64, 1)
await announceMainDrop(64, 1, 'unhide')
const waitingLive = 'LIVE_HELD_FOR_TIMEOUT\r\n'
drive.deliver(waitingLive, 64 + waitingLive.length)
await vi.advanceTimersByTimeAsync(800)
await flushAsyncTicks(30)
expect(drive.writtenChunks().join('')).toContain(waitingLive)
await announceMainDrop(256, 2)
await vi.advanceTimersByTimeAsync(2_100)
await flushAsyncTicks(30)
expect(getMainBufferSnapshot).toHaveBeenCalledTimes(2)
first.resolve(modelSnapshot('STALE_TIMED_OUT_CAPTURE', 128))
await flushAsyncTicks(30)
second.resolve(modelSnapshot('RECOVERED_AFTER_TIMEOUT', 512))
await flushAsyncTicks(30)
await vi.advanceTimersByTimeAsync(2_100)
await flushAsyncTicks(30)
expect(getMainBufferSnapshot).toHaveBeenCalledTimes(2)
expect(drive.writtenChunks().join('')).not.toContain('STALE_TIMED_OUT_CAPTURE')
expect(drive.writtenChunks().join('')).toContain('RECOVERED_AFTER_TIMEOUT')
expect(window.api.pty.ackHiddenOutputRestoreApplied).toHaveBeenCalledWith(PTY_ID, 2)
} finally {
drive.disposable.dispose()
}
})
it('recovers a successor unhide with one quiet repaint, not a retired-task requirement too', async () => {
const drive = await connectVisiblePane()
vi.useFakeTimers()
const getMainBufferSnapshot = vi.mocked(window.api.pty.getMainBufferSnapshot)
const oldPtySnapshot = createDeferred<MainSnapshot>()
const newPtySnapshot = createDeferred<MainSnapshot>()
getMainBufferSnapshot
.mockReturnValueOnce(oldPtySnapshot.promise)
.mockReturnValueOnce(newPtySnapshot.promise)
.mockResolvedValue(modelSnapshot('SECOND_SUCCESSOR_REPLAY', 1024))
try {
await announceMainDrop(64, 1)
await announceMainDrop(64, 1, 'unhide')
drive.transport.getPtyId.mockReturnValue('successor-pty')
drive.setVisible(false)
drive.deliver('NEW_PTY_OUTPUT\r\n', 32)
drive.setVisible(true)
await announceMainDrop(32, 2, 'hidden-drop', 'successor-pty')
await announceMainDrop(512, 2, 'unhide', 'successor-pty')
oldPtySnapshot.resolve(modelSnapshot('RETIRED_PTY_CAPTURE', 2048))
await flushAsyncTicks(30)
await vi.advanceTimersByTimeAsync(2_100)
await flushAsyncTicks(30)
expect(getMainBufferSnapshot).toHaveBeenCalledTimes(2)
// Seq below the marker: only a recorded unhide requirement would force a second replay.
newPtySnapshot.resolve(modelSnapshot('SUCCESSOR_QUIET_REPAINT', 128))
await flushAsyncTicks(30)
await vi.advanceTimersByTimeAsync(2_100)
await flushAsyncTicks(30)
expect(getMainBufferSnapshot).toHaveBeenCalledTimes(2)
const written = drive.writtenChunks().join('')
expect(written).not.toContain('RETIRED_PTY_CAPTURE')
expect(written).toContain('SUCCESSOR_QUIET_REPAINT')
expect(written).not.toContain('SECOND_SUCCESSOR_REPLAY')
expect(window.api.pty.ackHiddenOutputRestoreApplied).not.toHaveBeenCalledWith(PTY_ID, 1)
expect(window.api.pty.ackHiddenOutputRestoreApplied).toHaveBeenCalledWith('successor-pty', 2)
} finally {
drive.disposable.dispose()
}
})
it('recovers an unhide-only successor while a retired PTY snapshot is pending', async () => {
const drive = await connectVisiblePane()
vi.useFakeTimers()
const getMainBufferSnapshot = vi.mocked(window.api.pty.getMainBufferSnapshot)
const oldPtySnapshot = createDeferred<MainSnapshot>()
getMainBufferSnapshot
.mockReturnValueOnce(oldPtySnapshot.promise)
.mockResolvedValue(modelSnapshot('SUCCESSOR_UNHIDE_RECOVERED', 1024))
try {
await announceMainDrop(64, 1)
drive.transport.getPtyId.mockReturnValue('successor-pty')
drive.setVisible(false)
drive.deliver('NEW_PTY_OUTPUT\r\n', 32)
drive.setVisible(true)
await announceMainDrop(512, 2, 'unhide', 'successor-pty')
oldPtySnapshot.resolve(modelSnapshot('RETIRED_PTY_CAPTURE', 2048))
await flushAsyncTicks(30)
await vi.advanceTimersByTimeAsync(2_100)
await flushAsyncTicks(30)
expect(getMainBufferSnapshot).toHaveBeenCalledTimes(2)
expect(drive.writtenChunks().join('')).not.toContain('RETIRED_PTY_CAPTURE')
expect(drive.writtenChunks().join('')).toContain('SUCCESSOR_UNHIDE_RECOVERED')
expect(window.api.pty.ackHiddenOutputRestoreApplied).not.toHaveBeenCalledWith(PTY_ID, 1)
expect(window.api.pty.ackHiddenOutputRestoreApplied).toHaveBeenCalledWith('successor-pty', 2)
} finally {
drive.disposable.dispose()
}
})
it('cannot replay or acknowledge an unhide after its pane is disposed', async () => {
const drive = await connectVisiblePane()
vi.useFakeTimers()
const getMainBufferSnapshot = vi.mocked(window.api.pty.getMainBufferSnapshot)
const first = createDeferred<MainSnapshot>()
getMainBufferSnapshot.mockReturnValueOnce(first.promise)
await announceMainDrop(64, 1)
await announceMainDrop(64, 1, 'unhide')
drive.disposable.dispose()
const writesBeforeDisposal = drive.writtenChunks().slice()
first.resolve(modelSnapshot('DISPOSED_PANE_CAPTURE', 128))
await flushAsyncTicks(30)
await vi.advanceTimersByTimeAsync(2_100)
await flushAsyncTicks(30)
expect(getMainBufferSnapshot).toHaveBeenCalledTimes(1)
expect(drive.writtenChunks()).toEqual(writesBeforeDisposal)
expect(window.api.pty.ackHiddenOutputRestoreApplied).not.toHaveBeenCalled()
})
})
@@ -1,13 +1,11 @@
import { describe } from 'vitest'
import { registerPtyConnectionCommandFinishedCleanupTests } from '../agent-identity/pty-connection-command-finished-cleanup.spec'
import { registerPtyConnectionCommandFinishedInterruptArbitrationTests } from '../input/pty-connection-command-finished-interrupt-arbitration.spec'
import { registerPtyConnectionHookCompletionSideEffectsTests } from '../notifications/pty-connection-hook-completion-side-effects.spec'
import { registerPtyConnectionMainSideEffectAuthorityTests } from '../emulation/pty-connection-main-side-effect-authority.spec'
import { registerPtyConnectionTaskCompleteDispatchTests } from '../notifications/pty-connection-task-complete-dispatch.spec'
describe('pty-connection-command-finished-cleanup', () => {
registerPtyConnectionCommandFinishedCleanupTests()
registerPtyConnectionCommandFinishedInterruptArbitrationTests()
})
describe(
'pty-connection-hook-completion-side-effects',
@@ -1,212 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { toast } from 'sonner'
import type { WorkspaceCleanupRemoveResult } from '@/store/slices/workspace-cleanup/workspace-cleanup-removal'
import { startWorkspaceCleanupBackgroundRemoval } from './workspace-cleanup-background-removal'
import { makeCandidate } from '../../query/workspace-cleanup-candidate-state.test-fixture'
vi.mock('sonner', () => ({
toast: {
error: vi.fn(),
info: vi.fn(),
success: vi.fn()
}
}))
async function settleBackgroundRemoval(): Promise<void> {
for (let index = 0; index < 10; index += 1) {
await Promise.resolve()
}
}
describe('workspace cleanup late settlement reconciliation', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('uses a post-grace child success that arrives before its parent is considered', async () => {
const parent = makeCandidate({
worktreeId: 'repo-1::/repo/p',
displayName: 'parent',
branch: 'parent',
path: '/repo/p'
})
const child = makeCandidate({
worktreeId: 'repo-1::/repo/p/child-long',
displayName: 'child',
branch: 'child',
path: '/repo/p/child-long'
})
const unrelated = makeCandidate({
worktreeId: 'repo-1::/repo/other',
displayName: 'other',
branch: 'other',
path: '/repo/other'
})
let resolveChild: (result: WorkspaceCleanupRemoveResult) => void = () => {}
let resolveUnrelated: (result: WorkspaceCleanupRemoveResult) => void = () => {}
const removeCandidates = vi
.fn()
.mockImplementationOnce(
() =>
new Promise<WorkspaceCleanupRemoveResult>((resolve) => {
resolveChild = resolve
})
)
.mockImplementationOnce(
() =>
new Promise<WorkspaceCleanupRemoveResult>((resolve) => {
resolveUnrelated = resolve
})
)
.mockResolvedValueOnce({
removedIds: [parent.worktreeId],
removedIdentities: [parent.worktreeId],
failures: []
})
const onResult = vi.fn()
startWorkspaceCleanupBackgroundRemoval({
candidates: [parent, unrelated, child],
removeCandidates,
onProgress: vi.fn(),
onResult,
removalTimeoutMs: 5,
removalSettlementGraceMs: 5
})
await vi.advanceTimersByTimeAsync(10)
expect(removeCandidates).toHaveBeenCalledTimes(2)
resolveChild({
removedIds: [child.worktreeId],
removedIdentities: [child.worktreeId],
failures: []
})
await settleBackgroundRemoval()
resolveUnrelated({
removedIds: [unrelated.worktreeId],
removedIdentities: [unrelated.worktreeId],
failures: []
})
await settleBackgroundRemoval()
expect(removeCandidates).toHaveBeenNthCalledWith(3, [parent.worktreeId], {
approvedCandidates: [parent]
})
expect(onResult).toHaveBeenCalledWith({
removedIds: [child.worktreeId, unrelated.worktreeId, parent.worktreeId],
removedIdentities: [child.worktreeId, unrelated.worktreeId, parent.worktreeId],
failures: []
})
expect(toast.error).not.toHaveBeenCalled()
})
it('reports later child settlements while a post-batch ancestor retry is stalled', async () => {
const firstParent = makeCandidate({
worktreeId: 'repo-1::/repo/a',
displayName: 'first parent',
branch: 'first-parent',
path: '/repo/a'
})
const firstChild = makeCandidate({
worktreeId: 'repo-1::/repo/a/child-long',
displayName: 'first child',
branch: 'first-child',
path: '/repo/a/child-long'
})
const secondParent = makeCandidate({
worktreeId: 'repo-1::/repo/bb',
displayName: 'second parent',
branch: 'second-parent',
path: '/repo/bb'
})
const secondChild = makeCandidate({
worktreeId: 'repo-1::/repo/bb/c',
displayName: 'second child',
branch: 'second-child',
path: '/repo/bb/c'
})
let resolveFirstChild: (result: WorkspaceCleanupRemoveResult) => void = () => {}
let resolveSecondChild: (result: WorkspaceCleanupRemoveResult) => void = () => {}
const removeCandidates = vi
.fn()
.mockImplementationOnce(
() =>
new Promise<WorkspaceCleanupRemoveResult>((resolve) => {
resolveFirstChild = resolve
})
)
.mockImplementationOnce(
() =>
new Promise<WorkspaceCleanupRemoveResult>((resolve) => {
resolveSecondChild = resolve
})
)
.mockImplementationOnce(() => new Promise(() => {}))
.mockResolvedValueOnce({
removedIds: [secondParent.worktreeId],
removedIdentities: [secondParent.worktreeId],
failures: []
})
const onLateResult = vi.fn()
startWorkspaceCleanupBackgroundRemoval({
candidates: [firstParent, firstChild, secondParent, secondChild],
removeCandidates,
onProgress: vi.fn(),
onResult: vi.fn(),
onLateResult,
removalTimeoutMs: 5,
removalSettlementGraceMs: 5
})
await vi.advanceTimersByTimeAsync(20)
await settleBackgroundRemoval()
resolveFirstChild({
removedIds: [firstChild.worktreeId],
removedIdentities: [firstChild.worktreeId],
failures: []
})
await settleBackgroundRemoval()
expect(removeCandidates).toHaveBeenNthCalledWith(3, [firstParent.worktreeId], {
approvedCandidates: [firstParent]
})
expect(onLateResult).toHaveBeenNthCalledWith(1, {
removedIds: [firstChild.worktreeId],
removedIdentities: [firstChild.worktreeId],
failures: []
})
resolveSecondChild({
removedIds: [secondChild.worktreeId],
removedIdentities: [secondChild.worktreeId],
failures: []
})
await settleBackgroundRemoval()
expect(onLateResult).toHaveBeenNthCalledWith(2, {
removedIds: [secondChild.worktreeId],
removedIdentities: [secondChild.worktreeId],
failures: []
})
expect(removeCandidates).toHaveBeenCalledTimes(3)
await vi.advanceTimersByTimeAsync(10)
await settleBackgroundRemoval()
expect(removeCandidates).toHaveBeenNthCalledWith(4, [secondParent.worktreeId], {
approvedCandidates: [secondParent]
})
expect(onLateResult).toHaveBeenCalledWith({
removedIds: [secondParent.worktreeId],
removedIdentities: [secondParent.worktreeId],
failures: []
})
expect(toast.info).toHaveBeenCalledWith('Still removing workspaces: 1')
})
})
-178
View File
@@ -1,178 +0,0 @@
// @vitest-environment happy-dom
import { act, createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { getDefaultSettings } from '../../../shared/constants'
import {
getBrowserLanguageDetection,
setRendererLanguageDetection
} from '../../../shared/i18n/ui-locale'
import { useAppStore } from '@/store'
import { i18n } from './i18n'
import * as rendererI18n from './i18n'
import { useLanguageReadiness } from './language-readiness'
import * as languageReadiness from './language-readiness'
import { usePluginLanguagePackStore } from '../store/plugins/localization/plugin-language-packs'
import { I18nProvider } from './I18nProvider'
// Wait for async settings before selecting the OS locale, or an in-flight load can override the persisted preference.
const initialAppState = useAppStore.getInitialState()
const roots: Root[] = []
async function renderProvider(): Promise<void> {
const container = document.createElement('div')
document.body.appendChild(container)
const root = createRoot(container)
roots.push(root)
await act(async () => {
root.render(createElement(I18nProvider, null, null))
})
}
beforeEach(() => {
useLanguageReadiness.setState(useLanguageReadiness.getInitialState(), true)
vi.spyOn(languageReadiness, 'initializeLanguageDetection').mockImplementation(async () => {
const detection = getBrowserLanguageDetection()
setRendererLanguageDetection(detection)
useLanguageReadiness.setState({ detection })
return detection
})
useAppStore.setState(initialAppState, true)
})
afterEach(async () => {
for (const root of roots) {
await act(async () => {
root.unmount()
})
}
roots.length = 0
useAppStore.setState(initialAppState, true)
vi.restoreAllMocks()
})
describe('I18nProvider startup language', () => {
it.each(['loaded', 'failed'] as const)(
'starts an explicit catalog before detection finishes and waits for detection when %s',
async (outcome) => {
const detection = getBrowserLanguageDetection()
let finishDetection: () => void = () => {}
vi.spyOn(languageReadiness, 'initializeLanguageDetection').mockImplementation(
() =>
new Promise((resolve) => {
finishDetection = () => resolve(detection)
})
)
const load = vi.spyOn(rendererI18n, 'loadRendererUiLanguage')
if (outcome === 'loaded') {
load.mockResolvedValue('fr')
} else {
load.mockRejectedValue(new Error('Catalog offline'))
}
const changeLanguage = vi.spyOn(i18n, 'changeLanguage')
useAppStore.setState({ settings: { ...getDefaultSettings('/tmp'), uiLanguage: 'fr' } })
await renderProvider()
expect(load).toHaveBeenCalledWith('fr')
expect(changeLanguage).not.toHaveBeenCalled()
expect(useLanguageReadiness.getState()).toMatchObject({ ready: false, loading: true })
await act(async () => finishDetection())
expect(changeLanguage).toHaveBeenCalledWith(outcome === 'loaded' ? 'fr' : 'en')
await vi.waitFor(() =>
expect(useLanguageReadiness.getState()).toMatchObject({
ready: true,
loading: false,
error: outcome === 'failed'
})
)
}
)
it('waits for detection before resolving the system language catalog', async () => {
const detection = getBrowserLanguageDetection()
let finishDetection: () => void = () => {}
vi.spyOn(languageReadiness, 'initializeLanguageDetection').mockImplementation(
() =>
new Promise((resolve) => {
finishDetection = () => resolve(detection)
})
)
const load = vi.spyOn(rendererI18n, 'loadRendererUiLanguage').mockResolvedValue('en')
useAppStore.setState({ settings: { ...getDefaultSettings('/tmp'), uiLanguage: 'system' } })
await renderProvider()
expect(load).not.toHaveBeenCalled()
await act(async () => finishDetection())
expect(load).toHaveBeenCalledWith('system')
expect(useLanguageReadiness.getState().ready).toBe(true)
})
})
it('does not apply a delayed catalog after a newer saved preference', async () => {
let finishSpanish: (locale: string) => void = () => {}
const load = vi
.spyOn(rendererI18n, 'loadRendererUiLanguage')
.mockImplementation(async (language) => {
if (language === 'es') {
return new Promise<string>((resolve) => {
finishSpanish = resolve
})
}
return 'en'
})
const changeLanguage = vi.spyOn(i18n, 'changeLanguage')
await renderProvider()
await act(async () => {
useAppStore.setState({ settings: { ...getDefaultSettings('/tmp'), uiLanguage: 'es' } })
})
await vi.waitFor(() => expect(load).toHaveBeenCalledWith('es'))
await act(async () => {
useAppStore.setState({ settings: { ...getDefaultSettings('/tmp'), uiLanguage: 'en' } })
})
await vi.waitFor(() => expect(changeLanguage).toHaveBeenCalledWith('en'))
await act(async () => finishSpanish('es'))
expect(changeLanguage).not.toHaveBeenCalledWith('es')
expect(i18n.language).toBe('en')
})
it('settles catalog failure to English with recovery while preserving the saved language', async () => {
vi.spyOn(rendererI18n, 'loadRendererUiLanguage').mockRejectedValue(new Error('Catalog offline'))
await renderProvider()
await act(async () => {
useAppStore.setState({ settings: { ...getDefaultSettings('/tmp'), uiLanguage: 'fr' } })
})
await vi.waitFor(() =>
expect(useLanguageReadiness.getState()).toMatchObject({ ready: true, error: true })
)
expect(i18n.language).toBe('en')
expect(useAppStore.getState().settings?.uiLanguage).toBe('fr')
})
it('continues in English while plugin discovery is pending without changing the saved preference', async () => {
Object.defineProperty(window, 'api', {
configurable: true,
value: { plugins: { listLanguagePacks: () => new Promise(() => {}) } }
})
usePluginLanguagePackStore.setState({ entries: [], loaded: false })
useAppStore.setState({
settings: { ...getDefaultSettings('/tmp'), uiLanguage: 'plugin:example.missing/de' }
})
await renderProvider()
await vi.waitFor(() =>
expect(useLanguageReadiness.getState()).toMatchObject({ ready: true, error: false })
)
expect(i18n.language).toBe('en')
expect(usePluginLanguagePackStore.getState().loaded).toBe(false)
expect(useAppStore.getState().settings?.uiLanguage).toBe('plugin:example.missing/de')
})
@@ -1,193 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import '../../workspace-attention/workspace-unread-characterization-fixture'
import type { AppState } from '../../../types'
import type { FolderWorkspace } from '../../../../../../shared/folder-workspaces/folder-workspace-types'
import type { ProjectGroup } from '../../../../../../shared/project/groups/project-group-types'
import { folderWorkspaceKey } from '../../../../../../shared/workspace/identity/workspace-scope'
import {
createCompatibleRuntimeStatusResponseIfNeeded,
type RuntimeEnvironmentCallRequest
} from '../../../../runtime/rpc/testing/runtime-compatibility-test-fixture'
import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '../../../../runtime/rpc/compatibility/runtime-compatibility-cache'
import { createTestStore } from '../../../testing/app-store-test-fixture'
const folderWorkspacesUpdate = vi.fn()
const folderWorkspacesList = vi.fn()
const runtimeEnvironmentCall = vi.fn()
const runtimeEnvironmentTransportCall = vi.fn()
const projectGroup: ProjectGroup = {
id: 'group-1',
name: 'Platform',
parentPath: '/workspace/platform',
parentGroupId: null,
createdFrom: 'manual',
tabOrder: 0,
isCollapsed: false,
color: null,
createdAt: 1,
updatedAt: 1
}
function makeFolderWorkspace(overrides: Partial<FolderWorkspace> = {}): FolderWorkspace {
return {
id: 'folder-workspace-1',
projectGroupId: projectGroup.id,
name: 'Folder workspace',
folderPath: '/workspace/folder',
linkedTask: null,
comment: '',
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 1,
lastActivityAt: 0,
createdAt: 1,
updatedAt: 1,
...overrides
}
}
type FolderWorkspaceUpdateArgs = {
folderWorkspaceId: string
updates: Partial<FolderWorkspace>
}
function stubFolderWorkspaceApis(): void {
clearRuntimeCompatibilityCacheForTests()
folderWorkspacesUpdate.mockReset()
folderWorkspacesList.mockReset()
runtimeEnvironmentCall.mockReset()
runtimeEnvironmentTransportCall.mockReset()
runtimeEnvironmentTransportCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => {
return createCompatibleRuntimeStatusResponseIfNeeded(args) ?? runtimeEnvironmentCall(args)
})
vi.stubGlobal('window', {
api: {
folderWorkspaces: {
update: folderWorkspacesUpdate,
list: folderWorkspacesList
},
runtimeEnvironments: { call: runtimeEnvironmentTransportCall }
}
})
}
function seedLocalFolderStore(folderWorkspace: FolderWorkspace) {
const store = createTestStore()
store.setState({
projectGroups: [{ ...projectGroup, executionHostId: 'local' }],
folderWorkspaces: [folderWorkspace],
refreshGitHubForWorktreeIfStale: vi.fn()
} as Partial<AppState>)
return store
}
function respondWithUpdates(base: FolderWorkspace) {
return async (args: FolderWorkspaceUpdateArgs): Promise<FolderWorkspace> => ({
...base,
...args.updates,
updatedAt: Math.max(base.updatedAt + 1, Date.now())
})
}
beforeEach(() => {
stubFolderWorkspaceApis()
})
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
})
describe('folder workspace generic activation and activity', () => {
it('coalesces repeated activity persistence while keeping local activity current', async () => {
vi.useFakeTimers()
vi.setSystemTime(1_000)
const folderWorkspace = makeFolderWorkspace()
const workspaceKey = folderWorkspaceKey(folderWorkspace.id)
let resolveFirst!: (workspace: FolderWorkspace) => void
folderWorkspacesUpdate
.mockImplementationOnce(
() =>
new Promise<FolderWorkspace>((resolve) => {
resolveFirst = resolve
})
)
.mockImplementation(respondWithUpdates(folderWorkspace))
const store = seedLocalFolderStore(folderWorkspace)
store.getState().bumpWorktreeActivity(workspaceKey)
await vi.advanceTimersByTimeAsync(100)
store.getState().bumpWorktreeActivity(workspaceKey)
await vi.advanceTimersByTimeAsync(100)
store.getState().bumpWorktreeActivity(workspaceKey)
expect(store.getState().folderWorkspaces[0]?.lastActivityAt).toBe(1_200)
expect(folderWorkspacesUpdate).toHaveBeenCalledTimes(1)
expect(folderWorkspacesUpdate).toHaveBeenLastCalledWith({
folderWorkspaceId: folderWorkspace.id,
updates: { lastActivityAt: 1_000 }
})
// Why: the first IPC must not rewind local activity that advanced while it was in flight.
resolveFirst({
...folderWorkspace,
lastActivityAt: 1_000,
updatedAt: 2
})
await Promise.resolve()
await Promise.resolve()
expect(store.getState().folderWorkspaces[0]?.lastActivityAt).toBe(1_200)
await vi.advanceTimersByTimeAsync(800)
expect(folderWorkspacesUpdate).toHaveBeenCalledTimes(2)
expect(folderWorkspacesUpdate).toHaveBeenLastCalledWith({
folderWorkspaceId: folderWorkspace.id,
updates: { lastActivityAt: 1_200 }
})
await Promise.resolve()
await Promise.resolve()
expect(store.getState().folderWorkspaces[0]?.lastActivityAt).toBe(1_200)
})
it('does not rewind local activity when a failed early persist reconciles an older catalog value', async () => {
vi.useFakeTimers()
vi.setSystemTime(1_000)
const folderWorkspace = makeFolderWorkspace()
const workspaceKey = folderWorkspaceKey(folderWorkspace.id)
let rejectFirst!: (error: Error) => void
folderWorkspacesUpdate
.mockImplementationOnce(
() =>
new Promise<FolderWorkspace>((_resolve, reject) => {
rejectFirst = reject
})
)
.mockImplementation(respondWithUpdates(folderWorkspace))
folderWorkspacesList.mockResolvedValue([
{ ...folderWorkspace, lastActivityAt: 1_000, updatedAt: 2 }
])
const store = seedLocalFolderStore(folderWorkspace)
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
try {
store.getState().bumpWorktreeActivity(workspaceKey)
await vi.advanceTimersByTimeAsync(100)
store.getState().bumpWorktreeActivity(workspaceKey)
expect(store.getState().folderWorkspaces[0]?.lastActivityAt).toBe(1_100)
rejectFirst(new Error('persist failed'))
await Promise.resolve()
await Promise.resolve()
await Promise.resolve()
expect(folderWorkspacesList).toHaveBeenCalled()
expect(store.getState().folderWorkspaces[0]?.lastActivityAt).toBe(1_100)
} finally {
errorSpy.mockRestore()
}
})
})
@@ -1,231 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type * as AgentStatusModule from '@/lib/agent-status/aggregation/worktree-agent-status'
import { createTestStore, seedStore } from '../../../testing/app-store-test-fixture'
import { makeLayout, makeTab } from '../../testing/terminal-tab.test-fixture'
import { makeTabGroup, makeUnifiedTab } from '../../../slices/tabs/tab-group.test-fixture'
import { makeWorktree } from '../../../slices/worktrees/worktree.test-fixture'
import '../../retirement/terminal-orphan-cleanup'
import { createStoreCascadesMockApi } from '../../../testing/app-store-cascade-api.test-fixture'
const mockUnregisterPtyDataHandlers = vi.hoisted(() => vi.fn<() => unknown[]>(() => []))
const mockRestorePtyDataHandlersAfterFailedShutdown = vi.hoisted(() => vi.fn())
vi.mock('sonner', () => ({
toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() }
}))
vi.mock('@/components/terminal-pane/pty-transport/delivery/pty-dispatcher', () => ({}))
vi.mock('@/components/terminal-pane/pty-transport/shutdown/pty-shutdown-data-suspension', () => ({
restorePtyDataHandlersAfterFailedShutdown: mockRestorePtyDataHandlersAfterFailedShutdown,
unregisterPtyDataHandlers: mockUnregisterPtyDataHandlers
}))
vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => {
const actual = await importOriginal<typeof AgentStatusModule>()
return {
...actual,
detectAgentStatusFromTitle: vi.fn().mockReturnValue(null)
}
})
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) =>
(
await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture')
).runtimeRpcClientWithLayoutApply(await importOriginal())
)
vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (importOriginal) =>
(
await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture')
).runtimeLayoutClientWithTestFrames(await importOriginal())
)
const mockApi = createStoreCascadesMockApi()
describe('setActiveWorktree', () => {
beforeEach(() => {
vi.clearAllMocks()
mockApi.worktrees.updateMeta.mockResolvedValue({})
})
it('removes orphan terminal caches while creating a replacement tab', () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
const orphanId = 'orphan-terminal'
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [makeTab({ id: orphanId, worktreeId: wt })]
},
unifiedTabsByWorktree: {
[wt]: []
},
ptyIdsByTabId: {
[orphanId]: []
},
runtimePaneTitlesByTabId: {
[orphanId]: { 1: 'stale' }
},
terminalLayoutsByTabId: {
[orphanId]: makeLayout()
},
pendingStartupByTabId: {
[orphanId]: { command: 'codex' }
},
automaticAgentResumeClaimsByTabId: {
[orphanId]: {
worktreeId: wt,
launchAgent: 'codex',
providerSession: { key: 'session_id', id: 'sess-1' }
}
},
pendingInitialCwdByTabId: {
[orphanId]: '/repo/packages/web'
},
tabBarOrderByWorktree: {
[wt]: [orphanId]
},
cacheTimerByKey: {
[`${orphanId}:seed`]: 123
},
activeTabId: orphanId,
activeTabIdByWorktree: {
[wt]: orphanId
}
})
const replacement = store.getState().createTab(wt, undefined, undefined, {
id: 'replacement-terminal',
initialLeafId: '11111111-1111-4111-8111-111111111111'
})
const s = store.getState()
expect(s.ptyIdsByTabId[orphanId]).toBeUndefined()
expect(s.runtimePaneTitlesByTabId[orphanId]).toBeUndefined()
expect(s.terminalLayoutsByTabId[orphanId]).toBeUndefined()
expect(s.pendingStartupByTabId[orphanId]).toBeUndefined()
expect(s.automaticAgentResumeClaimsByTabId[orphanId]).toBeUndefined()
expect(s.pendingInitialCwdByTabId[orphanId]).toBeUndefined()
expect(s.cacheTimerByKey[`${orphanId}:seed`]).toBeUndefined()
const replacementLayout = s.terminalLayoutsByTabId[replacement.id]
expect(replacementLayout?.root).toEqual({
type: 'leaf',
leafId: '11111111-1111-4111-8111-111111111111'
})
})
it('keeps surviving target-group tab active when inactive creation removes an orphan', () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
const orphanId = 'orphan-terminal'
const existingId = 'existing-terminal'
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [
makeTab({ id: orphanId, worktreeId: wt }),
makeTab({ id: existingId, worktreeId: wt })
]
},
unifiedTabsByWorktree: {
[wt]: [
makeUnifiedTab({
id: existingId,
entityId: existingId,
worktreeId: wt,
groupId: 'group-1'
})
]
},
groupsByWorktree: {
[wt]: [
makeTabGroup({
id: 'group-1',
worktreeId: wt,
activeTabId: orphanId,
tabOrder: [orphanId, existingId],
recentTabIds: [orphanId]
})
]
},
ptyIdsByTabId: {
[orphanId]: [],
[existingId]: []
},
activeTabId: orphanId,
activeTabIdByWorktree: {
[wt]: orphanId
}
})
store.getState().createTab(wt, 'group-1', undefined, { activate: false })
const s = store.getState()
expect(s.activeTabIdByWorktree[wt]).toBe(existingId)
})
it('keeps surviving non-target group tab active when inactive creation removes an orphan', () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
const orphanId = 'orphan-terminal'
const existingId = 'existing-terminal'
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [
makeTab({ id: orphanId, worktreeId: wt }),
makeTab({ id: existingId, worktreeId: wt })
]
},
unifiedTabsByWorktree: {
[wt]: [
makeUnifiedTab({
id: existingId,
entityId: existingId,
worktreeId: wt,
groupId: 'group-a'
})
]
},
groupsByWorktree: {
[wt]: [
makeTabGroup({
id: 'group-a',
worktreeId: wt,
activeTabId: orphanId,
tabOrder: [orphanId, existingId],
recentTabIds: [orphanId]
}),
makeTabGroup({
id: 'group-b',
worktreeId: wt,
activeTabId: null,
tabOrder: []
})
]
},
ptyIdsByTabId: {
[orphanId]: [],
[existingId]: []
}
})
store.getState().createTab(wt, 'group-b', undefined, { activate: false })
const groups = store.getState().groupsByWorktree[wt] ?? []
expect(groups.find((group) => group.id === 'group-a')).toMatchObject({
activeTabId: existingId,
tabOrder: [existingId],
recentTabIds: [existingId]
})
})
})
@@ -1,206 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { RuntimeRpcResponse } from '../../../shared/remote-runtime/rpc/runtime-rpc-envelope'
import { buildNativeChatProviderUpdate } from '../../../shared/native-chat/native-chat-providers'
import { nativeChatPreferenceFor } from '../../../shared/agent-launch/choices/structured-native-chat-launch-route'
import {
installBrowserGlobals,
writeStoredRuntimeEnvironment
} from './web-preload-api-test-harness'
const SETTINGS_KEY = 'orca.web.settings.v1'
async function loadSettings(stored: Record<string, unknown> | null) {
const globals = installBrowserGlobals('Linux')
if (stored) {
globals.storage.setItem(SETTINGS_KEY, JSON.stringify(stored))
}
const { installWebPreloadApi } = await import('./web-preload-api')
installWebPreloadApi()
const settings = await globals.window.api.settings.get()
const saved: Record<string, unknown> = JSON.parse(globals.storage.getItem(SETTINGS_KEY) ?? '{}')
return { settings, saved, globals }
}
const oldHost = vi.hoisted(() => {
const calls: string[] = []
const state: {
on: boolean
fail: boolean
calls: string[]
reply?: Record<string, unknown>
call?: (
method: string,
params?: unknown,
options?: { timeoutMs?: number }
) => Promise<RuntimeRpcResponse<unknown>>
} = { on: false, fail: false, calls }
return state
})
vi.mock('./web-runtime-client', () => ({
WebRuntimeClient: class {
async call(method: string, params?: unknown, options?: { timeoutMs?: number }) {
oldHost.calls.push(method)
if (oldHost.call) {
return oldHost.call(method, params, options)
}
if (oldHost.fail) {
throw new Error('offline')
}
return {
id: method,
ok: true,
_meta: { runtimeId: 'released-host' },
result: {
settings: oldHost.reply ?? {
experimentalNativeChat: oldHost.on,
experimentalStructuredNativeChat: oldHost.on,
openAgentTabsInChatByDefault: false,
agentDefaultSurface: oldHost.on ? 'chat' : 'terminal',
nativeChatProviders: { claude: oldHost.on, codex: oldHost.on },
compactWorktreeCards: true,
minimaxGroupId: 'live-host-group'
}
}
}
}
close() {}
}
}))
describe('current browser owner at remote settlement', () => {
beforeEach(() => {
vi.resetModules()
oldHost.fail = false
oldHost.call = undefined
oldHost.reply = undefined
oldHost.calls = []
})
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
})
const methods = ['settings.get', 'settings.update', 'settings.updatePRBotAuthorOverride'] as const
async function paired(initialChat = false) {
const { globals } = await loadSettings({
agentDefaultSurface: initialChat ? 'chat' : 'terminal',
nativeChatProviders: { 'acme-agent': true }
})
writeStoredRuntimeEnvironment(globals.storage)
vi.resetModules()
const { installWebPreloadApi } = await import('./web-preload-api')
installWebPreloadApi()
return globals
}
function syncSettings(api: Window['api']) {
const settings = api.settings.getSync()
expect(settings).not.toBeNull()
if (settings === null) {
throw new Error('Browser settings must be synchronously available')
}
return settings
}
function start(api: Window['api'], method: string, visibility = false) {
if (method === 'settings.get') {
return api.settings.get()
}
if (method === 'settings.update') {
return api.settings.set(
visibility
? { worktreeVisibilityDefaults: { external: 'show' } }
: { compactWorktreeCards: false }
)
}
return api.settings.updatePRBotAuthorOverride({ author: ' Robot ', isBot: true })
}
async function choose(api: Window['api'], chat: boolean) {
const current = await api.settings.set({ agentDefaultSurface: chat ? 'chat' : 'terminal' })
return api.settings.set(buildNativeChatProviderUpdate(current, 'codex', !chat))
}
function check(settings: Awaited<ReturnType<Window['api']['settings']['get']>>, chat: boolean) {
expect(settings.agentDefaultSurface).toBe(chat ? 'chat' : 'terminal')
expect(settings.nativeChatProviders).toEqual({ 'acme-agent': true, codex: !chat })
expect(nativeChatPreferenceFor(settings, 'future-agent')).toBe(chat)
expect(nativeChatPreferenceFor(settings, 'codex')).toBe(!chat)
}
function delay() {
let release = (_settings?: Record<string, unknown>) => {}
let reject = (_reason: Error) => {}
let enter = () => {}
const entered = new Promise<void>((resolve) => {
enter = resolve
})
oldHost.call = (method) =>
new Promise((resolve, fail) => {
release = (settings) =>
resolve({
id: method,
ok: true,
result: { settings: settings ?? {} },
_meta: { runtimeId: 'released-host' }
})
reject = fail
enter()
})
return {
entered,
release: (settings?: Record<string, unknown>) => release(settings),
reject: (error: Error) => reject(error)
}
}
it.each(methods.flatMap((method) => [false, true].map((chat) => ({ method, chat }))))(
'retains current intent through delayed $method with Chat=$chat, persistence and reopen',
async ({ method, chat }) => {
const globals = await paired(!chat)
const pending = delay()
const earlier = start(globals.window.api, method)
await pending.entered
await choose(globals.window.api, chat)
const replacement = {
...JSON.parse(globals.storage.getItem(SETTINGS_KEY) ?? '{}'),
experimentalNativeChat: { replacement: chat }
}
globals.storage.setItem(SETTINGS_KEY, JSON.stringify(replacement))
pending.release({
compactWorktreeCards: true,
prBotAuthorOverrides: [' Robot '],
...(chat
? {
experimentalNativeChat: false,
experimentalStructuredNativeChat: false,
openAgentTabsInChatByDefault: false,
agentDefaultSurface: 'terminal',
nativeChatProviders: { codex: true }
}
: {})
})
const returned = await earlier
check(returned, chat)
expect(returned).not.toHaveProperty('experimentalNativeChat')
expect(
JSON.parse(globals.storage.getItem(SETTINGS_KEY) ?? '{}').experimentalNativeChat
).toEqual({ replacement: chat })
if (method === 'settings.updatePRBotAuthorOverride') {
expect(returned.prBotAuthorOverrides).toEqual(['robot'])
} else {
expect(returned.compactWorktreeCards).toBe(true)
}
check(syncSettings(globals.window.api), chat)
expect(JSON.parse(globals.storage.getItem(SETTINGS_KEY) ?? '{}')).toMatchObject({
agentDefaultSurface: returned.agentDefaultSurface,
nativeChatProviders: returned.nativeChatProviders
})
oldHost.call = undefined
vi.resetModules()
const { installWebPreloadApi } = await import('./web-preload-api')
installWebPreloadApi()
check(await globals.window.api.settings.get(), chat)
check(
await globals.window.api.settings.set({ agentDefaultSurface: chat ? 'chat' : 'terminal' }),
chat
)
}
)
})
@@ -1,22 +0,0 @@
import { describe, expect, it } from 'vitest'
import { agentSessionFailureSentence } from '../../failures/agent-session-failure-words'
describe('agent-specific sign-in guidance', () => {
it('keeps diagnostic text literal and keeps log-only detail off the visible sentence', () => {
const detail = 'No API key found for {{agent}} $t(fake.key)'
expect(
agentSessionFailureSentence(
{ kind: 'notSignedIn', detail: { text: detail, audience: 'person' } },
'rejection',
{ agentName: 'Pi' }
)
).toContain(detail)
expect(
agentSessionFailureSentence(
{ kind: 'notSignedIn', detail: { text: detail, audience: 'log' } },
'row',
{ agentName: 'Pi' }
)
).not.toContain(detail)
})
})
@@ -1,22 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { AgentJournalRenderItem } from '../journal/agent-session-journal-types'
import { projectStructuredItemToNativeChat } from './structured-agent-session-projection'
function item(
itemId: string,
sequence: number,
body: AgentJournalRenderItem['body']
): AgentJournalRenderItem {
return { itemId, sequence, revision: 1, observedAt: sequence, body }
}
describe('structured agent session status projection', () => {
it('projects an item kind this build does not know to no message, never a text bubble', () => {
const unknown = item('future', 1, {
kind: 'future-kind',
text: 'a newer host wrote this'
} as unknown as AgentJournalRenderItem['body'])
expect(projectStructuredItemToNativeChat(unknown)).toBeNull()
})
})
@@ -1,28 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
NodeReadableTextTooLargeError,
readNodeReadableTextWithinLimit
} from './node-readable-text'
async function* chunks(values: unknown[]): AsyncGenerator<unknown> {
yield* values
}
describe('readNodeReadableTextWithinLimit', () => {
it('preserves accepted UTF-8 bytes split across chunks', async () => {
const encoded = Buffer.from('hello 🌍')
await expect(
readNodeReadableTextWithinLimit(
chunks([encoded.subarray(0, 8), encoded.subarray(8)]),
encoded.byteLength
)
).resolves.toBe('hello 🌍')
})
it('rejects before retaining input beyond the byte limit', async () => {
await expect(readNodeReadableTextWithinLimit(chunks(['1234', '5']), 4)).rejects.toEqual(
new NodeReadableTextTooLargeError(5, 4)
)
})
})
@@ -1,19 +0,0 @@
import { expect, it } from 'vitest'
import { createAccumulator, ingestRgJsonLine } from './text-search'
it('reports byte-only filenames as incomplete without inventing a replacement-character path', () => {
const acc = createAccumulator()
const line = JSON.stringify({
type: 'match',
data: {
path: { bytes: Buffer.from([0xff, 0x2e, 0x74, 0x78, 0x74]).toString('base64') },
lines: { text: 'needle\n' },
line_number: 1,
submatches: [{ start: 0, end: 6 }]
}
})
expect(ingestRgJsonLine(line, '/root', acc, 20)).toBe('continue')
expect(acc.truncated).toBe(true)
expect(acc.totalMatches).toBe(0)
expect(acc.fileMap.size).toBe(0)
})
@@ -1,17 +0,0 @@
import { describe, expect, it } from 'vitest'
import { githubProjectIdentityKey } from './project-identity'
describe('GitHub project identity', () => {
it('keeps legacy github.com keys while isolating Enterprise hosts and ports', () => {
const project = { owner: 'Acme', ownerType: 'organization' as const, number: 7 }
expect(githubProjectIdentityKey(project)).toBe('organization:acme:7')
expect(githubProjectIdentityKey({ ...project, host: 'github.com' })).toBe('organization:acme:7')
expect(githubProjectIdentityKey({ ...project, host: ' GitHub.com ' })).toBe(
'organization:acme:7'
)
expect(githubProjectIdentityKey({ ...project, host: 'GHE.EXAMPLE:8443' })).toBe(
'ghe.example:8443:organization:acme:7'
)
})
})
@@ -1,26 +0,0 @@
import { describe, expect, it } from 'vitest'
import { isSameGitRepository } from './plugin-marketplace'
describe('isSameGitRepository', () => {
it('matches respellings and treats a GitLab subgroup move as a different repository', () => {
expect(
isSameGitRepository(
'https://gitlab.com/acme/team-a/tool.git',
'git@gitlab.com:Acme/Team-A/Tool'
)
).toBe(true)
// A self-hosted server may serve these as two repositories, so an approval must not carry.
expect(
isSameGitRepository(
'https://git.example.com/team/Plugin.git',
'https://git.example.com/team/plugin.git'
)
).toBe(false)
expect(
isSameGitRepository(
'https://gitlab.com/acme/team-a/tool',
'https://gitlab.com/acme/evil/tool'
)
).toBe(false)
})
})
@@ -1,20 +0,0 @@
import { expect, it } from 'vitest'
import { parseDenseRipgrepMatchJson } from './ripgrep-dense-match-json'
it('validates submatches after reaching the requested result cap', () => {
const source = JSON.stringify({
type: 'match',
data: {
submatches: [
{ start: 0, end: 1 },
{ start: null, end: 2 }
]
}
})
expect(() => parseDenseRipgrepMatchJson(source, 1, 16)).toThrow('Invalid rg submatch')
})
it('rejects duplicate coordinate fields whose final value is not numeric', () => {
const source = '{"data":{"submatches":[{"start":0,"start":{},"end":1}]}}'
expect(() => parseDenseRipgrepMatchJson(source, 1, 16)).toThrow('Invalid rg submatch')
})
@@ -1,24 +0,0 @@
import { describe, expect, it } from 'vitest'
import { CreateTerminalTab } from './session-tabs-schemas-params'
const SESSION = { key: 'session_id', id: 'codex-1' }
describe('session.tabs.createTerminal resumeProviderSession', () => {
it('drops a malformed value instead of refusing the create', () => {
const parsed = CreateTerminalTab.parse({
worktree: 'id:wt',
resumeProviderSession: { key: 'thread', id: '' }
})
expect(parsed.resumeProviderSession).toBeUndefined()
})
it('refuses it on a fork, which uses the host launch settings', () => {
const parsed = CreateTerminalTab.safeParse({
worktree: 'id:wt',
sourceChatFork: { sessionId: 'chat-1' },
clientMutationId: 'fork-1',
resumeProviderSession: SESSION
})
expect(parsed.success).toBe(false)
})
})
@@ -1,21 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
makeFolderWorkspace,
makeProjectGroup
} from '../../folder-workspaces/folder-workspace-host-routing.test-fixture'
import { getRenderableFolderWorkspaces } from './folder-workspace-lanes'
const manualGroup = makeProjectGroup({ id: 'group-manual', name: 'Manual', parentPath: null })
const folderWorkspace = makeFolderWorkspace({ projectGroupId: manualGroup.id })
describe('getRenderableFolderWorkspaces', () => {
it('renders a folder workspace whose owning group has no base folder', () => {
expect(getRenderableFolderWorkspaces([folderWorkspace], [manualGroup])).toEqual([
{ folderWorkspace, projectGroup: manualGroup }
])
})
it('hides a folder workspace whose owning group is not visible', () => {
expect(getRenderableFolderWorkspaces([folderWorkspace], [])).toEqual([])
})
})
@@ -1,21 +0,0 @@
import { describe, expect, it } from 'vitest'
import { detectTerminalFileUriLinks } from './terminal-file-uri-link'
describe('detectTerminalFileUriLinks', () => {
it('keeps standard unescaped parentheses and apostrophes inside the path', () => {
const uri = "file:///tmp/Brennan's%20Report%20(final)"
const [link] = detectTerminalFileUriLinks(`open (${uri})`)
expect(link.pathText).toBe("/tmp/Brennan's Report (final)")
expect(link.displayText).toBe(uri)
})
it('trims trailing sentence punctuation but keeps the extension', () => {
const [link] = detectTerminalFileUriLinks('see file:///tmp/out.html.')
expect(link.displayText).toBe('file:///tmp/out.html')
expect(link.pathText).toBe('/tmp/out.html')
})
it('does not expose oversized terminal tokens to filesystem probing', () => {
expect(detectTerminalFileUriLinks(`file:///tmp/${'a'.repeat(10_000)}`)).toEqual([])
})
})
@@ -1,19 +0,0 @@
import { describe, expect, it } from 'vitest'
import { createBellDetector } from './terminal-bell-detector'
describe('createBellDetector', () => {
it('keeps split OSC state so title terminators are not reported as bells', () => {
const detector = createBellDetector()
expect(detector.chunkContainsBell('\x1b]0;Codex working')).toBe(false)
expect(detector.chunkContainsBell('\x07')).toBe(false)
expect(detector.chunkContainsBell('\x07')).toBe(true)
})
it('treats BEL after a split non-OSC escape as a real bell', () => {
const detector = createBellDetector()
expect(detector.chunkContainsBell('\x1b')).toBe(false)
expect(detector.chunkContainsBell('\x07')).toBe(true)
})
})