test: remove 329 low-value tests (#39560)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-07 10:27:06 -08:00
committed by GitHub
co-authored by OrcaWin
parent 97f0dd7a04
commit ba0fc2d956
85 changed files with 74 additions and 8329 deletions
File diff suppressed because one or more lines are too long
@@ -2962,7 +2962,6 @@
"src/main/persistence/profile-state/profile-state-recovery-batch.test.ts": 180,
"src/main/persistence/profile-state/profile-state-recovery-copy.test.ts": 133,
"src/main/persistence/profile-state/profile-state-recovery-crash-boundaries.test.ts": 11125,
"src/main/persistence/profile-state/profile-state-recovery-crash-process.test.ts": 275,
"src/main/persistence/profile-state/profile-state-runtime-preflight.test.ts": 723,
"src/main/persistence/profile-state/profile-state-section-repair.test.ts": 5877,
"src/main/persistence/profile-state/profile-state-selected-profile-recovery.test.ts": 1860,
@@ -2976,9 +2975,7 @@
"src/main/persistence/profile-state/profile-state-write-transaction.test.ts": 94,
"src/main/persistence/profile-state/profile-state-writer-capacity-errors.test.ts": 84,
"src/main/persistence/profile-state/profile-state-writer-close.test.ts": 108,
"src/main/persistence/profile-state/profile-state-writer-open-error-cause.test.ts": 79,
"src/main/persistence/profile-state/profile-state-writer-protocol-faults.test.ts": 747,
"src/main/persistence/profile-state/profile-state-writer-reopen-policy.test.ts": 57,
"src/main/persistence/profile-state/profile-state-writer-sleep.test.ts": 803,
"src/main/persistence/profile-state/profile-state-writer-worker.test.ts": 1458,
"src/main/persistence/restoring-sessions/pane-alias-normalization.test.ts": 847,
@@ -3011,15 +3008,12 @@
"src/main/persistence/terminal-topology/persistence-ssh-remote-pty-binding-replay.test.ts": 1853,
"src/main/persistence/terminal-topology/persistence-ssh-remote-pty-leases.test.ts": 2079,
"src/main/persistence/terminal-topology/persistence-tab-terminal-pane-binding-load.test.ts": 1795,
"src/main/persistence/terminal-topology/persistence-terminal-option-key-migration.test.ts": 1937,
"src/main/persistence/terminal-topology/terminal-close-write-failure-store.test.ts": 2870,
"src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts": 2027,
"src/main/persistence/terminal-topology/terminal-close-write-failure.test.ts": 58,
"src/main/persistence/terminal-topology/terminal-late-bind-layout-rules.test.ts": 1808,
"src/main/persistence/terminal-topology/terminal-layout-apply.test.ts": 2005,
"src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts": 1773,
"src/main/persistence/terminal-topology/terminal-layout-create.test.ts": 2107,
"src/main/persistence/terminal-topology/terminal-layout-default-tabs-applied.test.ts": 1749,
"src/main/persistence/terminal-topology/terminal-layout-pane-ops.test.ts": 1753,
"src/main/persistence/terminal-topology/terminal-layout-rename-tabs.test.ts": 1977,
"src/main/persistence/terminal-topology/terminal-layout-sleep-wake.test.ts": 2198,
@@ -3027,13 +3021,11 @@
"src/main/persistence/terminal-topology/terminal-leaf-move.test.ts": 2197,
"src/main/persistence/terminal-topology/terminal-owner-invariants.test.ts": 285,
"src/main/persistence/terminal-topology/terminal-pane-admission-layout-owner.test.ts": 1796,
"src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts": 381,
"src/main/persistence/terminal-topology/terminal-sleep-quit-resume.test.ts": 1766,
"src/main/persistence/terminal-topology/terminal-window-pane-detach.test.ts": 1941,
"src/main/persistence/terminal-topology/unshown-live-terminal-placement-restart.test.ts": 2114,
"src/main/persistence/terminal-topology/windowless-host-reload-keeps-terminals.test.ts": 1872,
"src/main/persistence/terminal-topology/windowless-restart-lost-binding.test.ts": 1626,
"src/main/persistence/tracking-repos/local-worktree-metadata-batch-pruning.bench.test.ts": 673,
"src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.test.ts": 544,
"src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts": 619,
"src/main/persistence/tracking-repos/persistence-deregistered-repo-residue.test.ts": 2374,
@@ -3054,9 +3046,7 @@
"src/main/persistence/tracking-repos/persistence-worktree-meta-host-target-twins.test.ts": 2062,
"src/main/persistence/tracking-repos/persistence-worktree-name-retirement.test.ts": 2905,
"src/main/persistence/tracking-repos/persistence-worktree-visibility.test.ts": 1935,
"src/main/persistence/tracking-repos/probeable-local-worktree-metadata-candidates.test.ts": 541,
"src/main/persistence/tracking-repos/project-group-session-batch.test.ts": 496,
"src/main/persistence/tracking-repos/project-host-compatibility.test.ts": 75,
"src/main/persistence/tracking-repos/repo-update-host-guard.test.ts": 478,
"src/main/persistence/tracking-repos/worktree-identity-migration-field-coverage.test.ts": 505,
"src/main/persistence/tracking-repos/worktree-metadata-normalization.test.ts": 372,
@@ -5819,7 +5809,6 @@
"src/renderer/src/components/native-chat/session/options/controls/NativeChatModelCombobox.test.tsx": 692,
"src/renderer/src/components/native-chat/NativeChatNewRowsMarker.test.tsx": 3019,
"src/renderer/src/components/native-chat/usage/NativeChatNoticeRow.test.tsx": 3399,
"src/renderer/src/components/native-chat/markdown/NativeChatPacedMarkdown.mermaid.test.tsx": 2702,
"src/renderer/src/components/native-chat/NativeChatPaneHeader.test.tsx": 2736,
"src/renderer/src/components/native-chat/NativeChatPromptEditor.paragraph-selection.test.tsx": 652,
"src/renderer/src/components/native-chat/NativeChatPromptEditor.test.tsx": 1110,
@@ -5830,7 +5819,6 @@
"src/renderer/src/components/native-chat/queue/NativeChatQueuedMessageRows.test.tsx": 2691,
"src/renderer/src/components/native-chat/prompts/NativeChatResolutionReceipt.test.tsx": 912,
"src/renderer/src/components/native-chat/media/images/NativeChatResolvedView.context-menu.test.tsx": 4025,
"src/renderer/src/components/native-chat/media/images/NativeChatResolvedView.images.test.tsx": 3477,
"src/renderer/src/components/native-chat/NativeChatResolvedView.prompt-card-composer.test.tsx": 7151,
"src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx": 3594,
"src/renderer/src/components/native-chat/NativeChatResolvedView.turn-status.test.tsx": 4368,
@@ -5859,7 +5847,6 @@
"src/renderer/src/components/native-chat/usage/NativeChatUsageLimitActions.test.tsx": 3183,
"src/renderer/src/components/native-chat/NativeChatUserMessageFold.test.tsx": 3156,
"src/renderer/src/components/native-chat/NativeChatView.test.tsx": 5672,
"src/renderer/src/components/native-chat/media/visuals/NativeChatVisualFrame.test.tsx": 643,
"src/renderer/src/components/native-chat/session/attention/StructuredAgentSessionAttentionBridge.lifecycle.test.tsx": 2167,
"src/renderer/src/components/native-chat/session/attention/StructuredAgentSessionAttentionBridge.test.tsx": 2855,
"src/renderer/src/components/native-chat/StructuredAgentSessionPaneOverlayLayer.test.tsx": 620,
@@ -5892,7 +5879,6 @@
"src/renderer/src/components/native-chat/native-chat-element-file-drop.test.tsx": 2057,
"src/renderer/src/components/native-chat/native-chat-external-attachments-destination.test.tsx": 951,
"src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.test.ts": 1937,
"src/renderer/src/components/native-chat/links/actions/native-chat-file-link.test.ts": 336,
"src/renderer/src/components/native-chat/native-chat-header-ownership.test.tsx": 2796,
"src/renderer/src/components/native-chat/links/actions/native-chat-host-file-open.test.ts": 895,
"src/renderer/src/components/native-chat/links/previews/native-chat-hover-preview-cache.test.ts": 49,
@@ -5936,7 +5922,6 @@
"src/renderer/src/components/native-chat/native-chat-turn-diffs.test.ts": 340,
"src/renderer/src/components/native-chat/native-chat-unkerned-run-decorations.test.ts": 594,
"src/renderer/src/components/native-chat/media/visuals/native-chat-visual-markdown-syntax.test.tsx": 2351,
"src/renderer/src/components/native-chat/media/visuals/native-chat-visual-read-client.test.ts": 163,
"src/renderer/src/components/native-chat/native-chat-working-status-shared-clock.test.tsx": 412,
"src/renderer/src/components/native-chat/session/options/catalog/omp-model-switch-capability.test.ts": 211,
"src/renderer/src/components/native-chat/session/options/terminal/serialized-screen-background-rows.test.ts": 131,
@@ -5969,7 +5954,6 @@
"src/renderer/src/components/native-chat/host-access/use-native-chat-host-outage.test.tsx": 2131,
"src/renderer/src/components/native-chat/prompts/use-native-chat-interactive-prompt-card.test.ts": 1962,
"src/renderer/src/components/native-chat/use-native-chat-launch-draft-adoption.test.tsx": 319,
"src/renderer/src/components/native-chat/links/actions/use-native-chat-link-actions.test.tsx": 2225,
"src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-live-session-pending.test.ts": 2063,
"src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-live-session-visibility.test.ts": 2047,
"src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-live-session-wsl-wake.test.ts": 1800,
@@ -6473,8 +6457,6 @@
"src/renderer/src/components/task-page/task-page-initial-selection-scaling.test.tsx": 1953,
"src/renderer/src/components/task-page/task-page-work-item-pagination.test.ts": 63,
"src/renderer/src/components/task-page/use-task-page-source-display.test.tsx": 5228,
"src/renderer/src/components/terminal-pane/layout/close/CloseTerminalDialog.test.tsx": 484,
"src/renderer/src/components/terminal-pane/layout/close/PinnedTabCloseDialog.test.tsx": 2221,
"src/renderer/src/components/terminal-pane/layout/close/RunningTerminalCloseDialog.test.tsx": 2303,
"src/renderer/src/components/terminal-pane/session-fork/TerminalAgentSessionForkDialog.test.tsx": 266,
"src/renderer/src/components/terminal-pane/mounting/TerminalOverlaySlot.emptied-reaction.test.tsx": 430,
@@ -6504,7 +6486,6 @@
"src/renderer/src/components/terminal-pane/account-restart/detached/claude-detached-pane-restart.test.ts": 1938,
"src/renderer/src/components/terminal-pane/provider-notices/claude-diff-panel/claude-diff-panel-notice-banner.test.tsx": 1986,
"src/renderer/src/components/terminal-pane/notifications/claude-side-question-completion.test.ts": 2305,
"src/renderer/src/components/terminal-pane/layout/close/closed-terminal-leaf-notice-layout-owner.test.ts": 1032,
"src/renderer/src/components/terminal-pane/provider-notices/codex-backfill/codex-backfill-error-detector.test.ts": 26,
"src/renderer/src/components/terminal-pane/account-restart/detached/codex-detached-pane-restart.test.ts": 2270,
"src/renderer/src/components/terminal-pane/provider-notices/codex-server-isolation/codex-shared-server-banner.test.tsx": 2766,
@@ -6516,8 +6497,6 @@
"src/renderer/src/components/terminal-pane/viewport/desktop-fit-fallback.test.ts": 92,
"src/renderer/src/components/terminal-pane/pty-connection/output-restore/direct-ssh-hidden-output-restore-unavailable-banner.test.ts": 1975,
"src/renderer/src/components/terminal-pane/links/http/edge-wrapped-terminal-http-links.test.ts": 529,
"src/renderer/src/components/terminal-pane/layout/expand/expanded-pane-layout-render-stability.test.ts": 2069,
"src/renderer/src/components/terminal-pane/layout/expand/expanded-pane-layout.test.ts": 102,
"src/renderer/src/components/terminal-pane/links/floating-file-link-selection.test.ts": 2282,
"src/renderer/src/components/terminal-pane/links/http/framed-overlay-terminal-http-links.test.ts": 508,
"src/shared/git-bash-console-capacity.test.ts": 56,
@@ -6529,7 +6508,6 @@
"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,
"src/renderer/src/components/terminal-pane/pty-connection/startup/launch-parity-window-tab.test.ts": 17426,
"src/renderer/src/components/terminal-pane/layout/close/layout-owner-pane-close.test.ts": 2445,
"src/renderer/src/components/terminal-pane/layout-serialization.test.ts": 109,
"src/renderer/src/components/terminal-pane/pty-transport/legacy-relay/legacy-relay-bridge-transport.test.ts": 358,
"src/renderer/src/components/terminal-pane/parking/retention/manual-terminal-worktree-park-eligibility.test.ts": 302,
@@ -6713,7 +6691,6 @@
"src/renderer/src/components/terminal-pane/snapshots/remote-snapshot-history-seam.test.ts": 2093,
"src/renderer/src/components/terminal-pane/snapshots/replay-guard.test.ts": 371,
"src/renderer/src/components/terminal-pane/links/http/repro-8832-url-next-line.test.ts": 592,
"src/renderer/src/components/terminal-pane/layout/close/request-active-terminal-pane-close.test.ts": 187,
"src/renderer/src/components/terminal-pane/layout/split/resolve-split-cwd.test.ts": 56,
"src/renderer/src/components/terminal-pane/snapshots/restored-snapshot-coverage.test.ts": 44,
"src/renderer/src/components/terminal-pane/pty-transport/ipc/scan22-ssh-new-tab-disposed-spawn-kill.repro.test.ts": 577,
@@ -6763,8 +6740,6 @@
"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-midline-preedit-tail.test.ts": 980,
"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts": 498,
"src/renderer/src/components/terminal-pane/emulation/terminal-inline-image-da1.test.ts": 127,
"src/renderer/src/components/terminal-pane/input/terminal-input-host-platform.test.ts": 1681,
"src/renderer/src/components/terminal-pane/input/terminal-input-quarantine.test.ts": 62,
"src/renderer/src/components/terminal-pane/input/ime/terminal-ios-hangul-preedit-coexistence.test.ts": 621,
"src/renderer/src/components/terminal-pane/input/ime/terminal-ios-hangul-preedit-device-trace.test.ts": 415,
"src/renderer/src/components/terminal-pane/input/ime/terminal-ios-hangul-preedit.test.ts": 818,
@@ -6800,7 +6775,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/reconciliation/terminal-pane-frame-reconciliation.test.ts": 903,
"src/renderer/src/components/terminal-pane/host-state/terminal-pane-host-state-memo.test.ts": 4534,
"src/renderer/src/components/terminal-pane/layout/ownership/terminal-pane-layout-owner-commands.test.ts": 182,
"src/renderer/src/components/terminal-pane/mounting/terminal-pane-mount-bootstrap.test.ts": 1723,
"src/renderer/src/components/terminal-pane/mounting/terminal-pane-mount-events-layout-owner.test.ts": 986,
"src/renderer/src/components/terminal-pane/render-health/recovery/terminal-pane-recovery-host-rebind-cap.test.ts": 826,
@@ -6809,11 +6783,8 @@
"src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-request-routing.test.ts": 2015,
"src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-with-inherited-cwd.test.ts": 1834,
"src/renderer/src/components/terminal-pane/pty-transport/recovery/terminal-pane-surface-ownership.test.ts": 426,
"src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-commit.test.ts": 2141,
"src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-frame-drawn.test.ts": 1889,
"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/layout/detach/terminal-pane-tab-detach.test.ts": 1893,
"src/renderer/src/components/terminal-pane/parking/verdict/terminal-park-verdict-flip-telemetry.test.ts": 123,
"src/renderer/src/components/terminal-pane/parking/verdict/terminal-park-verdict-worktree-driver-loop.test.tsx": 735,
"src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-pane-candidates.test.ts": 252,
@@ -6841,7 +6812,6 @@
"src/renderer/src/components/terminal-pane/snapshots/terminal-snapshot-replay-paint.test.ts": 499,
"src/renderer/src/components/terminal-pane/titles/terminal-title-evidence.test.ts": 184,
"src/renderer/src/components/terminal-pane/links/http/terminal-url-link-click.test.ts": 2057,
"src/renderer/src/components/terminal-pane/input/terminal-user-input-signal.test.ts": 57,
"src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts": 1669,
"src/renderer/src/components/terminal-pane/render-health/terminal-webgl-atlas-recovery.test.ts": 48,
"src/renderer/src/components/terminal-pane/links/files/terminal-worktree-path-link.test.ts": 1878,
@@ -1,4 +1,4 @@
import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs'
import { existsSync, mkdtempSync, readdirSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -103,18 +103,6 @@ describe('the backup taken before the first boot-time rewrite of saved data', ()
expect(readGeneration(backupPath)).toBe(1)
})
it('refuses rather than replaces something else at the backup path', async () => {
const { databasePath, backupPath } = fixture()
mkdirSync(backupPath)
vi.spyOn(console, 'error').mockImplementation(() => {})
const runBackup = vi.fn(writeProfileStateBackup)
await expect(
ensureProfileStatePreMigrationBackup(databasePath, PROFILE, runBackup)
).resolves.toBe('failed')
expect(runBackup).not.toHaveBeenCalled()
})
it('is not one of the hourly backups, so rotation never prunes it', async () => {
const { databasePath, backupPath, write } = fixture()
await ensureProfileStatePreMigrationBackup(databasePath, PROFILE, writeProfileStateBackup)
@@ -15,7 +15,7 @@ import {
} from 'node:fs'
import type * as FileSystem from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, dirname, isAbsolute, join } from 'node:path'
import { basename, dirname, join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import * as processes from '@orca/process-host'
import { copyProfileStateRecoveryFiles } from './profile-state-recovery-copy'
@@ -109,38 +109,7 @@ describe('batched profile recovery copies', () => {
expectNoTemporary(directory)
})
it('does nothing for an empty batch', () => {
const run = vi.spyOn(processes, 'runProcessSync')
copyProfileStateRecoveryFiles([])
expect(run).not.toHaveBeenCalled()
})
describe.skipIf(process.platform !== 'darwin')('Darwin batch boundaries', () => {
it('shares one process with absolute arguments and the per-file timeout budget', () => {
const { directory, files } = fixture()
const run = vi.spyOn(processes, 'runProcessSync')
copyProfileStateRecoveryFiles(files)
expect(run).toHaveBeenCalledOnce()
const spec = run.mock.calls[0]?.[0]
expect(spec?.args?.slice(1).every(isAbsolute)).toBe(true)
expect(spec?.args).toHaveLength(4)
expect(spec?.timeoutMs).toBe(60_000)
expectIndependent(files)
expectNoTemporary(directory)
})
it('bounds a shared process when many large artifacts are retained', () => {
const { directory, files } = fixture(
Array.from({ length: 17 }, (_, index) => `backup-${index}.db`)
)
const run = vi.spyOn(processes, 'runProcessSync')
copyProfileStateRecoveryFiles(files)
expect(run).toHaveBeenCalledTimes(2)
expect(run.mock.calls.every(([spec]) => (spec.args?.length ?? 0) <= 18)).toBe(true)
expectIndependent(files)
expectNoTemporary(directory)
})
it.each([
['same.db', 'same.db'],
['CASE.db', 'case.db'],
@@ -461,35 +461,6 @@ describe('SQLite recovery process death', () => {
)
})
describe('seeded recovery fixture copies', () => {
it.each([
['json', false],
['json', true],
['sqlite', true]
] as const)(
'isolates %s/accepted=%s through corruption and WAL reopen',
async (kind, accepted) => {
const first = await fixture(kind, accepted)
const second = await fixture(kind, accepted)
const seed = seededFixtures.get(`${kind}/${accepted}`)
if (!seed) {
throw new Error('Seed fixture was not retained')
}
expect(new Set([first.root, second.root, seed.root]).size).toBe(3)
for (const [suffix, bytes] of seed.originalFamily) {
expect(readFileSync(`${first.databasePath}${suffix}`).equals(bytes)).toBe(true)
writeFileSync(`${first.databasePath}${suffix}`, 'corrupted-copy')
expect(readFileSync(`${second.databasePath}${suffix}`).equals(bytes)).toBe(true)
expect(readFileSync(`${seed.databasePath}${suffix}`).equals(bytes)).toBe(true)
}
const third = await fixture(kind, accepted)
expect(readSqlite(third.databasePath)).toEqual(oldState)
expect(readFileSync(seed.backupPath).equals(seed.backupBytes)).toBe(true)
expect(readFileSync(seed.exportPath, 'utf8')).toBe(selectedJson)
}
)
})
it.each(['first-export', 'authority-marker'] as const)(
'keeps current-JSON rollback safe through %s removal',
async (boundary) => {
@@ -1,25 +0,0 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it } from 'vitest'
import { buildRecoveryCrashProcess } from './profile-state-recovery-crash-process'
it('bundles one process-host source graph into the isolated recovery fixture', () => {
const root = mkdtempSync(join(tmpdir(), 'orca-recovery-bundle-'))
try {
const { metafile } = buildRecoveryCrashProcess(root)
const packageInputs = Object.keys(metafile.inputs).filter((file) =>
file.includes('/process-host/')
)
expect(packageInputs).toContain('src/packages/process-host/src/run-process.ts')
expect(packageInputs.every((file) => file.startsWith('src/packages/process-host/src/'))).toBe(
true
)
const packageExternals = Object.values(metafile.outputs)
.flatMap((output) => output.imports)
.filter((entry) => entry.external && entry.path.startsWith('@orca/process-host'))
expect(packageExternals).toEqual([])
} finally {
rmSync(root, { recursive: true, force: true })
}
})
@@ -35,15 +35,6 @@ describe('profile runtime preflight', () => {
expect(result.sqliteVersion).toMatch(/^\d+\.\d+\.\d+$/)
})
it('refuses readiness when a required worker artifact is absent', async () => {
await expect(
preflightProfileStateRuntime({
workerPath: join(directory, 'missing.js'),
backupWorkerPath
})
).rejects.toThrow('Profile state writer')
})
it('does not trust a backup success reply without a valid database', async () => {
const corruptBackup = join(directory, 'corrupt-backup.cjs')
writeFileSync(
@@ -4,7 +4,7 @@ import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { acquireProfileStateMaintenance } from './profile-state-access'
import { migrateProfileStateToSqlite } from './profile-state-migration'
import { getProfileStateExports, rollbackProfileState } from './profile-state-recovery-command'
import { rollbackProfileState } from './profile-state-recovery-command'
import { bootstrapProfileStateAuthority } from './profile-state-authority-bootstrap'
const roots: string[] = []
@@ -67,13 +67,4 @@ describe('explicit profile recovery selection', () => {
expect(reopened.migrated).toBe(true)
reopened.authority?.close()
})
it('refuses unknown and escaping IDs without falling back to the active profile', () => {
const f = fixture()
const before = readFileSync(f.active.databaseFile)
for (const id of ['missing', '../active']) {
expect(() => getProfileStateExports(f.root, id)).toThrow('Could not resolve')
}
expect(readFileSync(f.active.databaseFile).equals(before)).toBe(true)
})
})
@@ -9,7 +9,7 @@ import {
_resetSecretStoreForTests
} from '../../../shared/secret-store'
import { Store } from '../loading-store/store'
import * as storeDomains from '../loading-store/store-domain-composition'
import { ProfileStateSqliteAuthority } from './profile-state-sqlite-authority'
let keyState: 'available' | 'unavailable' | 'decrypt-fails' = 'available'
@@ -80,38 +80,6 @@ const secrets = {
}
const sealed = (value: string) => Buffer.from(`encrypted:${value}`, 'utf8').toString('base64')
it.each([false, true])(
'rejects reused input before Store context installation (secret=%s)',
(hasSecret) => {
const directory = mkdtempSync(join(tmpdir(), 'orca-consumed-startup-'))
directories.push(directory)
const authority = new ProfileStateSqliteAuthority(join(directory, 'profile-state.db'), 'once')
if (hasSecret) {
authority.writeSerializedState(
Buffer.from(
JSON.stringify({
settings: { opencodeSessionCookie: sealed(secrets.cookie) }
})
)
)
}
const options = {
dataFile: join(directory, 'orca-data.json'),
profileStateAuthority: authority,
initialAuthorityState: authority.readInitialState()
}
const store = new Store(options)
stores.push(store)
if (hasSecret) {
expect(store.getSettings().opencodeSessionCookie).toBe(secrets.cookie)
}
const install = vi.spyOn(storeDomains, 'installStoreDomainContexts')
expect(() => new Store(options)).toThrow('already been consumed')
expect(install).not.toHaveBeenCalled()
}
)
describe.each(['serialized', 'parsed'] as const)(
'%s startup secret retention',
(representation) => {
@@ -6,7 +6,7 @@ import type { ProfileStateAuthority } from '../loading-store/profile-state-autho
import { Store } from '../loading-store/store'
import { bootstrapProfileStateAuthority } from './profile-state-authority-bootstrap'
import * as profileStateDatabase from './profile-state-database'
import * as profileStateDocumentReader from './profile-state-document-reader'
import { hashProfileStateJson, importProfileStateJson } from './profile-state-documents'
import { ProfileStateSqliteAuthority } from './profile-state-sqlite-authority'
import { createProfileStateStore } from './profile-state-store-factory'
@@ -114,28 +114,6 @@ describe('profile state startup snapshot handoff', () => {
})
})
it.each([false, true])('reads established storage once with retained JSON=%s', (keepJson) => {
const paths = createEstablishedProfile(keepJson)
const open = vi.spyOn(profileStateDatabase, 'openProfileStateDatabaseReadOnly')
const documentRead = vi.spyOn(profileStateDocumentReader, 'readProfileStateDocuments')
const initialRead = vi.spyOn(ProfileStateSqliteAuthority.prototype, 'readInitialState')
const serializedRead = vi.spyOn(ProfileStateSqliteAuthority.prototype, 'readSerializedState')
const acceptedRead = vi.spyOn(ProfileStateSqliteAuthority.prototype, 'readAcceptedState')
const result = createProfileStateStore({ ...paths })
stores.push(result.store)
expect(open).toHaveBeenCalledTimes(1)
expect(documentRead).toHaveBeenCalledTimes(1)
expect(initialRead).toHaveBeenCalledTimes(keepJson ? 0 : 1)
expect(serializedRead).not.toHaveBeenCalled()
expect(acceptedRead).toHaveBeenCalledTimes(keepJson ? 1 : 0)
expect(result.store.getSettings().theme).toBe('dark')
expect(JSON.parse(result.store.prepareProfileStateExport().json)).toMatchObject({
futureDomain: { keep: true }
})
})
it('uses the validated empty snapshot without rereading SQLite or consulting JSON', () => {
const paths = createPaths()
const opened = profileStateDatabase.openProfileStateDatabase(
@@ -167,20 +145,6 @@ describe('profile state startup snapshot handoff', () => {
expect(bootstrapped.authority.readSerializedState()).toContain('"dark"')
})
it('consumes a parsed startup snapshot once, including an empty revision', () => {
const paths = createPaths()
const opened = profileStateDatabase.openProfileStateDatabase(
paths.databaseFile,
paths.profileId
)
opened.db.close()
const authority = new ProfileStateSqliteAuthority(paths.databaseFile, paths.profileId)
authorities.push(authority)
const initial = authority.readInitialState()
expect(initial.takeParsedState?.()).toBeUndefined()
expect(() => initial.takeParsedState?.()).toThrow('already been consumed')
})
it.each([false, true])(
'fences a writer between bootstrap and Store construction with retained JSON=%s',
(keepJson) => {
@@ -284,26 +248,4 @@ describe('profile state startup snapshot handoff', () => {
expect(again.getSettings().opencodeSessionCookie).toBe('startup-secret')
expect(again.getSettings().theme).toBe('light')
})
it('rejects initial state without its authority or alongside migration input', () => {
const paths = createPaths()
const authority = new ProfileStateSqliteAuthority(paths.databaseFile, paths.profileId)
const otherAuthority = new ProfileStateSqliteAuthority(paths.databaseFile, paths.profileId)
const initialAuthorityState = { authority, serializedState: '{}' }
expect(() => new Store({ dataFile: paths.dataFile, initialAuthorityState })).toThrow(
'must belong to its profile-state authority'
)
expect(
() => new Store({ profileStateAuthority: otherAuthority, initialAuthorityState })
).toThrow('must belong to its profile-state authority')
expect(
() =>
new Store({
profileStateAuthority: authority,
initialAuthorityState,
serializedState: '{}'
})
).toThrow('cannot use both a profile-state authority and serialized state')
})
})
@@ -68,25 +68,6 @@ describe('profile state write transaction ownership', () => {
}
})
it('keeps any other failed commit indeterminate even after SQLite rolled back', () => {
const db = new Database(':memory:')
db.exec('CREATE TABLE writes (id INTEGER)')
// Failed fsync can leave an already-written commit frame.
const ioerr = Object.assign(new Error('disk I/O error'), {
code: 'ERR_SQLITE_ERROR',
errcode: 1034
})
const restore = failCommitAfterAutoRollback(db, ioerr)
try {
expect(() =>
withProfileStateWriteTransaction(db, () => db.exec('INSERT INTO writes VALUES (1)'))
).toThrow(ProfileStateIndeterminateWriteError)
} finally {
restore()
db.close()
}
})
it('rolls back a failed deferred commit and leaves the connection usable', () => {
const db = new Database(':memory:')
try {
@@ -106,17 +106,3 @@ it('keeps an unacknowledged close pending, then holds abort until the terminated
expect(onFailure).toHaveBeenCalledOnce()
expect(vi.getTimerCount()).toBe(0)
})
it('joins an aborted writer without reporting a close request that was never sent', async () => {
const { client, worker } = await createClient()
const aborting = client.abort()
const closing = client.close()
await waitForPoll()
vi.advanceTimersByTime(WARNING_MS * 10)
expect(await isSettled(closing)).toBe(false)
expect(diagnostics.slow).not.toHaveBeenCalled()
expect(vi.getTimerCount()).toBe(0)
worker.emit('exit', 1)
await aborting
await closing
})
@@ -1,63 +0,0 @@
import { expect, it } from 'vitest'
import Database from '../../sqlite/sync-database'
import {
decodeProfileStateWriterError,
encodeProfileStateWriterError
} from './profile-state-writer-errors'
import { ProfileStateDatabaseOpenError } from './profile-state-database-errors'
function acrossWorker(error: unknown): Error {
return decodeProfileStateWriterError(
JSON.parse(JSON.stringify(encodeProfileStateWriterError(error)))
)
}
// Regression #27333: missing causes concealed the failing SQLite call.
it('keeps the SQLite failure behind a database open error across the writer boundary', () => {
const sqliteFailure = Object.assign(new Error('database is locked'), {
code: 'ERR_SQLITE_ERROR',
errcode: 261
})
const decoded = acrossWorker(
new ProfileStateDatabaseOpenError(
'unreadable',
'Unable to initialize profile state database',
sqliteFailure
)
)
expect(decoded).toBeInstanceOf(ProfileStateDatabaseOpenError)
expect(decoded.cause).toBeInstanceOf(Error)
expect(decoded.cause).toMatchObject({
code: 'ERR_SQLITE_ERROR',
errcode: 261,
message: 'database is locked'
})
})
it('carries a real SQLite error code from a failed open', () => {
const db = new Database(':memory:')
let failure: unknown
try {
db.exec('SELECT * FROM missing_table')
} catch (error) {
failure = error
} finally {
db.close()
}
const decoded = acrossWorker(
new ProfileStateDatabaseOpenError('unreadable', 'open failed', failure)
)
expect(decoded.cause).toMatchObject({
code: 'ERR_SQLITE_ERROR',
errcode: 1,
message: expect.stringContaining('missing_table')
})
})
it('keeps a cause-less open error cause-less', () => {
const decoded = acrossWorker(new ProfileStateDatabaseOpenError('unreadable', 'gone'))
expect(decoded).toBeInstanceOf(ProfileStateDatabaseOpenError)
expect(decoded.cause).toBeUndefined()
})
@@ -57,37 +57,6 @@ describe('writer protocol refuses uncertain acknowledgements', () => {
})
})
it.each(['undefined', 'null', '0', '2'])(
'refuses a versioned export with revision %s for an admitted revision of one',
async (exportedRevision) => {
const client = clientFor(`parentPort.postMessage({
id: request.id, ok: true, revision: 1, exportedRevision: ${exportedRevision}
})`)
await client.ready
await expect(client.writeLatestJsonExport('unused.json')).rejects.toMatchObject({
code: 'profile-state-writer-protocol',
outcome: 'indeterminate'
})
}
)
it('refuses a revision jump at an unchanged-state fence', async () => {
const client = clientFor('parentPort.postMessage({ id: request.id, ok: true, revision: 2 })')
await client.ready
await expect(client.assertCurrentRevision()).rejects.toMatchObject({
code: 'profile-state-writer-protocol',
outcome: 'indeterminate'
})
})
it('refuses an initialization acknowledgement for a different revision', async () => {
const client = clientFor('', '{ id: 0, ok: true, revision: 2 }')
await expect(client.ready).rejects.toMatchObject({
code: 'profile-state-writer-protocol',
outcome: 'known-failure'
})
})
it('reports an idle writer exit even without a subsequent save', async () => {
const notify = vi.fn()
const client = clientFor('', undefined, notify, 'setTimeout(() => process.exit(1), 50)')
@@ -99,34 +68,4 @@ describe('writer protocol refuses uncertain acknowledgements', () => {
await client.close()
expect(notify).toHaveBeenCalledOnce()
})
it('leaves startup failure reporting to the startup caller', async () => {
const notify = vi.fn()
const client = clientFor('', '{ id: 0, ok: true, revision: 2 }', notify)
await expect(client.ready).rejects.toThrow()
await client.close()
expect(notify).not.toHaveBeenCalled()
})
it('does not report saving stopped after a recoverable request failure or clean close', async () => {
const notify = vi.fn()
const client = clientFor(
`
if (request.command === 'close') {
parentPort.postMessage({ id: request.id, ok: true, revision: 1 })
parentPort.close()
} else {
parentPort.postMessage({ id: request.id, ok: false,
error: { code: 'SQLITE_BUSY', message: 'busy', outcome: 'known-failure' } })
}
`,
undefined,
notify
)
await client.ready
await expect(client.assertCurrentRevision()).rejects.toThrow('busy')
expect(() => client.assertWritable()).not.toThrow()
await client.close()
expect(notify).not.toHaveBeenCalled()
})
})
@@ -1,64 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ProfileStateWriterReopenPolicy } from './profile-state-writer-reopen-policy'
const spawnFailure = Object.assign(new Error('spawn failed'), {
code: 'profile-state-writer-unavailable'
})
describe('ProfileStateWriterReopenPolicy', () => {
beforeEach(() => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
})
afterEach(() => vi.restoreAllMocks())
it('retries the first failure at once, then backs off up to a minute', () => {
let now = 0
const policy = new ProfileStateWriterReopenPolicy(() => now)
expect(policy.recordFailure(spawnFailure)).toEqual({ retryInMs: 0 })
expect(() => policy.admit()).not.toThrow()
expect(policy.recordFailure(spawnFailure)).toEqual({ retryInMs: 1_000 })
expect(() => policy.admit()).toThrow('spawn failed')
now = 1_000
expect(() => policy.admit()).not.toThrow()
for (let failure = 0; failure < 10; failure += 1) {
policy.recordFailure(spawnFailure)
}
now += 59_999
expect(() => policy.admit()).toThrow('spawn failed')
now += 1
expect(() => policy.admit()).not.toThrow()
})
it('forgets the backoff once a reopen succeeds', () => {
let now = 0
const policy = new ProfileStateWriterReopenPolicy(() => now)
policy.recordFailure(spawnFailure)
policy.recordFailure(spawnFailure)
policy.recordSuccess()
expect(() => policy.admit()).not.toThrow()
expect(policy.recordFailure(spawnFailure)).toEqual({ retryInMs: 0 })
expect(() => policy.admit()).not.toThrow()
})
it('lets one attempt through a backoff for a final flush', () => {
const policy = new ProfileStateWriterReopenPolicy(() => 0)
policy.recordFailure(spawnFailure)
policy.recordFailure(spawnFailure)
policy.bypassBackoffOnce()
expect(() => policy.admit()).not.toThrow()
expect(() => policy.admit()).toThrow('spawn failed')
})
it('drops a pending bypass once a reopen succeeds', () => {
let now = 0
const policy = new ProfileStateWriterReopenPolicy(() => now)
policy.recordFailure(spawnFailure)
policy.bypassBackoffOnce()
policy.recordSuccess()
policy.recordFailure(spawnFailure)
policy.recordFailure(spawnFailure)
expect(() => policy.admit()).toThrow('spawn failed')
now = 1_000
expect(() => policy.admit()).not.toThrow()
})
})
@@ -9,8 +9,7 @@ import { openProfileStateDatabase } from './profile-state-database'
import { readProfileStateSnapshot } from './profile-state-documents'
import {
ProfileStateWriteWorkerClient,
profileStateWriterFailureOutcome,
resolveProfileStateWriterWorkerPath
profileStateWriterFailureOutcome
} from './profile-state-writer-worker-client'
let bundleRoot: string
@@ -139,27 +138,6 @@ describe('persistent profile state write worker', () => {
expect(existsSync(join(f.root, 'missing.db'))).toBe(false)
})
it('permanently retires bootstrap authority and refuses subsequent calls', () => {
const f = fixture()
for (const call of [
() => f.authority.readInitialState(),
() => f.authority.readAcceptedState('{}'),
() => f.authority.readSerializedState(),
() => f.authority.writeSerializedDomains([]),
() => f.authority.writeCompleteSerializedDomains([]),
() => f.authority.writeSerializedAutomationRuns([], []),
() => f.authority.writeSerializedState(Buffer.from('{}')),
() => f.authority.writeJsonExport(join(f.root, 'export.json')),
() => f.authority.scheduleBackup(),
() => f.authority.assertCurrentRevision(),
() => f.authority.initializeFromRevision(1),
() => f.authority.retireForWorker(),
() => f.authority.close()
]) {
expect(call).toThrow(/retired/)
}
})
it('preserves known validation failures and rejects a peer at the no-op fence', async () => {
const f = fixture()
const client = clientFor(f.initialization)
@@ -349,28 +327,4 @@ describe('persistent profile state write worker', () => {
await client.close()
expect(readState(f.path, f.profileId)).toEqual({ settings: { theme: 'dark' } })
})
it('aborts an active request without treating the pending write as rolled back', async () => {
const f = fixture()
const hung = script(
f.root,
`
const { parentPort } = require('node:worker_threads')
parentPort.postMessage({ id: 0, ok: true, revision: 1 })
parentPort.on('message', () => {})
`
)
const client = clientFor(f.initialization, hung)
await client.ready
const write = client.writeSerializedDomains([{ domain: 'settings', payload: '{}' }])
const failed = expect(write).rejects.toMatchObject({ outcome: 'indeterminate' })
await client.abort()
await failed
await client.close()
})
it('resolves flat and shared-chunk entry layouts', () => {
expect(resolveProfileStateWriterWorkerPath(bundleRoot)).toBe(workerPath)
expect(resolveProfileStateWriterWorkerPath(join(bundleRoot, 'chunks'))).toBe(workerPath)
})
})
@@ -1,51 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { AutomationCreateInput } from '../../../shared/automations-types'
import { getDefaultPersistedState } from '../../../shared/constants'
import { createAutomation } from './automation-definition-operations'
// Desktop rows on a managed SSH host never run; the desktop store refuses new ones for any caller.
describe('desktop automation create on a managed SSH host', () => {
it('refuses the write and keeps the store unchanged', () => {
const state = getDefaultPersistedState('/home/me')
state.sshTargets = [
{
id: 'box',
label: 'Build box',
host: 'box',
port: 22,
username: 'me',
generation: 3,
orcadFence: { environmentId: 'env-1' }
}
]
state.repos = [
{
id: 'repo-1',
path: '/srv/repo',
displayName: 'Repo',
badgeColor: '#000',
addedAt: 1,
connectionId: 'box'
}
]
const input: AutomationCreateInput = {
name: 'Nightly',
prompt: 'Run checks',
agentId: 'claude',
projectId: 'repo-1',
workspaceMode: 'new_per_run',
rrule: 'FREQ=DAILY',
dtstart: 1,
timezone: 'UTC'
}
const operations = {
state,
storageAuthority: 'desktop' as const,
flush: () => undefined,
recordCreated: () => undefined
}
expect(() => createAutomation(operations, input)).toThrow()
expect(state.automations ?? []).toEqual([])
})
})
@@ -89,38 +89,6 @@ describe("a pane's last grid (layout-owner build)", () => {
expect(layouts[movedTo!]?.lastGridsByLeafId).toEqual({ [LEAF_B]: { cols: 91, rows: 33 } })
})
it("writes only the pane's own tab record", async () => {
const { store } = await storeWithSplit()
await apply(store, { ...on, type: 'createTerminalTab', tabId: 'tab-other' })
const before = store.getWorkspaceSession()
await apply(store, {
...on,
type: 'setPaneGrid',
tabId: 'tab-1',
leafId: LEAF_B,
grid: { cols: 91, rows: 33 }
})
const after = store.getWorkspaceSession()
expect(after.terminalLayoutsByTabId['tab-other']).toBe(
before.terminalLayoutsByTabId['tab-other']
)
expect(after.unifiedTabs).toBe(before.unifiedTabs)
expect(after.tabsByWorktree).toBe(before.tabsByWorktree)
})
it('is refused for a pane the tab does not hold', async () => {
const { store } = await storeWithSplit()
const result = await store.applyLayoutCommand({
...on,
type: 'setPaneGrid',
tabId: 'tab-1',
leafId: '33333333-3333-4333-8333-333333333333',
grid: { cols: 80, rows: 24 }
})
expect(result).toMatchObject({ ok: false })
})
it("keeps a grid resized just before quit, written by the quit's flush", async () => {
const { store, directory } = await storeWithSplit()
await store.persistPtyBinding({
@@ -2,9 +2,7 @@ import {
closeTestStores,
createStore,
registerWorkspaceRepos,
testState,
workspaceRepos,
writeDataFile
testState
} from '../persistence-test-harness'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { rmSync, mkdtempSync } from 'node:fs'
@@ -65,58 +63,6 @@ describe('Store', () => {
await closeTestStores()
rmSync(testState.dir, { recursive: true, force: true })
})
it('remaps legacy SSH lease leaf ids by PTY when the layout is already normalized', async () => {
writeDataFile({
schemaVersion: 1,
repos: workspaceRepos('wt1'),
worktreeMeta: {},
settings: {},
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {
activeRepoId: 'r1',
activeWorktreeId: 'wt1',
activeTabId: 'tab1',
tabsByWorktree: {
wt1: [
{
id: 'tab1',
worktreeId: 'wt1',
title: 'Terminal',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1,
ptyId: 'remote-pty'
}
]
},
terminalLayoutsByTabId: {
tab1: {
root: { type: 'leaf', leafId: TEST_LEAF_1 },
activeLeafId: TEST_LEAF_1,
expandedLeafId: null,
ptyIdsByLeafId: { [TEST_LEAF_1]: 'remote-pty' }
}
}
},
sshRemotePtyLeases: [
{
targetId: 'ssh-1',
ptyId: 'remote-pty',
worktreeId: 'wt1',
tabId: 'tab1',
leafId: 'pane:1',
state: 'detached',
createdAt: 1,
updatedAt: 1
}
]
})
const store = await createStore()
expect(store.getSshRemotePtyLeases('ssh-1')[0].leafId).toBe(TEST_LEAF_1)
})
it('normalizes stale legacy session writes to prior UUID leaves before preserving bindings', async () => {
const store = await createStore()
@@ -183,52 +129,6 @@ describe('Store', () => {
expect(session.tabsByWorktree.wt1[0].ptyId).toBe('remote-pty')
})
it('promotes an empty tab layout to a durable UUID root when persisting the first PTY binding', async () => {
const store = await createStore()
store.setWorkspaceSession({
activeRepoId: 'r1',
activeWorktreeId: 'wt1',
activeTabId: 'tab1',
tabsByWorktree: {
wt1: [
{
id: 'tab1',
worktreeId: 'wt1',
title: 'Terminal',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1,
ptyId: null
}
]
},
terminalLayoutsByTabId: {
tab1: {
root: null,
activeLeafId: null,
expandedLeafId: null
}
}
})
await store.persistPtyBinding({
worktreeId: 'wt1',
tabId: 'tab1',
leafId: TEST_LEAF_1,
ptyId: 'daemon-pty'
})
const session = store.getWorkspaceSession()
expect(session.tabsByWorktree.wt1[0].ptyId).toBe('daemon-pty')
expect(session.terminalLayoutsByTabId.tab1).toEqual({
root: { type: 'leaf', leafId: TEST_LEAF_1 },
activeLeafId: TEST_LEAF_1,
expandedLeafId: null,
ptyIdsByLeafId: { [TEST_LEAF_1]: 'daemon-pty' }
})
})
it('admits a fresh host spawn after retirement while rejecting an older renderer topology', async () => {
const store = await createStore()
store.setWorkspaceSession({
@@ -110,15 +110,4 @@ describe("pinning existing hosts' orca CLI control switch on upgrade", () => {
expect(reopened.getSshTarget(added.id)?.allowRemoteCliControl).toBe(true)
expect(isRemoteCliControlAllowed(reopened.getSshTarget(added.id))).toBe(true)
})
it('does not re-run after a downgrade wrote an absent switch alongside the marker', async () => {
// Older builds preserve unknown migration markers when saving settings.
writeProfile([host('added-by-older-build')], {
sshRemoteCliControlExistingHostsMigrated: true
})
const store = await createStore()
expect(store.getSshTarget('added-by-older-build')).not.toHaveProperty('allowRemoteCliControl')
})
})
@@ -1,327 +0,0 @@
import {
closeTestStores,
testState,
createStore,
withPlatform,
writeDataFile,
readDataFile
} from '../persistence-test-harness'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { rmSync, mkdtempSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import type { PersistedState } from '../../../shared/persisted-state-types'
const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({
loadUserSshConfigMock: vi.fn(),
sshConfigHostsToTargetsMock: vi.fn()
}))
vi.mock('../../ssh/config/ssh-config-parser', () => ({
loadUserSshConfig: loadUserSshConfigMock,
sshConfigHostsToTargets: sshConfigHostsToTargetsMock
}))
const { trackMock, getCohortAtEmitMock } = vi.hoisted(() => ({
trackMock: vi.fn(),
getCohortAtEmitMock: vi.fn()
}))
vi.mock('electron', () => ({
app: {
getPath: () => testState.dir
},
safeStorage: {
isEncryptionAvailable: () => true,
encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'),
decryptString: (ciphertext: Buffer) => {
const decoded = ciphertext.toString('utf-8')
if (!decoded.startsWith('encrypted:')) {
throw new Error('invalid ciphertext')
}
return decoded.slice('encrypted:'.length)
}
}
}))
vi.mock('../../telemetry/client', () => ({
track: trackMock
}))
vi.mock('../../telemetry/cohort-classifier', () => ({
getCohortAtEmit: getCohortAtEmitMock
}))
describe('Store', () => {
beforeEach(() => {
testState.dir = mkdtempSync(join(tmpdir(), 'orca-test-'))
trackMock.mockReset()
getCohortAtEmitMock.mockReset()
getCohortAtEmitMock.mockReturnValue({ nth_repo_added: 2 })
})
afterEach(async () => {
await closeTestStores()
rmSync(testState.dir, { recursive: true, force: true })
})
it('migrates legacy "true" terminalMacOptionAsAlt to "auto" on first load', async () => {
// The old true default cannot reveal user intent; migrate it once to auto for non-US layouts.
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: { terminalMacOptionAsAlt: 'true' },
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().terminalMacOptionAsAlt).toBe('auto')
expect(store.getSettings().terminalMacOptionAsAltMigrated).toBe(true)
})
it('migrates inherited right-click paste to each platform default once', async () => {
for (const [platform, expected] of [
['win32', true],
['darwin', false],
['linux', false]
] as const) {
await withPlatform(platform, async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: { terminalRightClickToPaste: true },
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().terminalRightClickToPaste).toBe(expected)
expect(store.getSettings().terminalRightClickToPasteDefaultedForPlatform).toBe(true)
})
}
})
it('preserves an explicit Windows right-click paste opt-out during migration', async () => {
await withPlatform('win32', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: { terminalRightClickToPaste: false },
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().terminalRightClickToPaste).toBe(false)
expect(store.getSettings().terminalRightClickToPasteDefaultedForPlatform).toBe(true)
})
})
it('preserves right-click paste choices after the platform migration', async () => {
await withPlatform('darwin', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {
terminalRightClickToPaste: true,
terminalRightClickToPasteDefaultedForPlatform: true
},
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().terminalRightClickToPaste).toBe(true)
})
})
it('migrates inherited terminal bar cursor defaults to block on first load', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: { terminalCursorStyle: 'bar' },
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().terminalCursorStyle).toBe('block')
expect(store.getSettings().terminalCursorStyleDefaultedToBlock).toBe(true)
})
it('preserves terminal cursor choices after the block-default migration', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: { terminalCursorStyle: 'bar', terminalCursorStyleDefaultedToBlock: true },
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().terminalCursorStyle).toBe('bar')
expect(store.getSettings().terminalCursorStyleDefaultedToBlock).toBe(true)
})
it('replaces an invalid persisted terminal cursor choice after migration', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: { terminalCursorStyle: 'beam', terminalCursorStyleDefaultedToBlock: true },
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().terminalCursorStyle).toBe('block')
store.flush()
expect((readDataFile() as PersistedState).settings.terminalCursorStyle).toBe('block')
})
it('preserves explicit "false" terminalMacOptionAsAlt through migration', async () => {
// Legacy false differed from the default and therefore proves an explicit choice.
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: { terminalMacOptionAsAlt: 'false' },
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().terminalMacOptionAsAlt).toBe('false')
expect(store.getSettings().terminalMacOptionAsAltMigrated).toBe(true)
})
it.each(['left', 'right'] as const)(
'preserves explicit "%s" terminalMacOptionAsAlt through migration',
async (side) => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: { terminalMacOptionAsAlt: side },
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().terminalMacOptionAsAlt).toBe(side)
expect(store.getSettings().terminalMacOptionAsAltMigrated).toBe(true)
}
)
it('respects already-migrated settings with explicit "true"', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: { terminalMacOptionAsAlt: 'true', terminalMacOptionAsAltMigrated: true },
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().terminalMacOptionAsAlt).toBe('true')
expect(store.getSettings().terminalMacOptionAsAltMigrated).toBe(true)
})
it('fresh install defaults terminalMacOptionAsAlt to "auto" and marks migrated', async () => {
const store = await createStore()
expect(store.getSettings().terminalMacOptionAsAlt).toBe('auto')
// No migration ran on a new profile; a later legacy true value must still migrate.
expect(store.getSettings().terminalMacOptionAsAltMigrated).toBe(false)
})
it('missing terminalMacOptionAsAlt in persisted file defaults to "auto" and flags migrated', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {},
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().terminalMacOptionAsAlt).toBe('auto')
expect(store.getSettings().terminalMacOptionAsAltMigrated).toBe(true)
})
it('migrates the legacy experimentalSidekick setting to experimentalPet', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: { experimentalSidekick: true },
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().experimentalPet).toBe(true)
})
it('migrates the legacy experimental compact worktree cards setting', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: { experimentalCompactWorktreeCards: true },
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().compactWorktreeCards).toBe(true)
expect(store.getSettings().experimentalCompactWorktreeCards).toBeUndefined()
})
it('defaults legacy experimentalActivity profiles off once', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: { experimentalActivity: true },
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().experimentalActivity).toBe(false)
expect(store.getSettings().experimentalActivityDefaultedOffForAllUsers).toBe(true)
})
it('preserves experimentalActivity after the default-off migration has run', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {
experimentalActivity: true,
experimentalActivityDefaultedOffForAllUsers: true
},
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().experimentalActivity).toBe(true)
})
})
@@ -65,17 +65,3 @@ it('still refuses and rolls back a rename whose profile write fails', async () =
.tabsByWorktree[pane.worktreeId]?.find((row) => row.id === pane.tabId)
expect(tab?.customTitle ?? null).toBeNull()
})
it('refuses a close once profile writes are frozen, and changes nothing', async () => {
const { store, liveTabIds } = await openWithTab()
await store.freezeWritesAsync()
await expect(
store.applyLayoutCommand({
type: 'closeTabs',
workspace: pane.worktreeId,
tabIds: [pane.tabId]
})
).rejects.toThrow('finalized')
expect(liveTabIds()).toContain(pane.tabId)
})
@@ -1,55 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import type { DurableProfileStateMutation } from '../loading-store/store-runtime-state'
import { keptOnWriteFailure } from './terminal-close-write-failure'
function durableRun(write: () => void) {
return async <V>(mutate: () => DurableProfileStateMutation<V>): Promise<V> => {
const mutation = mutate()
try {
write()
} catch (error) {
mutation.rollback?.()
throw error
}
return mutation.value
}
}
describe('a terminal close whose profile write fails', () => {
it('stays closed, answers as applied, and is written again later', async () => {
let tabs = ['tab-1', 'tab-2']
const writeLater = vi.fn()
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const reply = await keptOnWriteFailure(
durableRun(() => {
throw new Error('ENOSPC')
}),
() => {
const before = tabs
tabs = tabs.filter((tab) => tab !== 'tab-2')
return { value: { ok: true as const }, rollback: () => (tabs = before) }
},
writeLater
)
expect(reply).toEqual({ ok: true })
expect(tabs).toEqual(['tab-1'])
expect(writeLater).toHaveBeenCalledTimes(1)
warn.mockRestore()
})
it('refuses a close the profile froze before it changed anything', async () => {
const writeLater = vi.fn()
const mutate = vi.fn()
await expect(
keptOnWriteFailure(
async () => {
throw new Error('Cannot mutate finalized profile persistence')
},
mutate,
writeLater
)
).rejects.toThrow('finalized')
expect(mutate).not.toHaveBeenCalled()
expect(writeLater).not.toHaveBeenCalled()
})
})
@@ -11,7 +11,7 @@ import {
FIXTURE_GIT_WORKTREE_ID,
openTopologyStore
} from './terminal-topology-profile-fixture'
import { WindowSession, withoutLeaf } from './terminal-topology-window-session-fixture'
import { WindowSession } from './terminal-topology-window-session-fixture'
import { checkWorkspaceLayoutRules } from '../../../shared/workspace-layout/workspace-layout-rules'
// Retire this rollback coverage with switch-off code.
@@ -96,37 +96,4 @@ describe('a terminal spawn that lands after its pane changed', () => {
expect(store.getWorkspaceSession().tabsByWorktree[WT] ?? []).toEqual([])
await store.freezeWritesAsync()
})
// Known switch-off gap: late spawn grafts a moved pane back; the renderer blocks in-flight drags.
it.fails('keeps a dragged-out pane in its new tab when its spawn lands late', async () => {
const { store, window } = await openWithSplit()
await expect(
store.moveTerminalLeafToNewTab({
worktreeId: WT,
sourceTabId: 'tab-a',
targetTabId: 'tab-b',
leafId: TEST_LEAF_2,
ptyId: 'pty-2'
})
).resolves.toEqual({ status: 'moved', ptyId: 'pty-2' })
const source = window.session.terminalLayoutsByTabId['tab-a']!
window.setLayout('tab-a', withoutLeaf(source.root!, TEST_LEAF_2)!, { [TEST_LEAF_1]: 'pty-1' })
window.addTab(WT, 'tab-b', TEST_LEAF_2)
window.bind('tab-b', TEST_LEAF_2, 'pty-2')
store.setWorkspaceSession(window.snapshot())
expect(violations(store)).toEqual([])
// Commit the spawn that began against the old source tab.
await store.persistPtyBinding({
worktreeId: WT,
tabId: 'tab-a',
leafId: TEST_LEAF_2,
ptyId: 'pty-2b'
})
try {
expect(violations(store)).toEqual([])
} finally {
await store.freezeWritesAsync()
}
})
})
@@ -9,7 +9,6 @@ import type { Store } from '../loading-store/store'
import { leafIds, WindowSession } from './terminal-topology-window-session-fixture'
import {
emptyTerminalSessionProfile,
FIXTURE_FOLDER_WORKTREE_ID,
FIXTURE_GIT_WORKTREE_ID,
openTopologyStore,
reopenTopologyStore
@@ -102,41 +101,6 @@ describe('Store.applyLayoutCommand (layout.apply)', () => {
expect(revision(store)).toBeGreaterThan(revisionBefore)
})
it('prunes the partition’s expired close records when it records one, as today', async () => {
const { store } = await storeWithOneTab()
store.setWorkspaceSession({
...store.getWorkspaceSession(),
closedTerminalTabTombstonesByTabId: {
'tab-old': { worktreeId: 'repo-other::/x', closedAt: 1, reason: 'user' }
}
})
await store.applyLayoutCommand({
type: 'closeTabs',
workspace: WORKTREE,
tabIds: [TAB],
force: true,
recordClose: 'cleanup'
})
expect(
Object.keys(store.getWorkspaceSession().closedTerminalTabTombstonesByTabId ?? {})
).toEqual([TAB])
})
it('writes a folder workspace’s split', async () => {
const { store } = await storeWithOneTab(undefined, FIXTURE_FOLDER_WORKTREE_ID)
const reply = await store.applyLayoutCommand({
...split,
workspace: FIXTURE_FOLDER_WORKTREE_ID
})
expect(reply.ok).toBe(true)
const root = store.getWorkspaceSession().terminalLayoutsByTabId[TAB]?.root
expect(leafIds(root)).toEqual([LEAF, reply.ok ? reply.result.leafId : undefined])
})
it('keeps records the split did not touch exactly as stored', async () => {
const directory = mkdtempSync(join(tmpdir(), 'orca-layout-apply-'))
directories.push(directory)
@@ -160,16 +124,6 @@ describe('Store.applyLayoutCommand (layout.apply)', () => {
expect(written.unifiedTabs).toEqual(stored.unifiedTabs)
})
it('refuses a pane main does not hold and writes nothing', async () => {
const { store } = await storeWithOneTab()
const before = store.getWorkspaceSession()
const reply = await store.applyLayoutCommand({ ...split, leafId: 'missing-leaf' })
expect(reply).toEqual({ ok: false, code: 'pane_not_found' })
expect(store.getWorkspaceSession()).toEqual(before)
})
it('writes an SSH workspace’s split into that host’s partition only', async () => {
const { store } = await storeWithOneTab('ssh:target-1')
const local = store.getWorkspaceSession()
@@ -102,38 +102,6 @@ describe('Store.applyLayoutCommand: a window’s terminal tab create', () => {
expect(leafIds(root)).toEqual([NEW_LEAF, reply.ok ? reply.result.leafId : undefined])
})
it('treats the same create again as done, and writes nothing', async () => {
const { store } = await openStore(withOneTab)
await store.applyLayoutCommand(create)
const before = store.getWorkspaceSession()
const reply = await store.applyLayoutCommand({ ...create, groupId: 'another-group' })
expect(reply).toEqual({
ok: true,
result: { tabId: NEW_TAB, leafId: NEW_LEAF, paneKey: `${NEW_TAB}:${NEW_LEAF}` }
})
expect(store.getWorkspaceSession()).toBe(before)
})
it('refuses an id another tab holds, in this workspace or another, and writes nothing', async () => {
const { store } = await openStore((window) => {
withOneTab(window)
window.addTab(FIXTURE_FOLDER_WORKTREE_ID, 'folder-tab', NEW_LEAF)
})
const before = store.getWorkspaceSession()
expect(await store.applyLayoutCommand({ ...create, tabId: TAB })).toEqual({
ok: false,
code: 'tab_exists'
})
expect(await store.applyLayoutCommand({ ...create, tabId: 'folder-tab' })).toEqual({
ok: false,
code: 'tab_exists'
})
expect(store.getWorkspaceSession()).toBe(before)
})
it('keeps records the create did not touch exactly as stored', async () => {
const { store } = await openStore((window) => {
withOneTab(window)
@@ -153,24 +121,6 @@ describe('Store.applyLayoutCommand: a window’s terminal tab create', () => {
expect(written.unifiedTabs?.[WORKTREE]?.[0]).toEqual(stored.unifiedTabs?.[WORKTREE]?.[0])
})
it('makes a workspace’s first tab on activation only while main’s copy holds no tab', async () => {
const { store } = await openStore(withOneTab)
const before = store.getWorkspaceSession()
const initial = { ...create, groupId: undefined, initial: 'activation' as const }
expect(await store.applyLayoutCommand(initial)).toEqual({ ok: true, result: {} })
expect(store.getWorkspaceSession()).toBe(before)
const empty = await store.applyLayoutCommand({
...initial,
workspace: FIXTURE_FOLDER_WORKTREE_ID
})
expect(empty.ok && empty.result.tabId).toBe(NEW_TAB)
expect(
store.getWorkspaceSession().tabsByWorktree[FIXTURE_FOLDER_WORKTREE_ID]?.map((tab) => tab.id)
).toEqual([NEW_TAB])
})
it('writes an SSH workspace’s tab into that host’s partition only', async () => {
const { store } = await openStore(withOneTab, 'ssh:target-1')
const local = store.getWorkspaceSession()
@@ -211,17 +161,4 @@ describe('Store.applyLayoutCommand: a workspace’s default tabs', () => {
])
expect(session.defaultTerminalTabsAppliedByWorktreeId?.[FIXTURE_FOLDER_WORKTREE_ID]).toBe(true)
})
it('refuses the whole command when another tab holds one of its ids, and writes nothing', async () => {
const { store } = await openStore(withOneTab)
const before = store.getWorkspaceSession()
const reply = await store.applyLayoutCommand({
...defaults,
tabs: [defaults.tabs[0]!, { ...defaults.tabs[1]!, tabId: TAB }]
})
expect(reply).toEqual({ ok: false, code: 'tab_exists' })
expect(store.getWorkspaceSession()).toBe(before)
})
})
@@ -1,64 +0,0 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
emptyTerminalSessionProfile,
FIXTURE_FOLDER_WORKTREE_ID,
FIXTURE_GIT_WORKTREE_ID,
openTopologyStore,
reopenTopologyStore
} from './terminal-topology-profile-fixture'
vi.mock('../../telemetry/client', () => ({ track: vi.fn() }))
vi.mock('../../ssh/config/ssh-config-parser', () => ({
loadUserSshConfig: () => ({ hosts: [] }),
sshConfigHostsToTargets: () => []
}))
const directories: string[] = []
afterEach(() => {
for (const directory of directories.splice(0)) {
rmSync(directory, { recursive: true, force: true })
}
})
async function emptyStore() {
const directory = mkdtempSync(join(tmpdir(), 'orca-layout-default-tabs-'))
directories.push(directory)
return { store: await openTopologyStore(directory, emptyTerminalSessionProfile()), directory }
}
describe('Store.applyLayoutCommand setDefaultTabsApplied (layout.apply)', () => {
it.each([
['a git worktree', FIXTURE_GIT_WORKTREE_ID],
['a folder workspace', FIXTURE_FOLDER_WORKTREE_ID]
])('records %s’s mark durably without making it a workspace', async (_kind, workspace) => {
const { store, directory } = await emptyStore()
const reply = await store.applyLayoutCommand({ type: 'setDefaultTabsApplied', workspace })
expect(reply).toEqual({ ok: true, result: {} })
const session = (await reopenTopologyStore(store, directory)).getWorkspaceSession()
expect(session.defaultTerminalTabsAppliedByWorktreeId).toEqual({ [workspace]: true })
expect(session.tabsByWorktree[workspace]).toBeUndefined()
expect(session.unifiedTabs?.[workspace]).toBeUndefined()
expect(session.tabGroups?.[workspace]).toBeUndefined()
})
it('a repeat changes nothing', async () => {
const { store, directory } = await emptyStore()
const workspace = FIXTURE_GIT_WORKTREE_ID
await store.applyLayoutCommand({ type: 'setDefaultTabsApplied', workspace })
const reopened = await reopenTopologyStore(store, directory)
const before = reopened.getWorkspaceSession()
const reply = await reopened.applyLayoutCommand({ type: 'setDefaultTabsApplied', workspace })
expect(reply).toEqual({ ok: true, result: {} })
expect(reopened.getWorkspaceSession()).toEqual(before)
const session = (await reopenTopologyStore(reopened, directory)).getWorkspaceSession()
expect(session.defaultTerminalTabsAppliedByWorktreeId).toEqual({ [workspace]: true })
})
})
@@ -2,10 +2,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { toSshExecutionHostId } from '../../../shared/execution-host'
import { _resetTracerForTests, setActiveSink } from '../../observability/tracer'
import { _resetTracerForTests } from '../../observability/tracer'
import { makeRepo } from '../persistence-test-harness'
import { makeTerminalTab } from '../persistence-session-fixtures'
import { planTerminalLeafMove } from './terminal-leaf-move'
import {
closeMoveTestStores,
FROM,
@@ -119,133 +118,6 @@ describe('moving a pane to a new tab', () => {
expect.objectContaining({ ptyId: 'pty-agent', tabId: TARGET, leafId: MOVED })
])
})
it('reports a leaf main never held instead of inventing one', async () => {
const store = openStore(newDataFile())
await expect(
store.moveTerminalLeafToNewTab({ ...moveRequest, ptyId: 'pty-agent' })
).resolves.toEqual({ status: 'not_held' })
expect(store.getWorkspaceSession().tabsByWorktree[WT]).toBeUndefined()
})
it('refuses a move that names another terminal or an existing tab', async () => {
const store = openStore(newDataFile())
await seedSplitSource(store)
await expect(
store.moveTerminalLeafToNewTab({ ...moveRequest, ptyId: 'pty-other' })
).resolves.toEqual({ status: 'refused', reason: 'pty_mismatch' })
await expect(
store.moveTerminalLeafToNewTab({ ...moveRequest, targetTabId: SOURCE, ptyId: 'pty-agent' })
).resolves.toEqual({ status: 'refused', reason: 'target_tab_exists' })
expect(tabsHoldingLeaf(store.getWorkspaceSession(), MOVED)).toEqual([SOURCE])
})
it('moves a leaf that a stray layout of a removed tab still names', () => {
const planned = planTerminalLeafMove(
[
{
hostId: 'local',
session: {
activeRepoId: 'repo-1',
activeWorktreeId: WT,
activeTabId: SOURCE,
tabsByWorktree: { [WT]: [makeTerminalTab({ id: SOURCE, worktreeId: WT })] },
terminalLayoutsByTabId: {
[SOURCE]: {
root: {
type: 'split',
direction: 'vertical',
first: { type: 'leaf', leafId: LEFT },
second: { type: 'leaf', leafId: MOVED }
},
activeLeafId: LEFT,
expandedLeafId: null
},
'tab-removed': {
root: { type: 'leaf', leafId: MOVED },
activeLeafId: MOVED,
expandedLeafId: null
}
}
}
}
],
{ ...moveRequest, ptyId: 'pty-agent' }
)
expect(planned.result).toEqual({ status: 'moved', ptyId: 'pty-agent' })
})
it('records a persistence.terminal-topology span without pane keys or PTY ids', async () => {
const records: {
name: string
attributes: Record<string, unknown>
traceId: string
spanId: string
parentSpanId?: string
startTimeUnixNano: string
endTimeUnixNano: string
durationMs: number
}[] = []
setActiveSink({
push: (record) => {
records.push(JSON.parse(JSON.stringify(record)))
},
flush: () => {},
close: () => {}
})
try {
const store = openStore(newDataFile())
await seedSplitSource(store)
records.length = 0
const request = { ...moveRequest, ptyId: 'pty-agent' }
await store.moveTerminalLeafToNewTab(request)
await store.moveTerminalLeafToNewTab(request)
await store.moveTerminalLeafToNewTab({ ...request, targetTabId: 'tab-other' })
const spans = records.filter((record) => record.name === 'persistence.terminal-topology')
expect(spans.map((span) => span.attributes)).toEqual([
{ kind: 'persistence', 'topology.kind': 'move_leaf', 'topology.outcome': 'committed' },
{
kind: 'persistence',
'topology.kind': 'move_leaf',
'topology.outcome': 'refused',
'topology.refusal': 'target_tab_exists'
},
{
kind: 'persistence',
'topology.kind': 'move_leaf',
'topology.outcome': 'refused',
'topology.refusal': 'leaf_in_other_tab'
}
])
const transportFields = new Set([
'traceId',
'spanId',
'parentSpanId',
'startTimeUnixNano',
'endTimeUnixNano',
'durationMs'
])
for (const span of spans) {
expect(span.traceId).toMatch(/^[a-f0-9]{32}$/)
expect(span.spanId).toMatch(/^[a-f0-9]{16}$/)
if (span.parentSpanId !== undefined) {
expect(span.parentSpanId).toMatch(/^[a-f0-9]{16}$/)
}
expect(span.startTimeUnixNano).toMatch(/^\d+$/)
expect(span.endTimeUnixNano).toMatch(/^\d+$/)
expect(Number.isFinite(span.durationMs)).toBe(true)
expect(span.durationMs).toBeGreaterThanOrEqual(0)
}
// Random IDs and clocks can coincidentally contain the leaf's numeric prefix.
const payloads = spans.map((span) =>
Object.fromEntries(Object.entries(span).filter(([key]) => !transportFields.has(key)))
)
expect(JSON.stringify(payloads)).not.toMatch(/pty-|tab-source|tab-target|2222/)
} finally {
_resetTracerForTests()
}
})
})
// Relay reattach can duplicate SSH panes into local; all holders must move or future binds refuse.
@@ -337,34 +209,6 @@ describe('moving an SSH pane held by both partitions', () => {
expect(store.getWorkspaceSession(hostId).terminalPtyIncarnationsByPaneKey?.[TO]).toBe('inc-2')
expect(store.getWorkspaceSession().terminalPtyIncarnationsByPaneKey?.[TO]).toBeUndefined()
})
it('refuses a move while another tab already holds the leaf', async () => {
const store = openStore(newDataFile())
await seedSplitSource(store)
const session = store.getWorkspaceSession()
store.setWorkspaceSession({
...session,
tabsByWorktree: {
...session.tabsByWorktree,
[WT]: [
...(session.tabsByWorktree[WT] ?? []),
{ ...(session.tabsByWorktree[WT] ?? [])[0]!, id: 'tab-earlier-move' }
]
},
terminalLayoutsByTabId: {
...session.terminalLayoutsByTabId,
'tab-earlier-move': {
root: { type: 'leaf', leafId: MOVED },
activeLeafId: MOVED,
expandedLeafId: null
}
}
})
await expect(
store.moveTerminalLeafToNewTab({ ...moveRequest, ptyId: 'pty-agent' })
).resolves.toEqual({ status: 'refused', reason: 'leaf_in_other_tab' })
})
})
// STA-9259: move, reattach, stale renderer save and restart must retain one leaf/PTY owner.
@@ -1,50 +0,0 @@
// Switch-off builds permit paired hosts to add panes and do not enforce main-owned close records.
import { describe, expect, it, vi } from 'vitest'
import { getDefaultWorkspaceSession } from '../../../shared/constants'
import { admitPaneToSession, applyCommandToSession } from './terminal-pane-admission'
vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: false }))
const WORKTREE = 'repo-1::/workspace'
const TAB = 'tab-1'
describe('a runtime pane in the shipped build', () => {
it("writes a client tab's second pane under the tab's id", () => {
const first = admitPaneToSession('local', getDefaultWorkspaceSession(), {
type: 'createTerminalTab',
workspace: WORKTREE,
tabId: TAB,
leafId: '11111111-1111-4111-8111-111111111111'
})
expect(first.value).toBe('admitted')
const second = admitPaneToSession('local', first.session!, {
type: 'createTerminalTab',
workspace: WORKTREE,
tabId: TAB,
leafId: '22222222-2222-4222-8222-222222222222'
})
expect(second.value).toBe('admitted')
})
it('writes a create under the id of a tab the user closed, on both pane write paths', () => {
const create = {
type: 'createTerminalTab',
workspace: WORKTREE,
tabId: TAB,
leafId: '11111111-1111-4111-8111-111111111111'
} as const
const opened = applyCommandToSession('local', getDefaultWorkspaceSession(), create)
const closed = applyCommandToSession('local', opened.session!, {
type: 'closeTabs',
workspace: WORKTREE,
tabIds: [TAB],
recordClose: 'user'
})
expect(closed.value.ok).toBe(true)
const afterClose = closed.session!
expect(afterClose.closedTerminalTabTombstonesByTabId?.[TAB]).toBeDefined()
expect(applyCommandToSession('local', afterClose, create).value.ok).toBe(true)
expect(admitPaneToSession('local', afterClose, create).value).toBe('admitted')
})
})
@@ -169,94 +169,6 @@ describe('a window drag-out through layout.apply', () => {
).toBe(true)
expect(tabsHoldingLeaf(store.getWorkspaceSession(), LEFT)).toEqual([SOURCE])
})
it('starts an unbound pane’s new tab in the folder the window sent', async () => {
const store = openStore(newDataFile())
await seedSplitSource(store)
const seeded = store.getWorkspaceSession()
store.setWorkspaceSession({
...seeded,
terminalLayoutsByTabId: {
[SOURCE]: {
...seeded.terminalLayoutsByTabId[SOURCE]!,
ptyIdsByLeafId: { [LEFT]: 'pty-left' }
}
}
})
await expect(detach(store, null, ['local'], '/wt/app')).resolves.toMatchObject({
ok: true,
result: { tabId: TARGET, ptyId: null }
})
const target = store.getWorkspaceSession().tabsByWorktree[WT]?.find((tab) => tab.id === TARGET)
expect(target?.startupCwd).toBe('/wt/app')
})
it('refuses a terminal no copy names, and a leaf another tab holds', async () => {
const store = openStore(newDataFile())
await seedSplitSource(store)
if (ORCA_LAYOUT_OWNER_IS_MAIN) {
// Main-owned binding outranks the renderer's claimed PTY.
const claimed = openStore(newDataFile())
await seedSplitSource(claimed)
await expect(detach(claimed, 'pty-other')).resolves.toEqual({
ok: true,
result: { tabId: TARGET, ptyId: 'pty-agent' }
})
} else {
await expect(detach(store, 'pty-other')).resolves.toEqual({ ok: false, code: 'pty_mismatch' })
}
const session = store.getWorkspaceSession()
store.setWorkspaceSession({
...session,
tabsByWorktree: {
...session.tabsByWorktree,
[WT]: [
...(session.tabsByWorktree[WT] ?? []),
{ ...(session.tabsByWorktree[WT] ?? [])[0]!, id: 'tab-earlier-move' }
]
},
terminalLayoutsByTabId: {
...session.terminalLayoutsByTabId,
'tab-earlier-move': {
root: { type: 'leaf', leafId: MOVED },
activeLeafId: MOVED,
expandedLeafId: null
}
}
})
await expect(detach(store, 'pty-agent')).resolves.toEqual({
ok: false,
code: 'pane_in_other_tab'
})
expect(tabsHoldingLeaf(store.getWorkspaceSession(), MOVED)).toContain(SOURCE)
})
it('takes the one bound terminal when the window has none', async () => {
const store = openStore(newDataFile())
await seedSplitSource(store)
await expect(detach(store, null)).resolves.toEqual({
ok: true,
result: { tabId: TARGET, ptyId: 'pty-agent' }
})
})
it('moves the remote session id with the moved terminal', async () => {
const store = openStore(newDataFile())
await seedSplitSource(store)
store.setWorkspaceSession({
...store.getWorkspaceSession(),
remoteSessionIdsByTabId: { [SOURCE]: 'pty-agent' }
})
await detach(store, 'pty-agent')
expect(store.getWorkspaceSession().remoteSessionIdsByTabId).toEqual({
[SOURCE]: 'pty-left',
[TARGET]: 'pty-agent'
})
})
})
describe('a window drag-out of an SSH pane held by both partitions', () => {
@@ -111,23 +111,6 @@ describe('main shows a live terminal no pane shows, at startup with no window',
})
})
it('a bind by main’s pass raises the pane’s binding generation by exactly one', async () => {
const store = await openStore((window) => window.addTab(WORKTREE, TAB, LEAF))
const before = store.getPtyBindingGeneration('local', LEAF) ?? 0
await placeOn(store, [livePty('pty-agent', { tabId: TAB, paneKey: `${TAB}:${LEAF}` })])
expect(store.getPtyBindingGeneration('local', LEAF)).toBe(before + 1)
await store.applyLayoutCommand({
type: 'renameTab',
workspace: WORKTREE,
tabId: TAB,
kind: 'custom',
title: 'x'
})
expect(store.getPtyBindingGeneration('local', LEAF)).toBe(before + 1)
})
it('shows a terminal no pane ever named in a new tab bound to it, kept across a restart', async () => {
const store = await openStore((window) => window.addTab(WORKTREE, TAB, LEAF))
@@ -145,83 +128,4 @@ describe('main shows a live terminal no pane shows, at startup with no window',
)
expect((await placeOn(relaunched, [livePty('pty-cli')])).placed).toEqual([])
})
it('leaves a terminal whose spawn is still binding its pane to that spawn', async () => {
const store = await openStore((window) => window.addTab(WORKTREE, TAB, LEAF))
const placement = await placeOn(store, [livePty('pty-starting')], {
isStillBinding: () => true
})
expect(placement).toMatchObject({ placed: [], declined: [] })
expect(terminalTabs(store)).toHaveLength(1)
})
it('leaves alone a terminal a pane shows, one being killed, and a remote one', async () => {
const store = await openStore((window) => {
window.addTab(WORKTREE, TAB, LEAF)
window.bind(TAB, LEAF, 'pty-bound')
})
const remote: LivePty = { ...livePty('ssh:host@@pty-remote'), connectionId: 'host' }
const placement = await placeOn(store, [livePty('pty-bound'), livePty('pty-closing'), remote], {
refreshInventory: async () => ({
exitingPtyIds: new Set(['pty-closing']),
workspaceIds: new Set([WORKTREE])
})
})
expect(placement).toMatchObject({ placed: [], declined: [] })
expect(terminalTabs(store).map((tab) => tab.id)).toEqual([TAB])
})
it('places nothing in a workspace this host does not know (removed outside the app)', async () => {
const store = await openStore((window) => window.addTab(WORKTREE, TAB, LEAF))
const stray: LivePty = { ...livePty('pty-stray'), worktreeId: 'repo-local::/fixture/removed' }
const placement = await placeOn(store, [stray])
expect(placement).toMatchObject({ placed: [], declined: [] })
expect(Object.keys(store.getWorkspaceSession().tabsByWorktree)).toEqual([WORKTREE])
})
it('a terminal main cannot place is declined, and the rest are still placed', async () => {
const store = await openStore((window) => window.addTab(WORKTREE, TAB, LEAF))
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const apply: LiveTerminalPlacementPorts['apply'] = (command) =>
command.adopt?.ptyId === 'pty-bad'
? Promise.reject(new Error('record unreadable'))
: store.applyLayoutCommand(command)
const placement = await placeOn(store, [livePty('pty-bad'), livePty('pty-good')], { apply })
expect(placement).toMatchObject({ placed: ['pty-good'], declined: ['pty-bad'] })
expect(warn).toHaveBeenCalledOnce()
expect(String(warn.mock.calls[0])).toContain('record unreadable')
warn.mockRestore()
})
it('places nothing, and does not fail, when the census itself fails', async () => {
const store = await openStore((window) => window.addTab(WORKTREE, TAB, LEAF))
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const placement = await placeOn(store, [livePty('pty-cli')], {
refreshInventory: () => Promise.reject(new Error('terminal service down'))
})
expect(placement).toMatchObject({ placed: [], declined: [] })
expect(terminalTabs(store)).toHaveLength(1)
warn.mockRestore()
})
it('places nothing when the host census could not answer', async () => {
const store = await openStore((window) => window.addTab(WORKTREE, TAB, LEAF))
const placement = await placeOn(store, [livePty('pty-cli')], {
refreshInventory: async () => null
})
expect(placement).toMatchObject({ placed: [], declined: [] })
expect(terminalTabs(store)).toHaveLength(1)
})
})
@@ -1,106 +0,0 @@
// Opt in: ORCA_LOCAL_METADATA_PRUNE_BENCH=1 pnpm test src/main/persistence/tracking-repos/local-worktree-metadata-batch-pruning.bench.test.ts
import { performance } from 'node:perf_hooks'
import { describe, expect, it, vi } from 'vitest'
import { getDefaultPersistedState } from '../../../shared/constants'
import type { PersistedState } from '../../../shared/persisted-state-types'
import type { Repo } from '../../../shared/repo-types'
import type { WorktreeMeta } from '../../../shared/worktree/meta-types'
import { removeWorkspaceSessionOwner } from '../restoring-sessions/session-owner-removal'
import {
pruneUnreferencedWorktreeIdentityMeta,
removeWorktreeMetadataForHost
} from '../loading-store/worktree-identity-metadata'
import {
captureNativeLocalWorktreeMetadataScanExpectation,
pruneSessionlessMissingLocalWorktreeMetadataForRepo
} from './missing-local-worktree-metadata-pruning'
const describeBench = process.env.ORCA_LOCAL_METADATA_PRUNE_BENCH ? describe : describe.skip
const ROW_COUNT = 2_709
const REPO: Repo = {
id: 'repo-1',
path: '/workspace/repo',
displayName: 'repo',
badgeColor: '#000',
addedAt: 0
}
function makeMeta(index: number): WorktreeMeta {
return {
instanceId: `instance-${index}`,
hostId: 'local',
displayName: `stale-${index}`,
comment: '',
linkedIssue: null,
linkedPR: null,
linkedLinearIssue: null,
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: index,
lastActivityAt: 0
}
}
function makeState(): { state: PersistedState; staleIds: string[] } {
const state = getDefaultPersistedState('/home/test')
state.repos = [REPO]
state.worktreeMetaByIdentity = {}
state.worktreeIdentityAliases = {}
const staleIds = Array.from(
{ length: ROW_COUNT },
(_, index) => `${REPO.id}::/workspace/stale-${index}`
)
for (const [index, worktreeId] of staleIds.entries()) {
const meta = makeMeta(index)
const identityKey = `identity-${index}`
state.worktreeMeta[worktreeId] = meta
state.worktreeMetaByIdentity[identityKey] = meta
state.worktreeIdentityAliases[`local|${worktreeId}`] = [identityKey]
}
return { state, staleIds }
}
describeBench('authoritative local metadata batch pruning', () => {
it('measures the reported 2,709-row sequential and batch shapes', () => {
const legacy = makeState()
const batch = makeState()
const cloneSpy = vi.spyOn(globalThis, 'structuredClone')
const legacyStartedAt = performance.now()
for (const worktreeId of legacy.staleIds) {
removeWorktreeMetadataForHost(legacy.state, worktreeId, undefined)
delete legacy.state.worktreeMeta[worktreeId]
legacy.state.workspaceSession = removeWorkspaceSessionOwner(
legacy.state.workspaceSession,
worktreeId
)!
}
pruneUnreferencedWorktreeIdentityMeta(legacy.state)
const legacyMs = performance.now() - legacyStartedAt
const legacySessionClones = cloneSpy.mock.calls.length
cloneSpy.mockClear()
const batchStartedAt = performance.now()
const scan = captureNativeLocalWorktreeMetadataScanExpectation(batch.state, REPO)
const removed = pruneSessionlessMissingLocalWorktreeMetadataForRepo(
batch.state,
scan,
scan.metadata
)
const batchMs = performance.now() - batchStartedAt
const batchSessionClones = cloneSpy.mock.calls.length
cloneSpy.mockRestore()
expect(removed).toHaveLength(ROW_COUNT)
expect(Object.keys(legacy.state.worktreeMeta)).toHaveLength(0)
expect(Object.keys(batch.state.worktreeMeta)).toHaveLength(0)
expect(legacySessionClones).toBe(ROW_COUNT)
expect(batchSessionClones).toBe(0)
console.log(
`[bench] rows=${ROW_COUNT} metadata+session=${legacyMs.toFixed(2)}ms -> ${batchMs.toFixed(2)}ms; ` +
`gitScans=${ROW_COUNT} -> 1; sessionClones=${legacySessionClones} -> ${batchSessionClones}; ` +
`minimumSaveSchedules=${ROW_COUNT * 2} -> 1`
)
})
})
@@ -72,19 +72,6 @@ describe('local worktree metadata scan expectations', () => {
expect(state.worktreeMetaByIdentity?.[IDENTITY_KEY]).toBeUndefined()
})
it('removes equal legacy and canonical projections after a persistence round trip', () => {
const state = makeState()
const meta = makeMeta()
state.worktreeMeta[WORKTREE_ID] = structuredClone(meta)
state.worktreeMetaByIdentity = { [IDENTITY_KEY]: structuredClone(meta) }
state.worktreeIdentityAliases = { [LOCAL_ALIAS]: [IDENTITY_KEY] }
expect(pruneCaptured(state)).toEqual([WORKTREE_ID])
expect(state.worktreeMeta[WORKTREE_ID]).toBeUndefined()
expect(state.worktreeIdentityAliases[LOCAL_ALIAS]).toBeUndefined()
expect(state.worktreeMetaByIdentity[IDENTITY_KEY]).toBeUndefined()
})
it('does not sweep an unrelated unaliased canonical row during pruning', () => {
const { state, meta } = makeCanonicalOnlyState()
const unrelated = makeMeta(`${REPO_ID}::/workspace/unrelated`)
@@ -96,31 +83,6 @@ describe('local worktree metadata scan expectations', () => {
expect(meta).not.toBe(unrelated)
})
it('allocates expectations only for the scanned repository', () => {
const state = makeState()
const otherRepo = makeRepo('repo-2')
const otherId = `${otherRepo.id}::/workspace/other`
const canonicalId = `${REPO_ID}::/workspace/canonical`
const canonicalKey = 'canonical-key'
state.repos.push(otherRepo)
state.worktreeMeta[WORKTREE_ID] = makeMeta()
state.worktreeMeta[otherId] = makeMeta(otherId)
state.worktreeMetaByIdentity = {
[canonicalKey]: makeMeta(canonicalId),
'other-key': makeMeta(otherId)
}
state.worktreeIdentityAliases = {
[`local|${canonicalId}`]: [canonicalKey],
[`local|${otherId}`]: ['other-key']
}
const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!)
expect(scan.metadata.map(({ worktreeId }) => worktreeId).sort()).toEqual(
[WORKTREE_ID, canonicalId].sort()
)
})
it('preserves metadata when an alias array is replaced with identical contents', () => {
const { state } = makeCanonicalOnlyState()
const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!)
@@ -132,54 +94,6 @@ describe('local worktree metadata scan expectations', () => {
expect(state.worktreeMetaByIdentity?.[IDENTITY_KEY]).toBeDefined()
})
it('preserves metadata when the captured alias array is mutated in place', () => {
const { state } = makeCanonicalOnlyState()
const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!)
state.worktreeIdentityAliases![LOCAL_ALIAS]!.push('new-identity')
state.worktreeMetaByIdentity!['new-identity'] = makeMeta()
expect(pruneSessionlessMissingLocalWorktreeMetadataForRepo(state, scan, scan.metadata)).toEqual(
[]
)
})
it.each([
[
'replaced',
(state: PersistedState) => {
state.worktreeMetaByIdentity![IDENTITY_KEY] = {
...state.worktreeMetaByIdentity![IDENTITY_KEY]!
}
}
],
[
'host-mutated',
(state: PersistedState) => {
state.worktreeMetaByIdentity![IDENTITY_KEY]!.hostId = 'ssh:builder'
}
],
[
'instance-mutated',
(state: PersistedState) => {
state.worktreeMetaByIdentity![IDENTITY_KEY]!.instanceId = 'new-instance'
}
],
[
'content-mutated',
(state: PersistedState) => {
state.worktreeMetaByIdentity![IDENTITY_KEY]!.comment = 'new comment'
}
]
] as const)('preserves metadata when a canonical row is %s', (_label, mutate) => {
const { state } = makeCanonicalOnlyState()
const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!)
mutate(state)
expect(pruneSessionlessMissingLocalWorktreeMetadataForRepo(state, scan, scan.metadata)).toEqual(
[]
)
})
it.each([
[
'added',
@@ -214,29 +128,4 @@ describe('local worktree metadata scan expectations', () => {
)
expect(state.worktreeMeta[WORKTREE_ID]).toBeDefined()
})
it.each([WORKTREE_ID, `bogus|${WORKTREE_ID}`, `ssh:builder|${WORKTREE_ID}`])(
'preserves metadata with an unqualified or foreign alias: %s',
(alias) => {
const state = makeState()
state.worktreeMeta[WORKTREE_ID] = makeMeta()
state.worktreeMetaByIdentity = { [IDENTITY_KEY]: state.worktreeMeta[WORKTREE_ID]! }
state.worktreeIdentityAliases = { [alias]: [IDENTITY_KEY] }
expect(pruneCaptured(state)).toEqual([])
expect(state.worktreeMeta[WORKTREE_ID]).toBeDefined()
}
)
it('preserves an unqualified alias whose worktree path contains a pipe', () => {
const state = makeState()
const pipedId = `${REPO_ID}::/workspace/a|b`
state.worktreeMeta[pipedId] = makeMeta(pipedId)
state.worktreeMetaByIdentity = { [IDENTITY_KEY]: state.worktreeMeta[pipedId]! }
state.worktreeIdentityAliases = { [pipedId]: [IDENTITY_KEY] }
expect(pruneCaptured(state)).toEqual([])
expect(state.worktreeMeta[pipedId]).toBeDefined()
expect(state.worktreeIdentityAliases[pipedId]).toEqual([IDENTITY_KEY])
})
})
@@ -116,26 +116,6 @@ describe('pruneSessionlessMissingLocalWorktreeMetadataForRepo', () => {
expect(state.workspaceSessionsByHostId?.['runtime:mirror']).toEqual(hostSessionSnapshot)
})
it('fails closed when metadata is mutated or replaced after the scan starts', () => {
const inPlaceState = makeState()
const inPlaceId = `${REPO_ID}::/workspace/in-place`
inPlaceState.worktreeMeta[inPlaceId] = makeMeta(inPlaceId)
const inPlaceScan = capture(inPlaceState)
inPlaceState.worktreeMeta[inPlaceId]!.instanceId = 'replacement-instance'
expect(pruneCaptured(inPlaceState, inPlaceScan, [inPlaceId])).toEqual([])
const replacedState = makeState()
const replacedId = `${REPO_ID}::/workspace/replaced`
const original = makeMeta(replacedId)
replacedState.worktreeMeta[replacedId] = original
const replacedScan = capture(replacedState)
replacedState.worktreeMeta[replacedId] = { ...original }
expect(pruneCaptured(replacedState, replacedScan, [replacedId])).toEqual([])
expect(replacedState.worktreeMeta[replacedId]).not.toBe(original)
})
it('fails closed when an identical repo row is removed and re-added during the scan', () => {
const state = makeState()
const worktreeId = `${REPO_ID}::/workspace/re-added-repo`
@@ -149,145 +129,6 @@ describe('pruneSessionlessMissingLocalWorktreeMetadataForRepo', () => {
expect(state.worktreeMeta[worktreeId]).toBeDefined()
})
it('uses the effective Git kind when the raw legacy repo omitted kind', () => {
const state = makeState()
const worktreeId = `${REPO_ID}::/workspace/legacy-git-kind`
const rawRepo = state.repos[0]!
state.worktreeMeta[worktreeId] = makeMeta(worktreeId)
const scan = capture(state, { ...rawRepo, kind: 'git' })
expect(rawRepo.kind).toBeUndefined()
expect(pruneCaptured(state, scan, [worktreeId])).toEqual([worktreeId])
})
it.each([
'tabsByWorktree',
'browserTabsByWorktree',
'openFilesByWorktree',
'activeFileIdByWorktree',
'activeBrowserTabIdByWorktree',
'clientHostedBrowserPagesByWorktree',
'activeTabTypeByWorktree',
'activeTabIdByWorktree',
'unifiedTabs',
'tabGroups',
'tabGroupLayouts',
'activeGroupIdByWorktree',
'lastVisitedAtByWorktreeId',
'defaultTerminalTabsAppliedByWorktreeId'
] as const)('preserves an owner named by workspaceSession.%s', (field) => {
const state = makeState()
const worktreeId = `${REPO_ID}::/workspace/${field}`
state.worktreeMeta[worktreeId] = makeMeta(worktreeId)
const scan = capture(state)
const ownerKey = field === 'lastVisitedAtByWorktreeId' ? `local|${worktreeId}` : worktreeId
;(state.workspaceSession as unknown as Record<string, unknown>)[field] = {
[ownerKey]: []
}
expect(pruneCaptured(state, scan, [worktreeId])).toEqual([])
expect(state.worktreeMeta[worktreeId]).toBeDefined()
})
it('preserves scalar, nested, remote-partition, mobile, and relay recovery owners', () => {
const ownerMutations: ((state: PersistedState, worktreeId: string) => void)[] = [
(state, worktreeId) => {
state.workspaceSession.activeWorktreeId = worktreeId
},
(state, worktreeId) => {
state.workspaceSession.activeWorkspaceKey = worktreeWorkspaceKey(worktreeId)
},
(state, worktreeId) => {
state.workspaceSession.activeWorktreeIdsOnShutdown = [worktreeId]
},
(state, worktreeId) => {
state.ui.lastActiveWorktreeId = worktreeId
},
(state, worktreeId) => {
state.workspaceSession.sleepingAgentSessionsByPaneKey = {
pane: { worktreeId } as never
}
},
(state, worktreeId) => {
state.workspaceSession.terminalSurfaceTombstonesByPaneKey = {
pane: { worktreeId } as never
}
},
(state, worktreeId) => {
state.workspaceSession.closedTerminalTabTombstonesByTabId = {
tab: { worktreeId, closedAt: 1 }
}
},
(state, worktreeId) => {
state.workspaceSession.clientHostedBrowserCloseIntentsByEnvironment = {
runtime: [{ worktreeId, browserPageId: 'page', closedAt: 1 }]
}
},
(state, worktreeId) => {
state.workspaceSession.browserPagesByWorkspace = {
browser: [{ worktreeId } as never]
}
},
(state, worktreeId) => {
state.workspaceSessionsByHostId = {
'ssh:builder': {
...getDefaultWorkspaceSession(),
lastVisitedAtByWorktreeId: { [worktreeId]: 1 }
}
}
},
(state, worktreeId) => {
state.mobileClientTabSelectionsByDeviceId = {
phone: { [worktreeId]: {} as never }
}
},
(state, worktreeId) => {
state.sshRemotePtyLeases = [
{
targetId: 'builder',
ptyId: 'pty',
worktreeId,
state: 'detached',
createdAt: 1,
updatedAt: 1
}
]
},
(state, worktreeId) => {
state.migrationUnsupportedPtyEntries = [
{
ptyId: 'pty',
worktreeId,
reason: 'legacy-numeric-pane-key',
source: 'local',
updatedAt: 1
}
]
},
(state, worktreeId) => {
state.automations = [
{
enabled: true,
workspaceMode: 'existing',
workspaceId: worktreeId
} as never
]
},
(state, worktreeId) => {
state.automationRuns = [{ status: 'dispatching', workspaceId: worktreeId } as never]
}
]
for (const [index, mutate] of ownerMutations.entries()) {
const state = makeState()
const worktreeId = `${REPO_ID}::/workspace/owner-${index}`
state.worktreeMeta[worktreeId] = makeMeta(worktreeId)
const scan = capture(state)
mutate(state, worktreeId)
expect(pruneCaptured(state, scan, [worktreeId])).toEqual([])
}
})
// Route-retired tombstones must not pin metadata forever (#17775).
it('does not let route-retired SSH leases pin a metadata row', () => {
const state = makeState()
@@ -324,85 +165,6 @@ describe('pruneSessionlessMissingLocalWorktreeMetadataForRepo', () => {
expect(Object.keys(state.worktreeMeta).sort()).toEqual([...liveIds].sort())
})
// Plain expiry proves only route loss; recoverable panes retain ownership.
it('keeps a metadata row pinned by an unmarked expired lease', () => {
const state = makeState()
const worktreeId = `${REPO_ID}::/workspace/orphaned`
state.worktreeMeta[worktreeId] = makeMeta(worktreeId)
const scan = capture(state)
state.sshRemotePtyLeases = [
{
targetId: 'builder',
ptyId: 'pty',
worktreeId,
state: 'expired',
createdAt: 1,
updatedAt: 1
}
]
expect(pruneCaptured(state, scan, [worktreeId])).toEqual([])
})
it('preserves canonically equivalent session and top-level owners', () => {
const candidateId = `${REPO_ID}::/workspace/Café`.normalize('NFC')
const ownerId = candidateId.normalize('NFD')
const ownerMutations: ((state: PersistedState) => void)[] = [
(state) => {
state.workspaceSession.activeWorktreeId = ownerId
},
(state) => {
state.ui.lastActiveWorktreeId = ownerId
}
]
for (const mutate of ownerMutations) {
const state = makeState()
state.worktreeMeta[candidateId] = makeMeta(candidateId)
const scan = capture(state)
mutate(state)
expect(pruneCaptured(state, scan, [candidateId])).toEqual([])
expect(state.worktreeMeta[candidateId]).toBeDefined()
}
})
it('removes a row on a later pass after its persisted owner is cleared', () => {
const state = makeState()
const worktreeId = `${REPO_ID}::/workspace/two-phase`
state.worktreeMeta[worktreeId] = makeMeta(worktreeId)
state.workspaceSession.lastVisitedAtByWorktreeId = { [worktreeId]: 1 }
const scan = capture(state)
expect(pruneCaptured(state, scan, [worktreeId])).toEqual([])
delete state.workspaceSession.lastVisitedAtByWorktreeId![worktreeId]
expect(pruneCaptured(state, scan, [worktreeId])).toEqual([worktreeId])
})
it('treats dotfile visibility and cleanup dismissals as non-owning preferences', () => {
const state = makeState()
const worktreeId = `${REPO_ID}::/workspace/non-owning-preferences`
state.worktreeMeta[worktreeId] = makeMeta(worktreeId)
const showDotfilesByWorktree = { [worktreeId]: true }
const workspaceCleanup = {
dismissals: {
[worktreeId]: {
worktreeId,
dismissedAt: 1,
fingerprint: 'fingerprint',
classifierVersion: 1
}
}
}
state.ui.showDotfilesByWorktree = showDotfilesByWorktree
state.ui.workspaceCleanup = workspaceCleanup
const scan = capture(state)
expect(pruneCaptured(state, scan, [worktreeId])).toEqual([worktreeId])
expect(state.ui.showDotfilesByWorktree).toBe(showDotfilesByWorktree)
expect(state.ui.workspaceCleanup).toBe(workspaceCleanup)
})
it('preserves foreign aliases, ambiguous local aliases, and divergent projections', () => {
const foreignState = makeState()
const foreignId = `${REPO_ID}::/workspace/foreign-alias`
@@ -438,34 +200,6 @@ describe('pruneSessionlessMissingLocalWorktreeMetadataForRepo', () => {
expect(pruneCaptured(divergentState, divergentScan, [divergentId])).toEqual([])
})
it('fails closed for repo replacement, host collisions, remote, runtime, and folder repos', () => {
const mutations: ((state: PersistedState) => void)[] = [
(state) => {
state.repos[0] = makeRepo({ path: '/workspace/replacement' })
},
(state) => {
state.repos.push(makeRepo({ connectionId: 'builder', executionHostId: 'ssh:builder' }))
},
(state) => {
state.repos[0] = makeRepo({ connectionId: 'builder', executionHostId: 'ssh:builder' })
},
(state) => {
state.repos[0] = makeRepo({ executionHostId: 'runtime:environment' })
},
(state) => {
state.repos[0] = makeRepo({ kind: 'folder' })
}
]
for (const mutate of mutations) {
const state = makeState()
const worktreeId = `${REPO_ID}::/workspace/stale`
state.worktreeMeta[worktreeId] = makeMeta(worktreeId)
const scan = capture(state)
mutate(state)
expect(pruneCaptured(state, scan, [worktreeId])).toEqual([])
}
})
it('fails closed when project runtime routing changes away and back during the scan', () => {
const state = makeState()
const worktreeId = `${REPO_ID}::/workspace/project-routing-race`
@@ -509,26 +243,4 @@ describe('pruneSessionlessMissingLocalWorktreeMetadataForRepo', () => {
expect(pruneCaptured(state, scan, [worktreeId])).toEqual([])
expect(state.worktreeMeta[worktreeId]).toBeDefined()
})
it('rejects malformed, folder-instance, WSL, and non-native Windows candidate paths', () => {
const state = makeState()
const foreignWindowsId = `${REPO_ID}::C:\\workspace\\stale`
const ids = [
`${REPO_ID}::relative/path`,
`${REPO_ID}::`,
`wrong::/workspace/stale`,
`${REPO_ID}::/workspace/folder::workspace:11111111-1111-4111-8111-111111111111`,
`${REPO_ID}::\\\\wsl.localhost\\Ubuntu\\home\\gone`,
`${REPO_ID}::/home/user/wsl-legacy`,
foreignWindowsId
]
for (const worktreeId of ids) {
state.worktreeMeta[worktreeId] = makeMeta(worktreeId)
}
const scan = capture(state)
expect(pruneCaptured(state, scan, ids.slice(0, -2))).toEqual([])
expect(pruneCaptured(state, scan, [ids.at(-2)!], 'win32')).toEqual([])
expect(pruneCaptured(state, scan, [foreignWindowsId], 'linux')).toEqual([])
})
})
@@ -1,86 +0,0 @@
import {
closeTestStores,
testState,
createStore,
writeDataFile,
makeRepo
} from '../persistence-test-harness'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { rmSync, mkdtempSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import type { Repo } from '../../../shared/repo-types'
vi.mock('../../ssh/config/ssh-config-parser', () => ({
loadUserSshConfig: vi.fn(),
sshConfigHostsToTargets: vi.fn()
}))
vi.mock('electron', () => ({
app: { getPath: () => testState.dir },
safeStorage: {
isEncryptionAvailable: () => true,
encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'),
decryptString: (ciphertext: Buffer) => ciphertext.toString('utf-8').slice('encrypted:'.length)
}
}))
vi.mock('../../telemetry/client', () => ({ track: vi.fn() }))
vi.mock('../../telemetry/cohort-classifier', () => ({
getCohortAtEmit: () => ({ nth_repo_added: 2 })
}))
function writeProfile(repos: Repo[], settings: Record<string, unknown> = {}): void {
writeDataFile({
schemaVersion: 1,
repos,
worktreeMeta: {},
settings,
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
}
describe('keeping agent pre-trust for repos saved before per-repo decisions', () => {
beforeEach(() => {
testState.dir = mkdtempSync(join(tmpdir(), 'orca-test-'))
})
afterEach(async () => {
await closeTestStores()
rmSync(testState.dir, { recursive: true, force: true })
})
it('pins existing repos to pre-trust and keeps explicit answers', async () => {
writeProfile([
makeRepo({ id: 'existing', path: '/repos/existing' }),
makeRepo({ id: 'asks', path: '/repos/asks', agentWorkspaceTrust: 'agent-asks' })
])
const store = await createStore()
expect(store.getRepo('existing')?.agentWorkspaceTrust).toBe('pre-trust')
expect(store.getRepo('asks')?.agentWorkspaceTrust).toBe('agent-asks')
expect(store.getSettings().agentWorkspaceTrustExistingReposMigrated).toBe(true)
})
it('leaves repos undecided when the user had turned folder trust off', async () => {
writeProfile([makeRepo({ id: 'existing', path: '/repos/existing' })], {
agentWorkspaceTrustEnabled: false
})
const store = await createStore()
expect(store.getRepo('existing')).not.toHaveProperty('agentWorkspaceTrust')
expect(store.getSettings().agentWorkspaceTrustEnabled).toBe(false)
})
it('runs once, so repos added after the upgrade stay undecided', async () => {
writeProfile([makeRepo({ id: 'added-later', path: '/repos/added-later' })], {
agentWorkspaceTrustExistingReposMigrated: true
})
const store = await createStore()
expect(store.getRepo('added-later')).not.toHaveProperty('agentWorkspaceTrust')
})
})
@@ -10,10 +10,8 @@ import {
testState,
writeDataFile
} from '../persistence-test-harness'
import { getDefaultPersistedState } from '../../../shared/constants'
import { createProjectGroup } from '../../../shared/project-groups'
import { normalizeRuntimePathSeparators } from '../../../shared/cross-platform-path'
import { LoadedStateAdaptationOperations } from '../loading-store/loaded-state-adaptation'
vi.mock('electron', () => ({
app: {
@@ -44,34 +42,6 @@ describe('Flat folder-scan project groups adaptation', () => {
rmSync(testState.dir, { recursive: true, force: true })
})
it('leaves unchanged group membership and manual order clean on load', () => {
const state = getDefaultPersistedState(testState.dir)
const parentPath = join(testState.dir, 'projects')
const group = createProjectGroup({
name: 'Projects',
parentPath,
createdFrom: 'folder-scan',
tabOrder: 0
})
state.projectGroups = [group]
state.repos = ['alpha', 'beta'].map((name, index) =>
makeRepo({
id: name,
path: join(parentPath, name),
projectGroupId: group.id,
projectGroupOrder: 1 - index
})
)
const operations = new LoadedStateAdaptationOperations({ state, loadNeedsSave: false })
expect(operations.adaptFlatFolderScanProjectGroups()).toBe(false)
expect(state.projectGroups).toEqual([group])
expect(state.repos.map((repo) => [repo.projectGroupId, repo.projectGroupOrder])).toEqual([
[group.id, 1],
[group.id, 0]
])
})
it.each([false, true])(
'preserves saved order through a Store restart (folder repo: %s)',
async (includeFolder) => {
@@ -11,13 +11,6 @@ import { join } from 'node:path'
import { tmpdir } from 'node:os'
import type { PersistedState } from '../../../shared/persisted-state-types'
import {
REORDERED_DEFAULT_WORKSPACE_STATUSES,
REORDERED_DONE_DEFAULT_WORKSPACE_STATUSES,
LEGACY_DEFAULT_WORKSPACE_STATUSES,
WORKFLOW_DEFAULT_WORKSPACE_STATUSES
} from './persistence-workspace-status-fixtures'
const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({
loadUserSshConfigMock: vi.fn(),
sshConfigHostsToTargetsMock: vi.fn()
@@ -69,85 +62,6 @@ describe('Store', () => {
await closeTestStores()
rmSync(testState.dir, { recursive: true, force: true })
})
it('preserves persisted smart sort value', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {},
ui: { sortBy: 'smart' },
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getUI().sortBy).toBe('smart')
})
it('migrates legacy recent sort to smart on first load', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {},
ui: { sortBy: 'recent' },
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getUI().sortBy).toBe('smart')
expect(store.getUI()._sortBySmartMigrated).toBe(true)
})
it('preserves new recent sort after migration flag is set', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {},
ui: { sortBy: 'recent', _sortBySmartMigrated: true },
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getUI().sortBy).toBe('recent')
})
it('uses recent as the default sort for a fresh install (no persisted sortBy)', async () => {
// Gate migration on the raw stored sort, or normalization would misclassify fresh profiles.
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {},
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getUI().sortBy).toBe('recent')
})
it('defaults workspace board task status sync off and normalizes persisted values', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {},
ui: { syncTaskStatusFromWorkspaceBoard: 'yes' },
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getUI().syncTaskStatusFromWorkspaceBoard).toBe(false)
store.updateUI({ syncTaskStatusFromWorkspaceBoard: true })
expect(store.getUI().syncTaskStatusFromWorkspaceBoard).toBe(true)
})
it('preserves workflows above 20 statuses across load, write, and restart', async () => {
const imported = Array.from({ length: 21 }, (_, index) => ({
@@ -188,147 +102,4 @@ describe('Store', () => {
authored.map((status) => status.id)
)
})
it('repairs the known-bad reordered default workspace statuses once on load', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {},
ui: { workspaceStatuses: REORDERED_DEFAULT_WORKSPACE_STATUSES },
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
const ui = store.getUI()
expect(ui.workspaceStatuses?.map((status) => status.id)).toEqual([
'todo',
'in-progress',
'in-review',
'completed'
])
expect(ui.workspaceStatuses?.at(-1)?.label).toBe('Done')
expect(ui._workspaceStatusesDefaultOrderMigrated).toBe(true)
expect(ui._workspaceStatusesDefaultWorkflowMigrated).toBe(true)
store.flush()
const persisted = readDataFile() as PersistedState
expect(persisted.ui._workspaceStatusesDefaultOrderMigrated).toBe(true)
expect(persisted.ui._workspaceStatusesReorderedDefaultRepaired).toBe(true)
expect(persisted.ui._workspaceStatusesDefaultWorkflowMigrated).toBe(true)
expect(persisted.ui._workspaceStatusesDefaultVisualsMigrated).toBe(true)
expect(persisted.ui.workspaceStatuses?.map((status) => status.id)).toEqual([
'todo',
'in-progress',
'in-review',
'completed'
])
expect(persisted.ui.workspaceStatuses?.at(-1)?.label).toBe('Done')
})
it('repairs the known-bad reordered default statuses after old migration flags are set', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {},
ui: {
workspaceStatuses: REORDERED_DONE_DEFAULT_WORKSPACE_STATUSES,
_workspaceStatusesDefaultOrderMigrated: true,
_workspaceStatusesDefaultWorkflowMigrated: true,
_workspaceStatusesDefaultVisualsMigrated: true
},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getUI().workspaceStatuses?.map((status) => status.id)).toEqual([
'todo',
'in-progress',
'in-review',
'completed'
])
expect(store.getUI().workspaceStatuses?.at(-1)?.label).toBe('Done')
expect(store.getUI()._workspaceStatusesReorderedDefaultRepaired).toBe(true)
})
it('migrates legacy default workspace status visuals and workflow once on load', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {},
ui: {
workspaceStatuses: LEGACY_DEFAULT_WORKSPACE_STATUSES,
_workspaceStatusesDefaultOrderMigrated: true
},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getUI().workspaceStatuses).toEqual(WORKFLOW_DEFAULT_WORKSPACE_STATUSES)
expect(store.getUI()._workspaceStatusesDefaultWorkflowMigrated).toBe(true)
expect(store.getUI()._workspaceStatusesDefaultVisualsMigrated).toBe(true)
store.flush()
const persisted = readDataFile() as {
ui?: {
_workspaceStatusesDefaultWorkflowMigrated?: boolean
_workspaceStatusesDefaultVisualsMigrated?: boolean
}
}
expect(persisted.ui?._workspaceStatusesDefaultWorkflowMigrated).toBe(true)
expect(persisted.ui?._workspaceStatusesDefaultVisualsMigrated).toBe(true)
})
it('preserves legacy-looking workspace status visuals after the load migration', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {},
ui: {
workspaceStatuses: LEGACY_DEFAULT_WORKSPACE_STATUSES,
_workspaceStatusesDefaultOrderMigrated: true,
_workspaceStatusesDefaultWorkflowMigrated: true,
_workspaceStatusesDefaultVisualsMigrated: true
},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
const inProgress = store
.getUI()
.workspaceStatuses?.find((status) => status.id === 'in-progress')
expect(inProgress).toMatchObject({ color: 'blue', icon: 'circle-dot' })
})
it('preserves intentionally reordered default workspace statuses after the load migration', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {},
ui: {
workspaceStatuses: REORDERED_DEFAULT_WORKSPACE_STATUSES,
_workspaceStatusesDefaultOrderMigrated: true,
_workspaceStatusesReorderedDefaultRepaired: true,
_workspaceStatusesDefaultWorkflowMigrated: true
},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getUI().workspaceStatuses?.map((status) => status.id)).toEqual([
'completed',
'in-review',
'in-progress',
'todo'
])
})
})
@@ -123,39 +123,6 @@ describe('Store', () => {
})
})
it('advances host topology when a live spawn adds a split leaf after retirement', async () => {
const store = await createStore()
store.setWorkspaceSession({
...getDefaultWorkspaceSession(),
tabsByWorktree: {
wt1: [makeTerminalTab({ id: 'tab1', worktreeId: 'wt1', ptyId: 'pty-1' })]
},
terminalLayoutsByTabId: {
tab1: {
root: { type: 'leaf', leafId: TEST_LEAF_1 },
activeLeafId: TEST_LEAF_1,
expandedLeafId: null,
ptyIdsByLeafId: { [TEST_LEAF_1]: 'pty-1' }
}
},
terminalTopologyRevisionByRepoId: { wt1: 1 }
})
await store.persistPtyBinding({
worktreeId: 'wt1',
tabId: 'tab1',
leafId: TEST_LEAF_2,
ptyId: 'pty-2'
})
const session = store.getWorkspaceSession()
expect(session.terminalTopologyRevisionByRepoId?.wt1).toBe(2)
expect(session.terminalLayoutsByTabId.tab1.ptyIdsByLeafId).toEqual({
[TEST_LEAF_1]: 'pty-1',
[TEST_LEAF_2]: 'pty-2'
})
})
it('keeps worktree deletion authoritative against stale writes and later same-path reuse', async () => {
const store = await createStore()
store.setWorktreeMeta(hostWorktreeTarget({ id: 'wt1', hostId: 'local' }), {
@@ -224,35 +191,6 @@ describe('Store', () => {
expect(store.getWorkspaceSession().tabsByWorktree[worktreeId]).toEqual([])
})
it('advances deletion authority when only a legacy retirement fence existed', async () => {
const store = await createStore()
const worktreeId = 'repo::/legacy-tombstone'
store.setWorktreeMeta(hostWorktreeTarget({ id: worktreeId, hostId: 'local' }), {
displayName: 'Legacy worktree'
})
store.setWorkspaceSession({
...getDefaultWorkspaceSession(),
terminalSurfaceTombstonesByPaneKey: {
'old-tab:old-leaf': {
worktreeId,
parentTabId: 'old-tab',
leafId: 'old-leaf',
ptyId: 'old-pty',
incarnationId: 'old-incarnation',
retiredAt: 1
}
}
})
const revisionBeforeDelete =
store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.repo ?? 0
removeWorktreeMetaRow(store, worktreeId, undefined)
expect(store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.repo).toBe(
revisionBeforeDelete + 1
)
})
it('enforces one repo epoch across siblings and admits a fresh sibling spawn', async () => {
const store = await createStore()
const worktreeA = 'repo::/worktree-a'
@@ -290,28 +228,6 @@ describe('Store', () => {
expect(store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.repo).toBe(2)
})
it('keeps one deletion watermark for many historical worktrees in the same repo', async () => {
const store = await createStore()
for (let index = 0; index < 25; index += 1) {
const worktreeId = `repo::/worktree-${index}`
store.setWorktreeMeta(hostWorktreeTarget({ id: worktreeId, hostId: 'local' }), {
displayName: `Worktree ${index}`
})
await store.persistPtyBinding({
worktreeId,
tabId: `tab-${index}`,
leafId: TEST_LEAF_1,
ptyId: `pty-${index}`
})
removeWorktreeMetaRow(store, worktreeId, undefined)
}
const session = store.getWorkspaceSession()
expect(Object.keys(session.terminalTopologyRevisionByRepoId ?? {})).toEqual(['repo'])
expect(session.tabsByWorktree).toEqual({})
})
it('does not remove colliding worktree ids from other execution-host partitions', async () => {
const store = await createStore()
const worktreeId = 'repo::/same-path'
@@ -7,7 +7,6 @@ import {
writeDataFile,
readDataFile,
makeRepo,
makeWorktreeLineage,
makeWorkspaceLineage
} from '../persistence-test-harness'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
@@ -20,8 +19,6 @@ import { restoreProfileStateJsonExport } from '../profile-state/legacy-json/prof
import { acquireProfileStateMaintenance } from '../profile-state/profile-state-access'
import type { Repo } from '../../../shared/repo-types'
import { folderWorkspaceKey, worktreeWorkspaceKey } from '../../../shared/workspace-scope'
import { hostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity'
import { removeWorktreeMetaRow } from '../host-qualified-worktree-meta'
const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({
loadUserSshConfigMock: vi.fn(),
@@ -75,81 +72,6 @@ describe('Store', () => {
rmSync(testState.dir, { recursive: true, force: true })
})
it('getAllWorktreeMeta returns all entries', async () => {
const store = await createStore()
store.setWorktreeMeta(hostWorktreeTarget({ id: 'a', hostId: 'local' }), { displayName: 'A' })
store.setWorktreeMeta(hostWorktreeTarget({ id: 'b', hostId: 'local' }), { displayName: 'B' })
const all = store.getAllWorktreeMeta()
expect(Object.keys(all)).toHaveLength(2)
expect(all['a'].displayName).toBe('A')
expect(all['b'].displayName).toBe('B')
})
it('removeWorktreeMeta deletes a single entry', async () => {
const store = await createStore()
store.setWorktreeMeta(hostWorktreeTarget({ id: 'a', hostId: 'local' }), { displayName: 'A' })
store.setWorktreeMeta(hostWorktreeTarget({ id: 'b', hostId: 'local' }), { displayName: 'B' })
removeWorktreeMetaRow(store, 'a', undefined)
expect(store.getWorktreeMeta('a')).toBeUndefined()
expect(store.getWorktreeMeta('b')).toBeDefined()
})
it('stores and removes worktree lineage independently from metadata', async () => {
const store = await createStore()
const lineage = makeWorktreeLineage()
store.setWorktreeMeta(hostWorktreeTarget({ id: lineage.worktreeId, hostId: 'local' }), {
displayName: 'child'
})
store.setWorktreeLineage(
hostWorktreeTarget({ id: lineage.worktreeId, hostId: 'local' }),
lineage
)
expect(store.getWorktreeLineage(lineage.worktreeId)).toEqual(lineage)
expect(store.getAllWorktreeLineage()).toEqual({ [lineage.worktreeId]: lineage })
store.removeWorktreeLineage(hostWorktreeTarget({ id: lineage.worktreeId, hostId: 'local' }))
expect(store.getWorktreeLineage(lineage.worktreeId)).toBeUndefined()
expect(store.getWorktreeMeta(lineage.worktreeId)).toBeDefined()
})
it('removeWorktreeMeta deletes that worktree lineage entry', async () => {
const store = await createStore()
const lineage = makeWorktreeLineage()
store.setWorktreeMeta(hostWorktreeTarget({ id: lineage.worktreeId, hostId: 'local' }), {
displayName: 'child'
})
store.setWorktreeLineage(
hostWorktreeTarget({ id: lineage.worktreeId, hostId: 'local' }),
lineage
)
removeWorktreeMetaRow(store, lineage.worktreeId, undefined)
expect(store.getWorktreeMeta(lineage.worktreeId)).toBeUndefined()
expect(store.getWorktreeLineage(lineage.worktreeId)).toBeUndefined()
})
it('stores workspace lineage and removes it with the child worktree metadata', async () => {
const store = await createStore()
const lineage = makeWorkspaceLineage()
store.setWorktreeMeta(hostWorktreeTarget({ id: 'r1::/path/child', hostId: 'local' }), {
displayName: 'child'
})
store.setWorkspaceLineage(lineage)
expect(store.getWorkspaceLineage(lineage.childWorkspaceKey)).toEqual(lineage)
expect(store.getAllWorkspaceLineage()).toEqual({ [lineage.childWorkspaceKey]: lineage })
removeWorktreeMetaRow(store, 'r1::/path/child', undefined)
expect(store.getWorkspaceLineage(lineage.childWorkspaceKey)).toBeUndefined()
})
it('removeFolderWorkspace deletes child workspace lineage for that folder parent', async () => {
const store = await createStore()
const group = store.createProjectGroup({
@@ -179,29 +101,6 @@ describe('Store', () => {
})
describe('mobileClientTabSelectionsByDeviceId', () => {
it('persists device tab selections across reloads and drops malformed payloads', async () => {
const store = await createStore()
// Register the owner so orphan cleanup cannot erase the fixture on reload.
store.addRepo(makeRepo({ id: 'repo-1', path: '/repo-1' }))
store.setMobileClientTabSelections({
'device-a': {
'repo-1::/tmp/wt': { activeTabId: 'tab-1', activeGroupId: 'g1', activeTabIdByGroupId: {} }
}
})
store.flush()
const reloaded = await createStore()
expect(reloaded.getMobileClientTabSelections()['device-a']?.['repo-1::/tmp/wt']).toEqual({
activeTabId: 'tab-1',
activeGroupId: 'g1',
activeTabIdByGroupId: {}
})
writeDataFile({ mobileClientTabSelectionsByDeviceId: { 'device-a': 'corrupt' } })
const corrupted = await createStore()
expect(corrupted.getMobileClientTabSelections()).toEqual({})
})
it('prunes selections for a removed repo worktree', async () => {
const store = await createStore()
store.addRepo(makeRepo())
@@ -9,8 +9,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { rmSync, mkdtempSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import type { GlobalSettings } from '../../../shared/global-settings-types'
import type { ExternalWorktreeVisibility } from '../../../shared/repo-types'
import { getDefaultPersistedState } from '../../../shared/constants'
const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({
@@ -64,21 +63,6 @@ describe('Store', () => {
await closeTestStores()
rmSync(testState.dir, { recursive: true, force: true })
})
it('updateRepo stamps legacy external-worktree visibility before changing old repos', async () => {
const store = await createStore()
store.addRepo(
makeRepo({
addedAt: Date.UTC(2026, 4, 24),
externalWorktreeVisibility: undefined,
externalWorktreeVisibilityLegacy: undefined
})
)
const updated = store.updateRepo({ id: 'r1' }, { externalWorktreeVisibility: 'hide' })
expect(updated!.externalWorktreeVisibility).toBe('hide')
expect(updated!.externalWorktreeVisibilityLegacy).toBe(true)
})
it('migrates implicit legacy visibility to an explicit override before defaulting global hide', async () => {
const persisted = getDefaultPersistedState(testState.dir)
@@ -117,287 +101,4 @@ describe('Store', () => {
})
expect(reloaded.getRepo('inherited')?.externalWorktreeVisibility).toBeUndefined()
})
it('merges visibility-default patches so future source defaults survive older controls', async () => {
const store = await createStore()
store.updateSettings({
worktreeVisibilityDefaults: {
external: 'show',
futureSource: 'hide'
} as GlobalSettings['worktreeVisibilityDefaults']
})
store.updateSettings({ worktreeVisibilityDefaults: { external: 'hide' } })
expect(store.getSettings().worktreeVisibilityDefaults).toEqual({
external: 'hide',
futureSource: 'hide'
})
})
it('normalizes and persists global worktree source defaults', async () => {
const store = await createStore()
store.updateSettings({
worktreeVisibilityDefaults: {
external: 'show',
customSources: [
{ id: 'team', rootPath: ' /srv/team-worktrees ' },
{ id: 'invalid', rootPath: '../relative' }
],
sourcePreferences: {
builtIn: { claude: 'show', gsd: 'hide' },
custom: { team: 'show' }
}
}
})
expect(store.getSettings().worktreeVisibilityDefaults).toEqual({
external: 'show',
customSources: [{ id: 'team', rootPath: '/srv/team-worktrees' }],
sourcePreferences: {
builtIn: { claude: 'show', gsd: 'hide' },
custom: { team: 'show' }
}
})
store.flush()
const reloaded = await createStore()
expect(reloaded.getSettings().worktreeVisibilityDefaults).toEqual(
store.getSettings().worktreeVisibilityDefaults
)
})
it('persists agent worktree visibility independently from external visibility', async () => {
const store = await createStore()
store.addRepo(makeRepo({ externalWorktreeVisibility: 'hide' }))
const updated = store.updateRepo({ id: 'r1' }, { agentWorktreeVisibility: 'show' })
expect(updated).toMatchObject({
externalWorktreeVisibility: 'hide',
agentWorktreeVisibility: 'show',
worktreeVisibilitySourcePreferences: {
builtIn: { claude: 'show', gsd: 'show' }
}
})
store.flush()
const reloaded = await createStore()
expect(reloaded.getRepo('r1')).toMatchObject({
externalWorktreeVisibility: 'hide',
agentWorktreeVisibility: 'show',
worktreeVisibilitySourcePreferences: {
builtIn: { claude: 'show', gsd: 'show' }
}
})
})
it('persists bounded custom worktree sources separately from their preferences', async () => {
const store = await createStore()
store.addRepo(makeRepo())
const updated = store.updateRepo(
{ id: 'r1' },
{
customWorktreeVisibilitySources: [
{ id: 'team', rootPath: ' /srv/team-worktrees ' },
{ id: 'invalid', rootPath: '../relative' }
],
worktreeVisibilitySourcePreferences: {
builtIn: { claude: 'show', gsd: 'hide' },
custom: { team: 'show' }
}
}
)
expect(updated).toMatchObject({
customWorktreeVisibilitySources: [{ id: 'team', rootPath: '/srv/team-worktrees' }],
worktreeVisibilitySourcePreferences: {
builtIn: { claude: 'show', gsd: 'hide' },
custom: { team: 'show' }
}
})
store.flush()
const reloaded = await createStore()
expect(reloaded.getRepo('r1')?.customWorktreeVisibilitySources).toEqual([
{ id: 'team', rootPath: '/srv/team-worktrees' }
])
})
it('clears an explicit external-worktree override without stamping an inherited default', async () => {
const store = await createStore()
store.addRepo(
makeRepo({
externalWorktreeVisibility: 'show',
externalWorktreeVisibilityLegacy: true
})
)
const updated = store.updateRepo({ id: 'r1' }, { externalWorktreeVisibility: null })
expect(updated?.externalWorktreeVisibility).toBeUndefined()
expect(updated?.externalWorktreeVisibilityLegacy).toBe(false)
store.flush()
const reloaded = await createStore()
expect(reloaded.getRepo('r1')?.externalWorktreeVisibility).toBeUndefined()
expect(reloaded.getRepo('r1')?.externalWorktreeVisibilityLegacy).toBe(false)
})
it('sanitizes raw custom worktree visibility sources on the read path', async () => {
const persisted = getDefaultPersistedState(testState.dir)
persisted.repos = [
makeRepo({
id: 'r1',
customWorktreeVisibilitySources: [
{ id: 'team', rootPath: ' /srv/team-worktrees ' },
{ id: 'invalid', rootPath: '../relative' }
],
worktreeVisibilitySourcePreferences: {
builtIn: { claude: 'show', gsd: 'show' },
custom: { team: 'show', missing: 'bogus' as unknown as ExternalWorktreeVisibility }
}
})
]
writeDataFile(persisted)
const store = await createStore()
expect(store.getRepo('r1')).toMatchObject({
customWorktreeVisibilitySources: [{ id: 'team', rootPath: '/srv/team-worktrees' }],
worktreeVisibilitySourcePreferences: {
builtIn: { claude: 'show', gsd: 'show' },
custom: { team: 'show' }
}
})
})
it('updateRepo clears source-control AI overrides independently from other clearable fields', async () => {
const store = await createStore()
store.addRepo(
makeRepo({
issueSourcePreference: 'origin',
sourceControlAi: {
instructionsByOperation: { commitMessage: 'Repo style' },
prCreationDefaults: { draft: true }
}
})
)
store.updateRepo(
{ id: 'r1' },
{
issueSourcePreference: undefined,
sourceControlAi: undefined
}
)
expect(store.getRepo('r1')!.issueSourcePreference).toBeUndefined()
expect(store.getRepo('r1')!.sourceControlAi).toBeUndefined()
store.flush()
const reloaded = await createStore()
expect(reloaded.getRepo('r1')!.issueSourcePreference).toBeUndefined()
expect(reloaded.getRepo('r1')!.sourceControlAi).toBeUndefined()
})
it('updateRepo treats source-control AI null as a transport clear sentinel', async () => {
const store = await createStore()
store.addRepo(
makeRepo({
sourceControlAi: {
enabled: true,
customAgentCommand: 'repo-agent {prompt}'
}
})
)
store.updateRepo(
{ id: 'r1' },
{
sourceControlAi: null
}
)
expect(store.getRepo('r1')!.sourceControlAi).toBeUndefined()
store.flush()
const reloaded = await createStore()
expect(reloaded.getRepo('r1')!.sourceControlAi).toBeUndefined()
})
it('updateRepo normalizes source-control AI overrides before storing', async () => {
const store = await createStore()
store.addRepo(makeRepo())
const updated = store.updateRepo(
{ id: 'r1' },
{
sourceControlAi: {
instructionsByOperation: {
commitMessage: 'Repo style',
pullRequest: 42,
unknown: 'ignored'
},
prCreationDefaults: {
draft: true,
useTemplate: null,
openAfterCreate: 'yes'
},
modelOverridesByOperation: {
commitMessage: {
selectedModelByAgent: { codex: 'gpt-5.4', claude: false },
selectedThinkingByModel: { 'gpt-5.4': 'high', bad: true }
},
unknown: {
selectedModelByAgent: { codex: 'ignored' }
}
}
} as never
}
)
expect(updated!.sourceControlAi).toEqual({
instructionsByOperation: {
commitMessage: 'Repo style'
},
actionOverrides: {
commitMessage: {
commandInputTemplate: '{basePrompt}\n\nRepo style'
}
},
prCreationDefaults: {
draft: true,
useTemplate: null
},
modelOverridesByOperation: {
commitMessage: {
selectedModelByAgent: { codex: 'gpt-5.4' },
selectedThinkingByModel: { 'gpt-5.4': 'high' }
}
}
})
})
it('updateRepo ignores malformed source-control AI overrides without clearing existing overrides', async () => {
const store = await createStore()
store.addRepo(
makeRepo({
sourceControlAi: {
instructionsByOperation: { commitMessage: 'Keep me' }
}
})
)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: feeds the sanitizer a value its type forbids, on purpose.
const updated = store.updateRepo({ id: 'r1' }, { sourceControlAi: 'bad' as never })
expect(updated!.sourceControlAi).toEqual({
instructionsByOperation: { commitMessage: 'Keep me' },
actionOverrides: {
commitMessage: {
commandInputTemplate: '{basePrompt}\n\nKeep me'
}
}
})
})
})
@@ -1,118 +0,0 @@
import { describe, expect, it } from 'vitest'
import { getDefaultPersistedState } from '../../../shared/constants'
import type { PersistedState } from '../../../shared/persisted-state-types'
import type { Repo } from '../../../shared/repo-types'
import type { WorktreeMeta } from '../../../shared/worktree/meta-types'
import {
captureNativeLocalWorktreeMetadataScanExpectation,
pruneSessionlessMissingLocalWorktreeMetadataForRepo,
selectProbeableLocalWorktreeMetadataCandidates
} from './missing-local-worktree-metadata-pruning'
const REPO_ID = 'repo-1'
function makeRepo(): Repo {
return {
id: REPO_ID,
path: '/workspace/repo',
displayName: 'repo',
badgeColor: '#000',
addedAt: 0
}
}
function makeMeta(worktreeId: string, overrides: Partial<WorktreeMeta> = {}): WorktreeMeta {
return {
instanceId: `instance-${worktreeId}`,
hostId: 'local',
displayName: worktreeId,
comment: '',
linkedIssue: null,
linkedPR: null,
linkedLinearIssue: null,
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 0,
...overrides
}
}
function makeState(): PersistedState {
const state = getDefaultPersistedState('/home/test')
state.repos = [makeRepo()]
return state
}
function probeableIds(state: PersistedState): string[] {
const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!)
return selectProbeableLocalWorktreeMetadataCandidates(state, scan, 'linux').map(
({ worktreeId }) => worktreeId
)
}
describe('selectProbeableLocalWorktreeMetadataCandidates', () => {
it('keeps an ordinary sessionless local row', () => {
const state = makeState()
const id = `${REPO_ID}::/workspace/gone`
state.worktreeMeta[id] = makeMeta(id)
expect(probeableIds(state)).toEqual([id])
})
it('drops a row a persisted session still pins', () => {
const state = makeState()
const pinned = `${REPO_ID}::/workspace/pinned`
const free = `${REPO_ID}::/workspace/free`
state.worktreeMeta[pinned] = makeMeta(pinned)
state.worktreeMeta[free] = makeMeta(free)
state.ui.lastActiveWorktreeId = pinned
expect(probeableIds(state)).toEqual([free])
})
it('drops a row whose locator is also known on a remote host', () => {
const state = makeState()
const shared = `${REPO_ID}::/workspace/shared`
const free = `${REPO_ID}::/workspace/free`
state.worktreeMeta[shared] = makeMeta(shared)
state.worktreeMeta[free] = makeMeta(free)
state.worktreeIdentityAliases = { [`ssh:box|${shared}`]: ['identity-1'] }
expect(probeableIds(state)).toEqual([free])
})
it('drops a row pinned to another execution host', () => {
const state = makeState()
const remote = `${REPO_ID}::/workspace/remote`
state.worktreeMeta[remote] = makeMeta(remote, { hostId: 'ssh:box' })
expect(probeableIds(state)).toEqual([])
})
it('never widens what the authoritative prune would remove', () => {
const state = makeState()
const ids = [
`${REPO_ID}::/workspace/free`,
`${REPO_ID}::/workspace/pinned`,
`${REPO_ID}::/workspace/remote`
]
state.worktreeMeta[ids[0]] = makeMeta(ids[0])
state.worktreeMeta[ids[1]] = makeMeta(ids[1])
state.worktreeMeta[ids[2]] = makeMeta(ids[2], { hostId: 'ssh:box' })
state.ui.lastActiveWorktreeId = ids[1]
const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!)
const selected = selectProbeableLocalWorktreeMetadataCandidates(state, scan, 'linux')
// Prefiltering must preserve the authoritative deletion verdict.
const removed = pruneSessionlessMissingLocalWorktreeMetadataForRepo(
state,
scan,
scan.metadata,
'linux'
)
expect(selected.map(({ worktreeId }) => worktreeId)).toEqual(removed)
})
})
@@ -1,67 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { ProjectHostSetup } from '../../../shared/project-types'
import type { Repo } from '../../../shared/repo-types'
import { mergeProjectHostSetupCompatibilityState } from './project-host-compatibility'
const PROJECT_ID = 'github:acme/orca'
function repo(overrides: Partial<Repo> & Pick<Repo, 'id'>): Repo {
return {
path: `/src/${overrides.id}`,
displayName: 'orca',
addedAt: 1,
upstream: { owner: 'acme', repo: 'orca' },
...overrides
} as Repo
}
function pendingSetup(overrides: Partial<ProjectHostSetup> = {}): ProjectHostSetup {
return {
id: `${PROJECT_ID}::ssh:devbox`,
projectId: PROJECT_ID,
hostId: 'ssh:devbox',
repoId: '',
path: '',
displayName: 'orca',
setupState: 'not-set-up',
setupMethod: 'pending',
createdAt: 1,
updatedAt: 1,
...overrides
} as ProjectHostSetup
}
describe('mergeProjectHostSetupCompatibilityState', () => {
it('keeps a placeholder for a host with no repo yet', () => {
const merged = mergeProjectHostSetupCompatibilityState(
{ projects: [], projectHostSetups: [pendingSetup()] },
[repo({ id: 'local-repo' })]
)
expect(merged.projectHostSetups.map((setup) => setup.hostId)).toEqual(['local', 'ssh:devbox'])
})
// Ready repo projections must displace same-project/host placeholders or they shadow setup state.
it('drops a placeholder once a repo covers the same project and host', () => {
const merged = mergeProjectHostSetupCompatibilityState(
{ projects: [], projectHostSetups: [pendingSetup()] },
[repo({ id: 'local-repo' }), repo({ id: 'devbox-repo', executionHostId: 'ssh:devbox' })]
)
expect(merged.projectHostSetups).toHaveLength(2)
expect(merged.projectHostSetups.every((setup) => setup.setupState === 'ready')).toBe(true)
expect(merged.projectHostSetups.map((setup) => setup.id)).toEqual(['local-repo', 'devbox-repo'])
})
it('keeps the placeholder when the repo covers a different host', () => {
const merged = mergeProjectHostSetupCompatibilityState(
{ projects: [], projectHostSetups: [pendingSetup({ hostId: 'ssh:other' })] },
[repo({ id: 'devbox-repo', executionHostId: 'ssh:devbox' })]
)
expect(merged.projectHostSetups.map((setup) => setup.hostId)).toEqual([
'ssh:devbox',
'ssh:other'
])
})
})
@@ -55,35 +55,4 @@ describe('chat appearance write queue', () => {
fontSize: 15
})
})
it('consumes chat size actions without changing saved size while terminal matching is active', async () => {
const updateSettings = vi.fn(async (updates: Partial<GlobalSettings>) => {
mock.state.settings = { ...mock.state.settings!, ...updates }
})
mock.state.updateSettings = updateSettings
mock.state.settings = {
...getDefaultSettings('/tmp'),
nativeChatAppearance: {
fontSize: 18,
codeFontSize: 16,
contrast: 125,
matchTerminalInterface: true
}
}
await writeNativeChatFontSize('increase')
await writeNativeChatFontSize('decrease')
await writeNativeChatFontSize('reset')
expect(updateSettings).not.toHaveBeenCalled()
expect(mock.state.settings.nativeChatAppearance?.fontSize).toBe(18)
mock.state.settings = {
...mock.state.settings,
nativeChatAppearance: {
...mock.state.settings.nativeChatAppearance,
matchTerminalInterface: false
}
}
await writeNativeChatFontSize('increase')
expect(updateSettings).toHaveBeenCalledTimes(1)
expect(mock.state.settings.nativeChatAppearance?.fontSize).toBe(19)
})
})
@@ -3,9 +3,8 @@ import type { ParsedTerminalFileLink } from '../../../../../../shared/terminal/l
import type * as FileLinkTargetModule from '@/components/terminal-pane/links/files/terminal-file-link-target'
import type { FileLinkPathExistence } from '@/components/terminal-pane/links/files/terminal-file-link-target'
import type * as FilePathMappingModule from '@/components/terminal-pane/host-files/terminal-file-path-mapping'
import { RECENT_PATH_ANSWERS_MAX } from '../../../../../../shared/recent-path-answers'
import { createNativeChatFileLinkExistence } from './native-chat-file-link-existence'
import { UNVERIFIABLE_RETRY_DELAYS_MS } from '../../../../../../shared/native-chat/native-chat-file-link-existence'
const connection = vi.hoisted(() => ({
resolved: true,
@@ -91,43 +90,6 @@ describe('createNativeChatFileLinkExistence', () => {
connection.currentOwnerResolved = true
})
it('links a path the turn created once the turn ends, without re-rendering first', async () => {
let created = false
const { asked, pathExists } = hostWith(() => created)
const existence = createNativeChatFileLinkExistence(host, pathExists)
const { watcher, onChange } = watching(existence)
watcher.getSnapshot().check(link('src/new.ts'))
await settle()
created = true
existence.recheck()
expect(onChange).not.toHaveBeenCalled()
await settle()
expect(asked).toEqual(['/repo/src/new.ts', '/repo/src/new.ts'])
expect(onChange).toHaveBeenCalledOnce()
expect(watcher.getSnapshot().check(link('src/new.ts'))).toBe(true)
})
it('removes the underline of a confirmed path deleted during the turn', async () => {
let deleted = false
const { pathExists } = hostWith(() => !deleted)
const existence = createNativeChatFileLinkExistence(host, pathExists)
const { watcher, onChange } = watching(existence)
watcher.getSnapshot().check(link('src/old.ts'))
await settle()
expect(watcher.getSnapshot().check(link('src/old.ts'))).toBe(true)
deleted = true
existence.recheck()
// Why: the old answer keeps showing until the host replies, so nothing flickers.
expect(watcher.getSnapshot().check(link('src/old.ts'))).toBe(true)
await settle()
expect(onChange).toHaveBeenCalledTimes(2)
expect(watcher.getSnapshot().check(link('src/old.ts'))).toBe(false)
})
it('shows an answer that landed between a message rendering and subscribing', async () => {
const { pathExists } = hostWith(() => true)
const existence = createNativeChatFileLinkExistence(host, pathExists)
@@ -145,48 +107,6 @@ describe('createNativeChatFileLinkExistence', () => {
expect(pathExists).toHaveBeenCalledOnce()
})
it('asks again on subscribe when the host failed before the message subscribed', async () => {
vi.useFakeTimers()
let reachable = false
const { pathExists } = hostWith(() => (reachable ? true : new Error('SSH connection closed')))
const existence = createNativeChatFileLinkExistence(host, pathExists)
const late = existence.watch()
late.getSnapshot().check(link('src/App.tsx'))
await settle()
// Why: nothing showed the path yet, so no retry was armed for it.
expect(vi.getTimerCount()).toBe(0)
reachable = true
const onChange = vi.fn()
late.subscribe(onChange)
await settle()
expect(pathExists).toHaveBeenCalledTimes(2)
expect(onChange).toHaveBeenCalledOnce()
expect(late.getSnapshot().check(link('src/App.tsx'))).toBe(true)
})
it('keeps every answer a shown message needs, past the unobserved cache limit', async () => {
const { pathExists } = hostWith(() => true)
const existence = createNativeChatFileLinkExistence(host, pathExists)
const { watcher } = watching(existence)
const names = Array.from(
{ length: RECENT_PATH_ANSWERS_MAX + 100 },
(_, index) => `file-${index}.md`
)
const render = (): boolean[] => names.map((name) => watcher.getSnapshot().check(link(name)))
render()
await settle()
expect(render().every(Boolean)).toBe(true)
await settle()
expect(pathExists).toHaveBeenCalledTimes(names.length)
existence.recheck()
await settle()
expect(pathExists).toHaveBeenCalledTimes(names.length * 2)
})
it('keeps a reply to an older question from overwriting a newer answer', async () => {
const replies: ((exists: boolean) => void)[] = []
const pathExists = vi.fn<FileLinkPathExistence>(
@@ -207,43 +127,4 @@ describe('createNativeChatFileLinkExistence', () => {
expect(watcher.getSnapshot().check(link('src/new.ts'))).toBe(true)
})
it('links a path once a host that could not answer comes back, without a remount', async () => {
vi.useFakeTimers()
let reachable = false
const { pathExists } = hostWith(() => (reachable ? true : new Error('SSH connection closed')))
const { watcher, onChange } = watching(createNativeChatFileLinkExistence(host, pathExists))
watcher.getSnapshot().check(link('src/App.tsx'))
await settle()
// Why: re-renders while the host is down must not ask again; the retry owns that.
watcher.getSnapshot().check(link('src/App.tsx'))
await settle()
expect(pathExists).toHaveBeenCalledOnce()
expect(onChange).not.toHaveBeenCalled()
reachable = true
await vi.advanceTimersByTimeAsync(UNVERIFIABLE_RETRY_DELAYS_MS[0])
expect(pathExists).toHaveBeenCalledTimes(2)
expect(onChange).toHaveBeenCalledOnce()
expect(watcher.getSnapshot().check(link('src/App.tsx'))).toBe(true)
})
it('keeps the shown answer when the host cannot answer a recheck', async () => {
let reachable = true
const { pathExists } = hostWith(() => (reachable ? true : new Error('SSH connection closed')))
const existence = createNativeChatFileLinkExistence(host, pathExists)
const { watcher, onChange } = watching(existence)
watcher.getSnapshot().check(link('src/App.tsx'))
await settle()
onChange.mockClear()
reachable = false
existence.recheck()
await settle()
expect(onChange).not.toHaveBeenCalled()
expect(watcher.getSnapshot().check(link('src/App.tsx'))).toBe(true)
})
})
@@ -1,52 +0,0 @@
import { describe, expect, it } from 'vitest'
import { createNativeChatFileHref } from '../../../../../../shared/native-chat/native-chat-href-routing'
import { resolveNativeChatFileLink } from './native-chat-file-link'
import type { NativeChatFileLinkContext } from './native-chat-file-link-context'
const context: NativeChatFileLinkContext = {
worktreeId: 'wt-1',
worktreePath: '/repo/worktree',
runtimeEnvironmentId: null
}
describe('resolveNativeChatFileLink', () => {
it.each([
['/repo/report:12', '/repo/report:12'],
['/repo/report:0', '/repo/report:0'],
['/repo/report:12:4', '/repo/report:12:4'],
['/repo/ leading ', '/repo/ leading '],
[' leading ', '/repo/worktree/ leading '],
['notes%23?#.md', '/repo/worktree/notes%23?#.md'],
['https:notes.md', '/repo/worktree/https:notes.md'],
['file:notes.md', '/repo/worktree/file:notes.md'],
['../sibling/readme.md', '/repo/sibling/readme.md']
])('resolves literal tool path %j without parsing a reply location', (path, absolutePath) => {
expect(resolveNativeChatFileLink(createNativeChatFileHref(path, 'literal'), context)).toEqual({
absolutePath,
line: null,
column: null
})
})
it('reads URL-style /D:/ targets as the drive only in a Windows workspace', () => {
const windowsContext = { ...context, worktreePath: 'D:/repo' }
for (const href of ['/D:/Temp/report.txt', createNativeChatFileHref('/D:/Temp/report.txt')]) {
expect(resolveNativeChatFileLink(href, windowsContext)?.absolutePath).toBe(
'D:/Temp/report.txt'
)
}
expect(
resolveNativeChatFileLink(
createNativeChatFileHref('/D:/Temp/report.txt', 'literal'),
windowsContext
)?.absolutePath
).toBe('D:/Temp/report.txt')
expect(
resolveNativeChatFileLink('//server/share/report.txt', windowsContext)?.absolutePath
).toBe('//server/share/report.txt')
expect(resolveNativeChatFileLink('/D:/Temp/report.txt', context)?.absolutePath).toBe(
'/D:/Temp/report.txt'
)
})
})
@@ -1,115 +0,0 @@
// @vitest-environment happy-dom
import type { ReactNode } from 'react'
import { useRef } from 'react'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { LinkActionPopover } from '@/components/link-actions/LinkActionPopover'
import CommentMarkdown from '@/components/sidebar/CommentMarkdown'
import { useNativeChatLinkActions } from './use-native-chat-link-actions'
import type * as HttpLinkRoutingModule from '@/lib/browser/navigation/http-link-routing'
const mocks = vi.hoisted(() => ({
openHttpLink: vi.fn(),
openFileLink: vi.fn(),
settings: { openLinksInApp: true, terminalLinkActionPopoverEnabled: true } as {
openLinksInApp?: boolean
terminalLinkActionPopoverEnabled?: boolean
}
}))
vi.mock('@/lib/browser/navigation/http-link-routing', async (importOriginal) => ({
...(await importOriginal<typeof HttpLinkRoutingModule>()),
openHttpLink: mocks.openHttpLink
}))
vi.mock('./native-chat-http-link-source-owner', () => ({
resolveNativeChatHttpLinkSourceOwner: () => ({ kind: 'local' }),
canNativeChatOpenOwnedBrowser: () => false
}))
vi.mock('./use-native-chat-file-link-click', () => ({
useNativeChatFileLinkClick: (context: unknown) => (context ? mocks.openFileLink : undefined)
}))
vi.mock('@/store', () => ({
useAppStore: Object.assign(
(selector: (state: Record<string, unknown>) => unknown) =>
selector({ openSettingsPage: vi.fn(), openSettingsTarget: vi.fn() }),
{ getState: () => ({ settings: mocks.settings }) }
)
}))
vi.mock('@/components/ui/tooltip', () => ({
Tooltip: ({ children }: { children: ReactNode }) => children,
TooltipTrigger: ({ children }: { children: ReactNode }) => children,
TooltipContent: ({ children }: { children: ReactNode }) => <span>{children}</span>
}))
vi.mock('@/components/ui/popover', () => ({
Popover: ({ children, open }: { children: ReactNode; open: boolean }) =>
open ? <div>{children}</div> : null,
PopoverAnchor: () => null,
PopoverContent: ({ children }: { children: ReactNode }) => <div>{children}</div>
}))
const context = { worktreeId: 'wt-1', worktreePath: '/repo', runtimeEnvironmentId: null }
function Transcript({
markdown,
sessionId = 'session-1',
isVisible = true,
linkContext = context
}: {
markdown: string
sessionId?: string
isVisible?: boolean
linkContext?: typeof context | null
}): React.JSX.Element {
const rootRef = useRef<HTMLDivElement>(null)
const { onLinkClick, linkActionRequest, closeLinkActions } = useNativeChatLinkActions(
linkContext,
rootRef,
{ sessionId, isVisible }
)
return (
<div ref={rootRef}>
<CommentMarkdown
content={markdown}
variant="document"
onLinkClick={onLinkClick}
allowFileUriLinks
/>
<LinkActionPopover request={linkActionRequest} onClose={closeLinkActions} />
</div>
)
}
afterEach(() => {
cleanup()
vi.clearAllMocks()
mocks.settings = { openLinksInApp: true, terminalLinkActionPopoverEnabled: true }
})
describe('native chat transcript links', () => {
it('keeps mailto links on the anchor default', async () => {
const { container } = render(<Transcript markdown="[email](mailto:hello@example.com)" />)
const anchorDefault = vi.fn((event: Event) => {
expect(event.defaultPrevented).toBe(false)
event.preventDefault()
})
container.addEventListener('click', anchorDefault)
fireEvent.click(await screen.findByRole('link', { name: 'email' }))
expect(anchorDefault).toHaveBeenCalledOnce()
expect(mocks.openHttpLink).not.toHaveBeenCalled()
expect(mocks.openFileLink).not.toHaveBeenCalled()
expect(screen.queryByText('System Browser')).toBeNull()
})
it('restores focus to the clicked transcript link', async () => {
render(<Transcript markdown="[link](https://example.com)" />)
const anchor = await screen.findByRole('link', { name: 'link' })
fireEvent.click(anchor)
fireEvent.click(screen.getByText('System Browser'))
expect(document.activeElement).toBe(anchor)
})
})
@@ -2,39 +2,6 @@ import { describe, expect, it } from 'vitest'
import { createHoverPreviewCache } from './native-chat-hover-preview-cache'
describe('createHoverPreviewCache', () => {
it('drops the oldest answers once their total size passes the budget', async () => {
const cache = createHoverPreviewCache<string>({
freshMs: 60_000,
maxEntries: 100,
budget: { maxBytes: 10, sizeOf: (value) => value.length }
})
await cache.load('a', async () => 'aaaa')
await cache.load('b', async () => 'bbbb')
await cache.load('c', async () => 'cccc')
expect(cache.read('a')).toBeNull()
expect(cache.read('b')).toBe('bbbb')
expect(cache.read('c')).toBe('cccc')
})
it('stays within the budget when an older request finishes last', async () => {
const cache = createHoverPreviewCache<string>({
freshMs: 60_000,
maxEntries: 100,
budget: { maxBytes: 10, sizeOf: (value) => value.length }
})
let finishSlow: (value: string) => void = () => {}
const slow = cache.load('slow', () => new Promise((resolve) => (finishSlow = resolve)))
await cache.load('b', async () => 'bbbb')
await cache.load('c', async () => 'cccc')
finishSlow('ssss')
await slow
expect(cache.read('slow')).toBe('ssss')
expect(cache.read('b')).toBeNull()
expect(cache.read('c')).toBe('cccc')
})
it('keeps the last answer through a reread that fails, and rereads past one started earlier', async () => {
const cache = createHoverPreviewCache<string>({ freshMs: 60_000, maxEntries: 100 })
await cache.load('pr', async () => 'closed')
@@ -55,20 +22,4 @@ describe('createHoverPreviewCache', () => {
await cache.load('pr', async () => null)
expect(cache.read('pr')).toBe('open')
})
it('keeps counting an answer against the budget while it is reread', async () => {
const cache = createHoverPreviewCache<string>({
freshMs: 60_000,
maxEntries: 100,
budget: { maxBytes: 10, sizeOf: (value) => value.length }
})
await cache.load('a', async () => 'aaaaaa')
cache.expire('a')
let failA: (value: null) => void = () => {}
const reread = cache.load('a', () => new Promise((resolve) => (failA = resolve)))
await cache.load('b', async () => 'bbbbbb')
failA(null)
await reread
expect([cache.read('a'), cache.read('b')]).toEqual([null, 'bbbbbb'])
})
})
@@ -36,9 +36,6 @@ import { NativeChatMarkdown } from './NativeChatMarkdown'
import { NativeChatCodeBlock } from './code/NativeChatCodeBlock'
import { TooltipProvider } from '@/components/ui/tooltip'
const partial = 'flowchart TD\n A["Sync with main '
const complete = `${partial}once"]`
function reply(source: string, streaming: boolean): React.JSX.Element {
return (
<TooltipProvider>
@@ -104,35 +101,4 @@ describe('native chat Mermaid fences', () => {
expect(container.querySelector('svg')).toHaveTextContent('Finished')
expect(container.querySelector('[data-code-language="mermaid"]')).toBeNull()
})
it('keeps the source mounted until a pending diagram fails', async () => {
const pending = holdNextRender()
const view = render(reply(partial, true))
const source = view.container.querySelector('pre')
view.rerender(reply(partial, false))
await waitFor(() => expect(mermaid.render).toHaveBeenCalledTimes(1))
expect(view.container.querySelector('pre')).toBe(source)
expect(screen.queryByText(/Diagram error:/)).toBeNull()
await act(async () => pending.reject(new Error('Invalid mermaid syntax')))
expect(screen.getByText(/Diagram error: Invalid mermaid syntax/)).toBeInTheDocument()
expect(view.container.querySelector('pre')?.textContent).toBe(partial.trimEnd())
})
it('waits for the updated diagram when a previously rendered fence grows again', async () => {
const view = render(reply(complete, false))
await waitFor(() =>
expect(view.container.querySelector('.mermaid-block svg')).toBeInTheDocument()
)
const next = `${complete}\n B["Next step"]`
view.rerender(reply(next, true))
const source = view.container.querySelector('pre')
expect(source).toHaveTextContent('Next step')
const pending = holdNextRender()
view.rerender(reply(next, false))
await waitFor(() => expect(mermaid.render).toHaveBeenCalledTimes(2))
expect(view.container.querySelector('pre')).toBe(source)
expect(view.container.querySelector('.mermaid-block svg')).toBeNull()
await act(async () => pending.resolve({ svg: '<svg><text>Next step</text></svg>' }))
expect(view.container.querySelector('.mermaid-block svg')).toHaveTextContent('Next step')
})
})
@@ -1,77 +0,0 @@
// @vitest-environment happy-dom
import { act, cleanup, render } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import { NativeChatPacedMarkdown } from './NativeChatPacedMarkdown'
import { NativeChatReplyRevealsContext } from './native-chat-reply-reveals'
import type { NativeChatReplyReveals } from '../../../../../shared/native-chat/transcript/native-chat-reply-reveals'
import { NATIVE_CHAT_TEXT_REVEAL_DELAY_MS } from '../../../../../shared/native-chat/transcript/native-chat-text-reveal'
const reveals: NativeChatReplyReveals = { begun: new Set(['reply']), drawn: new Map() }
const mermaid = vi.hoisted(() => ({ rendered: vi.fn() }))
vi.mock('@/components/sidebar/CommentMermaidBlock', () => ({
default: ({
content: code,
pendingContent,
renderEnabled
}: {
content: string
pendingContent?: React.ReactNode
renderEnabled?: boolean
}) => {
if (renderEnabled === false) {
return <>{pendingContent}</>
}
mermaid.rendered(code)
return <div data-testid="diagram">{code}</div>
}
}))
vi.mock('@/hooks/usePrefersReducedMotion', () => ({ usePrefersReducedMotion: () => false }))
vi.mock('../media/visuals/native-chat-visual-markdown-extension', () => ({
useNativeChatVisualMarkdownExtension: () => undefined
}))
afterEach(() => {
cleanup()
vi.useRealTimers()
mermaid.rendered.mockClear()
reveals.drawn.clear()
})
it('keeps surrounding paragraphs, links, and code mounted when Mermaid switches to a diagram', () => {
vi.useFakeTimers({
toFake: [
'setTimeout',
'clearTimeout',
'requestAnimationFrame',
'cancelAnimationFrame',
'performance'
]
})
const content =
'Read [this](https://example.com).\n\n```ts\nconst value = 1\n```\n\n```mermaid\ngraph TD\nA --> B\n```'
const reply = (streaming: boolean) => (
<NativeChatReplyRevealsContext.Provider value={reveals}>
<NativeChatPacedMarkdown
rowKey="reply"
content={content}
streaming={streaming}
variant="document"
/>
</NativeChatReplyRevealsContext.Provider>
)
const view = render(reply(true))
act(() => vi.advanceTimersByTime(NATIVE_CHAT_TEXT_REVEAL_DELAY_MS + 16))
const paragraph = view.container.querySelector('p')
const code = view.container.querySelector('pre')
const link = view.getByRole('link')
expect(paragraph).not.toBeNull()
expect(code).not.toBeNull()
expect(mermaid.rendered).not.toHaveBeenCalled()
view.rerender(reply(false))
expect(view.getByTestId('diagram')).toBeTruthy()
expect(view.container.querySelector('p')).toBe(paragraph)
expect(view.container.querySelector('pre')).toBe(code)
expect(view.getByRole('link')).toBe(link)
expect(view.container.querySelector('[data-block-fade]')).toBeNull()
})
@@ -1,7 +1,7 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { cleanup, render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { NativeChatCodeBlock } from './NativeChatCodeBlock'
@@ -37,29 +37,4 @@ describe('NativeChatCodeBlock', () => {
expect(screen.getByText('lastLine')).toBeInTheDocument()
expect(second.container.querySelector('pre')?.textContent).toBe(code)
})
it('colors and wraps fenced code, copies its text, and confirms success', async () => {
const writeClipboardText = vi.fn().mockResolvedValue(undefined)
Object.assign(window, { api: { ui: { writeClipboardText } } })
const code = 'const answer = 42\nconsole.log(answer)\n'
const { container } = render(
<NativeChatCodeBlock language="typescript">
<code>{code}</code>
</NativeChatCodeBlock>
)
const pre = container.querySelector('pre')
expect(screen.getByText('TypeScript')).toBeInTheDocument()
await waitFor(() => expect(pre?.querySelector('span[style*="--syntax-dark"]')).not.toBeNull(), {
timeout: 10_000
})
fireEvent.click(screen.getByRole('button', { name: 'Wrap lines' }))
expect(pre).toHaveClass('whitespace-pre-wrap')
expect(pre?.querySelector('span[style*="--syntax-dark"]')).not.toBeNull()
expect(pre?.textContent).toBe(code)
fireEvent.click(screen.getByRole('button', { name: 'Copy code' }))
await waitFor(() => expect(writeClipboardText).toHaveBeenCalledWith(code))
expect(await screen.findByRole('button', { name: 'Copied' })).toBeInTheDocument()
})
})
@@ -21,7 +21,7 @@ import {
NativeChatDisclosureContext,
useNativeChatDisclosures
} from '../../native-chat-disclosure-store'
import { NativeChatNoticeRow } from '../../NativeChatNoticeRow'
import { NativeChatReasoningRow } from '../../NativeChatReasoningRow'
vi.mock('@/lib/syntax-highlighting/oniguruma', async () => ({
@@ -86,45 +86,6 @@ describe('native chat code block line wrap', () => {
expect(wrapToggle()).toHaveAttribute('aria-pressed', 'true')
})
it('keeps each block of a row to its own wrap', () => {
const content = '```ts\nconst first = 1\n```\n\n```ts\nconst second = 2\n```'
render(<Transcript content={content} />)
fireEvent.click(screen.getAllByRole('button', { name: 'Wrap lines' })[1])
expect(screen.getAllByRole('button', { name: /^(Wrap lines|Disable line wrap)$/ })).toEqual([
screen.getByRole('button', { name: 'Wrap lines' }),
screen.getByRole('button', { name: 'Disable line wrap' })
])
})
// Streaming escape fixes can shift a fence’s source offset when the finished block is reparsed.
it.each([
[
'the reply finishes',
'1. Undo with git reset HEAD~1:\n ```sh\n git status\n ```\n',
(content: string) => ({ content, growing: false })
],
[
'another block follows a list item',
'- >5 users need x~y:\n ```sh\n scale up\n ```\n',
(content: string) => ({ content: `${content}\nDone.`, growing: true })
],
[
'the reply merges into one block',
'Undo with git reset HEAD~1 first.\n\n```sh\ngit status\n```\n\nThen press ',
(content: string) => ({ content: `${content}<kbd>Enter</kbd>`, growing: true })
]
])('stays on when %s after streaming escaped text before it', (_name, content, next) => {
const view = render(<Transcript content={content} />)
fireEvent.click(wrapToggle())
expect(wrapToggle()).toHaveAttribute('aria-pressed', 'true')
view.rerender(<Transcript {...next(content)} />)
expect(wrapToggle()).toHaveAttribute('aria-pressed', 'true')
})
it('keeps a reasoning block and the reply of one message apart', () => {
const fence = '```ts\nconst first = 1\n```'
function Row(): React.JSX.Element {
@@ -153,31 +114,4 @@ describe('native chat code block line wrap', () => {
expect(reasoningWrap).toHaveAttribute('aria-pressed', 'false')
expect(replyWrap).toHaveAttribute('aria-pressed', 'true')
})
it("keeps a plan card's wrap when its row remounts", () => {
function Row({ mounted }: { mounted: boolean }): React.JSX.Element {
const disclosures = useNativeChatDisclosures()
return (
<NativeChatDisclosureContext.Provider value={disclosures}>
{mounted ? (
<NativeChatNoticeRow
messageId="message-2"
block={{
type: 'text',
text: '# Steps\n\n```sh\npnpm install\n```',
presentation: 'plan-document'
}}
/>
) : null}
</NativeChatDisclosureContext.Provider>
)
}
const view = render(<Row mounted />)
fireEvent.click(wrapToggle())
view.rerender(<Row mounted={false} />)
view.rerender(<Row mounted />)
expect(wrapToggle()).toHaveAttribute('aria-pressed', 'true')
})
})
@@ -4,7 +4,7 @@ import type { ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { NativeChatReplyRevealsContext } from './native-chat-reply-reveals'
import type { NativeChatReplyReveals } from '../../../../../shared/native-chat/transcript/native-chat-reply-reveals'
import { NATIVE_CHAT_TEXT_REVEAL_DELAY_MS as D } from '../../../../../shared/native-chat/transcript/native-chat-text-reveal'
import { useNativeChatPacedText } from './use-native-chat-paced-text'
const motion = vi.hoisted(() => ({ reduced: false }))
@@ -64,34 +64,4 @@ describe('fixed latency text reveal', () => {
advance(50)
expect(returned.result.current.text).toHaveLength(2000)
})
it('shows text received while unmounted immediately rather than resetting its deadline', () => {
const wrapper = within()
const row = renderHook(() => useNativeChatPacedText('reply', 'a '.repeat(100), true), {
wrapper
})
advance(50)
row.unmount()
advance(D)
const returned = renderHook(() => useNativeChatPacedText('reply', 'a '.repeat(2000), true), {
wrapper
})
expect(returned.result.current.text).toHaveLength(4000)
})
it('shows reduced-motion text immediately without fading or replay on remount', () => {
motion.reduced = true
const wrapper = within()
const row = renderHook(() => useNativeChatPacedText('reply', 'a '.repeat(1000), true), {
wrapper
})
expect(row.result.current.text).toHaveLength(2000)
expect(row.result.current.fading).toBe(false)
row.unmount()
motion.reduced = false
const returned = renderHook(() => useNativeChatPacedText('reply', 'a '.repeat(1000), true), {
wrapper
})
expect(returned.result.current.text).toHaveLength(2000)
})
})
@@ -2,17 +2,14 @@
import '@testing-library/jest-dom/vitest'
import { useRef, type ComponentProps } from 'react'
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { LinkActionPopover } from '@/components/link-actions/LinkActionPopover'
import { TooltipProvider } from '@/components/ui/tooltip'
import '@/components/editor/document-images/useLocalImageSrc'
import {
invalidateLocalImageCache as invalidateLocalImageSrcCacheForTests,
resetLocalImageCacheState as resetLocalImageSrcStateForTests
} from '@/components/editor/document-images/local-image-src-cache'
import { resetLocalImageCacheState as resetLocalImageSrcStateForTests } from '@/components/editor/document-images/local-image-src-cache'
import { useAppStore } from '@/store'
import * as imageCache from '@/components/editor/document-images/local-image-src-cache'
import { NativeChatMarkdown } from '../../markdown/NativeChatMarkdown'
import {
NativeChatMarkdownImageOwnerContext,
@@ -28,8 +25,6 @@ import {
import type * as TerminalFileOpenRouting from '@/components/terminal-pane/links/files/terminal-file-open-routing'
import type * as HttpLinkRouting from '@/lib/browser/navigation/http-link-routing'
import * as imageCachePinning from '@/components/editor/document-images/local-image-cache-pinning'
import { ImageVisibilityObserver } from './native-chat-image-visibility-observer.test-fixture'
import { NativeChatLinkClickContext } from '../../links/actions/native-chat-link-click-context'
const mocks = vi.hoisted(() => ({
@@ -236,176 +231,6 @@ describe('native chat Markdown image preview', () => {
}
})
it('loads only visible nearby images and keeps their bytes when they leave the viewport', async () => {
vi.stubGlobal('IntersectionObserver', ImageVisibilityObserver)
const { rerender } = render(<Transcript owner={{ ...localOwner, isVisible: false }} />)
const trigger = screen.getByRole('button', { name: 'View image: Chart' })
act(() => ImageVisibilityObserver.current.emit(trigger, true))
expect(mocks.readRuntimeFilePreview).not.toHaveBeenCalled()
rerender(<Transcript />)
expect(await screen.findByRole('img')).toHaveAttribute('src', 'blob:image-1')
vi.spyOn(trigger, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 640, 360))
act(() => ImageVisibilityObserver.current.emit(trigger, false))
expect(screen.queryByRole('img')).toBeNull()
expect(trigger).toHaveStyle({ width: '640px', aspectRatio: '640 / 360' })
act(() => ImageVisibilityObserver.current.emit(trigger, true))
const returned = await screen.findByRole('img')
expect(returned).toHaveAttribute('src', 'blob:image-1')
fireEvent.load(returned)
expect(trigger.style.width).toBe('')
rerender(<Transcript owner={{ ...localOwner, isVisible: false }} />)
expect(screen.queryByRole('img')).toBeNull()
expect(trigger).toHaveStyle({ width: '640px', aspectRatio: '640 / 360' })
rerender(<Transcript />)
expect(await screen.findByRole('img')).toHaveAttribute('src', 'blob:image-1')
expect(mocks.readRuntimeFilePreview).toHaveBeenCalledOnce()
expect(URL.revokeObjectURL).not.toHaveBeenCalled()
})
it('retries a cache-byte-budget rejection on open after another image releases its lease', async () => {
vi.stubGlobal('IntersectionObserver', ImageVisibilityObserver)
imageCachePinning.pinLocalImageCacheKey('reserved')
expect(imageCache.cacheLocalImageBlob('reserved', 'blob:reserved', 2 ** 27 - 2)).toBe(true)
const content = [0, 1, 2].map((i) => `![Chart ${i}](chart-${i}.png)`).join('\n\n')
const { container } = render(<Transcript content={content} />)
const triggers = screen.getAllByRole('button')
expect(mocks.readRuntimeFilePreview).not.toHaveBeenCalled()
await act(async () => {
for (const trigger of triggers) {
ImageVisibilityObserver.current.emit(trigger, true)
}
})
expect(container.querySelectorAll('img')).toHaveLength(2)
expect(mocks.readRuntimeFilePreview).toHaveBeenCalledTimes(3)
act(() => ImageVisibilityObserver.current.emit(triggers[0]!, false))
fireEvent.click(triggers[2]!)
const dialog = screen.getByRole('dialog', { name: 'Chart 2' })
expect(await within(dialog).findByRole('img')).toHaveAttribute('src', 'blob:image-4')
expect(mocks.readRuntimeFilePreview).toHaveBeenCalledTimes(4)
fireEvent.click(within(dialog).getByRole('button', { name: 'Close' }))
act(() => {
for (const trigger of triggers) {
ImageVisibilityObserver.current.emit(trigger, false)
}
})
expect(container.querySelectorAll('img')).toHaveLength(0)
imageCache.unpinLocalImageCache('reserved')
})
it('closes stale previews when session metadata resolves or the session changes', () => {
const { rerender } = render(<Transcript owner={{ ...localOwner, sessionId: null }} />)
fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' }))
expect(screen.getByRole('dialog')).toBeInTheDocument()
rerender(<Transcript owner={{ ...localOwner, sessionId: 'session-1' }} />)
expect(screen.queryByRole('dialog')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' }))
rerender(<Transcript owner={{ ...localOwner, sessionId: 'session-2' }} />)
expect(screen.queryByRole('dialog')).toBeNull()
})
it('keeps a streamed image dialog mounted when later prose arrives', async () => {
const content = '![Chart](data:image/png;base64,AA==)\n\n'
const { rerender } = render(<Transcript content={content} growing />)
fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' }))
const dialog = screen.getByRole('dialog', { name: 'Chart' })
rerender(<Transcript content={`${content}More words`} growing />)
expect(screen.getByRole('dialog', { name: 'Chart' })).toBe(dialog)
})
it('retains a closable unavailable preview after image decoding fails', async () => {
render(<Transcript content="![Chart](chart.png)" />)
await screen.findByRole('img', { name: 'Chart' })
fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' }))
const dialog = screen.getByRole('dialog')
fireEvent.error(within(dialog).getByRole('img'))
expect(within(dialog).getByRole('status')).toHaveTextContent('Preview unavailable')
expect(within(dialog).getByRole('button', { name: 'File actions' })).toBeInTheDocument()
fireEvent.click(within(dialog).getByRole('button', { name: 'Close' }))
expect(screen.queryByRole('dialog')).toBeNull()
})
it('recovers from a failed thumbnail when refreshed image bytes become available', async () => {
render(<Transcript content="![Chart](chart.png)" />)
fireEvent.error(await screen.findByRole('img', { name: 'Chart' }))
expect(screen.queryByRole('img', { name: 'Chart' })).toBeNull()
act(() => invalidateLocalImageSrcCacheForTests())
expect(await screen.findByRole('img', { name: 'Chart' })).toHaveAttribute('src', 'blob:image-2')
fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' }))
expect(within(screen.getByRole('dialog')).getByRole('img')).toHaveAttribute(
'src',
'blob:image-2'
)
})
it('dismisses the nested file menu before the dialog and runs an action after preview closes', async () => {
const user = userEvent.setup()
render(
<>
<Transcript />
<input aria-label="Opened editor" />
</>
)
await user.click(screen.getByRole('button', { name: 'View image: Chart' }))
const trigger = screen.getByRole('button', { name: 'File actions' })
await user.click(trigger)
expect(screen.getByRole('menuitem', { name: 'Open file' })).toBeInTheDocument()
await user.keyboard('{Escape}')
expect(screen.queryByRole('menu')).toBeNull()
expect(screen.getByRole('dialog', { name: 'Chart' })).toBeInTheDocument()
expect(trigger).toHaveFocus()
await user.click(trigger)
mocks.openDetectedFilePath.mockImplementationOnce(() => {
expect(screen.queryByRole('dialog')).toBeNull()
screen.getByRole('textbox', { name: 'Opened editor' }).focus()
})
await user.click(screen.getByRole('menuitem', { name: 'Open file' }))
expect(mocks.openDetectedFilePath).toHaveBeenCalledExactlyOnceWith(
'/repo/worktree/screenshots/chart.png',
null,
null,
expect.objectContaining({ worktreeId: 'wt-1', sourceTabId: 'tab-1' })
)
expect(screen.queryByRole('menu')).toBeNull()
await waitFor(() =>
expect(screen.getByRole('textbox', { name: 'Opened editor' })).toHaveFocus()
)
})
it('opens while a remote read is pending and clears image bytes and actions on owner loss', async () => {
const pendingRead = Promise.withResolvers<{
content: string
isBinary: boolean
mimeType: string
}>()
mocks.readRuntimeFilePreview.mockReturnValueOnce(pendingRead.promise)
const owner: ImageOwner = {
...localOwner,
runtimeContext: {
...localOwner.runtimeContext,
target: { kind: 'environment', environmentId: 'remote-a' }
},
fileLinkContext: { ...localOwner.fileLinkContext, runtimeEnvironmentId: 'remote-a' }
}
const { rerender } = render(<Transcript owner={owner} />)
fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' }))
expect(screen.getByRole('dialog', { name: 'Chart' })).toBeInTheDocument()
expect(mocks.readRuntimeFilePreview).toHaveBeenCalledWith(
expect.objectContaining({ target: { kind: 'environment', environmentId: 'remote-a' } }),
'/repo/worktree/screenshots/chart.png',
{ kind: 'chat-image' }
)
rerender(<Transcript owner={{ ...owner, runtimeContext: null }} />)
fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' }), { ctrlKey: true })
expect(mocks.openDetectedFilePath).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' }))
expect(screen.queryByRole('button', { name: 'File actions' })).toBeNull()
await act(async () =>
pendingRead.resolve({ content: 'AA==', isBinary: true, mimeType: 'image/png' })
)
expect(within(screen.getByRole('dialog')).queryByRole('img')).toBeNull()
expect(mocks.readRuntimeFilePreview).toHaveBeenCalledOnce()
})
it('closes the preview when the owning chat becomes hidden', () => {
const { rerender } = render(<Transcript />)
fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' }))
@@ -1,8 +1,8 @@
import type * as RuntimeRpcCallModule from '@/runtime/rpc/calls/runtime-rpc-call'
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
import type { ComponentProps } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -134,79 +134,6 @@ describe('session image source resolution', () => {
)
})
it.each(['matched', 'missing'] as const)(
'retains an already loaded workspace image during expansion until refresh settles %s',
async (settlement) => {
const originalPath = '/repo/worktree/images/chart.png'
const nextPath = '/session/images/chart.png'
let complete!: (value: { exists: boolean; absolutePath: string | null }) => void
mocks.callRuntimeRpc
.mockResolvedValueOnce({ exists: true, absolutePath: originalPath })
.mockReturnValueOnce(
new Promise((resolve) => {
complete = resolve
})
)
render(<Transcript content="![Chart](images/chart.png)" />)
const thumbnail = await screen.findByRole('img', { name: 'Chart' })
const originalSrc = thumbnail.getAttribute('src')
fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' }))
await waitFor(() => expect(mocks.callRuntimeRpc).toHaveBeenCalledTimes(2))
const dialog = screen.getByRole('dialog')
expect(thumbnail).toHaveAttribute('src', originalSrc)
expect(within(dialog).getByRole('img')).toHaveAttribute('src', originalSrc)
expect(within(dialog).queryByText('Preview unavailable')).not.toBeInTheDocument()
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'File actions' }))
await user.click(screen.getByRole('menuitem', { name: 'Open file' }))
expect(mocks.openDetectedFilePath).toHaveBeenLastCalledWith(
originalPath,
null,
null,
expect.anything()
)
await act(async () =>
complete({
exists: settlement === 'matched',
absolutePath: settlement === 'matched' ? nextPath : null
})
)
if (settlement === 'matched') {
await waitFor(() =>
expect(screen.getByRole('img', { name: 'Chart' })).toHaveAttribute('src', 'blob:image-2')
)
expect(mocks.readRuntimeFilePreview).toHaveBeenLastCalledWith(expect.anything(), nextPath, {
kind: 'chat-image'
})
} else {
await waitFor(() =>
expect(screen.queryByRole('img', { name: 'Chart' })).not.toBeInTheDocument()
)
}
}
)
it('retries a missing live session image on expand without reading a workspace decoy', async () => {
mocks.callRuntimeRpc
.mockResolvedValueOnce({ exists: false, absolutePath: null })
.mockResolvedValue({ exists: true, absolutePath: '/session/images/chart.png' })
render(
<Transcript
owner={{ ...localOwner, sessionId: 'grok-session' }}
content="![Chart](images/chart.png)"
/>
)
await waitFor(() => expect(mocks.callRuntimeRpc).toHaveBeenCalledTimes(1))
expect(mocks.readRuntimeFilePreview).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' }))
await within(screen.getByRole('dialog')).findByRole('img')
expect(mocks.readRuntimeFilePreview).toHaveBeenCalledExactlyOnceWith(
expect.anything(),
'/session/images/chart.png',
{ kind: 'chat-image' }
)
})
it('discards a session lookup after its owner changes', async () => {
let complete!: (value: unknown) => void
mocks.callRuntimeRpc
@@ -3,7 +3,7 @@
import '@testing-library/jest-dom/vitest'
import { isValidElement, type ComponentProps } from 'react'
import type { NativeChatCrewFrame } from '../../../orchestration-crew/NativeChatCrewPanel'
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as ImageBlobPng from '@/lib/image-blob-png'
import { NativeChatImageAttachmentPreview } from '../../NativeChatImageAttachmentPreview'
@@ -74,9 +74,6 @@ vi.mock('sonner', () => ({ toast: { success: mocks.success, error: mocks.error }
const { NativeChatResolvedView } = await import('../../NativeChatResolvedView')
const { useAppStore } = await import('../../../../store/index')
const { installNativeChatMessageListTestViewport } =
await import('../../native-chat-message-list-test-viewport')
const { TooltipProvider } = await import('@/components/ui/tooltip')
function RetainedBridgeChat({ visible = true }: { visible?: boolean }) {
return (
@@ -124,74 +121,6 @@ afterEach(() => {
})
describe('NativeChatResolvedView image menu ownership', () => {
it('refuses image capture from a portaled preview while its retained owner is hidden', async () => {
mocks.fetch.mockResolvedValue({ ok: true, blob: async () => new Blob(['original image']) })
const view = render(<RetainedBridgeChat />)
fireEvent.click(screen.getByRole('button', { name: 'Image #1: View image: original.png' }))
const preview = screen.getByRole('dialog')
expect(screen.getByTestId('retained-owner').contains(preview)).toBe(false)
view.rerender(<RetainedBridgeChat visible={false} />)
fireEvent.contextMenu(within(preview).getByRole('img'))
expect(mocks.fetch).not.toHaveBeenCalled()
view.rerender(<RetainedBridgeChat />)
expect(screen.queryByRole('menu')).toBeNull()
expect(mocks.writeClipboardImage).not.toHaveBeenCalled()
})
it('closes the image preview on the first Close click while its copy menu is open', async () => {
mocks.fetch.mockResolvedValue({ ok: true, blob: async () => new Blob(['original image']) })
render(<RetainedBridgeChat />)
fireEvent.click(screen.getByRole('button', { name: 'Image #1: View image: original.png' }))
const preview = screen.getByRole('dialog', { name: 'original.png' })
fireEvent.contextMenu(within(preview).getByRole('img'))
await screen.findByRole('menuitem', { name: 'Copy image' })
const close = within(preview).getByRole('button', { name: 'Close' })
fireEvent.pointerDown(close, { button: 0 })
fireEvent.pointerUp(close, { button: 0 })
fireEvent.click(close)
await waitFor(() => expect(preview).not.toBeInTheDocument())
expect(mocks.writeClipboardImage).not.toHaveBeenCalled()
})
it.each(['thumbnail', 'preview'])(
'copies the original image from the %s through the visible bridge chat menu',
async (surface) => {
mocks.fetch.mockResolvedValue({ ok: true, blob: async () => new Blob(['original image']) })
render(<RetainedBridgeChat />)
if (surface === 'preview') {
fireEvent.click(screen.getByRole('button', { name: 'Image #1: View image: original.png' }))
}
const preview =
surface === 'preview' ? screen.getByRole('dialog', { name: 'original.png' }) : null
const image = preview
? within(preview).getByRole('img')
: screen.getByRole('img', { name: 'original.png' })
fireEvent.contextMenu(image)
const copy = await screen.findByRole('menuitem', { name: 'Copy image' })
fireEvent.pointerDown(copy, { button: 0, pointerType: 'mouse' })
fireEvent.pointerUp(copy, { button: 0, pointerType: 'mouse' })
fireEvent.click(copy)
await waitFor(() =>
expect(mocks.writeClipboardImage).toHaveBeenCalledWith(
`data:image/png;base64,${Buffer.from('original image').toString('base64')}`
)
)
expect(mocks.fetch).toHaveBeenCalledWith('blob:original')
expect(mocks.success).toHaveBeenCalledWith('Image copied')
expect(mocks.error).not.toHaveBeenCalled()
if (preview) {
expect(preview).toBeInTheDocument()
expect(preview).toHaveAttribute('data-state', 'open')
}
}
)
it('removes the portaled menu and captured image when the retained bridge owner hides', async () => {
const capturedImage = Promise.withResolvers<Blob>()
mocks.fetch.mockResolvedValue({ ok: true, blob: () => capturedImage.promise })
@@ -229,54 +158,3 @@ describe('NativeChatResolvedView image menu ownership', () => {
expect(mocks.error).not.toHaveBeenCalled()
})
})
function chatMessage(id: string, role: 'user' | 'assistant', text: string): NativeChatMessage {
return { id, role, blocks: [{ type: 'text', text }], timestamp: 1, source: 'transcript' }
}
const REPLY = [
'Run the build:',
'',
'```sh',
'pnpm build',
'```',
'',
'::orca-visual{file="chart.html"}'
].join('\n')
describe('NativeChatResolvedView right-click targets', () => {
let restoreViewport = (): void => {}
beforeEach(() => {
restoreViewport = installNativeChatMessageListTestViewport()
})
afterEach(() => restoreViewport())
it('copies a reply and its code block with the text their hover buttons copy', async () => {
mocks.session.messages = [
chatMessage('ask', 'user', 'Fix the build'),
chatMessage('reply', 'assistant', REPLY)
]
render(
<TooltipProvider>
<RetainedBridgeChat />
</TooltipProvider>
)
fireEvent.contextMenu(screen.getByText('Run the build:'))
fireEvent.click(await screen.findByRole('menuitem', { name: 'Copy message' }))
expect(mocks.writeClipboardText).toHaveBeenLastCalledWith(
'Run the build:\n\n```sh\npnpm build\n```'
)
fireEvent.click(screen.getByRole('button', { name: 'Copy code' }))
const hoverCopy = mocks.writeClipboardText.mock.lastCall
fireEvent.contextMenu(screen.getByText('pnpm build'))
fireEvent.click(await screen.findByRole('menuitem', { name: 'Copy code' }))
expect(mocks.writeClipboardText.mock.lastCall).toEqual(hoverCopy)
expect(hoverCopy).toEqual(['pnpm build\n'])
fireEvent.contextMenu(screen.getByText('Fix the build'))
fireEvent.click(await screen.findByRole('menuitem', { name: 'Copy message' }))
expect(mocks.writeClipboardText).toHaveBeenLastCalledWith('Fix the build')
})
})
@@ -1,93 +0,0 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { cleanup, screen, waitFor } from '@testing-library/react'
import { render } from '../../native-chat-tooltip-test-harness'
import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract'
import '@/components/editor/document-images/useLocalImageSrc'
import { resetLocalImageCacheState as resetLocalImageSrcStateForTests } from '@/components/editor/document-images/local-image-src-cache'
import { useAppStore } from '@/store'
import { nativeChatFanoutFixture } from '../../native-chat-workspace-test-fixtures'
import { installNativeChatMessageListTestViewport } from '../../native-chat-message-list-test-viewport'
const session: NativeChatLiveSession = {
messages: [
{
id: 'user-image',
role: 'user',
blocks: [{ type: 'image-ref', path: '/repo/0/orca-paste-shot.png' }],
timestamp: 1,
source: 'transcript'
}
],
status: 'ready',
sessionId: 'session-image',
agent: 'claude',
hasMore: false,
loadingEarlier: false,
olderHistoryGeneration: 0,
loadEarlier: vi.fn(),
readPhase: 'ready'
}
vi.mock('../../session/terminal/read/use-native-chat-retained-session', () => ({
useNativeChatRetainedSession: () => session
}))
vi.mock('../../NativeChatComposer', () => ({ NativeChatComposer: () => null }))
const { NativeChatResolvedView } = await import('../../NativeChatResolvedView')
const original = useAppStore.getState()
const readFile = vi.fn()
let restoreViewport = (): void => {}
beforeEach(() => {
restoreViewport = installNativeChatMessageListTestViewport()
resetLocalImageSrcStateForTests()
vi.stubGlobal('IntersectionObserver', undefined)
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:terminal-image')
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined)
readFile.mockResolvedValue({ content: 'AA==', isBinary: true, mimeType: 'image/png' })
vi.stubGlobal('api', { ...window.api, fs: { ...window.api?.fs, readFile } })
useAppStore.setState({
...useAppStore.getInitialState(),
...nativeChatFanoutFixture(0, 1, 1),
activeWorktreeId: null,
activeWorkspaceExecutionHostId: null,
runtimeEnvironmentCatalogHydrated: true
})
})
afterEach(() => {
cleanup()
restoreViewport()
resetLocalImageSrcStateForTests()
useAppStore.setState(original, true)
vi.unstubAllGlobals()
vi.restoreAllMocks()
readFile.mockReset()
})
it('previews a terminal transcript image from the terminal tab’s workspace owner', async () => {
render(
<NativeChatResolvedView
paneKey="terminal-0-0:leaf"
agent="claude"
sessionId="session-image"
transcriptPath={null}
isVisible
isFocusedGroup={false}
targetPtyId={null}
terminalTabId="terminal-0-0"
ownsTabWideLaunchDraft={false}
/>
)
const preview = await screen.findByRole('button', { name: 'View image: Pasted image' })
await waitFor(() =>
expect(preview.querySelector('img')?.getAttribute('src')).toBe('blob:terminal-image')
)
expect(readFile).toHaveBeenCalledExactlyOnceWith({
filePath: '/repo/0/orca-paste-shot.png',
connectionId: undefined,
access: { kind: 'chat-image' }
})
})
@@ -4,11 +4,8 @@ import { act, createElement } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types'
import {
invalidateLocalImageCache as invalidateLocalImageSrcCacheForTests,
resetLocalImageCacheState as resetLocalImageSrcStateForTests
} from '@/components/editor/document-images/local-image-src-cache'
import { resetLocalImageCacheState as resetLocalImageSrcStateForTests } from '@/components/editor/document-images/local-image-src-cache'
import { useAppStore } from '@/store'
import { NativeChatImageAttachments } from './NativeChatImageAttachments'
import { useNativeChatImageRuntimeContext } from './native-chat-image-runtime-context'
@@ -34,15 +31,6 @@ vi.mock('@/lib/connection-context', () => ({
globalThis.IS_REACT_ACT_ENVIRONMENT = true
function runtimeContext(worktreeId: string): RuntimeFileOperationArgs {
return {
target: { kind: 'local' as const },
worktreeId,
worktreePath: `/repo/${worktreeId}`,
expectedExecutionHostId: 'local'
}
}
async function flushPromises(): Promise<void> {
await Promise.resolve()
await Promise.resolve()
@@ -147,81 +135,4 @@ describe('NativeChatImageAttachments', () => {
useAppStore.setState(original, true)
}
})
it('preserves same-image errors but retries when the runtime owner changes', async () => {
const container = document.createElement('div')
const root = createRoot(container)
const blocks = [{ type: 'image-ref' as const, path: '/repo/image.png' }]
const ownerOne = runtimeContext('wt-1')
await act(async () => {
root.render(
createElement(NativeChatImageAttachments, {
blocks,
runtimeContext: ownerOne
})
)
await flushPromises()
})
const firstOwnerSrc = container.querySelector('img')?.getAttribute('src')
expect(firstOwnerSrc).toBe('blob:owner-1')
await act(async () => {
container.querySelector('img')?.dispatchEvent(new Event('error'))
})
expect(container.querySelector('img')).toBeNull()
await act(async () => {
root.render(
createElement(NativeChatImageAttachments, {
blocks,
runtimeContext: ownerOne
})
)
await flushPromises()
})
expect(container.querySelector('img')).toBeNull()
await act(async () => {
root.render(
createElement(NativeChatImageAttachments, {
blocks,
runtimeContext: runtimeContext('wt-2')
})
)
await flushPromises()
})
expect(container.querySelector('img')?.getAttribute('src')).not.toBe(firstOwnerSrc)
expect(window.api.fs.readFile).toHaveBeenCalledTimes(2)
root.unmount()
})
it('retries a failed thumbnail after the image cache refreshes', async () => {
const container = document.createElement('div')
const root = createRoot(container)
const props = {
blocks: [{ type: 'image-ref' as const, path: '/repo/image.png' }],
runtimeContext: runtimeContext('wt-1')
}
await act(async () => {
root.render(createElement(NativeChatImageAttachments, props))
await flushPromises()
})
expect(container.querySelector('img')?.getAttribute('src')).toBe('blob:owner-1')
await act(async () => {
container.querySelector('img')?.dispatchEvent(new Event('error'))
})
expect(container.querySelector('img')).toBeNull()
await act(async () => {
invalidateLocalImageSrcCacheForTests()
await flushPromises()
})
expect(container.querySelector('img')?.getAttribute('src')).toBe('blob:owner-2')
root.unmount()
})
})
@@ -10,7 +10,7 @@ import {
NativeChatTextAttachmentScope,
NativeChatTextAttachmentOpener
} from './NativeChatTextAttachments'
import { NativeChatTextAttachmentPreview } from './NativeChatTextAttachmentPreview'
import { AGENT_SESSION_TEXT_ATTACHMENT_READ_CAPABILITY } from '../../../../../../shared/agent-session/agent-session-runtime-capabilities'
import { NativeChatMarkdownImageOwnerContext } from '../images/native-chat-markdown-image-owner'
import { replaceRuntimeEnvironmentRevisions } from '@/runtime/rpc/environment-revisions/runtime-environment-revision'
@@ -90,16 +90,6 @@ afterEach(async () => {
const waitUntilEnabled = (name: string) =>
waitFor(() => expect(screen.getByRole('button', { name }).hasAttribute('disabled')).toBe(false))
it('shows the old-host limitation and refreshes capability on Retry without affecting the message', async () => {
capable = false
render(<NativeChatTextAttachmentPreview path={path} target={target} onClose={() => {}} />)
await screen.findByText(/This host cannot open text attachments yet/)
expect(mocks.rpc.mock.calls.every((call) => call[1] === 'status.get')).toBe(true)
capable = true
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
await waitUntilEnabled('Copy contents')
})
it('keeps focused stateful composer descendants mounted when owner context changes', async () => {
mocks.context = { target: { kind: 'local' }, worktreeId: 'w', worktreePath: '/repo' }
function Child() {
@@ -1,211 +0,0 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { act, cleanup, render } from '@testing-library/react'
import { useRef } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
NATIVE_CHAT_VISUAL_FRAME_NAME_PREFIX,
NATIVE_CHAT_VISUAL_OPEN_LINK_TYPE,
NATIVE_CHAT_VISUAL_PING_TYPE,
NATIVE_CHAT_VISUAL_PONG_TIMEOUT_MS,
NATIVE_CHAT_VISUAL_PONG_TYPE,
NATIVE_CHAT_VISUAL_THEME_TYPE
} from '../../../../../../shared/native-chat/native-chat-visual-shell'
const openHttpLink = vi.fn()
vi.mock('@/lib/browser/navigation/http-link-routing', () => ({
openHttpLink: (...args: unknown[]) => openHttpLink(...args)
}))
import { NativeChatVisualFrame } from './NativeChatVisualFrame'
import type { ReaderGesture } from '../../native-chat-autoscroll'
const visual = { revision: 'r1', html: '<p>chart</p>', path: '/v' }
function Harness(props: {
onRetired?: () => void
onReaderGesture?: (gesture: ReaderGesture) => void
}) {
const scope = useRef<HTMLDivElement | null>(null)
return (
<div ref={scope}>
<NativeChatVisualFrame
document={visual}
title="Chart"
themeScope={scope}
onRetired={props.onRetired ?? (() => {})}
onReaderGesture={props.onReaderGesture}
/>
</div>
)
}
function frameOf(container: HTMLElement): HTMLIFrameElement {
const frame = container.querySelector('iframe')
if (!frame) {
throw new Error('no frame')
}
return frame
}
function channelOf(frame: HTMLIFrameElement): string {
return frame.name.slice(NATIVE_CHAT_VISUAL_FRAME_NAME_PREFIX.length)
}
function post(data: unknown, source: MessageEventSource | null): void {
act(() => {
window.dispatchEvent(new MessageEvent('message', { data, source }))
})
}
function load(frame: HTMLIFrameElement): void {
act(() => {
frame.dispatchEvent(new Event('load'))
})
}
function answer(frame: HTMLIFrameElement, id: number): void {
post({ type: NATIVE_CHAT_VISUAL_PONG_TYPE, channel: channelOf(frame), id }, frame.contentWindow)
}
/** Records what the host posts into the frame, so only the test answers its pings. */
function captureFramePosts(frame: HTMLIFrameElement): ReturnType<typeof vi.fn> {
const contentWindow = frame.contentWindow
if (!contentWindow) {
throw new Error('no content window')
}
const posted = vi.fn()
vi.spyOn(contentWindow, 'postMessage').mockImplementation(posted)
return posted
}
/** Renders the frame and lets its own first load land, then hands the clock to the test. */
async function renderLoaded(onRetired: () => void) {
const view = render(<Harness onRetired={onRetired} />)
const frame = frameOf(view.container)
const posted = captureFramePosts(frame)
await vi.waitFor(() => {
expect(posted).toHaveBeenCalledWith(
expect.objectContaining({ type: NATIVE_CHAT_VISUAL_THEME_TYPE }),
'*'
)
})
vi.useFakeTimers()
return { ...view, frame, posted }
}
function waitOutTheAnswer(): void {
act(() => {
vi.advanceTimersByTime(NATIVE_CHAT_VISUAL_PONG_TIMEOUT_MS)
})
}
function setUserActivation(isActive: boolean): void {
Object.defineProperty(navigator, 'userActivation', {
configurable: true,
value: { isActive, hasBeenActive: isActive }
})
}
beforeEach(() => {
openHttpLink.mockReset()
})
afterEach(() => {
vi.useRealTimers()
cleanup()
document.documentElement.classList.remove('dark')
})
describe('NativeChatVisualFrame', () => {
it('runs the visual in a scripts-only sandbox, named for host registration, with its CSP first', () => {
const { container } = render(<Harness />)
const frame = frameOf(container)
expect(frame.getAttribute('sandbox')).toBe('allow-scripts')
expect(frame.name.startsWith(NATIVE_CHAT_VISUAL_FRAME_NAME_PREFIX)).toBe(true)
const srcdoc = frame.getAttribute('srcdoc') ?? ''
expect(srcdoc.indexOf('Content-Security-Policy')).toBeLessThan(srcdoc.indexOf('<p>chart</p>'))
expect(channelOf(frame)).toMatch(/^[0-9a-f]{32}$/)
})
it('opens a link only while the frame has focus and the user has just acted', () => {
const { container } = render(<Harness />)
const frame = frameOf(container)
const channel = channelOf(frame)
const link = { type: NATIVE_CHAT_VISUAL_OPEN_LINK_TYPE, channel, url: 'https://example.com/' }
setUserActivation(true)
post(link, frame.contentWindow)
expect(openHttpLink).not.toHaveBeenCalled()
frame.tabIndex = 0
frame.focus()
setUserActivation(false)
post(link, frame.contentWindow)
expect(openHttpLink).not.toHaveBeenCalled()
setUserActivation(true)
post(link, window)
post({ ...link, url: 'javascript:alert(1)' }, frame.contentWindow)
expect(openHttpLink).not.toHaveBeenCalled()
post(link, frame.contentWindow)
expect(openHttpLink).toHaveBeenCalledWith('https://example.com/', { forceSystemBrowser: true })
// A burst of requests opens at most one page.
post(link, frame.contentWindow)
expect(openHttpLink).toHaveBeenCalledTimes(1)
})
it('keeps the visual through a later load it answers, as for an in-page link in WebKit', async () => {
const onRetired = vi.fn()
const { frame, posted } = await renderLoaded(onRetired)
const ping = expect.objectContaining({ type: NATIVE_CHAT_VISUAL_PING_TYPE })
expect(posted).not.toHaveBeenCalledWith(ping, '*')
load(frame)
expect(posted).toHaveBeenCalledWith(
{ type: NATIVE_CHAT_VISUAL_PING_TYPE, channel: channelOf(frame), id: 2 },
'*'
)
answer(frame, 2)
waitOutTheAnswer()
expect(onRetired).not.toHaveBeenCalled()
})
it('retires itself when a later load goes unanswered: the frame went blank or left', async () => {
const onRetired = vi.fn()
const { frame } = await renderLoaded(onRetired)
load(frame)
act(() => {
vi.advanceTimersByTime(NATIVE_CHAT_VISUAL_PONG_TIMEOUT_MS - 1)
})
expect(onRetired).not.toHaveBeenCalled()
act(() => {
vi.advanceTimersByTime(1)
})
expect(onRetired).toHaveBeenCalledTimes(1)
})
it('ignores answers from another window, another channel, or an earlier load', async () => {
const onRetired = vi.fn()
const { frame } = await renderLoaded(onRetired)
load(frame)
load(frame)
answer(frame, 2)
const pong = { type: NATIVE_CHAT_VISUAL_PONG_TYPE, id: 3 }
post({ ...pong, channel: channelOf(frame) }, window)
post({ ...pong, channel: 'other' }, frame.contentWindow)
waitOutTheAnswer()
expect(onRetired).toHaveBeenCalledTimes(1)
})
it('owes no answer once it unmounts', async () => {
const onRetired = vi.fn()
const { frame, unmount } = await renderLoaded(onRetired)
load(frame)
unmount()
waitOutTheAnswer()
expect(onRetired).not.toHaveBeenCalled()
})
})
@@ -61,31 +61,6 @@ function mountedFiles(markup: string): string[] {
const LINE = '::orca-visual{file="usage.html" title="Usage by day"}'
describe('remarkNativeChatVisuals', () => {
it('splits a paragraph that runs straight into and out of the directive', () => {
const markup = render(`Here it is:\n${LINE}\nThat is the trend.`)
expect(mountedFiles(markup)).toEqual(['usage.html'])
expect(markup).toContain('Here it is:')
expect(markup).toContain('That is the trend.')
})
it.each([
['fenced code', `\`\`\`\n${LINE}\n\`\`\``],
['tilde fenced code', `~~~md\n${LINE}\n~~~`],
['indented code', `Intro\n\n ${LINE}`],
['inline code', `Use \`${LINE}\` to show a chart.`],
['a block quote', `> ${LINE}`],
['a list item', `- ${LINE}`],
['an ordered list item', `1. ${LINE}`],
['mid-sentence', `See ${LINE} here`],
['a malformed directive', '::orca-visual{file="../usage.html"}'],
['an unclosed directive', '::orca-visual{file="usage.html"'],
['trailing prose on the line', `${LINE} done`]
])('leaves it as text inside %s', (_name, content) => {
const markup = render(content)
expect(mountedFiles(markup)).toEqual([])
expect(markup).toContain('::orca-visual')
})
it('does not mount a raw HTML placeholder forged without the nonce', () => {
const markup = render(
'<div data-orca-visual="guess" data-orca-visual-file="usage.html">x</div>\n\nafter'
@@ -93,19 +68,6 @@ describe('remarkNativeChatVisuals', () => {
expect(mountedFiles(markup)).toEqual([])
})
it('caps how many visuals one reply mounts and shows the rest as text', () => {
const lines = Array.from(
{ length: 10 },
(_, index) => `::orca-visual{file="chart-${index}.html"}`
)
const markup = render(lines.join('\n\n'))
expect(mountedFiles(markup)).toEqual(
Array.from({ length: 8 }, (_, index) => `chart-${index}.html`)
)
expect(markup).toContain('chart-8.html')
expect(markup).toContain('chart-9.html')
})
it('keeps reference links defined after the directive working', () => {
const markup = render(`See [the docs][d].\n\n${LINE}\n\n[d]: https://example.com/docs`)
expect(mountedFiles(markup)).toEqual(['usage.html'])
@@ -1,72 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const callRuntimeRpc = vi.fn()
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({
callRuntimeRpc: (...args: unknown[]) => callRuntimeRpc(...args)
}))
import {
clearNativeChatVisualCacheForTests,
peekCachedNativeChatVisual,
readNativeChatVisual
} from './native-chat-visual-read-client'
const local = { target: { kind: 'local' as const }, sessionId: 'session-alpha', file: 'a.html' }
const remote = {
target: { kind: 'environment' as const, environmentId: 'env-1' },
sessionId: 'session-alpha',
file: 'a.html'
}
beforeEach(() => {
clearNativeChatVisualCacheForTests()
callRuntimeRpc.mockReset()
})
afterEach(() => {
clearNativeChatVisualCacheForTests()
})
describe('readNativeChatVisual', () => {
it('revalidates with the held revision and keeps the cached bytes when unchanged', async () => {
callRuntimeRpc.mockResolvedValueOnce({ ok: true, revision: 'r1', html: '<p>', path: '/v' })
await readNativeChatVisual(local)
callRuntimeRpc.mockResolvedValueOnce({
ok: true,
revision: 'r1',
sizeBytes: 3,
unchanged: true
})
expect(await readNativeChatVisual(local)).toEqual({
ok: true,
document: { revision: 'r1', html: '<p>', path: '/v' }
})
expect(callRuntimeRpc.mock.calls[1][2]).toEqual({
sessionId: 'session-alpha',
file: 'a.html',
knownRevision: 'r1'
})
})
it('keeps one runtime from answering for another', async () => {
callRuntimeRpc.mockResolvedValueOnce({ ok: true, revision: 'r1', html: '<p>', path: '/v' })
await readNativeChatVisual(local)
expect(peekCachedNativeChatVisual(remote)).toBeNull()
})
it('passes host refusals through, degrades an unknown one, and forgets a refused file', async () => {
callRuntimeRpc.mockResolvedValueOnce({ ok: true, revision: 'r1', html: '<p>', path: '/v' })
await readNativeChatVisual(local)
callRuntimeRpc.mockResolvedValueOnce({ ok: false, error: 'not_found' })
expect(await readNativeChatVisual(local)).toEqual({ ok: false, reason: 'not_found' })
expect(peekCachedNativeChatVisual(local)).toBeNull()
callRuntimeRpc.mockResolvedValueOnce({ ok: true, revision: 'r2', html: '<p>', path: '/v' })
await readNativeChatVisual(local)
callRuntimeRpc.mockResolvedValueOnce({ ok: false, error: 'too_large' })
expect(await readNativeChatVisual(local)).toEqual({ ok: false, reason: 'too_large' })
// A rewrite the host now refuses must not keep showing the old bytes on the next mount.
expect(peekCachedNativeChatVisual(local)).toBeNull()
callRuntimeRpc.mockResolvedValueOnce({ ok: false, error: 'some_future_reason' })
expect(await readNativeChatVisual(local)).toEqual({ ok: false, reason: 'unavailable' })
})
})
@@ -1,346 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { RuntimeStatus } from '../../../../../shared/runtime-session-contracts'
import type { RuntimeEnvironmentStatus } from '../../../../../shared/remote-runtime/host-status/runtime-host-status'
import type { AppState } from '@/store/types'
import { resolveTerminalInputHostPlatform } from './terminal-input-host-platform'
function state(overrides: Partial<AppState> = {}): AppState {
return {
repos: [],
worktreesByRepo: {},
detectedWorktreesByRepo: {},
folderWorkspaces: [],
projectGroups: [],
settings: { activeRuntimeEnvironmentId: null },
sshConnectionStates: new Map(),
sshStateByEnvironment: new Map(),
runtimeStatusByEnvironmentId: new Map(),
restoredRuntimeHostIdByWorkspaceSessionKey: {},
...overrides
} as AppState
}
/** A Windows host that answered once and whose latest probe came back unverifiable. */
function unverifiableWindowsHost(): RuntimeEnvironmentStatus {
const answered: RuntimeStatus = {
runtimeId: 'rt-win',
rendererGraphEpoch: 0,
graphStatus: 'ready',
authoritativeWindowId: null,
liveTabCount: 0,
liveLeafCount: 0,
hostPlatform: 'win32'
}
return {
status: null,
checkedAt: 2,
snapshot: {
environmentId: 'windows-box',
pairingRevision: 1,
sequence: 2,
checkedAt: 2,
status: answered,
verification: 'unavailable',
transport: 'ready'
}
}
}
describe('resolveTerminalInputHostPlatform', () => {
it('uses a paired runtime host platform instead of the macOS client', () => {
const worktreeId = 'repo::C:\\repo'
expect(
resolveTerminalInputHostPlatform({
clientPlatform: 'darwin',
state: state({
repos: [
{
id: 'repo',
path: 'C:\\repo',
displayName: 'repo',
badgeColor: '#000',
addedAt: 0,
executionHostId: 'runtime:windows-box'
}
],
runtimeStatusByEnvironmentId: new Map([
[
'windows-box',
{
status: { hostPlatform: 'win32' }
} as AppState['runtimeStatusByEnvironmentId'] extends Map<string, infer T> ? T : never
]
])
}),
worktreeId,
transport: null
})
).toBe('win32')
})
it('uses the active remote runtime PTY owner after worktree ownership changes', () => {
expect(
resolveTerminalInputHostPlatform({
clientPlatform: 'darwin',
state: state({
repos: [
{
id: 'repo',
path: 'C:\\repo',
displayName: 'repo',
badgeColor: '#000',
addedAt: 0,
executionHostId: 'runtime:linux-box'
}
],
runtimeStatusByEnvironmentId: new Map([
['windows-box', { status: { hostPlatform: 'win32' } } as never],
['linux-box', { status: { hostPlatform: 'linux' } } as never]
])
}),
worktreeId: 'repo::C:\\repo',
transport: {
getConnectionId: () => null,
getPtyId: () => 'remote:windows-box@@terminal-1'
}
})
).toBe('win32')
})
it('uses the nested SSH host platform instead of the outer HUB platform', () => {
expect(
resolveTerminalInputHostPlatform({
clientPlatform: 'darwin',
state: state({
runtimeStatusByEnvironmentId: new Map([
['hub', { status: { hostPlatform: 'linux' } } as never]
]),
sshStateByEnvironment: new Map([
[
'hub',
{
connectionStates: new Map([['ssh-windows', { remotePlatform: 'win32' } as never]])
} as never
]
])
}),
worktreeId: 'repo::C:\\repo',
transport: {
getConnectionId: () => null,
getPtyId: () => 'remote:hub@@terminal-1',
getRuntimeEnvironmentId: () => 'hub',
getExecutionHostId: () => 'ssh:ssh-windows'
}
})
).toBe('win32')
})
it('uses captured runtime ownership for a legacy remote PTY id', () => {
expect(
resolveTerminalInputHostPlatform({
clientPlatform: 'darwin',
state: state({
runtimeStatusByEnvironmentId: new Map([
['windows-box', { status: { hostPlatform: 'win32' } } as never]
])
}),
worktreeId: 'repo::/repo',
transport: {
getConnectionId: () => null,
getPtyId: () => 'remote:terminal-1',
getRuntimeEnvironmentId: () => 'windows-box'
}
})
).toBe('win32')
})
it('keeps a live local PTY on the client after worktree ownership changes', () => {
expect(
resolveTerminalInputHostPlatform({
clientPlatform: 'darwin',
state: state({
repos: [
{
id: 'repo',
path: '/repo',
displayName: 'repo',
badgeColor: '#000',
addedAt: 0,
executionHostId: 'runtime:windows-box'
}
],
runtimeStatusByEnvironmentId: new Map([
['windows-box', { status: { hostPlatform: 'win32' } } as never]
])
}),
worktreeId: 'repo::/repo',
transport: {
getConnectionId: () => null,
getPtyId: () => 'local-pty-1',
getLocalSessionMetadata: () => ({ cwd: '/repo' })
}
})
).toBe('darwin')
})
it('normalizes a live WSL session to a Linux terminal host', () => {
expect(
resolveTerminalInputHostPlatform({
clientPlatform: 'win32',
state: state(),
worktreeId: 'repo::C:\\repo',
transport: {
getConnectionId: () => null,
getPtyId: () => 'local-pty-1',
getLocalSessionMetadata: () => ({
shellOverride: ' "C:\\Windows\\System32\\wsl.exe" -d Ubuntu-24.04'
})
}
})
).toBe('linux')
})
it('keeps a live native Windows session after the worktree switches to WSL', () => {
expect(
resolveTerminalInputHostPlatform({
clientPlatform: 'win32',
state: state({
repos: [
{
id: 'repo',
path: 'C:\\repo',
displayName: 'repo',
badgeColor: '#000',
addedAt: 0,
executionHostId: 'runtime:linux-box'
}
],
runtimeStatusByEnvironmentId: new Map([
['linux-box', { status: { hostPlatform: 'linux' } } as never]
])
}),
worktreeId: 'repo::C:\\repo',
transport: {
getConnectionId: () => null,
getPtyId: () => 'windows-pty-1',
getLocalSessionMetadata: () => ({ cwd: 'C:\\repo', shellOverride: 'pwsh.exe' })
}
})
).toBe('win32')
})
it('uses SSH remote platform metadata', () => {
expect(
resolveTerminalInputHostPlatform({
clientPlatform: 'darwin',
state: state({
sshConnectionStates: new Map([['ssh-win', { remotePlatform: 'win32' } as never]])
}),
worktreeId: 'repo::C:\\repo',
transport: { getConnectionId: () => 'ssh-win' }
})
).toBe('win32')
})
it('uses conservative POSIX input when SSH platform metadata is unavailable', () => {
expect(
resolveTerminalInputHostPlatform({
clientPlatform: 'darwin',
state: state({ sshConnectionStates: new Map([['ssh-unknown', {} as never]]) }),
worktreeId: 'repo::/repo',
transport: { getConnectionId: () => 'ssh-unknown' }
})
).toBe('linux')
})
it('prefers the PTY-owner platform over stale nested SSH state', () => {
expect(
resolveTerminalInputHostPlatform({
clientPlatform: 'darwin',
state: state({ sshStateByEnvironment: new Map() }),
worktreeId: 'repo::/repo',
transport: {
getConnectionId: () => null,
getRuntimeEnvironmentId: () => 'hub',
getExecutionHostId: () => 'ssh:ssh-win',
getRemotePlatform: () => 'win32'
}
})
).toBe('win32')
})
it('falls back to the client when runtime platform metadata is unavailable', () => {
expect(
resolveTerminalInputHostPlatform({
clientPlatform: 'darwin',
state: state(),
worktreeId: 'repo::/repo',
transport: {
getConnectionId: () => null,
getPtyId: () => 'remote:windows-box@@terminal-1',
getRuntimeEnvironmentId: () => 'windows-box'
}
})
).toBe('darwin')
})
it('uses the SSH execution host when the transport has no connection id', () => {
const worktreeId = 'repo::C:\\repo'
expect(
resolveTerminalInputHostPlatform({
clientPlatform: 'darwin',
state: state({
repos: [
{
id: 'repo',
path: 'C:\\repo',
displayName: 'repo',
badgeColor: '#000',
addedAt: 0,
executionHostId: 'ssh:ssh-win'
}
],
sshConnectionStates: new Map([['ssh-win', { remotePlatform: 'win32' } as never]])
}),
worktreeId,
transport: { getConnectionId: () => null }
})
).toBe('win32')
})
// Unanswered probes cannot substitute client platform: Mac-driven Windows hosts must retain host input/path conventions.
it('keeps the Windows host platform while its probe is unverifiable', () => {
const worktreeId = 'repo::C:\\repo'
expect(
resolveTerminalInputHostPlatform({
clientPlatform: 'darwin',
state: state({
repos: [
{
id: 'repo',
path: 'C:\\repo',
displayName: 'repo',
badgeColor: '#000',
addedAt: 0,
executionHostId: 'runtime:windows-box'
}
],
runtimeStatusByEnvironmentId: new Map([['windows-box', unverifiableWindowsHost()]])
}),
worktreeId,
transport: null
})
).toBe('win32')
})
it('keeps the client platform for local terminals', () => {
expect(
resolveTerminalInputHostPlatform({
clientPlatform: 'darwin',
state: state(),
worktreeId: 'repo::/repo',
transport: null
})
).toBe('darwin')
})
})
@@ -1,44 +0,0 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
const { notifyTerminalInputNotSent } = vi.hoisted(() => ({ notifyTerminalInputNotSent: vi.fn() }))
vi.mock('./terminal-input-not-sent-notice', () => ({ notifyTerminalInputNotSent }))
import {
_resetTerminalInputQuarantineForTests,
armTerminalInputQuarantine,
isTerminalInputQuarantined,
shouldDropQuarantinedTerminalInput
} from './terminal-input-quarantine'
const TAB = 'tab-1'
// Re-attach measured at ~1.1s in STA-2373 live QA; the tail lands just after.
const REATTACH_MS = 1_100
beforeEach(() => {
_resetTerminalInputQuarantineForTests()
notifyTerminalInputNotSent.mockReset()
})
describe('terminal input quarantine', () => {
it('drops the surviving tail of an interrupted line and its Enter', () => {
armTerminalInputQuarantine(TAB, 0)
// The tail of `echo hi; rm -rf x` after the head was eaten by recovery.
let at = REATTACH_MS
for (const char of 'cho hi; rm -rf x') {
expect(shouldDropQuarantinedTerminalInput(TAB, char, at)).toBe(true)
at += 30
}
// The user's own Enter would have submitted the mangled line.
expect(shouldDropQuarantinedTerminalInput(TAB, '\r', at)).toBe(true)
expect(isTerminalInputQuarantined(TAB)).toBe(false)
})
it('releases on an idle gap once a quarantined byte has been seen', () => {
armTerminalInputQuarantine(TAB, 0)
// Burst tail, no Enter — the user was still mid-line when the endpoint died.
expect(shouldDropQuarantinedTerminalInput(TAB, 'c', REATTACH_MS)).toBe(true)
expect(shouldDropQuarantinedTerminalInput(TAB, 'h', REATTACH_MS + 40)).toBe(true)
// Then they notice, pause, and type a real command.
expect(shouldDropQuarantinedTerminalInput(TAB, 'l', REATTACH_MS + 40 + 700)).toBe(false)
expect(isTerminalInputQuarantined(TAB)).toBe(false)
})
})
@@ -1,101 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { Terminal } from '@xterm/xterm'
import {
subscribeToTerminalInputData,
subscribeToTerminalUserInput
} from './terminal-user-input-signal'
type CoreServiceAccess = {
_core: {
coreService: {
triggerDataEvent: (data: string, wasUserInput?: boolean) => void
}
}
}
// Use vendored xterm so private input-signal API drift fails here instead of silently disabling activity tracking.
describe('subscribeToTerminalUserInput', () => {
it('fires for real user input and not for parser auto-replies', () => {
const terminal = new Terminal({ allowProposedApi: true })
const listener = vi.fn()
const subscription = subscribeToTerminalUserInput(terminal, listener)
expect(subscription).not.toBeNull()
const coreService = (terminal as unknown as CoreServiceAccess)._core.coreService
// Keyboard/IME/paste/mouse paths mark their data as user input.
coreService.triggerDataEvent('a', true)
expect(listener).toHaveBeenCalledTimes(1)
// Parser replies still reach onData but must not count as user input.
const onData = vi.fn()
terminal.onData(onData)
coreService.triggerDataEvent('\x1b[O', false)
coreService.triggerDataEvent('\x1b[?1;2c')
expect(listener).toHaveBeenCalledTimes(1)
expect(onData).toHaveBeenCalledTimes(2)
subscription?.dispose()
coreService.triggerDataEvent('b', true)
expect(listener).toHaveBeenCalledTimes(1)
terminal.dispose()
})
it('returns null when the core signal is unavailable', () => {
const listener = vi.fn()
expect(subscribeToTerminalUserInput({} as never, listener)).toBeNull()
expect(
subscribeToTerminalUserInput({ _core: { coreService: {} } } as never, listener)
).toBeNull()
expect(
subscribeToTerminalUserInput(
{
_core: {
coreService: {
onUserInput: () => {
throw new Error('unavailable')
}
}
}
} as never,
listener
)
).toBeNull()
// A subscription without usable disposal is unavailable; preserve callers’ onData fallback.
expect(
subscribeToTerminalUserInput(
{ _core: { coreService: { onUserInput: () => undefined } } } as never,
listener
)
).toBeNull()
expect(
subscribeToTerminalUserInput(
{ _core: { coreService: { onUserInput: () => ({}) } } } as never,
listener
)
).toBeNull()
expect(listener).not.toHaveBeenCalled()
})
})
describe('subscribeToTerminalInputData', () => {
it('classifies real xterm events independently and disposes both subscriptions', () => {
const terminal = new Terminal({ allowProposedApi: true })
const core = (terminal as unknown as CoreServiceAccess)._core.coreService
const listener = vi.fn()
const subscription = subscribeToTerminalInputData(terminal, listener)
core.triggerDataEvent('keyboard', true)
core.triggerDataEvent('\x1b[?1;2c')
core.triggerDataEvent('\x1b[200~paste\x1b[201~', true)
core.triggerDataEvent('\x1b[O', false)
expect(listener.mock.calls).toEqual([
['keyboard', true],
['\x1b[?1;2c', false],
['\x1b[200~paste\x1b[201~', true],
['\x1b[O', false]
])
subscription.dispose()
core.triggerDataEvent('after-dispose', true)
expect(listener).toHaveBeenCalledTimes(4)
terminal.dispose()
})
})
@@ -1,113 +0,0 @@
// @vitest-environment happy-dom
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, describe, expect, it, vi } from 'vitest'
import CloseTerminalDialog from './CloseTerminalDialog'
vi.mock('@/i18n/i18n', () => ({
translate: vi.fn((_key: string, fallback: string) => fallback)
}))
const mountedRoots: Root[] = []
async function renderDialog(props: {
copyKind?: 'command' | 'agent'
onConfirm: (dontAskAgain: boolean) => void
onCancel?: () => void
}): Promise<void> {
const container = document.createElement('div')
document.body.appendChild(container)
const root = createRoot(container)
mountedRoots.push(root)
await act(async () => {
root.render(
<CloseTerminalDialog
open
copyKind={props.copyKind}
onCancel={props.onCancel ?? vi.fn()}
onConfirm={props.onConfirm}
/>
)
})
}
function clickButton(label: string): void {
const button = [...document.body.querySelectorAll<HTMLButtonElement>('button')].find(
(candidate) => candidate.textContent === label
)
if (!button) {
throw new Error(`Button not found: ${label}`)
}
button.click()
}
afterEach(async () => {
await act(async () => {
for (const root of mountedRoots.splice(0)) {
root.unmount()
}
})
document.body.innerHTML = ''
})
describe('CloseTerminalDialog', () => {
it('renders running command copy and confirms without skipping by default', async () => {
const onConfirm = vi.fn()
await renderDialog({ copyKind: 'command', onConfirm })
await act(async () => {
clickButton('Stop and Close')
})
expect(onConfirm).toHaveBeenCalledWith(false)
})
it('renders agent copy and passes the skip preference when checked', async () => {
const onConfirm = vi.fn()
await renderDialog({ copyKind: 'agent', onConfirm })
const checkbox = document.body.querySelector<HTMLButtonElement>('[role="checkbox"]')
expect(checkbox).not.toBeNull()
await act(async () => {
checkbox?.click()
})
await act(async () => {
clickButton('Stop Agent')
})
expect(onConfirm).toHaveBeenCalledWith(true)
})
it('resets the skip preference when the dialog closes and reopens', async () => {
const onConfirm = vi.fn()
const onCancel = vi.fn()
const container = document.createElement('div')
document.body.appendChild(container)
const root = createRoot(container)
mountedRoots.push(root)
const render = async (open: boolean): Promise<void> => {
await act(async () => {
root.render(<CloseTerminalDialog open={open} onCancel={onCancel} onConfirm={onConfirm} />)
})
}
await render(true)
const checkbox = document.body.querySelector<HTMLButtonElement>('[role="checkbox"]')
await act(async () => {
checkbox?.click()
})
expect(checkbox?.getAttribute('aria-checked')).toBe('true')
await render(false)
await render(true)
expect(document.body.querySelector('[role="checkbox"]')?.getAttribute('aria-checked')).toBe(
'false'
)
})
})
@@ -1,142 +0,0 @@
// @vitest-environment happy-dom
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useAppStore } from '@/store/index'
import type { AppState } from '@/store/types'
import PinnedTabCloseDialog from './PinnedTabCloseDialog'
const initialState = useAppStore.getInitialState()
const mountedRoots: Root[] = []
async function renderDialog({
tabLabel = 'Docs',
onConfirm,
onCancel,
updateSettings
}: {
tabLabel?: string
onConfirm: () => void
onCancel?: () => void
updateSettings: AppState['updateSettings']
}): Promise<void> {
useAppStore.setState({
settings: { confirmClosePinnedTab: true } as AppState['settings'],
updateSettings
})
useAppStore.getState().requestPinnedTabCloseConfirm({
tabLabel,
onConfirm,
...(onCancel ? { onCancel } : {})
})
const container = document.createElement('div')
document.body.appendChild(container)
const root = createRoot(container)
mountedRoots.push(root)
await act(async () => {
root.render(<PinnedTabCloseDialog />)
})
}
function getButton(label: string): HTMLButtonElement {
const button = [...document.body.querySelectorAll<HTMLButtonElement>('button')].find(
(candidate) => candidate.textContent === label
)
if (!button) {
throw new Error(`Button not found: ${label}`)
}
return button
}
function getCheckbox(): HTMLButtonElement {
const checkbox = document.body.querySelector<HTMLButtonElement>('[role="checkbox"]')
if (!checkbox) {
throw new Error('Checkbox not found')
}
return checkbox
}
beforeEach(() => {
useAppStore.setState(initialState, true)
})
afterEach(async () => {
await act(async () => {
for (const root of mountedRoots.splice(0)) {
root.unmount()
}
})
document.body.innerHTML = ''
useAppStore.setState(initialState, true)
})
describe('PinnedTabCloseDialog', () => {
it('confirms without changing the preference by default', async () => {
const onConfirm = vi.fn()
const updateSettings = vi.fn().mockResolvedValue(undefined)
await renderDialog({ onConfirm, updateSettings })
await act(async () => {
getButton('Close').click()
})
expect(updateSettings).not.toHaveBeenCalled()
expect(onConfirm).toHaveBeenCalledTimes(1)
})
it('turns off future pinned-tab confirmations when checked and confirmed', async () => {
const onConfirm = vi.fn()
const updateSettings = vi.fn().mockResolvedValue(undefined)
await renderDialog({ onConfirm, updateSettings })
await act(async () => {
getCheckbox().click()
})
await act(async () => {
getButton('Close').click()
})
expect(updateSettings).toHaveBeenCalledWith({ confirmClosePinnedTab: false })
expect(onConfirm).toHaveBeenCalledTimes(1)
})
it('does not persist the checkbox on cancel and resets it for the next request', async () => {
const firstOnConfirm = vi.fn()
const secondOnConfirm = vi.fn()
const onCancel = vi.fn()
const updateSettings = vi.fn().mockResolvedValue(undefined)
await renderDialog({ onConfirm: firstOnConfirm, onCancel, updateSettings })
await act(async () => {
getCheckbox().click()
})
await act(async () => {
getButton('Cancel').click()
})
expect(onCancel).toHaveBeenCalledTimes(1)
expect(firstOnConfirm).not.toHaveBeenCalled()
expect(updateSettings).not.toHaveBeenCalled()
await act(async () => {
useAppStore.getState().requestPinnedTabCloseConfirm({
tabLabel: 'Console',
onConfirm: secondOnConfirm
})
})
expect(getCheckbox().getAttribute('aria-checked')).toBe('false')
await act(async () => {
getButton('Close').click()
})
expect(updateSettings).not.toHaveBeenCalled()
expect(secondOnConfirm).toHaveBeenCalledTimes(1)
})
})
@@ -83,40 +83,6 @@ afterEach(async () => {
})
describe('RunningTerminalCloseDialog', () => {
it('names the tab so a background close is not ambiguous', async () => {
const onConfirm = vi.fn()
const updateSettings = vi.fn().mockResolvedValue(undefined)
await renderDialog({ onConfirm }, updateSettings)
expect(document.body.textContent).toContain('Stop running command?')
expect(document.body.textContent).toContain('dev server')
await act(async () => {
getButton('Stop and Close').click()
})
expect(updateSettings).not.toHaveBeenCalled()
expect(onConfirm).toHaveBeenCalledTimes(1)
})
it('uses truthful chat copy and the shared opt-out without terminal sleep advice', async () => {
const updateSettings = vi.fn().mockResolvedValue(undefined)
const onConfirm = vi.fn()
await renderDialog({ onConfirm, copyKind: 'chat-agent' }, updateSettings)
await act(async () => {
getCheckbox().click()
})
await act(async () => {
getButton('Stop Agent').click()
})
expect(updateSettings).toHaveBeenCalledWith({
skipCloseTerminalWithRunningProcessConfirm: true
})
expect(onConfirm).toHaveBeenCalledTimes(1)
})
it('waits for a visible pinned confirmation instead of stacking a second modal', async () => {
const updateSettings = vi.fn().mockResolvedValue(undefined)
useAppStore.setState({
@@ -134,38 +100,6 @@ describe('RunningTerminalCloseDialog', () => {
expect(document.body.textContent).toContain('Stop running command?')
})
it('does not carry the opt-out tick over to the next queued tab', async () => {
const updateSettings = vi.fn().mockResolvedValue(undefined)
const nextOnConfirm = vi.fn()
await renderDialog({ onConfirm: vi.fn(), onCancel: vi.fn() }, updateSettings)
await act(async () => {
useRunningTerminalCloseConfirmStore.getState().requestRunningTerminalCloseConfirm({
terminalTabId: 'tab-2',
tabLabel: 'build watcher',
copyKind: 'command',
onConfirm: nextOnConfirm
})
})
await act(async () => {
getCheckbox().click()
})
await act(async () => {
getButton('Cancel').click()
})
expect(document.body.textContent).toContain('build watcher')
advancePastGuard()
await act(async () => {
getButton('Stop and Close').click()
})
expect(updateSettings).not.toHaveBeenCalled()
expect(nextOnConfirm).toHaveBeenCalledTimes(1)
})
it('drops a queued prompt once the user opts out of asking again', async () => {
const updateSettings = vi.fn().mockResolvedValue(undefined)
const onConfirm = vi.fn()
@@ -195,36 +129,4 @@ describe('RunningTerminalCloseDialog', () => {
expect(nextOnConfirm).toHaveBeenCalledTimes(1)
expect(document.body.textContent).not.toContain('build watcher')
})
it('cancels without closing and shows the next queued tab', async () => {
const onConfirm = vi.fn()
const onCancel = vi.fn()
const nextOnConfirm = vi.fn()
const updateSettings = vi.fn().mockResolvedValue(undefined)
await renderDialog({ onConfirm, onCancel }, updateSettings)
await act(async () => {
useRunningTerminalCloseConfirmStore.getState().requestRunningTerminalCloseConfirm({
terminalTabId: 'tab-2',
tabLabel: 'build watcher',
copyKind: 'command',
onConfirm: nextOnConfirm
})
})
await act(async () => {
getButton('Cancel').click()
})
expect(onCancel).toHaveBeenCalledTimes(1)
expect(onConfirm).not.toHaveBeenCalled()
expect(document.body.textContent).toContain('build watcher')
advancePastGuard()
await act(async () => {
getButton('Stop and Close').click()
})
expect(nextOnConfirm).toHaveBeenCalledTimes(1)
})
})
@@ -1,41 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { CLOSE_TERMINAL_PANE_EVENT } from '@/constants/terminal'
vi.mock('../../../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true }))
vi.mock('@/store/index', () => ({ useAppStore: { getState: () => ({}) } }))
import { applyClosedTerminalLeafNotice } from './closed-terminal-leaf-notice'
import {
_resetTerminalPaneSplitRequestRoutingForTests,
hasTerminalPaneSplitMountLease,
takeQueuedTerminalPaneSplitRequests
} from '../split/terminal-pane-split-request-routing'
afterEach(() => {
_resetTerminalPaneSplitRequestRoutingForTests()
vi.unstubAllGlobals()
})
describe('a pane main closed before its tab mounted, in a layout-owner build', () => {
// Main-owned splits mount from frames; once main removes the leaf, no window-side deferred mount may remain.
it('leaves nothing waiting to mount it, and drops it from a mounted tab as before', () => {
const target = new EventTarget()
vi.stubGlobal('window', target)
const closed = vi.fn()
target.addEventListener(CLOSE_TERMINAL_PANE_EVENT, (event) => {
if (event instanceof CustomEvent) {
closed(event.detail)
}
})
applyClosedTerminalLeafNotice('tab-1', '22222222-2222-4222-8222-222222222222', 'requested')
expect(takeQueuedTerminalPaneSplitRequests('tab-1', 'wt-1')).toEqual([])
expect(hasTerminalPaneSplitMountLease('tab-1')).toBe(false)
expect(closed).toHaveBeenCalledWith({
tabId: 'tab-1',
leafId: '22222222-2222-4222-8222-222222222222',
lastPaneCloseReason: 'requested'
})
})
})
@@ -1,189 +0,0 @@
import { beforeEach, expect, it, vi } from 'vitest'
import { preparePendingSplitClose } from './pending-split-close-test-fixture'
import type { sendLayoutCommandToOwner } from '@/runtime/layout-owner-command'
import { LOCAL_LAYOUT_APPLY_ORIGIN } from '@/runtime/server-layout-apply-routes'
const mocks = vi.hoisted(() => ({
layoutOwnerIsMain: false,
commitTerminalSurfaceClose: vi.fn(),
sendLayoutCommandToOwner: vi.fn<typeof sendLayoutCommandToOwner>(),
noteAgentLaunchPaneClosedByUser: vi.fn()
}))
vi.mock('../../../../../../shared/layout-owner-switch', () => ({
get ORCA_LAYOUT_OWNER_IS_MAIN() {
return mocks.layoutOwnerIsMain
}
}))
vi.mock('@/runtime/layout-owner-command', () => ({
sendLayoutCommandToOwner: mocks.sendLayoutCommandToOwner
}))
vi.mock('@/lib/agent-session/launch/pane/agent-launch-pane-closes', () => ({
noteAgentLaunchPaneClosedByUser: mocks.noteAgentLaunchPaneClosedByUser
}))
vi.mock('@/store/terminals/terminal-surface-close-intent', () => ({
commitTerminalSurfaceClose: mocks.commitTerminalSurfaceClose
}))
const LEAF = '11111111-1111-4111-8111-111111111111'
beforeEach(() => {
mocks.layoutOwnerIsMain = false
mocks.commitTerminalSurfaceClose.mockReset()
mocks.sendLayoutCommandToOwner.mockReset()
mocks.noteAgentLaunchPaneClosedByUser.mockReset()
mocks.sendLayoutCommandToOwner.mockReturnValue(true)
})
it('a window-owned build closes the pane at once and reports it to main', async () => {
const p = await preparePendingSplitClose()
p.actions.executeClosePane(1, 'user')
expect(mocks.sendLayoutCommandToOwner).not.toHaveBeenCalled()
expect(mocks.commitTerminalSurfaceClose).toHaveBeenCalledWith('workspace', {
kind: 'pane',
tabId: 'tab-parent',
leafId: LEAF
})
expect(p.transports.has(1)).toBe(false)
})
it('a layout-owner build removes the pane only once main’s frame drops it', async () => {
mocks.layoutOwnerIsMain = true
const p = await preparePendingSplitClose()
const intents = await import('@/runtime/layout-owner-pane-intents')
;(await import('@/runtime/layout-frame-position')).noteLayoutFramePosition(1)
p.actions.executeClosePane(1, 'user')
expect(mocks.sendLayoutCommandToOwner).toHaveBeenCalledWith(
'workspace',
{ type: 'closePane', tabId: 'tab-parent', leafId: LEAF },
{
apply: expect.any(Function),
asToday: expect.any(Function),
refused: expect.any(Function)
}
)
mocks.sendLayoutCommandToOwner.mock.calls[0]?.[2].apply({}, LOCAL_LAYOUT_APPLY_ORIGIN)
expect(p.transports.has(1)).toBe(true)
// The frame without the pane finds the window's close and runs it.
expect(intents.takePaneCloseIntent('tab-parent', LEAF)).toBe('user')
p.actions.closePaneLocally(1, LEAF, 'user')
expect(p.transports.has(1)).toBe(false)
expect(mocks.commitTerminalSurfaceClose).not.toHaveBeenCalled()
})
it('a layout-owner build closes the pane itself when main closed it and no frame is coming', async () => {
mocks.layoutOwnerIsMain = true
const p = await preparePendingSplitClose()
;(await import('@/runtime/layout-frame-position')).endLayoutFramePositions()
p.actions.executeClosePane(1, 'user')
mocks.sendLayoutCommandToOwner.mock.calls[0]?.[2].apply({}, LOCAL_LAYOUT_APPLY_ORIGIN)
expect(p.transports.has(1)).toBe(false)
expect(mocks.commitTerminalSurfaceClose).not.toHaveBeenCalled()
})
it('a layout-owner build closes the pane itself when main holds no such pane, so no frame drops it', async () => {
mocks.layoutOwnerIsMain = true
const p = await preparePendingSplitClose()
;(await import('@/runtime/layout-frame-position')).noteLayoutFramePosition(1)
p.actions.executeClosePane(1, 'user')
mocks.sendLayoutCommandToOwner.mock.calls[0]?.[2].apply(
{ alreadyClosed: true },
LOCAL_LAYOUT_APPLY_ORIGIN
)
const intents = await import('@/runtime/layout-owner-pane-intents')
expect(intents.takePaneCloseIntent('tab-parent', LEAF)).toBeNull()
expect(p.transports.has(1)).toBe(false)
expect(mocks.commitTerminalSurfaceClose).not.toHaveBeenCalled()
})
it('a layout-owner build closes as today, forgetting its close, when main lacks the pane', async () => {
mocks.layoutOwnerIsMain = true
const p = await preparePendingSplitClose()
p.actions.executeClosePane(1, 'user')
mocks.sendLayoutCommandToOwner.mock.calls[0]?.[2].asToday()
const intents = await import('@/runtime/layout-owner-pane-intents')
expect(intents.takePaneCloseIntent('tab-parent', LEAF)).toBeNull()
expect(mocks.commitTerminalSurfaceClose).toHaveBeenCalledOnce()
expect(p.transports.has(1)).toBe(false)
})
it('a layout-owner build closes the tab when main refuses a second close as the last pane', async () => {
mocks.layoutOwnerIsMain = true
const p = await preparePendingSplitClose()
p.actions.executeClosePane(1, 'user')
p.actions.executeClosePane(2, 'user')
const [first, second] = mocks.sendLayoutCommandToOwner.mock.calls.map(([, , on]) => on)
// Main took pane 1; its frame is still on the way when main refuses pane 2 as its last.
;(await import('@/runtime/layout-frame-position')).noteLayoutFramePosition(1)
first?.apply({}, LOCAL_LAYOUT_APPLY_ORIGIN)
second?.refused?.('last_pane')
expect(p.controller.onCloseTab).toHaveBeenCalledOnce()
})
it("a layout-owner build closes the tab with the pane close's own reason, never an implied user close", async () => {
mocks.layoutOwnerIsMain = true
const p = await preparePendingSplitClose()
p.actions.executeClosePane(1, 'cleanup')
p.actions.executeClosePane(2, 'cleanup')
const [first, second] = mocks.sendLayoutCommandToOwner.mock.calls.map(([, , on]) => on)
;(await import('@/runtime/layout-frame-position')).noteLayoutFramePosition(1)
first?.apply({}, LOCAL_LAYOUT_APPLY_ORIGIN)
second?.refused?.('last_pane')
expect(p.controller.onCloseTab).toHaveBeenCalledWith('cleanup')
})
it('a layout-owner build leaves an unmounted tab alone when main refuses its last pane', async () => {
mocks.layoutOwnerIsMain = true
const p = await preparePendingSplitClose()
p.actions.executeClosePane(1, 'user')
p.controller.managerRef.current = null
mocks.sendLayoutCommandToOwner.mock.calls[0]?.[2].refused?.('last_pane')
expect(p.controller.onCloseTab).not.toHaveBeenCalled()
})
it('a layout-owner build closes as today when main calls it the last pane but the window has more', async () => {
mocks.layoutOwnerIsMain = true
const p = await preparePendingSplitClose()
p.actions.executeClosePane(1, 'user')
mocks.sendLayoutCommandToOwner.mock.calls[0]?.[2].refused?.('last_pane')
expect(p.controller.onCloseTab).not.toHaveBeenCalled()
expect(mocks.commitTerminalSurfaceClose).toHaveBeenCalledOnce()
expect(p.transports.has(1)).toBe(false)
})
it.each([
['user', true],
['cleanup', false]
] as const)(
'a %s close of a starting launch pane stops its launch only when the user closed it',
async (reason, stopsLaunch) => {
const p = await preparePendingSplitClose()
const { useAppStore } = await import('../../../../store/index')
const [tab] = useAppStore.getState().tabsByWorktree.workspace ?? []
Object.assign(tab!, { agentLaunchPane: { leafId: LEAF } })
p.actions.executeClosePane(1, reason)
expect(mocks.noteAgentLaunchPaneClosedByUser).toHaveBeenCalledTimes(stopsLaunch ? 1 : 0)
}
)
@@ -44,131 +44,6 @@ async function prepare(remote = false, requestedPtyId?: string) {
return { ...p, paired, actions, probePtyRunningWork, verdict, reply, closed, settle }
}
it.each([false, true])('requires confirmation for pending live work, paired=%s', async (remote) => {
const p = await prepare(remote)
p.actions.handleRequestClosePane(1)
expect(p.probePtyRunningWork).toHaveBeenCalledWith(
[remote ? 'remote:env-1@@term_original' : 'pty-restored'],
expect.any(Object)
)
expect(p.closed()).toBe(false)
p.verdict('live')
await flushPtySideEffects()
expect(p.controller.setPendingCloseConfirmation).toHaveBeenCalledWith(
expect.objectContaining({ paneId: 1 })
)
expect(p.closed()).toBe(false)
p.actions.handleConfirmClose(false)
await p.settle()
expect(p.closed()).toBe(true)
})
it.each([false, true])('Cancel preserves pending work, paired=%s', async (remote) => {
const p = await prepare(remote)
p.actions.handleRequestClosePane(1)
p.verdict('live')
await flushPtySideEffects()
p.actions.handleCancelClose()
p.actions.handleConfirmClose(false)
await p.settle()
expect(p.closed()).toBe(false)
})
it.each(['unverifiable', 'rejected', 'timeout'] as const)(
'requires confirmation when a pending owner probe is %s',
async (mode) => {
vi.useFakeTimers()
const p = await prepare()
p.actions.handleRequestClosePane(1)
if (mode === 'rejected') {
p.reply.reject(new Error('owner unavailable'))
} else if (mode === 'unverifiable') {
p.verdict(mode)
} else {
await vi.advanceTimersByTimeAsync(101)
}
await Promise.resolve()
await Promise.resolve()
expect(p.controller.setPendingCloseConfirmation).toHaveBeenCalled()
expect(p.closed()).toBe(false)
p.actions.handleCancelClose()
p.verdict('exited')
vi.useRealTimers()
await p.settle()
expect(p.closed()).toBe(false)
}
)
it('uses the direct SSH identity in the running-work probe', async () => {
const id = 'ssh:ssh-1@@pty-restored'
const p = await prepare(false, id)
p.state.worktreesByRepo = { repo: [{ id: 'workspace', repoId: 'repo', hostId: 'ssh:ssh-1' }] }
p.actions.handleRequestClosePane(1)
p.verdict('live')
await flushPtySideEffects()
expect(p.probePtyRunningWork).toHaveBeenCalledWith([id], expect.any(Object))
expect(p.closed()).toBe(false)
p.actions.handleConfirmClose(false)
await p.settle()
expect(p.closed()).toBe(true)
expect(window.api.pty.kill).toHaveBeenCalledWith(id)
})
it.each(['rejected', 'timeout'] as const)(
'honors the skip-confirmation setting when a pending probe is %s',
async (mode) => {
vi.useFakeTimers()
const p = await prepare()
Object.assign(p.state, { settings: { skipCloseTerminalWithRunningProcessConfirm: true } })
p.actions.handleRequestClosePane(1)
if (mode === 'rejected') {
p.reply.reject(new Error('owner unavailable'))
} else {
await vi.advanceTimersByTimeAsync(101)
}
await Promise.resolve()
await Promise.resolve()
expect(p.controller.setPendingCloseConfirmation).not.toHaveBeenCalled()
expect(p.closed()).toBe(true)
p.verdict('exited')
vi.useRealTimers()
await p.settle()
}
)
it.each(['exited', 'skip-setting'] as const)('keeps allowed pending close for %s', async (mode) => {
const p = await prepare()
if (mode === 'skip-setting') {
Object.assign(p.state, { settings: { skipCloseTerminalWithRunningProcessConfirm: true } })
}
p.actions.handleRequestClosePane(1)
p.verdict(mode === 'exited' ? 'exited' : 'live')
await flushPtySideEffects()
expect(p.controller.setPendingCloseConfirmation).not.toHaveBeenCalled()
await p.settle()
expect(p.closed()).toBe(true)
})
it.each(['probe', 'dialog'] as const)(
'accepts the same pending attach finishing during %s',
async (phase) => {
const p = await prepare()
p.actions.handleRequestClosePane(1)
if (phase === 'dialog') {
p.verdict('live')
await flushPtySideEffects()
}
p.spawn.resolve({ id: 'pty-restored', isReattach: true })
await p.connecting
p.verdict('live')
await flushPtySideEffects()
expect(p.closed()).toBe(false)
p.actions.handleConfirmClose(false)
await flushPtySideEffects()
expect(p.closed()).toBe(true)
}
)
it.each(['tab', 'generation', 'leaf', 'transport', 'manager', 'whole-tab', 'binding'] as const)(
'does not apply a pending confirmation to a replacement %s',
async (replacement) => {
@@ -1,40 +1,7 @@
import { expect, it, vi } from 'vitest'
import { expect, it } from 'vitest'
import { preparePendingRuntimeClose } from './pending-runtime-pane-close-test-fixture'
import { makeCloseTestTab } from './pending-split-close-test-fixture'
it('closes the captured scoped handle while actual remote attach is still unbound', async () => {
const p = await preparePendingRuntimeClose()
expect(p.runtimeCall).toHaveBeenCalledWith(
expect.objectContaining({ method: 'terminal.resolvePane' })
)
expect(p.remote.getPtyId()).toBeNull()
p.actions.executeClosePane(1, 'user')
expect(p.runtimeCall).toHaveBeenCalledWith(expect.objectContaining({ method: 'status.get' }))
p.acceptCompatibility()
await p.settle()
expect(p.runtimeCall).toHaveBeenCalledWith(
expect.objectContaining({
method: 'terminal.close',
params: { terminal: 'term_original' },
expectedEnvironmentPairingRevision: 1
})
)
expect(window.api.pty.kill).not.toHaveBeenCalled()
})
it('normal remount keeps the captured remote handle', async () => {
const p = await preparePendingRuntimeClose()
p.remote.detach?.()
p.acceptCompatibility()
await p.settle()
expect(p.runtimeCall.mock.calls.map(([request]) => request.method)).not.toContain(
'terminal.close'
)
expect(p.state.terminalLayoutsByTabId[p.tabId].ptyIdsByLeafId?.[p.leafId]).toBe(
'remote:env-1@@term_original'
)
})
it.each(['same-leaf', 'other-tab', 'bound-transport', 'worktree-owner', 'pairing'] as const)(
'rechecks %s ownership after compatibility settles',
async (owner) => {
@@ -68,49 +35,6 @@ it.each(['same-leaf', 'other-tab', 'bound-transport', 'worktree-owner', 'pairing
}
)
it('protects a sibling legacy alias before issuing a compatibility request', async () => {
const p = await preparePendingRuntimeClose()
p.state.terminalLayoutsByTabId[p.tabId].ptyIdsByLeafId = {
[p.leafId]: 'remote:env-1@@term_original',
[p.siblingLeafId]: 'remote:term_original'
}
p.actions.executeClosePane(1, 'user')
p.acceptCompatibility()
await p.settle()
expect(p.runtimeCall.mock.calls.map(([request]) => request.method)).toEqual([
'terminal.resolvePane'
])
})
it.each(['ssh:host@@native-hint', 'remote:term_original', 'remote:env-2@@term_original'])(
'refuses to infer close authority from %s',
async (id) => {
const p = await preparePendingRuntimeClose(id)
p.actions.executeClosePane(1, 'user')
p.acceptCompatibility()
await p.settle()
expect(p.runtimeCall.mock.calls.map(([request]) => request.method)).not.toContain(
'terminal.close'
)
expect(window.api.pty.kill).not.toHaveBeenCalled()
}
)
it('does not bypass a failed compatibility check', async () => {
const p = await preparePendingRuntimeClose()
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
p.actions.executeClosePane(1, 'user')
p.compatibility.reject(new Error('incompatible runtime'))
await p.settle()
expect(p.runtimeCall.mock.calls.map(([request]) => request.method)).not.toContain(
'terminal.close'
)
expect(warn).toHaveBeenCalledWith(
'[terminal-retirement] provider teardown failed',
expect.objectContaining({ runtimeFailures: 1 })
)
})
it('never turns a late different resolved handle into close authority', async () => {
const p = await preparePendingRuntimeClose()
p.actions.executeClosePane(1, 'user')
@@ -1,7 +1,6 @@
import { expect, it, vi } from 'vitest'
import { makeCloseTestTab, preparePendingSplitClose } from './pending-split-close-test-fixture'
import { folderWorkspaceKey } from '../../../../../../shared/workspace-scope'
import { flushPtySideEffects } from '../../pty-transport/ipc/pty-transport-test-harness'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/layout-owner-switch'
const replyFor = (kind: 'reattach' | 'cold-restore-new' | 'ordinary-fresh') => ({
@@ -10,75 +9,6 @@ const replyFor = (kind: 'reattach' | 'cold-restore-new' | 'ordinary-fresh') => (
...(kind === 'cold-restore-new' ? { coldRestore: { scrollback: 'saved', cwd: '/tmp' } } : {})
})
it.each(['reattach', 'cold-restore-new', 'ordinary-fresh'] as const)(
'explicit split close retires a pending %s before and after its reply',
async (kind) => {
const p = await preparePendingSplitClose()
expect(p.transport.getPtyId()).toBeNull()
p.actions.executeClosePane(1, 'user')
await p.mainAnswered()
expect(p.transports.has(1)).toBe(false)
expect(p.state.terminalLayoutsByTabId[p.tabId].ptyIdsByLeafId?.[p.leafId]).toBeUndefined()
expect(window.api.pty.kill).toHaveBeenCalledExactlyOnceWith('pty-restored')
p.spawn.resolve(replyFor(kind))
await p.connecting
expect(window.api.pty.kill).toHaveBeenCalledTimes(2)
expect(p.transport.getPtyId()).toBeNull()
}
)
it.each(['reattach', 'cold-restore-new'] as const)(
'ordinary remount preserves pending %s for adoption',
async (kind) => {
const p = await preparePendingSplitClose()
p.transport.detach?.({ preserveExitObserver: false })
p.spawn.resolve(replyFor(kind))
await p.connecting
expect(window.api.pty.kill).not.toHaveBeenCalled()
expect(p.state.terminalLayoutsByTabId[p.tabId].ptyIdsByLeafId?.[p.leafId]).toBe('pty-restored')
const { createIpcPtyTransport } = await import('../../pty-transport/ipc/pty-transport')
vi.mocked(window.api.pty.spawn).mockResolvedValueOnce({ id: 'pty-restored', isReattach: true })
const replacement = createIpcPtyTransport({})
await replacement.connect({ url: '', sessionId: 'pty-restored', callbacks: {} })
expect(replacement.getPtyId()).toBe('pty-restored')
replacement.detach?.({ preserveExitObserver: false })
}
)
it.each(['layout', 'transport'] as const)(
'protects a sibling owner recorded only in %s',
async (owner) => {
const p = await preparePendingSplitClose()
const { createIpcPtyTransport } = await import('../../pty-transport/ipc/pty-transport')
const survivor = createIpcPtyTransport({})
if (owner === 'transport') {
survivor.attach({ existingPtyId: 'pty-restored', callbacks: {} })
p.transports.set(2, survivor)
} else {
p.state.terminalLayoutsByTabId[p.tabId].ptyIdsByLeafId = {
[p.leafId]: 'pty-restored',
[p.siblingLeafId]: 'pty-restored'
}
}
p.actions.executeClosePane(1, 'user')
await p.mainAnswered()
p.spawn.resolve(replyFor('reattach'))
await p.connecting
expect(window.api.pty.kill).not.toHaveBeenCalled()
survivor.detach?.({ preserveExitObserver: false })
}
)
it('protects a different tab owner present before explicit close', async () => {
const p = await preparePendingSplitClose()
p.state.tabsByWorktree.workspace.push(makeCloseTestTab('survivor', 'pty-restored'))
p.actions.executeClosePane(1, 'user')
await p.mainAnswered()
p.spawn.resolve(replyFor('cold-restore-new'))
await p.connecting
expect(window.api.pty.kill).not.toHaveBeenCalled()
})
it.each(['same-leaf', 'different-tab', 'new-transport-map'] as const)(
'protects a %s replacement that adopts after explicit close',
async (owner) => {
@@ -102,108 +32,6 @@ it.each(['same-leaf', 'different-tab', 'new-transport-map'] as const)(
}
)
it('retains explicit close intent across repeated generic destroy calls', async () => {
const p = await preparePendingSplitClose()
p.actions.executeClosePane(1, 'user')
await p.mainAnswered()
p.transport.destroy?.()
p.transport.destroy?.()
p.spawn.resolve(replyFor('cold-restore-new'))
await p.connecting
expect(window.api.pty.kill).toHaveBeenCalledTimes(2)
})
it('preserves a different returned reattach identity', async () => {
const p = await preparePendingSplitClose()
p.actions.executeClosePane(1, 'user')
await p.mainAnswered()
p.spawn.resolve({ id: 'different-existing-session', isReattach: true })
await p.connecting
expect(window.api.pty.kill).toHaveBeenCalledExactlyOnceWith('pty-restored')
})
it('retries an eager provider failure when the same-ID reply arrives', async () => {
const p = await preparePendingSplitClose()
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.mocked(window.api.pty.kill).mockRejectedValueOnce(
new Error('provider temporarily unavailable')
)
p.actions.executeClosePane(1, 'user')
await p.mainAnswered()
await flushPtySideEffects()
expect(warn).toHaveBeenCalledWith(
'[terminal-retirement] provider teardown failed',
expect.any(Object)
)
p.spawn.resolve(replyFor('reattach'))
await p.connecting
expect(window.api.pty.kill).toHaveBeenCalledTimes(2)
})
it('does not invent a late session after a rejected spawn', async () => {
const p = await preparePendingSplitClose()
vi.spyOn(console, 'error').mockImplementation(() => {})
p.actions.executeClosePane(1, 'user')
await p.mainAnswered()
p.spawn.reject(new Error('spawn rejected'))
await p.connecting
expect(window.api.pty.kill).toHaveBeenCalledExactlyOnceWith('pty-restored')
})
it('routes direct SSH retirement through the existing IPC identity', async () => {
const id = 'ssh:ssh-1@@pty-restored'
const p = await preparePendingSplitClose(id)
p.state.worktreesByRepo = { repo: [{ id: 'workspace', repoId: 'repo', hostId: 'ssh:ssh-1' }] }
p.actions.executeClosePane(1, 'user')
await p.mainAnswered()
p.spawn.resolve({ id, isReattach: true })
await p.connecting
expect(window.api.pty.kill).toHaveBeenNthCalledWith(1, id)
expect(window.api.pty.kill).toHaveBeenNthCalledWith(2, id)
})
it.each(['runtime-handle', 'runtime-legacy', 'unresolved-owner', 'runtime-native-hint'] as const)(
'never falls through to local kill for %s',
async (kind) => {
const id =
kind === 'runtime-handle'
? 'remote:env-1@@pty-restored'
: kind === 'runtime-legacy'
? 'remote:pty-restored'
: 'pty-restored'
const p = await preparePendingSplitClose(id)
if (kind === 'unresolved-owner') {
p.state.worktreesByRepo = {}
} else if (kind === 'runtime-native-hint') {
p.state.worktreesByRepo = {
repo: [
{
id: 'workspace',
repoId: 'repo',
hostId: 'ssh:ssh-1',
runtimeOwnerEnvironmentId: 'env-1'
}
]
}
}
p.actions.executeClosePane(1, 'user')
await p.mainAnswered()
p.spawn.resolve({ id, isReattach: true })
await p.connecting
expect(window.api.pty.kill).not.toHaveBeenCalled()
}
)
it('retires a local folder-workspace split without a git worktree row', async () => {
const p = await preparePendingSplitClose('pty-restored', folderWorkspaceKey('folder-1'))
p.state.worktreesByRepo = {}
p.actions.executeClosePane(1, 'user')
await p.mainAnswered()
p.spawn.resolve(replyFor('reattach'))
await p.connecting
expect(window.api.pty.kill).toHaveBeenCalledTimes(2)
})
it('commits the explicit split close in main by its leaf without waiting for its write', async () => {
const p = await preparePendingSplitClose()
// Main's durable write never settles here: the pane must still leave and be killed at once.
@@ -1,35 +0,0 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
onActiveTerminalPaneCloseRequest,
requestActiveTerminalPaneClose
} from './request-active-terminal-pane-close'
describe('active terminal pane close request', () => {
const unsubscribes: (() => void)[] = []
afterEach(() => {
unsubscribes.splice(0).forEach((unsubscribe) => unsubscribe())
})
it('reaches only the pane mounted for the named tab', () => {
const closeA = vi.fn()
const closeB = vi.fn()
unsubscribes.push(onActiveTerminalPaneCloseRequest('tab-a', closeA))
unsubscribes.push(onActiveTerminalPaneCloseRequest('tab-b', closeB))
requestActiveTerminalPaneClose('tab-a')
expect(closeA).toHaveBeenCalledOnce()
expect(closeB).not.toHaveBeenCalled()
})
it('stops reaching a pane once it unsubscribes', () => {
const close = vi.fn()
onActiveTerminalPaneCloseRequest('tab-a', close)()
requestActiveTerminalPaneClose('tab-a')
expect(close).not.toHaveBeenCalled()
})
})
@@ -1,206 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import {
applyTerminalPaneCloseRequest,
retireMountedTerminalPaneSurface,
suppressIntentionalPaneCloseExit
} from './terminal-pane-lifecycle-close'
describe('applyTerminalPaneCloseRequest', () => {
it('detaches a rolled-back split surface without closing its PTY', () => {
const manager = {
getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]),
getNumericIdForLeaf: vi.fn(() => 2),
closePane: vi.fn(),
detachPaneForExternalMove: vi.fn(() => true),
retirePanePreservingPty: vi.fn(() => true)
}
const closeTab = vi.fn()
const closeTabPreservingPty = vi.fn()
expect(
applyTerminalPaneCloseRequest({
detail: {
lastPaneCloseReason: 'cleanup',
tabId: 'legacy-worker',
leafId: '11111111-1111-4111-8111-111111111111',
preservePty: true
},
manager,
closeTab,
closeTabPreservingPty
})
).toBe('pane')
expect(manager.detachPaneForExternalMove).toHaveBeenCalledWith(2)
expect(manager.closePane).not.toHaveBeenCalled()
expect(closeTab).not.toHaveBeenCalled()
expect(closeTabPreservingPty).not.toHaveBeenCalled()
})
it("closes a tab through its last pane with the requester's reason, never an implied user close", () => {
// A withdrawn launch pane closing the tab must not reach a paired host as the user's close (#37245).
const closeTab = vi.fn()
const manager = {
getPanes: vi.fn(() => [{ id: 1 }]),
getNumericIdForLeaf: vi.fn(() => 1),
closePane: vi.fn(),
detachPaneForExternalMove: vi.fn(() => true),
retirePanePreservingPty: vi.fn(() => true)
}
applyTerminalPaneCloseRequest({
detail: {
lastPaneCloseReason: 'cleanup',
tabId: 'launch-tab',
leafId: '11111111-1111-4111-8111-111111111111'
},
manager,
closeTab,
closeTabPreservingPty: vi.fn()
})
expect(closeTab).toHaveBeenCalledWith('cleanup')
})
it('uses non-destructive tab close semantics for the last rolled-back pane', () => {
const closeTab = vi.fn()
const closeTabPreservingPty = vi.fn()
expect(
applyTerminalPaneCloseRequest({
detail: {
lastPaneCloseReason: 'cleanup',
tabId: 'legacy-worker',
paneRuntimeId: 1,
preservePty: true
},
manager: {
getPanes: vi.fn(() => [{ id: 1 }]),
getNumericIdForLeaf: vi.fn(() => 1),
closePane: vi.fn(),
detachPaneForExternalMove: vi.fn(() => true),
retirePanePreservingPty: vi.fn(() => true)
},
closeTab,
closeTabPreservingPty
})
).toBe('tab')
expect(closeTabPreservingPty).toHaveBeenCalledOnce()
expect(closeTab).not.toHaveBeenCalled()
})
it('ignores a delayed rollback after the pane PTY identity changed', () => {
const manager = {
getPanes: vi.fn(() => [{ id: 1 }]),
getNumericIdForLeaf: vi.fn(() => 1),
closePane: vi.fn(),
detachPaneForExternalMove: vi.fn(() => true),
retirePanePreservingPty: vi.fn(() => true)
}
const closeTab = vi.fn()
const closeTabPreservingPty = vi.fn()
expect(
applyTerminalPaneCloseRequest({
detail: {
lastPaneCloseReason: 'cleanup',
tabId: 'legacy-worker',
leafId: '11111111-1111-4111-8111-111111111111',
preservePty: true,
expectedPtyId: 'pty-legacy'
},
manager,
closeTab,
closeTabPreservingPty,
getPtyIdForLeaf: () => 'pty-replacement'
})
).toBe('ignored')
expect(manager.detachPaneForExternalMove).not.toHaveBeenCalled()
expect(closeTabPreservingPty).not.toHaveBeenCalled()
})
it('retires a mounted rollback pane without detaching it as a movable surface', () => {
const manager = {
getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]),
getNumericIdForLeaf: vi.fn(() => 2),
closePane: vi.fn(),
detachPaneForExternalMove: vi.fn(() => true),
retirePanePreservingPty: vi.fn(() => true)
}
expect(
applyTerminalPaneCloseRequest({
detail: {
lastPaneCloseReason: 'cleanup',
tabId: 'legacy-worker',
leafId: '11111111-1111-4111-8111-111111111111',
preservePty: true,
retireSurface: true,
expectedPtyId: 'pty-legacy'
},
manager,
closeTab: vi.fn(),
closeTabPreservingPty: vi.fn(),
getPtyIdForLeaf: () => 'pty-legacy'
})
).toBe('pane')
expect(manager.retirePanePreservingPty).toHaveBeenCalledWith(2)
expect(manager.detachPaneForExternalMove).not.toHaveBeenCalled()
expect(manager.closePane).not.toHaveBeenCalled()
})
it('retires mounted authority and binding while preserving the process and sleeping fence', () => {
const retireAgentPaneAuthority = vi.fn()
const syncPanePtyLayoutBinding = vi.fn()
const clearExitedPanePtyLayoutBindingForLeaf = vi.fn()
const clearTabPtyId = vi.fn()
const transport = { detach: vi.fn(), destroy: vi.fn() }
retireMountedTerminalPaneSurface({
paneKey: 'legacy-worker:11111111-1111-4111-8111-111111111111',
leafId: '11111111-1111-4111-8111-111111111111',
paneId: 2,
tabId: 'legacy-worker',
ptyId: 'pty-legacy',
retireAgentPaneAuthority,
syncPanePtyLayoutBinding,
clearExitedPanePtyLayoutBindingForLeaf,
clearTabPtyId,
transport
})
expect(retireAgentPaneAuthority).toHaveBeenCalledWith(
'legacy-worker:11111111-1111-4111-8111-111111111111',
{ preserveSleepingAgentSession: true }
)
expect(clearExitedPanePtyLayoutBindingForLeaf).toHaveBeenCalledWith(
'11111111-1111-4111-8111-111111111111',
'pty-legacy'
)
expect(syncPanePtyLayoutBinding).not.toHaveBeenCalled()
expect(clearTabPtyId).toHaveBeenCalledWith('legacy-worker', 'pty-legacy')
expect(transport.detach).toHaveBeenCalledOnce()
expect(transport.destroy).not.toHaveBeenCalled()
})
})
describe('suppressIntentionalPaneCloseExit', () => {
it('suppresses the pane PTY exit before intentional close teardown destroys the transport', () => {
const suppressPtyExit = vi.fn()
const transport = {
getPtyId: vi.fn(() => 'pty-pane-2')
}
expect(suppressIntentionalPaneCloseExit(transport, suppressPtyExit)).toBe('pty-pane-2')
expect(suppressPtyExit).toHaveBeenCalledWith('pty-pane-2')
})
it('does not suppress natural PTY exits that already cleared the transport id', () => {
const suppressPtyExit = vi.fn()
const transport = {
getPtyId: vi.fn(() => null)
}
expect(suppressIntentionalPaneCloseExit(transport, suppressPtyExit)).toBeNull()
expect(suppressPtyExit).not.toHaveBeenCalled()
})
})
@@ -85,43 +85,6 @@ describe('a pane move a client asked this window for', () => {
vi.useRealTimers()
})
it('moves the named pane into the tab the client drew, where the client dropped it', async () => {
const detachPaneToNewTab = vi.fn<DetachTerminalPaneToNewTab>(() => moved('pty-2'))
unmount = mountTab(detachPaneToNewTab)
await expect(
moveTerminalPaneToNewTabForClient({ ...request, targetGroupId: 'group-2', index: 0 })
).resolves.toEqual({ status: 'moved', ptyId: 'pty-2' })
expect(detachPaneToNewTab).toHaveBeenCalledWith(2, {
groupId: 'group-2',
index: 0,
targetTabId: 'client-tab'
})
})
it('puts the tab beside its source when this window has no such drop group', async () => {
const detachPaneToNewTab = vi.fn<DetachTerminalPaneToNewTab>(() => moved('pty-2'))
unmount = mountTab(detachPaneToNewTab)
await moveTerminalPaneToNewTabForClient({ ...request, targetGroupId: 'gone', index: 3 })
expect(detachPaneToNewTab).toHaveBeenCalledWith(2, {
groupId: 'group-1',
targetTabId: 'client-tab'
})
})
it('mounts a parked source tab, then moves its pane', async () => {
const detachPaneToNewTab = vi.fn<DetachTerminalPaneToNewTab>(() => moved('pty-2'))
const answer = moveTerminalPaneToNewTabForClient(request)
expect(requestBackgroundTerminalWorktreeMount).toHaveBeenCalledWith({
worktreeId: 'wt-1',
tabIds: ['tab-1']
})
unmount = mountTab(detachPaneToNewTab)
await expect(answer).resolves.toEqual({ status: 'moved', ptyId: 'pty-2' })
})
it('keeps a parked source tab mounted until a move slower than the mount lease settles', async () => {
const detached = Promise.withResolvers<Awaited<ReturnType<DetachTerminalPaneToNewTab>>>()
const answer = moveTerminalPaneToNewTabForClient(request)
@@ -133,12 +96,4 @@ describe('a pane move a client asked this window for', () => {
await expect(answer).resolves.toEqual({ status: 'moved', ptyId: 'pty-2' })
expect(hasTerminalPaneSplitMountLease('tab-1', 'wt-1')).toBe(false)
})
it('refuses when the source tab does not mount, so the client puts the pane back', async () => {
const answer = moveTerminalPaneToNewTabForClient(request)
await vi.runAllTimersAsync()
await expect(answer).resolves.toEqual({ status: 'refused', reason: 'pane_unavailable' })
expect(hasTerminalPaneSplitMountLease('tab-1', 'wt-1')).toBe(false)
})
})
@@ -1,288 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type {
TerminalLeafMoveRequest,
TerminalLeafMoveResult
} from '../../../../../../shared/workspace-layout/terminal-leaf-move'
import { detachTerminalPaneToTab } from './terminal-pane-tab-detach'
import {
createStore,
LEAF_1,
LEAF_2,
SOURCE_TAB_ID,
splitLayout,
TARGET_GROUP_ID,
unboundSplitLayout,
WORKTREE_ID
} from './terminal-pane-tab-detach-fixture'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/layout-owner-switch'
// Window-side IPC coverage; main-command/frame equivalents live in terminal-pane-tab-detach-main-commit.test.ts.
const itSwitchOff = it.skipIf(ORCA_LAYOUT_OWNER_IS_MAIN)
const toastErrorMock = vi.hoisted(() => vi.fn())
vi.mock('sonner', () => ({ toast: { error: toastErrorMock } }))
const closeTerminalSurface = vi.fn(async () => {})
beforeEach(() => {
toastErrorMock.mockClear()
closeTerminalSurface.mockClear()
vi.spyOn(console, 'warn').mockImplementation(() => {})
})
/** Answers each call with the next result; an Error throws. */
function mainAnswering(results: (TerminalLeafMoveResult | Error)[]) {
return vi.fn((_request: TerminalLeafMoveRequest): Promise<TerminalLeafMoveResult> => {
const next = results.shift() ?? { status: 'not_held' }
return next instanceof Error ? Promise.reject(next) : Promise.resolve(next)
})
}
function managerWithPanes(paneIds: () => number[] = () => [1, 2]) {
return {
getPanes: vi.fn(() => paneIds().map((id) => ({ id }))),
getLeafId: vi.fn((paneId: number): string | null => (paneId === 2 ? LEAF_2 : LEAF_1)),
detachPaneForExternalMove: vi.fn(() => true)
}
}
type CommitMove = (request: TerminalLeafMoveRequest) => Promise<TerminalLeafMoveResult>
function detach(
overrides: Partial<Parameters<typeof detachTerminalPaneToTab>[0]> & {
commitMove?: CommitMove
store?: ReturnType<typeof createStore>
}
) {
const { commitMove = mainAnswering([]), store = createStore(), ...rest } = overrides
vi.stubGlobal('window', {
api: { pty: { moveLeafToNewTab: commitMove }, session: { closeTerminalSurface } }
})
return detachTerminalPaneToTab({
getStore: () => store,
manager: managerWithPanes(),
persistLayoutSnapshot: vi.fn(),
sourcePaneId: 2,
sourceTabId: SOURCE_TAB_ID,
targetGroupId: TARGET_GROUP_ID,
worktreeId: WORKTREE_ID,
...rest
})
}
const moved: TerminalLeafMoveResult = { status: 'moved', ptyId: 'remote:env-1@@terminal-1' }
describe('detachTerminalPaneToTab rolls a committed move forward', () => {
it('refuses, silently, a pane whose PTY spawn is still in flight', async () => {
const commitMove = mainAnswering([{ status: 'moved', ptyId: null }])
const store = createStore(unboundSplitLayout())
await expect(detach({ commitMove, store, sourceConnectPending: true })).resolves.toBeNull()
expect(commitMove).not.toHaveBeenCalled()
expect(store.createTab).not.toHaveBeenCalled()
expect(toastErrorMock).not.toHaveBeenCalled()
})
it('shows the failure toast and keeps the pane when main refuses or the commit throws', async () => {
for (const results of [
[{ status: 'refused', reason: 'pty_mismatch' } as const],
[new Error('write failed')]
]) {
toastErrorMock.mockClear()
const store = createStore()
const manager = managerWithPanes()
await expect(
detach({ commitMove: mainAnswering(results), store, manager })
).resolves.toBeNull()
expect(manager.detachPaneForExternalMove).not.toHaveBeenCalled()
expect(store.createTab).not.toHaveBeenCalled()
expect(toastErrorMock).toHaveBeenCalledOnce()
}
})
itSwitchOff(
'closes main’s new tab, without a toast, when the user closed the pane meanwhile',
async () => {
let paneIds = [1, 2]
const manager = managerWithPanes(() => paneIds)
const commitMove = vi.fn(
async (_request: TerminalLeafMoveRequest): Promise<TerminalLeafMoveResult> => {
paneIds = [1]
manager.getLeafId.mockImplementation((paneId) => (paneId === 1 ? LEAF_1 : null))
return moved
}
)
const store = createStore()
await expect(detach({ commitMove, manager, store })).resolves.toBeNull()
const targetTabId = commitMove.mock.calls[0]?.[0]?.targetTabId
expect(closeTerminalSurface).toHaveBeenCalledWith({
worktreeId: WORKTREE_ID,
target: { kind: 'tab', tabId: targetTabId },
reason: 'cleanup'
})
expect(store.createTab).not.toHaveBeenCalled()
expect(toastErrorMock).not.toHaveBeenCalled()
}
)
itSwitchOff('closes main’s new tab when the user closed the source tab meanwhile', async () => {
const store = createStore()
const commitMove = vi.fn(
async (_request: TerminalLeafMoveRequest): Promise<TerminalLeafMoveResult> => {
// A tab close drops its row and its layout.
store.tabsByWorktree[WORKTREE_ID] = []
delete store.terminalLayoutsByTabId[SOURCE_TAB_ID]
return moved
}
)
await expect(detach({ commitMove, store })).resolves.toBeNull()
expect(closeTerminalSurface).toHaveBeenCalledOnce()
expect(store.createTab).not.toHaveBeenCalled()
})
itSwitchOff('finds the pane by its leaf when its pane id changed meanwhile', async () => {
const manager = managerWithPanes(() => [1, 7])
manager.getLeafId.mockImplementation((paneId) => (paneId === 1 ? LEAF_1 : LEAF_2))
const commitMove = vi.fn(
async (_request: TerminalLeafMoveRequest): Promise<TerminalLeafMoveResult> => {
manager.getLeafId.mockImplementation((paneId) =>
paneId === 1 ? LEAF_1 : paneId === 7 ? LEAF_2 : null
)
return moved
}
)
await expect(detach({ commitMove, manager })).resolves.toMatchObject({ leafId: LEAF_2 })
expect(manager.detachPaneForExternalMove).toHaveBeenCalledWith(7)
})
itSwitchOff(
'closes main’s new tab when the pane manager refuses to detach the pane',
async () => {
const manager = managerWithPanes()
manager.detachPaneForExternalMove.mockReturnValue(false)
const commitMove = mainAnswering([moved])
const store = createStore()
await expect(detach({ commitMove, manager, store })).resolves.toBeNull()
expect(closeTerminalSurface).toHaveBeenCalledWith({
worktreeId: WORKTREE_ID,
target: { kind: 'tab', tabId: commitMove.mock.calls[0]?.[0]?.targetTabId },
reason: 'cleanup'
})
expect(store.createTab).not.toHaveBeenCalled()
expect(store.setTabLayout).not.toHaveBeenCalled()
}
)
itSwitchOff(
'moves the last pane, after a sibling closed meanwhile, without killing its PTY',
async () => {
const store = createStore()
let paneIds = [1, 2]
const manager = managerWithPanes(() => paneIds)
const commitMove = vi.fn(async (_request: TerminalLeafMoveRequest) => {
// Closing a pane persists the layout synchronously (onLayoutChanged), as the real close does.
paneIds = [2]
store.terminalLayoutsByTabId[SOURCE_TAB_ID] = {
root: { type: 'leaf', leafId: LEAF_2 },
activeLeafId: LEAF_2,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF_2]: 'pty-right' }
}
return { status: 'moved', ptyId: 'pty-right' } satisfies TerminalLeafMoveResult
})
await expect(detach({ commitMove, manager, store })).resolves.toMatchObject({
leafId: LEAF_2,
ptyId: 'pty-right'
})
expect(closeTerminalSurface).not.toHaveBeenCalled()
expect(manager.detachPaneForExternalMove).not.toHaveBeenCalled()
expect(store.createTab).toHaveBeenCalledOnce()
expect(store.syncPaneDetachPtyOwnership).toHaveBeenCalledWith(
expect.objectContaining({ detachedLeafId: LEAF_2, detachedPtyId: 'pty-right' })
)
expect(store.closeTab).toHaveBeenCalledWith(
SOURCE_TAB_ID,
expect.objectContaining({ localPtyTeardownOwnedExternally: true })
)
}
)
itSwitchOff(
'commits the move in main before the target tab exists, using the same tab id',
async () => {
const store = createStore()
let release!: () => void
const commitMove = vi.fn(
(_request: TerminalLeafMoveRequest) =>
new Promise<TerminalLeafMoveResult>((resolve) => {
release = () => resolve(moved)
})
)
const detaching = detach({ commitMove, store })
await vi.waitFor(() => expect(commitMove).toHaveBeenCalledOnce())
expect(store.createTab).not.toHaveBeenCalled()
release()
await detaching
const request = commitMove.mock.calls[0]?.[0]
expect(request).toEqual({
worktreeId: WORKTREE_ID,
sourceTabId: SOURCE_TAB_ID,
targetTabId: expect.any(String),
leafId: LEAF_2,
ptyId: expect.any(String)
})
expect(store.createTab).toHaveBeenCalledWith(
WORKTREE_ID,
TARGET_GROUP_ID,
'powershell.exe',
expect.objectContaining({ id: request?.targetTabId, initialLeafId: LEAF_2 })
)
}
)
itSwitchOff('ignores a repeat drop of a pane whose move is still committing', async () => {
const store = createStore()
let release!: () => void
const commitMove = vi.fn(
(_request: TerminalLeafMoveRequest) =>
new Promise<TerminalLeafMoveResult>((resolve) => {
release = () => resolve(moved)
})
)
const first = detach({ commitMove, store })
await vi.waitFor(() => expect(commitMove).toHaveBeenCalledOnce())
await expect(detach({ commitMove, store })).resolves.toBeNull()
release()
await expect(first).resolves.toMatchObject({ leafId: LEAF_2 })
expect(commitMove).toHaveBeenCalledOnce()
expect(toastErrorMock).not.toHaveBeenCalled()
})
itSwitchOff('binds the moved tab’s layout to the live PTY, not the saved one', async () => {
const store = createStore(splitLayout())
const saved = store.terminalLayoutsByTabId[SOURCE_TAB_ID]?.ptyIdsByLeafId?.[LEAF_2]
expect(saved).toBeTruthy()
const result = await detach({ livePtyId: 'pty-respawned', store })
expect(result?.ptyId).toBe('pty-respawned')
expect(store.terminalLayoutsByTabId['tab-detached']?.ptyIdsByLeafId?.[LEAF_2]).toBe(
'pty-respawned'
)
})
})
@@ -1,303 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type * as AgentStatusModule from '../../../../../../shared/agent-status/title/agent-title-status'
import type { sendLayoutCommandToOwner } from '@/runtime/layout-owner-command'
import { createTestStore, seedStore } from '../../../../store/testing/app-store-test-fixture'
import { makeWorktree } from '../../../../store/slices/worktrees/worktree.test-fixture'
import { createStoreCascadesMockApi } from '../../../../store/testing/app-store-cascade-api.test-fixture'
import { detachTerminalPaneToTab } from './terminal-pane-tab-detach'
import { buildWorkspaceSessionPayload } from '@/lib/workspace/persistence/workspace-session'
import { buildLayoutFrameSlices } from '../../../../store/workspace-layout/frames/workspace-layout-frame-slices'
import { buildLayoutFrameStorePatch } from '../../../../store/workspace-layout/frames/workspace-layout-frame-store-patch'
import { applyLayoutCommand } from '../../../../../../shared/workspace-layout/workspace-layout-commands'
import { testContext } from '../../../../../../shared/workspace-layout/workspace-layout-command.test-fixture'
import { loadWorkspaceLayoutWithoutReport } from '../../../../../../shared/workspace-layout/workspace-layout-load'
import { nameBasedLoadContext } from '../../../../../../shared/workspace-layout/workspace-layout-minted-ids'
import { publishWorkspaceLayout } from '../../../../../../shared/workspace-layout/workspace-layout-published'
import { LEAF_1, LEAF_2, splitLayout } from './terminal-pane-tab-detach-fixture'
import { LOCAL_LAYOUT_APPLY_ORIGIN } from '@/runtime/server-layout-apply-routes'
const mocks = vi.hoisted(() => ({
send: vi.fn<typeof sendLayoutCommandToOwner>(),
callRuntimeRpc: vi.fn(async (..._args: unknown[]) => ({ ok: true, result: {} }))
}))
vi.mock('../../../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true }))
vi.mock('@/runtime/layout-owner-command', () => ({ sendLayoutCommandToOwner: mocks.send }))
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({
callRuntimeRpc: mocks.callRuntimeRpc
}))
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: vi.fn(),
unregisterPtyDataHandlers: vi.fn(() => [])
}))
vi.mock(
'../../../../../../shared/agent-status/title/agent-title-status',
async (importOriginal) => {
const actual = await importOriginal<typeof AgentStatusModule>()
return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) }
}
)
createStoreCascadesMockApi()
const WT = 'repo1::/path/wt'
const SOURCE = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'
const MOVED = 'bbbbbbbb-cccc-4ddd-8eee-ffffffffffff'
const GROUP = 'group-1'
function row(id: string, ptyId: string, createdAt: number) {
return {
id,
ptyId,
worktreeId: WT,
title: 'Terminal 1',
defaultTitle: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt
}
}
function entry(id: string, createdAt: number) {
return {
id,
entityId: id,
groupId: GROUP,
worktreeId: WT,
contentType: 'terminal' as const,
label: 'Terminal 1',
customLabel: null,
color: null,
sortOrder: 0,
createdAt
}
}
/** The source tab split in two, and main's frame already showing the tab the pane moved into. */
function storeWithFrameDrawnMove() {
const store = createTestStore()
seedStore(store, {
worktreesByRepo: { repo1: [makeWorktree({ id: WT, repoId: 'repo1', path: '/path/wt' })] },
tabsByWorktree: { [WT]: [row(SOURCE, 'pty-left', 1), row(MOVED, 'pty-right', 2)] },
unifiedTabsByWorktree: { [WT]: [entry(SOURCE, 1), entry(MOVED, 2)] },
groupsByWorktree: {
[WT]: [
{
id: GROUP,
worktreeId: WT,
activeTabId: SOURCE,
tabOrder: [SOURCE, MOVED],
recentTabIds: [SOURCE]
}
]
},
activeGroupIdByWorktree: { [WT]: GROUP },
terminalLayoutsByTabId: {
[SOURCE]: {
...splitLayout(),
ptyIdsByLeafId: { [LEAF_1]: 'pty-left', [LEAF_2]: 'pty-right' }
},
[MOVED]: {
root: { type: 'leaf', leafId: LEAF_2 },
activeLeafId: LEAF_2,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF_2]: 'pty-right' }
}
}
})
return store
}
/** The source tab alone, split in two, its second pane showing chat. */
function storeWithChatSplit() {
const store = createTestStore()
seedStore(store, {
worktreesByRepo: { repo1: [makeWorktree({ id: WT, repoId: 'repo1', path: '/path/wt' })] },
tabsByWorktree: { [WT]: [row(SOURCE, 'pty-left', 1)] },
unifiedTabsByWorktree: { [WT]: [{ ...entry(SOURCE, 1), viewMode: 'chat' }] },
groupsByWorktree: {
[WT]: [
{ id: GROUP, worktreeId: WT, activeTabId: SOURCE, tabOrder: [SOURCE], recentTabIds: [] }
]
},
activeGroupIdByWorktree: { [WT]: GROUP },
terminalLayoutsByTabId: {
[SOURCE]: {
...splitLayout(),
chatLeafId: LEAF_2,
ptyIdsByLeafId: { [LEAF_1]: 'pty-left', [LEAF_2]: 'pty-right' }
}
}
})
return store
}
/** The source tab split in two, its second pane not yet bound to a terminal. */
function storeWithUnboundSplit() {
const store = storeWithChatSplit()
const layout = store.getState().terminalLayoutsByTabId[SOURCE]!
store.setState({
unifiedTabsByWorktree: { [WT]: [entry(SOURCE, 1)] },
terminalLayoutsByTabId: {
[SOURCE]: { ...layout, chatLeafId: undefined, ptyIdsByLeafId: { [LEAF_1]: 'pty-left' } }
}
})
return store
}
type MoveCommand = Parameters<typeof sendLayoutCommandToOwner>[1] & { type: 'movePaneToNewTab' }
/** Main applies the window's drag-out to its copy and the frame with the result is drawn. */
function drawMainMove(
store: ReturnType<typeof createTestStore>,
windowDetach: MoveCommand['windowDetach'] = { ptyId: 'pty-right' }
): void {
const state = store.getState()
const loaded = loadWorkspaceLayoutWithoutReport(
'local',
buildWorkspaceSessionPayload(state),
nameBasedLoadContext()
)
const applied = applyLayoutCommand(
loaded.layout,
{
type: 'movePaneToNewTab',
workspace: WT,
tabId: SOURCE,
leafId: LEAF_2,
groupId: GROUP,
windowDetach: { ...windowDetach, tabId: MOVED }
},
testContext()
)
if (!applied.ok) {
throw new Error(`main refused the move: ${applied.code}`)
}
const slices = buildLayoutFrameSlices({
layouts: { [WT]: publishWorkspaceLayout(applied.model.workspaces[WT]!, 'local') },
facts: loaded.facts,
view: loaded.desktopView
})
store.setState(buildLayoutFrameStorePatch(state, slices, [WT]))
}
beforeEach(() => {
mocks.send.mockReset()
mocks.callRuntimeRpc.mockClear()
vi.stubGlobal('window', { api: { pty: { moveLeafToNewTab: vi.fn() } } })
})
describe('a drag-out whose new tab main’s frame drew first', () => {
it('shows the pane in the tab the frame drew instead of making a second one', async () => {
const store = storeWithFrameDrawnMove()
mocks.send.mockImplementation((_worktreeId, _command, handlers) => {
handlers.apply({ tabId: MOVED, ptyId: 'pty-right' }, LOCAL_LAYOUT_APPLY_ORIGIN)
return true
})
const moved = await detachTerminalPaneToTab({
getStore: () => store.getState(),
manager: {
getPanes: () => [{ id: 1 }, { id: 2 }],
getLeafId: (paneId: number) => (paneId === 2 ? LEAF_2 : LEAF_1),
detachPaneForExternalMove: () => true
},
persistLayoutSnapshot: vi.fn(),
sourcePaneId: 2,
sourceTabId: SOURCE,
targetGroupId: GROUP,
worktreeId: WT
})
expect(moved).toMatchObject({ leafId: LEAF_2, ptyId: 'pty-right', tab: { id: MOVED } })
const state = store.getState()
expect(state.tabsByWorktree[WT]!.map((tab) => tab.id)).toEqual([SOURCE, MOVED])
expect(state.terminalLayoutsByTabId[SOURCE]!.root).toEqual({ type: 'leaf', leafId: LEAF_1 })
expect(state.terminalLayoutsByTabId[MOVED]!.root).toEqual({ type: 'leaf', leafId: LEAF_2 })
expect(state.activeTabIdByWorktree[WT]).toBe(MOVED)
})
it('leaves the tab where main’s frame placed it, asked for an index', async () => {
const store = storeWithFrameDrawnMove()
mocks.send.mockImplementation((_worktreeId, _command, handlers) => {
handlers.apply({ tabId: MOVED, ptyId: 'pty-right' }, LOCAL_LAYOUT_APPLY_ORIGIN)
return true
})
await detachTerminalPaneToTab({
getStore: () => store.getState(),
manager: {
getPanes: () => [{ id: 1 }, { id: 2 }],
getLeafId: (paneId: number) => (paneId === 2 ? LEAF_2 : LEAF_1),
detachPaneForExternalMove: () => true
},
persistLayoutSnapshot: vi.fn(),
sourcePaneId: 2,
sourceTabId: SOURCE,
targetGroupId: GROUP,
targetIndex: 0,
worktreeId: WT
})
expect(store.getState().groupsByWorktree[WT]![0]!.tabOrder).toEqual([SOURCE, MOVED])
})
it('opens a dragged-out chat pane’s tab in chat view, as a window-owned build does', async () => {
const store = storeWithChatSplit()
mocks.send.mockImplementation((_worktreeId, _command, handlers) => {
drawMainMove(store)
handlers.apply({ tabId: MOVED, ptyId: 'pty-right' }, LOCAL_LAYOUT_APPLY_ORIGIN)
return true
})
await detachTerminalPaneToTab({
getStore: () => store.getState(),
manager: {
getPanes: () => [{ id: 1 }, { id: 2 }],
getLeafId: (paneId: number) => (paneId === 2 ? LEAF_2 : LEAF_1),
detachPaneForExternalMove: () => true
},
persistLayoutSnapshot: vi.fn(),
sourcePaneId: 2,
sourceTabId: SOURCE,
targetGroupId: GROUP,
worktreeId: WT
})
const moved = store.getState().unifiedTabsByWorktree[WT]!.find((tab) => tab.entityId === MOVED)
expect(moved?.viewMode).toBe('chat')
expect(store.getState().terminalLayoutsByTabId[MOVED]?.chatLeafId).toBe(LEAF_2)
})
it('starts an unbound pane’s new tab in the pane’s folder, as a window-owned build does', async () => {
const store = storeWithUnboundSplit()
mocks.send.mockImplementation((_worktreeId, command, handlers) => {
drawMainMove(store, command.type === 'movePaneToNewTab' ? command.windowDetach : undefined)
handlers.apply({ tabId: MOVED, ptyId: null }, LOCAL_LAYOUT_APPLY_ORIGIN)
return true
})
await detachTerminalPaneToTab({
getStore: () => store.getState(),
manager: {
getPanes: () => [{ id: 1 }, { id: 2 }],
getLeafId: (paneId: number) => (paneId === 2 ? LEAF_2 : LEAF_1),
detachPaneForExternalMove: () => true
},
persistLayoutSnapshot: vi.fn(),
sourcePaneCwd: { cwd: '/path/wt/packages/app', confirmed: false },
sourcePaneId: 2,
sourceTabId: SOURCE,
targetGroupId: GROUP,
worktreeId: WT
})
const moved = store.getState().tabsByWorktree[WT]!.find((tab) => tab.id === MOVED)
expect(moved).toMatchObject({ startupCwd: '/path/wt/packages/app' })
})
})
@@ -7,11 +7,9 @@ import { createStoreCascadesMockApi } from '../../../../store/testing/app-store-
import { LEAF_1, LEAF_2, splitLayout } from './terminal-pane-tab-detach-fixture'
import {
detachFrom,
GROUP,
mainMovedTabId,
openMainFrames,
seedDetachStore,
sentMove,
SOURCE,
twoPaneManager,
WT,
@@ -124,20 +122,6 @@ describe('detachTerminalPaneToTab rolls main’s committed move forward (layout-
expectOnlyMainTabs(store)
})
it('finds the pane by its leaf when its pane id changed meanwhile', async () => {
const store = await seeded()
const manager = twoPaneManager()
const move = await moveHeldByMain(() => detachFrom(store, { manager }))
manager.getPanes.mockImplementation(() => [{ id: 1 }, { id: 7 }])
manager.getLeafId.mockImplementation((paneId) =>
paneId === 1 ? LEAF_1 : paneId === 7 ? LEAF_2 : null
)
await expect(move.answer()).resolves.toMatchObject({ leafId: LEAF_2 })
expect(manager.detachPaneForExternalMove).toHaveBeenCalledWith(7)
})
it('moves the last pane, after a sibling closed meanwhile, without killing its PTY', async () => {
const store = await seeded({
...splitLayout(),
@@ -173,53 +157,4 @@ describe('detachTerminalPaneToTab rolls main’s committed move forward (layout-
expect(api.pty.kill).not.toHaveBeenCalledWith('pty-right', expect.anything())
expect(api.pty.kill).not.toHaveBeenCalledWith('pty-right')
})
it('commits the move in main before the target tab exists, then shows main’s tab', async () => {
const store = await seeded()
const tabsBefore = store.getState().tabsByWorktree[WT]?.map((tab) => tab.id)
const move = await moveHeldByMain(() => detachFrom(store))
expect(sentMove()).toEqual({
type: 'movePaneToNewTab',
workspace: WT,
tabId: SOURCE,
leafId: LEAF_2,
groupId: GROUP,
windowDetach: { ptyId: 'remote:env-1@@terminal-1' }
})
expect(store.getState().tabsByWorktree[WT]?.map((tab) => tab.id)).toEqual(tabsBefore)
const result = await move.answer()
const movedId = mainMovedTabId()
expect(result?.tab.id).toBe(movedId)
expect(store.getState().terminalLayoutsByTabId[movedId]?.root).toEqual({
type: 'leaf',
leafId: LEAF_2
})
})
it('ignores a repeat drop of a pane whose move is still committing', async () => {
const store = await seeded()
const move = await moveHeldByMain(() => detachFrom(store))
await expect(detachFrom(store)).resolves.toBeNull()
await expect(move.answer()).resolves.toMatchObject({ leafId: LEAF_2 })
expect(main.sentOfType('movePaneToNewTab')).toHaveLength(1)
expect(toast.error).not.toHaveBeenCalled()
})
it('binds the moved tab’s layout to the live PTY, not the saved one', async () => {
const store = await seeded()
const saved = store.getState().terminalLayoutsByTabId[SOURCE]?.ptyIdsByLeafId?.[LEAF_2]
expect(saved).toBeTruthy()
const result = await detachFrom(store, { livePtyId: 'pty-respawned' })
expect(sentMove().windowDetach).toEqual({ ptyId: 'pty-respawned' })
expect(result?.ptyId).toBe('pty-respawned')
expect(store.getState().terminalLayoutsByTabId[mainMovedTabId()]?.ptyIdsByLeafId).toEqual({
[LEAF_2]: 'pty-respawned'
})
})
})
@@ -3,14 +3,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as AgentStatusModule from '../../../../../../shared/agent-status/title/agent-title-status'
import { buildWorkspaceSessionPayload } from '@/lib/workspace/persistence/workspace-session'
import { createStoreCascadesMockApi } from '../../../../store/testing/app-store-cascade-api.test-fixture'
import { LEAF_1, LEAF_2, splitLayout, unboundSplitLayout } from './terminal-pane-tab-detach-fixture'
import { LEAF_1, LEAF_2, splitLayout } from './terminal-pane-tab-detach-fixture'
import {
detachFrom,
GROUP,
mainMovedTabId,
openMainFrames,
OTHER_1,
OTHER_2,
seedDetachStore,
sentMove,
SOURCE,
@@ -66,23 +64,6 @@ function movedRow(store: DetachStore) {
}
describe('detachTerminalPaneToTab, main moving the pane (layout-owner build)', () => {
it.each([LEAF_1, LEAF_2])('moves chat mode only with its owning leaf %s', async (chatLeafId) => {
const store = await seeded({ ...splitLayout(), chatLeafId })
await detachFrom(store)
const movedId = mainMovedTabId()
const state = store.getState()
const movedTab = state.unifiedTabsByWorktree[WT]?.find((tab) => tab.entityId === movedId)
expect(movedTab?.viewMode ?? 'terminal').toBe(chatLeafId === LEAF_2 ? 'chat' : 'terminal')
expect(state.terminalLayoutsByTabId[movedId]?.chatLeafId).toBe(
chatLeafId === LEAF_2 ? LEAF_2 : undefined
)
expect(state.terminalLayoutsByTabId[SOURCE]?.chatLeafId).toBe(
chatLeafId === LEAF_1 ? LEAF_1 : undefined
)
})
it('shows main’s new terminal tab holding the moved pane and its terminal', async () => {
const store = await seeded(splitLayout(), { shellOverride: 'powershell.exe', sshRepo: true })
const manager = twoPaneManager()
@@ -131,92 +112,4 @@ describe('detachTerminalPaneToTab, main moving the pane (layout-owner build)', (
expect(state.activeTabTypeByWorktree[WT]).toBe('terminal')
expect(persistLayoutSnapshot).toHaveBeenCalled()
})
it.each(['powershell.exe', 'wsl.exe'])(
'preserves the moved PTY shell override when the source uses %s',
async (shellOverride) => {
const store = await seeded(splitLayout(), { shellOverride })
await detachFrom(store, { sourcePaneId: 1 })
expect(sentMove()).toMatchObject({ leafId: LEAF_1, windowDetach: { ptyId: 'pty-left' } })
expect(movedRow(store)).toMatchObject({ shellOverride })
expect(store.getState().ptyIdsByTabId[mainMovedTabId()]).toEqual(['pty-left'])
}
)
it('syncs PTY ownership when the primary source pane is detached', async () => {
const store = await seeded(splitLayout())
const result = await detachFrom(store, { sourcePaneId: 1 })
const movedId = mainMovedTabId()
expect(result?.ptyId).toBe('pty-left')
const state = store.getState()
expect(state.terminalLayoutsByTabId[SOURCE]).toMatchObject({
root: { type: 'leaf', leafId: LEAF_2 },
activeLeafId: LEAF_2,
ptyIdsByLeafId: { [LEAF_2]: 'remote:env-1@@terminal-1' },
titlesByLeafId: { [LEAF_2]: 'remote shell' }
})
expect(state.terminalLayoutsByTabId[movedId]?.root).toEqual({ type: 'leaf', leafId: LEAF_1 })
expect(state.ptyIdsByTabId[SOURCE]).toEqual(['remote:env-1@@terminal-1'])
expect(state.ptyIdsByTabId[movedId]).toEqual(['pty-left'])
})
it('moves the detached tab into the requested group slot', async () => {
const store = await seeded(splitLayout())
await detachFrom(store, { targetIndex: 1 })
expect(sentMove()).toMatchObject({ groupId: GROUP, index: 1 })
expect(store.getState().groupsByWorktree[WT]?.[0]?.tabOrder).toEqual([
OTHER_1,
mainMovedTabId(),
OTHER_2,
SOURCE
])
})
it('uses the live transport PTY id when the snapshot has not persisted it yet', async () => {
const store = await seeded(unboundSplitLayout())
await detachFrom(store, {
livePtyId: 'remote:env-2@@terminal-9',
sourcePaneCwd: {
cwd: '/remote/repo',
confirmed: false,
deferredSplitSpawn: true,
pendingCwd: Promise.resolve('/remote/repo/packages/app')
}
})
expect(sentMove().windowDetach).toMatchObject({ ptyId: 'remote:env-2@@terminal-9' })
expect(store.getState().terminalLayoutsByTabId[mainMovedTabId()]).toMatchObject({
root: { type: 'leaf', leafId: LEAF_2 },
activeLeafId: LEAF_2,
ptyIdsByLeafId: { [LEAF_2]: 'remote:env-2@@terminal-9' }
})
})
it('carries resolved cwd when detaching an unbound non-deferred pane', async () => {
const store = await seeded(unboundSplitLayout(), { shellOverride: 'powershell.exe' })
const result = await detachFrom(store, {
sourcePaneCwd: { cwd: '/remote/repo/packages/app', confirmed: false }
})
expect(sentMove().windowDetach).toEqual({
ptyId: null,
startupCwd: '/remote/repo/packages/app'
})
expect(result?.ptyId).toBeNull()
expect(movedRow(store)).toMatchObject({
ptyId: null,
shellOverride: 'powershell.exe',
startupCwd: '/remote/repo/packages/app',
pendingActivationSpawn: true
})
expect(store.getState().activeTabIdByWorktree[WT]).toBe(mainMovedTabId())
})
})
@@ -1,417 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { detachTerminalPaneToTab } from './terminal-pane-tab-detach'
import {
createStore,
EXISTING_TAB_1,
EXISTING_TAB_2,
LEAF_1,
LEAF_2,
SOURCE_TAB_ID,
splitLayout,
TARGET_GROUP_ID,
unboundSplitLayout,
WORKTREE_ID
} from './terminal-pane-tab-detach-fixture'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/layout-owner-switch'
// Window-created tab coverage; main-command/frame equivalents live in terminal-pane-tab-detach-main-move.test.ts.
const itSwitchOff = it.skipIf(ORCA_LAYOUT_OWNER_IS_MAIN)
const toastErrorMock = vi.hoisted(() => vi.fn())
vi.mock('sonner', () => ({ toast: { error: toastErrorMock } }))
beforeEach(() => {
toastErrorMock.mockClear()
// No local main holds these sessions, so each move stays in the renderer.
vi.stubGlobal('window', {
api: { pty: { moveLeafToNewTab: () => Promise.resolve({ status: 'not_held' }) } }
})
})
type SourcePaneCwd = NonNullable<Parameters<typeof detachTerminalPaneToTab>[0]['sourcePaneCwd']>
async function expectDeferredSplitDetachRejected(sourcePaneCwd: SourcePaneCwd): Promise<void> {
const store = createStore(unboundSplitLayout())
const manager = {
getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]),
getLeafId: vi.fn(() => LEAF_2),
detachPaneForExternalMove: vi.fn(() => true)
}
const persistLayoutSnapshot = vi.fn()
const result = await detachTerminalPaneToTab({
getStore: () => store,
manager,
persistLayoutSnapshot,
sourcePaneCwd,
sourcePaneId: 2,
sourceTabId: SOURCE_TAB_ID,
targetGroupId: TARGET_GROUP_ID,
worktreeId: WORKTREE_ID
})
expect(result).toBeNull()
expect(persistLayoutSnapshot).not.toHaveBeenCalled()
expect(manager.detachPaneForExternalMove).not.toHaveBeenCalled()
expect(store.createTab).not.toHaveBeenCalled()
expect(store.setTabLayout).not.toHaveBeenCalled()
expect(store.syncPaneDetachPtyOwnership).not.toHaveBeenCalled()
expect(store.setActiveTab).not.toHaveBeenCalled()
expect(store.setActiveTabType).not.toHaveBeenCalled()
}
describe('detachTerminalPaneToTab', () => {
itSwitchOff.each([LEAF_1, LEAF_2])(
'moves chat mode only with its owning leaf %s',
async (chatLeafId) => {
const store = createStore({ ...splitLayout(), chatLeafId })
await detachTerminalPaneToTab({
getStore: () => store,
manager: {
getPanes: () => [{ id: 1 }, { id: 2 }],
getLeafId: () => LEAF_2,
detachPaneForExternalMove: () => true
},
persistLayoutSnapshot: vi.fn(),
sourcePaneId: 2,
sourceTabId: SOURCE_TAB_ID,
targetGroupId: TARGET_GROUP_ID,
worktreeId: WORKTREE_ID
})
const options = vi.mocked(store.createTab).mock.calls[0]?.[3]
expect(options?.viewMode ?? 'terminal').toBe(chatLeafId === LEAF_2 ? 'chat' : 'terminal')
expect(store.terminalLayoutsByTabId['tab-detached']?.chatLeafId).toBe(
chatLeafId === LEAF_2 ? LEAF_2 : undefined
)
expect(store.terminalLayoutsByTabId[SOURCE_TAB_ID]?.chatLeafId).toBe(
chatLeafId === LEAF_1 ? LEAF_1 : undefined
)
}
)
itSwitchOff('creates a new terminal tab with the detached leaf layout and PTY id', async () => {
const store = createStore()
const manager = {
getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]),
getLeafId: vi.fn((paneId: number) => (paneId === 2 ? LEAF_2 : LEAF_1)),
detachPaneForExternalMove: vi.fn(() => true)
}
const persistLayoutSnapshot = vi.fn()
const result = await detachTerminalPaneToTab({
manager,
getStore: () => store,
persistLayoutSnapshot,
sourcePaneCwd: {
cwd: '/remote/repo',
confirmed: false,
deferredSplitSpawn: true,
pendingCwd: Promise.resolve('/remote/repo/packages/app')
},
sourcePaneId: 2,
sourceTabId: SOURCE_TAB_ID,
targetGroupId: TARGET_GROUP_ID,
worktreeId: WORKTREE_ID
})
expect(result?.ptyId).toBe('remote:env-1@@terminal-1')
expect(manager.detachPaneForExternalMove).toHaveBeenCalledWith(2)
expect(store.createTab).toHaveBeenCalledWith(WORKTREE_ID, TARGET_GROUP_ID, 'powershell.exe', {
id: expect.any(String),
activate: true,
initialPtyId: 'remote:env-1@@terminal-1',
initialLeafId: LEAF_2,
recordInteraction: true
})
expect(store.setTabLayout).toHaveBeenCalledWith(SOURCE_TAB_ID, {
root: { type: 'leaf', leafId: LEAF_1 },
activeLeafId: LEAF_1,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF_1]: 'pty-left' }
})
expect(store.setTabLayout).toHaveBeenCalledWith('tab-detached', {
root: { type: 'leaf', leafId: LEAF_2 },
activeLeafId: LEAF_2,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF_2]: 'remote:env-1@@terminal-1' },
buffersByLeafId: { [LEAF_2]: 'remote-buffer' },
titlesByLeafId: { [LEAF_2]: 'remote shell' }
})
expect(store.syncPaneDetachPtyOwnership).toHaveBeenCalledWith({
detachedLeafId: LEAF_2,
detachedPtyId: 'remote:env-1@@terminal-1',
sourceLayout: {
root: { type: 'leaf', leafId: LEAF_1 },
activeLeafId: LEAF_1,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF_1]: 'pty-left' }
},
sourceTabId: SOURCE_TAB_ID,
targetTabId: 'tab-detached'
})
expect(store.setActiveTab).toHaveBeenCalledWith('tab-detached')
expect(store.setActiveTabType).toHaveBeenCalledWith('terminal', WORKTREE_ID)
expect(persistLayoutSnapshot).toHaveBeenCalled()
})
itSwitchOff.each(['powershell.exe', 'wsl.exe'])(
'preserves the moved PTY shell override when the source uses %s',
async (shellOverride) => {
const store = createStore(splitLayout(), [EXISTING_TAB_1], shellOverride)
const manager = {
getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]),
getLeafId: vi.fn(() => LEAF_1),
detachPaneForExternalMove: vi.fn(() => true)
}
await detachTerminalPaneToTab({
getStore: () => store,
manager,
persistLayoutSnapshot: vi.fn(),
sourcePaneId: 1,
sourceTabId: SOURCE_TAB_ID,
targetGroupId: TARGET_GROUP_ID,
worktreeId: WORKTREE_ID
})
expect(store.createTab).toHaveBeenCalledWith(
WORKTREE_ID,
TARGET_GROUP_ID,
shellOverride,
expect.objectContaining({ initialPtyId: 'pty-left' })
)
}
)
itSwitchOff('syncs PTY ownership when the primary source pane is detached', async () => {
const store = createStore()
const manager = {
getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]),
getLeafId: vi.fn((paneId: number) => (paneId === 1 ? LEAF_1 : LEAF_2)),
detachPaneForExternalMove: vi.fn(() => true)
}
const result = await detachTerminalPaneToTab({
getStore: () => store,
manager,
persistLayoutSnapshot: vi.fn(),
sourcePaneId: 1,
sourceTabId: SOURCE_TAB_ID,
targetGroupId: TARGET_GROUP_ID,
worktreeId: WORKTREE_ID
})
expect(result?.ptyId).toBe('pty-left')
expect(store.setTabLayout).toHaveBeenCalledWith(SOURCE_TAB_ID, {
root: { type: 'leaf', leafId: LEAF_2 },
activeLeafId: LEAF_2,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF_2]: 'remote:env-1@@terminal-1' },
buffersByLeafId: { [LEAF_2]: 'remote-buffer' },
titlesByLeafId: { [LEAF_2]: 'remote shell' }
})
expect(store.syncPaneDetachPtyOwnership).toHaveBeenCalledWith({
detachedLeafId: LEAF_1,
detachedPtyId: 'pty-left',
sourceLayout: {
root: { type: 'leaf', leafId: LEAF_2 },
activeLeafId: LEAF_2,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF_2]: 'remote:env-1@@terminal-1' },
buffersByLeafId: { [LEAF_2]: 'remote-buffer' },
titlesByLeafId: { [LEAF_2]: 'remote shell' }
},
sourceTabId: SOURCE_TAB_ID,
targetTabId: 'tab-detached'
})
})
itSwitchOff('names the new tab as the client that already drew it did', async () => {
const moveLeafToNewTab = vi.fn(() => Promise.resolve({ status: 'moved', ptyId: 'pty-left' }))
vi.stubGlobal('window', { api: { pty: { moveLeafToNewTab } } })
const store = createStore()
const manager = {
getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]),
getLeafId: vi.fn((paneId: number) => (paneId === 1 ? LEAF_1 : LEAF_2)),
detachPaneForExternalMove: vi.fn(() => true)
}
await detachTerminalPaneToTab({
getStore: () => store,
manager,
persistLayoutSnapshot: vi.fn(),
sourcePaneId: 1,
sourceTabId: SOURCE_TAB_ID,
targetGroupId: TARGET_GROUP_ID,
targetTabId: 'client-drawn-tab',
worktreeId: WORKTREE_ID
})
expect(moveLeafToNewTab).toHaveBeenCalledWith(
expect.objectContaining({ targetTabId: 'client-drawn-tab', leafId: LEAF_1 })
)
expect(store.createTab).toHaveBeenCalledWith(
WORKTREE_ID,
TARGET_GROUP_ID,
'powershell.exe',
expect.objectContaining({ id: 'client-drawn-tab' })
)
})
itSwitchOff.each([
["this window's own drag", undefined, 1],
["another client's move", 'client-drawn-tab', 0]
])('reports a refused move as a toast only for %s', async (_label, targetTabId, toasts) => {
const moveLeafToNewTab = vi.fn(() =>
Promise.resolve({ status: 'refused', reason: 'target_tab_exists' })
)
vi.stubGlobal('window', { api: { pty: { moveLeafToNewTab } } })
const store = createStore()
const manager = {
getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]),
getLeafId: vi.fn((paneId: number) => (paneId === 1 ? LEAF_1 : LEAF_2)),
detachPaneForExternalMove: vi.fn(() => true)
}
await expect(
detachTerminalPaneToTab({
getStore: () => store,
manager,
persistLayoutSnapshot: vi.fn(),
sourcePaneId: 1,
sourceTabId: SOURCE_TAB_ID,
targetGroupId: TARGET_GROUP_ID,
...(targetTabId ? { targetTabId } : {}),
worktreeId: WORKTREE_ID
})
).resolves.toBeNull()
expect(toastErrorMock).toHaveBeenCalledTimes(toasts)
})
itSwitchOff('moves the detached tab into the requested group slot', async () => {
const store = createStore(splitLayout(), [EXISTING_TAB_1, EXISTING_TAB_2])
const manager = {
getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]),
getLeafId: vi.fn((paneId: number) => (paneId === 2 ? LEAF_2 : LEAF_1)),
detachPaneForExternalMove: vi.fn(() => true)
}
await detachTerminalPaneToTab({
getStore: () => store,
manager,
persistLayoutSnapshot: vi.fn(),
sourcePaneId: 2,
sourceTabId: SOURCE_TAB_ID,
targetGroupId: TARGET_GROUP_ID,
targetIndex: 1,
worktreeId: WORKTREE_ID
})
expect(store.reorderUnifiedTabs).toHaveBeenCalledWith(
TARGET_GROUP_ID,
[EXISTING_TAB_1, 'tab-detached', EXISTING_TAB_2],
{ recordInteraction: false, layoutOwnerHandled: false }
)
})
itSwitchOff(
'uses the live transport PTY id when the snapshot has not persisted it yet',
async () => {
const store = createStore({
root: {
type: 'split',
direction: 'vertical',
first: { type: 'leaf', leafId: LEAF_1 },
second: { type: 'leaf', leafId: LEAF_2 }
},
activeLeafId: LEAF_2,
expandedLeafId: null
})
const manager = {
getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]),
getLeafId: vi.fn(() => LEAF_2),
detachPaneForExternalMove: vi.fn(() => true)
}
await detachTerminalPaneToTab({
livePtyId: 'remote:env-2@@terminal-9',
getStore: () => store,
manager,
persistLayoutSnapshot: vi.fn(),
sourcePaneCwd: {
cwd: '/remote/repo',
confirmed: false,
deferredSplitSpawn: true,
pendingCwd: Promise.resolve('/remote/repo/packages/app')
},
sourcePaneId: 2,
sourceTabId: SOURCE_TAB_ID,
targetGroupId: TARGET_GROUP_ID,
worktreeId: WORKTREE_ID
})
expect(store.setTabLayout).toHaveBeenCalledWith('tab-detached', {
root: { type: 'leaf', leafId: LEAF_2 },
activeLeafId: LEAF_2,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF_2]: 'remote:env-2@@terminal-9' }
})
}
)
it('rejects a deferred split while inherited cwd is pending', async () => {
await expectDeferredSplitDetachRejected({
cwd: '/remote/repo',
deferredSplitSpawn: true,
pendingCwd: new Promise<string>(() => {})
})
})
it('rejects a pending cwd even when the deferred marker is absent', async () => {
await expectDeferredSplitDetachRejected({
cwd: '/remote/repo',
pendingCwd: new Promise<string>(() => {})
})
})
it('still rejects a deferred split after cwd resolves but before PTY bind', async () => {
await expectDeferredSplitDetachRejected({
cwd: '/remote/repo/packages/app',
confirmed: false,
deferredSplitSpawn: true
})
})
itSwitchOff('carries resolved cwd when detaching an unbound non-deferred pane', async () => {
const store = createStore(unboundSplitLayout())
const manager = {
getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]),
getLeafId: vi.fn(() => LEAF_2),
detachPaneForExternalMove: vi.fn(() => true)
}
const result = await detachTerminalPaneToTab({
getStore: () => store,
manager,
persistLayoutSnapshot: vi.fn(),
sourcePaneCwd: {
cwd: '/remote/repo/packages/app',
confirmed: false
},
sourcePaneId: 2,
sourceTabId: SOURCE_TAB_ID,
targetGroupId: TARGET_GROUP_ID,
worktreeId: WORKTREE_ID
})
expect(result?.ptyId).toBeNull()
expect(store.createTab).toHaveBeenCalledWith(WORKTREE_ID, TARGET_GROUP_ID, 'powershell.exe', {
id: expect.any(String),
activate: true,
pendingActivationSpawn: true,
recordInteraction: true,
startupCwd: '/remote/repo/packages/app'
})
})
})
@@ -1,138 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AppState } from '@/store/types'
import { resolveTerminalTabStripDropTarget } from './terminal-tab-strip-drop-target'
import {
EXISTING_TAB_1,
EXISTING_TAB_2,
TARGET_GROUP_ID,
WORKTREE_ID
} from './terminal-pane-tab-detach-fixture'
const toastErrorMock = vi.hoisted(() => vi.fn())
vi.mock('sonner', () => ({ toast: { error: toastErrorMock } }))
beforeEach(() => {
toastErrorMock.mockClear()
// No local main holds these sessions, so each move stays in the renderer.
vi.stubGlobal('window', {
api: { pty: { moveLeafToNewTab: () => Promise.resolve({ status: 'not_held' }) } }
})
})
function rect(args: { left: number; top: number; width: number; height: number }): DOMRect {
return {
left: args.left,
top: args.top,
right: args.left + args.width,
bottom: args.top + args.height,
width: args.width,
height: args.height
} as DOMRect
}
describe('resolveTerminalTabStripDropTarget', () => {
afterEach(() => {
vi.unstubAllGlobals()
})
it('finds a same-worktree tab strip under overlay elements', () => {
const stripRect = rect({ left: 0, top: 0, width: 300, height: 32 })
const strip = {
dataset: { tabGroupStripId: TARGET_GROUP_ID, worktreeId: WORKTREE_ID },
getBoundingClientRect: () => stripRect,
querySelectorAll: () => []
}
const overlay = { closest: () => null }
const child = { closest: () => strip }
vi.stubGlobal('document', {
elementsFromPoint: vi.fn(() => [overlay, child]),
elementFromPoint: vi.fn()
})
expect(
resolveTerminalTabStripDropTarget({
clientX: 10,
clientY: 10,
groupsByWorktree: {
[WORKTREE_ID]: [{ id: TARGET_GROUP_ID } as AppState['groupsByWorktree'][string][number]]
},
worktreeId: WORKTREE_ID
})
).toEqual({
id: TARGET_GROUP_ID,
groupId: TARGET_GROUP_ID,
worktreeId: WORKTREE_ID,
rect: stripRect
})
})
it('resolves the insertion slot from the hovered tab side', () => {
const stripRect = rect({ left: 0, top: 0, width: 300, height: 32 })
const firstTabRect = rect({ left: 0, top: 0, width: 80, height: 32 })
const secondTabRect = rect({ left: 80, top: 0, width: 80, height: 32 })
const firstTab = {
dataset: { tabId: EXISTING_TAB_1 },
getBoundingClientRect: () => firstTabRect
}
const secondTab = {
dataset: { tabId: EXISTING_TAB_2 },
getBoundingClientRect: () => secondTabRect
}
const strip = {
dataset: { tabGroupStripId: TARGET_GROUP_ID, worktreeId: WORKTREE_ID },
getBoundingClientRect: () => stripRect,
querySelectorAll: () => [firstTab, secondTab]
}
vi.stubGlobal('document', {
elementsFromPoint: vi.fn(() => [{ closest: () => firstTab }, { closest: () => strip }]),
elementFromPoint: vi.fn()
})
expect(
resolveTerminalTabStripDropTarget({
clientX: 60,
clientY: 10,
groupsByWorktree: {
[WORKTREE_ID]: [
{
id: TARGET_GROUP_ID,
activeTabId: EXISTING_TAB_1,
tabOrder: [EXISTING_TAB_1, EXISTING_TAB_2],
worktreeId: WORKTREE_ID
} as AppState['groupsByWorktree'][string][number]
]
},
worktreeId: WORKTREE_ID
})
).toMatchObject({
groupId: TARGET_GROUP_ID,
insertionIndex: 1,
overlayKind: 'insertion',
rect: rect({ left: 80, top: 0, width: 2, height: 32 })
})
})
it('ignores strips from another worktree', () => {
const strip = {
dataset: { tabGroupStripId: TARGET_GROUP_ID, worktreeId: 'other-worktree' },
getBoundingClientRect: () =>
({ left: 0, top: 0, right: 300, bottom: 32, width: 300, height: 32 }) as DOMRect
}
vi.stubGlobal('document', {
elementsFromPoint: vi.fn(() => [{ closest: () => strip }]),
elementFromPoint: vi.fn()
})
expect(
resolveTerminalTabStripDropTarget({
clientX: 10,
clientY: 10,
groupsByWorktree: {
[WORKTREE_ID]: [{ id: TARGET_GROUP_ID } as AppState['groupsByWorktree'][string][number]]
},
worktreeId: WORKTREE_ID
})
).toBeNull()
})
})
@@ -1,126 +0,0 @@
// @vitest-environment happy-dom
import { cleanup, renderHook } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { PaneManager } from '@/lib/pane-manager/pane-manager'
import type { PtyTransport } from '../../pty-transport/pty-transport-types'
import { useExpandCollapseActions } from './expanded-pane-layout'
import { useTerminalKeyboardShortcuts } from '../../input/keyboard/terminal-keyboard-hook'
type ExpandCollapseHookState = Parameters<typeof useExpandCollapseActions>[0]
type KeyboardHandlersDeps = Parameters<typeof useTerminalKeyboardShortcuts>[0]
// Match TerminalPane’s stable fields inside a newly allocated dependency wrapper each render.
function createStableFields(): Omit<ExpandCollapseHookState, 'tabId'> {
return {
expandedPaneIdRef: { current: null },
expandedStyleSnapshotRef: { current: new Map() },
containerRef: { current: null },
managerRef: { current: null },
setExpandedPaneId: vi.fn(),
setTabPaneExpanded: vi.fn(),
pendingPaneSizeRefreshFrameIdsRef: { current: [] },
persistLayoutSnapshot: vi.fn()
}
}
afterEach(() => {
cleanup()
vi.restoreAllMocks()
})
describe('useExpandCollapseActions render stability', () => {
it('keeps all five action identities across rerenders that rebuild the state object', () => {
const fields = createStableFields()
const hook = renderHook(() => useExpandCollapseActions({ ...fields, tabId: 'tab-1' }))
const first = hook.result.current
hook.rerender()
hook.rerender()
const actionNames = Object.keys(first) as (keyof typeof first)[]
expect(actionNames).toHaveLength(5)
for (const name of actionNames) {
expect(Object.is(hook.result.current[name], first[name])).toBe(true)
}
})
it('remints actions when tabId changes', () => {
const fields = createStableFields()
const hook = renderHook(({ tabId }) => useExpandCollapseActions({ ...fields, tabId }), {
initialProps: { tabId: 'tab-1' }
})
const first = hook.result.current
hook.rerender({ tabId: 'tab-2' })
expect(Object.is(hook.result.current.setExpandedPane, first.setExpandedPane)).toBe(false)
})
})
describe('terminal keyboard effect registration stability', () => {
it('registers window listeners once across rerenders with TerminalPane-shaped wiring', () => {
const scope = document.createElement('div')
document.body.append(scope)
const pane = {
id: 1,
leafId: '00000000-0000-4000-8000-000000000001',
terminal: { element: scope, focus: vi.fn(), getSelection: vi.fn(() => '') }
}
const manager = {
getActivePane: () => pane,
getPanes: () => [pane]
} as unknown as PaneManager
const transport = { getPtyId: () => 'pty-1', sendInput: vi.fn(() => true) }
const fields = createStableFields()
const stableDeps = {
tabId: 'tab-1',
worktreeId: 'worktree-1',
isActive: true,
keyboardScopeRef: { current: scope },
managerRef: { current: manager },
paneTransportsRef: {
current: new Map([[pane.id, transport as unknown as PtyTransport]])
},
panePtyBindingsRef: { current: new Map() },
paneCwdRef: { current: new Map() },
fallbackCwd: '',
expandedPaneIdRef: { current: null },
setSearchOpen: vi.fn(),
focusSearchInput: vi.fn(),
onSearchSelectedText: vi.fn(),
onRequestClosePane: vi.fn(),
onClearPaneScrollback: vi.fn(),
onSetTitle: vi.fn(),
onClearPaneTitle: vi.fn(),
searchOpenRef: { current: false },
searchStateRef: { current: { query: '', caseSensitive: false, regex: false } },
macOptionAsAltRef: { current: 'false' as const }
}
const addSpy = vi.spyOn(window, 'addEventListener')
const countBeforeinputAdds = (): number =>
addSpy.mock.calls.filter(([type]) => type === 'beforeinput').length
const hook = renderHook(() => {
// Same wiring shape as TerminalPane: both dep objects are rebuilt every render.
const actions = useExpandCollapseActions({ ...fields, tabId: stableDeps.tabId })
useTerminalKeyboardShortcuts({
...stableDeps,
setExpandedPane: actions.setExpandedPane,
restoreExpandedLayout: actions.restoreExpandedLayout,
refreshPaneSizes: actions.refreshPaneSizes,
persistLayoutSnapshot: fields.persistLayoutSnapshot,
toggleExpandPane: actions.toggleExpandPane
} as KeyboardHandlersDeps)
})
expect(countBeforeinputAdds()).toBe(1)
for (let render = 0; render < 10; render++) {
hook.rerender()
}
expect(countBeforeinputAdds()).toBe(1)
hook.unmount()
scope.remove()
})
})
@@ -1,99 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
cancelPendingPaneSizeRefreshFrames,
createExpandCollapseActions
} from './expanded-pane-layout'
type ExpandCollapseStateForTest = Parameters<typeof createExpandCollapseActions>[0]
function ref<T>(current: T): React.MutableRefObject<T> {
return { current }
}
function createState(
overrides: Partial<ExpandCollapseStateForTest> = {}
): ExpandCollapseStateForTest {
return {
expandedPaneIdRef: ref(null),
expandedStyleSnapshotRef: ref(new Map()),
containerRef: ref(null),
managerRef: ref(null),
pendingPaneSizeRefreshFrameIdsRef: ref([]),
setExpandedPaneId: vi.fn(),
setTabPaneExpanded: vi.fn(),
tabId: 'tab-1',
persistLayoutSnapshot: vi.fn(),
...overrides
}
}
describe('createExpandCollapseActions', () => {
afterEach(() => {
vi.unstubAllGlobals()
})
it('cancels pending pane-size refresh frames', () => {
const cancelAnimationFrame = vi.fn()
vi.stubGlobal(
'requestAnimationFrame',
vi.fn(() => 42)
)
vi.stubGlobal('cancelAnimationFrame', cancelAnimationFrame)
const state = createState()
createExpandCollapseActions(state).refreshPaneSizes(true)
expect(state.pendingPaneSizeRefreshFrameIdsRef.current).toEqual([42])
cancelPendingPaneSizeRefreshFrames(state)
expect(cancelAnimationFrame).toHaveBeenCalledWith(42)
expect(state.pendingPaneSizeRefreshFrameIdsRef.current).toEqual([])
})
it('forgets completed pane-size refresh frames', () => {
const callbacks: FrameRequestCallback[] = []
vi.stubGlobal(
'requestAnimationFrame',
vi.fn((next: FrameRequestCallback) => {
callbacks.push(next)
return 7
})
)
vi.stubGlobal('cancelAnimationFrame', vi.fn())
const state = createState({
managerRef: ref({
getPanes: () => [],
getActivePane: () => null
} as never)
})
createExpandCollapseActions(state).refreshPaneSizes(false)
expect(state.pendingPaneSizeRefreshFrameIdsRef.current).toEqual([7])
const callback = callbacks[0]
if (!callback) {
throw new Error('expected pane-size refresh frame to be scheduled')
}
callback(16)
expect(state.pendingPaneSizeRefreshFrameIdsRef.current).toEqual([])
})
it('does not retain synchronously completed pane-size refresh frames', () => {
vi.stubGlobal(
'requestAnimationFrame',
vi.fn((callback: FrameRequestCallback) => {
callback(16)
return 9
})
)
vi.stubGlobal('cancelAnimationFrame', vi.fn())
const state = createState()
createExpandCollapseActions(state).refreshPaneSizes(false)
expect(state.pendingPaneSizeRefreshFrameIdsRef.current).toEqual([])
})
})
@@ -1,100 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { PaneManager } from '@/lib/pane-manager/pane-manager'
import { equalizeTerminalPanes } from './terminal-pane-layout-owner-commands'
import {
_resetLayoutFramePositionForTests,
beginLayoutFramePositions,
endLayoutFramePositions
} from '@/runtime/layout-frame-position'
import { provideServerLayoutApplyRoutes } from '@/runtime/server-layout-apply-routes'
const mocks = vi.hoisted(
(): {
callRuntimeRpc: ReturnType<typeof vi.fn>
ownerEnvironmentId: string | null
layoutOwnerIsMain: boolean
} => ({
callRuntimeRpc: vi.fn(),
ownerEnvironmentId: null,
layoutOwnerIsMain: false
})
)
vi.mock('../../../../../../shared/layout-owner-switch', () => ({
get ORCA_LAYOUT_OWNER_IS_MAIN() {
return mocks.layoutOwnerIsMain
}
}))
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({
callRuntimeRpc: mocks.callRuntimeRpc
}))
vi.mock('@/store/index', () => ({ useAppStore: { getState: () => ({}) } }))
vi.mock('@/lib/resolve-owner', () => ({
runtimeEnvironmentIdUnlessTwin: () => mocks.ownerEnvironmentId
}))
describe('equalizeTerminalPanes', () => {
beforeEach(() => {
mocks.callRuntimeRpc.mockReset()
mocks.ownerEnvironmentId = null
mocks.layoutOwnerIsMain = false
_resetLayoutFramePositionForTests()
})
function manager() {
const equalizePaneSizes = vi.fn()
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: equalize calls only equalizePaneSizes.
return { equalizePaneSizes } as unknown as PaneManager & {
equalizePaneSizes: typeof equalizePaneSizes
}
}
it('a layout-owner build equalizes itself when no frame is coming', async () => {
mocks.layoutOwnerIsMain = true
beginLayoutFramePositions()
endLayoutFramePositions()
mocks.callRuntimeRpc.mockResolvedValue({ ok: true, result: {} })
const current = manager()
const then = vi.fn()
equalizeTerminalPanes(
{ worktreeId: 'worktree-1', tabId: 'tab-1', getManager: () => current },
then
)
await vi.waitFor(() => expect(then).toHaveBeenCalledWith(current))
expect(current.equalizePaneSizes).toHaveBeenCalledOnce()
})
it('leaves a paired server’s panes to that server’s frames, whatever this window’s stream does', async () => {
mocks.layoutOwnerIsMain = true
mocks.ownerEnvironmentId = 'env-1'
// This window's own stream is down; the server's frames draw the workspace.
const stop = provideServerLayoutApplyRoutes('env-1', () => ({
environmentId: 'env-1',
serverTabId: () => 'server-tab-1',
desktopTabId: (id) => id,
redraw: vi.fn()
}))
mocks.callRuntimeRpc.mockResolvedValue({ ok: true, result: {} })
const current = manager()
const then = vi.fn()
try {
equalizeTerminalPanes(
{ worktreeId: 'worktree-1', tabId: 'tab-1', getManager: () => current },
then
)
expect(mocks.callRuntimeRpc).toHaveBeenCalledWith(
{ kind: 'environment', environmentId: 'env-1' },
'layout.apply',
{ command: { type: 'equalizePanes', tabId: 'server-tab-1', workspace: 'worktree-1' } }
)
await vi.waitFor(() => expect(then).toHaveBeenCalledWith(current))
expect(current.equalizePaneSizes).not.toHaveBeenCalled()
} finally {
stop()
}
})
})
@@ -12,8 +12,6 @@ const { notePendingPaneTitleRename } = await import('@/runtime/pending-pane-titl
const { toRemoteRuntimePtyId } =
await import('../../../../../../shared/remote-runtime/remote-runtime-pty-id')
const PERSISTS = 100
function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
let resolve = (_value: T): void => undefined
const promise = new Promise<T>((complete) => {
@@ -44,124 +42,6 @@ describe('createRemotePaneLayoutPusher', () => {
updateWebRuntimePaneLayout.mockReset().mockResolvedValue(true)
})
it('pushes once across 100 persists of an unchanged layout', () => {
const pusher = createRemotePaneLayoutPusher()
for (let i = 0; i < PERSISTS; i += 1) {
// Fresh object each time: persistLayoutSnapshot re-serializes on every call.
pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() })
}
expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(1)
})
it('sends the same payload the un-deduped path sent', () => {
const pusher = createRemotePaneLayoutPusher()
const layout = makeLayout()
pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout })
expect(updateWebRuntimePaneLayout).toHaveBeenCalledWith({
worktreeId: 'wt-1',
tabId: 'tab-1',
root: layout.root,
expandedLeafId: layout.expandedLeafId,
chatLeafId: null,
titlesByLeafId: layout.titlesByLeafId
})
})
it('omits titlesByLeafId when the layout carries no titles', () => {
const pusher = createRemotePaneLayoutPusher()
pusher.push({
worktreeId: 'wt-1',
tabId: 'tab-1',
layout: makeLayout({ titlesByLeafId: undefined })
})
expect(updateWebRuntimePaneLayout.mock.calls[0][0]).not.toHaveProperty('titlesByLeafId')
})
it('publishes owner changes and an explicit clear without a geometry change', () => {
const pusher = createRemotePaneLayoutPusher()
for (const chatLeafId of ['leaf-a', 'leaf-b', undefined]) {
pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout({ chatLeafId }) })
}
expect(updateWebRuntimePaneLayout.mock.calls.map(([args]) => args.chatLeafId)).toEqual([
'leaf-a',
'leaf-b',
null
])
})
it('pushes again for every host-visible change', () => {
const pusher = createRemotePaneLayoutPusher()
pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() })
pusher.push({
worktreeId: 'wt-1',
tabId: 'tab-1',
layout: makeLayout({ expandedLeafId: 'leaf-a' })
})
pusher.push({
worktreeId: 'wt-1',
tabId: 'tab-1',
layout: makeLayout({
expandedLeafId: 'leaf-a',
titlesByLeafId: { 'leaf-a': 'test' }
})
})
pusher.push({
worktreeId: 'wt-1',
tabId: 'tab-1',
layout: makeLayout({
expandedLeafId: 'leaf-a',
titlesByLeafId: { 'leaf-a': 'test' },
root: {
type: 'split',
direction: 'vertical',
ratio: 0.7,
first: { type: 'leaf', leafId: 'leaf-a' },
second: { type: 'leaf', leafId: 'leaf-b' }
}
})
})
expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(4)
})
it('pushes again when a remote pane swaps its pty', () => {
// ptyIdsByLeafId is not in the payload, but a swap means a different host session.
const pusher = createRemotePaneLayoutPusher()
pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() })
pusher.push({
worktreeId: 'wt-1',
tabId: 'tab-1',
layout: makeLayout({ ptyIdsByLeafId: { 'leaf-a': 'remote:pty-c', 'leaf-b': 'remote:pty-b' } })
})
expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(2)
})
it('does not carry a cached layout across tabs', () => {
const pusher = createRemotePaneLayoutPusher()
pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() })
pusher.push({ worktreeId: 'wt-1', tabId: 'tab-2', layout: makeLayout() })
pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() })
expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(3)
})
it('does not carry a cached layout across worktrees', () => {
const pusher = createRemotePaneLayoutPusher()
pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() })
pusher.push({ worktreeId: 'wt-2', tabId: 'tab-1', layout: makeLayout() })
expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(2)
})
it('retries an unchanged layout after a failed push', async () => {
updateWebRuntimePaneLayout.mockResolvedValueOnce(false)
const pusher = createRemotePaneLayoutPusher()
const input = { worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() }
pusher.push(input)
await Promise.resolve()
pusher.push(input)
expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(2)
})
it('does not let a stale failure invalidate a newer in-flight layout', async () => {
const first = deferred<boolean>()
const second = deferred<boolean>()
@@ -180,17 +60,6 @@ describe('createRemotePaneLayoutPusher', () => {
second.resolve(true)
})
it('re-pushes after a remount re-establishes host geometry', () => {
const pusher = createRemotePaneLayoutPusher()
pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() })
createRemotePaneLayoutPusher().push({
worktreeId: 'wt-1',
tabId: 'tab-1',
layout: makeLayout()
})
expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(2)
})
it('names a renamed pane in its push, and again in the retry after that push fails', async () => {
const remote = { 'leaf-a': toRemoteRuntimePtyId('pty-a', 'env-1') }
notePendingPaneTitleRename({
@@ -215,23 +84,4 @@ describe('createRemotePaneLayoutPusher', () => {
expect(sent[1]).toMatchObject({ renamedLeafIds: ['leaf-a'] })
expect(sent[2]).not.toHaveProperty('renamedLeafIds')
})
it('sends a rename back to the title the last push carried', () => {
const remote = { 'leaf-b': toRemoteRuntimePtyId('pty-b', 'env-1') }
const pusher = createRemotePaneLayoutPusher()
const layout = makeLayout()
pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout })
// The host renamed leaf-b meanwhile; the user names it back to what the last push held.
notePendingPaneTitleRename({
leafId: 'leaf-b',
title: null,
layout: makeLayout({ ptyIdsByLeafId: remote, titlesByLeafId: { 'leaf-b': 'host' } })
})
pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout })
expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(2)
expect(updateWebRuntimePaneLayout.mock.calls[1]?.[0]).toMatchObject({
renamedLeafIds: ['leaf-b']
})
})
})