test: remove 129 low-value definitions and four whole suites (#41000)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-10 19:29:10 -08:00
committed by GitHub
co-authored by OrcaWin
parent 81d3091515
commit 8ef629becd
19 changed files with 42 additions and 6116 deletions
@@ -2,14 +2,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
TerminalStreamOpcode,
decodeTerminalStreamFrame,
decodeTerminalStreamJson,
decodeTerminalStreamText
} from '../../../../../../shared/terminal/stream/terminal-stream-protocol'
import {
TERMINAL_INPUT_CHUNK_MAX_BYTES,
TERMINAL_INPUT_MAX_BYTES
} from '../../../../../../shared/terminal/input/terminal-input'
import { CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS } from '../../../../../../shared/clipboard-text'
import { TERMINAL_INPUT_CHUNK_MAX_BYTES } from '../../../../../../shared/terminal/input/terminal-input'
import { createRemoteRuntimeTransportMocks } from '../remote/remote-runtime-pty-transport-test-harness'
import type { MultiplexSubscriptionCallbacks } from '../remote/remote-runtime-pty-transport-stream-fixtures'
@@ -33,8 +28,6 @@ const {
runtimeSubscribe,
subscriptionSendBinary,
emitMultiplexReady,
latestSubscribePayload,
latestFrameForOpcode,
resetRemoteRuntimeTransport
} = createRemoteRuntimeTransportMocks({
getCallbacks: () => subscriptionCallbacks,
@@ -52,76 +45,6 @@ describe('createRemoteRuntimePtyTransport', () => {
resetRemoteRuntimeTransport()
})
it('resubscribes with the latest pane viewport after the remote stream closes', async () => {
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
await transport.connect({ url: '', cols: 80, rows: 24, callbacks: {} })
await vi.waitFor(() => expect(subscriptionSendBinary).toHaveBeenCalled())
expect(latestSubscribePayload().viewport).toEqual({ cols: 80, rows: 24 })
expect(transport.resize(132, 43)).toBe(true)
subscriptionCallbacks?.onClose?.()
await vi.waitFor(() => expect(runtimeSubscribe).toHaveBeenCalledTimes(2))
await vi.waitFor(() => {
expect(latestSubscribePayload().viewport).toEqual({ cols: 132, rows: 43 })
})
})
it('replays a viewport that changed during the subscribe round-trip once the stream is current', async () => {
// Hold subscribe readiness while resize hits the refresh-only fallback; the resolved stream must replay latest geometry before the viewport timer.
runtimeSubscribe.mockImplementation(
async (_args: unknown, callbacks: typeof subscriptionCallbacks) => {
subscriptionCallbacks = callbacks
return { unsubscribe: vi.fn(), sendBinary: subscriptionSendBinary }
}
)
// Drain only microtasks so the 33ms viewport timer cannot hide a missing round-trip flush.
const flushMicrotasks = async (): Promise<void> => {
for (let i = 0; i < 20; i += 1) {
await Promise.resolve()
}
}
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
transport.attach({
existingPtyId: 'remote:terminal-1',
cols: 80,
rows: 24,
callbacks: {}
})
await vi.waitFor(() => expect(runtimeSubscribe).toHaveBeenCalled())
// Resize while the stream is not yet current (subscribe still pending).
expect(transport.resize(132, 43)).toBe(true)
// Release readiness and drain the resolution chain by microtasks only.
emitMultiplexReady()
await flushMicrotasks()
// The Subscribe frame still carries the subscribe-time viewport...
expect(latestSubscribePayload().viewport).toEqual({ cols: 80, rows: 24 })
// Require newer Resize before the batch timer can produce it.
const resizeFrame = latestFrameForOpcode(TerminalStreamOpcode.Resize)
expect(resizeFrame && decodeTerminalStreamJson(resizeFrame.payload)).toEqual({
cols: 132,
rows: 43
})
transport.destroy?.()
})
it('replays a claim before separately framed input and query replies', async () => {
vi.useFakeTimers()
try {
@@ -180,184 +103,6 @@ describe('createRemoteRuntimePtyTransport', () => {
}
})
it('coalesces rapid remote terminal input before sending it to the runtime', async () => {
vi.useFakeTimers()
try {
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
await transport.connect({ url: '', callbacks: {} })
const { streamId } = latestSubscribePayload()
runtimeCall.mockClear()
subscriptionSendBinary.mockClear()
expect(transport.sendInput('a', 'driving')).toBe(true)
expect(transport.sendInput('b', 'driving')).toBe(true)
expect(runtimeCall).not.toHaveBeenCalled()
await vi.runOnlyPendingTimersAsync()
expect(runtimeCall).not.toHaveBeenCalled()
expect(subscriptionSendBinary).toHaveBeenCalledTimes(1)
const frame = decodeTerminalStreamFrame(subscriptionSendBinary.mock.calls[0][0])
expect(frame?.opcode).toBe(TerminalStreamOpcode.Input)
expect(frame?.streamId).toBe(streamId)
expect(frame ? decodeTerminalStreamText(frame.payload) : '').toBe('ab')
} finally {
vi.useRealTimers()
}
})
it('flushes a full terminal input chunk before the following input', async () => {
vi.useFakeTimers()
try {
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
await transport.connect({ url: '', callbacks: {} })
const { streamId } = latestSubscribePayload()
runtimeCall.mockClear()
subscriptionSendBinary.mockClear()
const chunk = 'x'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES)
expect(transport.sendInput(chunk, 'driving')).toBe(true)
expect(subscriptionSendBinary).toHaveBeenCalledTimes(1)
let frame = decodeTerminalStreamFrame(subscriptionSendBinary.mock.calls[0][0])
expect(frame?.opcode).toBe(TerminalStreamOpcode.Input)
expect(frame?.streamId).toBe(streamId)
expect(frame ? decodeTerminalStreamText(frame.payload) : '').toBe(chunk)
expect(transport.sendInput('tail', 'driving')).toBe(true)
await vi.runOnlyPendingTimersAsync()
expect(runtimeCall).not.toHaveBeenCalled()
expect(subscriptionSendBinary).toHaveBeenCalledTimes(2)
frame = decodeTerminalStreamFrame(subscriptionSendBinary.mock.calls[1][0])
expect(frame?.opcode).toBe(TerminalStreamOpcode.Input)
expect(frame?.streamId).toBe(streamId)
expect(frame ? decodeTerminalStreamText(frame.payload) : '').toBe('tail')
} finally {
vi.useRealTimers()
}
})
it('returns runtime acceptance for acknowledged terminal input', async () => {
runtimeCall.mockImplementation((args) => {
if (args.method === 'terminal.create') {
return Promise.resolve({ ok: true, result: { terminal: { handle: 'terminal-1' } } })
}
if (args.method === 'terminal.send') {
return Promise.resolve({
ok: true,
result: { send: { handle: 'terminal-1', accepted: true, bytesWritten: 1 } }
})
}
return Promise.resolve({ ok: true, result: {} })
})
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
await transport.connect({ url: '', callbacks: {} })
await expect(transport.sendInputAccepted?.('\x03', 'driving')).resolves.toBe(true)
expect(runtimeCall).toHaveBeenCalledWith({
selector: 'env-1',
method: 'terminal.send',
params: {
terminal: 'terminal-1',
text: '\x03',
client: { id: expect.stringMatching(/^desktop:tab-1:pane:1:/), type: 'desktop' },
viewport: { cols: 80, rows: 24 },
claimViewport: true
},
timeoutMs: 15_000
})
})
it('preserves queued remote input order before acknowledged terminal input', async () => {
vi.useFakeTimers()
try {
runtimeCall.mockImplementation((args) => {
if (args.method === 'terminal.create') {
return Promise.resolve({ ok: true, result: { terminal: { handle: 'terminal-1' } } })
}
if (args.method === 'terminal.send') {
return Promise.resolve({
ok: true,
result: { send: { handle: 'terminal-1', accepted: true, bytesWritten: 2 } }
})
}
return Promise.resolve({ ok: true, result: {} })
})
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
await transport.connect({ url: '', callbacks: {} })
subscriptionSendBinary.mockClear()
expect(transport.sendInput('a', 'driving')).toBe(true)
await expect(transport.sendInputAccepted?.('\x03', 'driving')).resolves.toBe(true)
await vi.runOnlyPendingTimersAsync()
expect(runtimeCall).toHaveBeenCalledWith({
selector: 'env-1',
method: 'terminal.send',
params: {
terminal: 'terminal-1',
text: 'a\x03',
client: { id: expect.stringMatching(/^desktop:tab-1:pane:1:/), type: 'desktop' },
viewport: { cols: 80, rows: 24 },
claimViewport: true
},
timeoutMs: 15_000
})
expect(subscriptionSendBinary).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
}
})
it('returns false when acknowledged terminal input is rejected by the runtime', async () => {
runtimeCall.mockImplementation((args) => {
if (args.method === 'terminal.create') {
return Promise.resolve({ ok: true, result: { terminal: { handle: 'terminal-1' } } })
}
if (args.method === 'terminal.send') {
return Promise.resolve({
ok: true,
result: { send: { handle: 'terminal-1', accepted: false, bytesWritten: 0 } }
})
}
return Promise.resolve({ ok: true, result: {} })
})
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
await transport.connect({ url: '', callbacks: {} })
await expect(transport.sendInputAccepted?.('\x03', 'driving')).resolves.toBe(false)
})
it('splits large acknowledged remote input before terminal.send RPCs', async () => {
runtimeCall.mockImplementation((args) => {
if (args.method === 'terminal.create') {
@@ -394,257 +139,4 @@ describe('createRemoteRuntimePtyTransport', () => {
expect(sendCalls[0]?.[0].params.text).toBe(chunk)
expect(sendCalls[1]?.[0].params.text).toBe('tail')
})
it('yields while validating accepted large acknowledged remote input before terminal.send RPCs', async () => {
vi.useFakeTimers()
try {
runtimeCall.mockImplementation((args) => {
if (args.method === 'terminal.create') {
return Promise.resolve({ ok: true, result: { terminal: { handle: 'terminal-1' } } })
}
if (args.method === 'terminal.send') {
return Promise.resolve({
ok: true,
result: {
send: {
handle: 'terminal-1',
accepted: true,
bytesWritten: args.params.text.length
}
}
})
}
return Promise.resolve({ ok: true, result: {} })
})
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
const text = 'é'.repeat(CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS + 1)
await transport.connect({ url: '', callbacks: {} })
runtimeCall.mockClear()
const accepted = transport.sendInputAccepted?.(text, 'driving')
await Promise.resolve()
expect(runtimeCall).not.toHaveBeenCalled()
await vi.runAllTimersAsync()
await expect(accepted).resolves.toBe(true)
const sendTexts = runtimeCall.mock.calls
.filter((call) => call[0].method === 'terminal.send')
.map((call) => call[0].params.text)
expect(sendTexts.join('')).toBe(text)
} finally {
vi.useRealTimers()
}
})
it('stops large acknowledged remote input after a rejected chunk', async () => {
const firstChunk = 'x'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES)
const rejectedChunk = `tail${'y'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES - 4)}`
runtimeCall.mockImplementation((args) => {
if (args.method === 'terminal.create') {
return Promise.resolve({ ok: true, result: { terminal: { handle: 'terminal-1' } } })
}
if (args.method === 'terminal.send') {
return Promise.resolve({
ok: true,
result: {
send: {
handle: 'terminal-1',
accepted: args.params.text !== rejectedChunk,
bytesWritten: args.params.text === rejectedChunk ? 0 : args.params.text.length
}
}
})
}
return Promise.resolve({ ok: true, result: {} })
})
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
await transport.connect({ url: '', callbacks: {} })
await expect(
transport.sendInputAccepted?.(`${firstChunk}${rejectedChunk}after`, 'driving')
).resolves.toBe(false)
const sendTexts = runtimeCall.mock.calls
.filter((call) => call[0].method === 'terminal.send')
.map((call) => call[0].params.text)
expect(sendTexts).toEqual([firstChunk, rejectedChunk])
})
it('rejects oversized acknowledged remote input before runtime RPCs', async () => {
runtimeCall.mockImplementation((args) => {
if (args.method === 'terminal.create') {
return Promise.resolve({ ok: true, result: { terminal: { handle: 'terminal-1' } } })
}
return Promise.resolve({ ok: true, result: {} })
})
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
await transport.connect({ url: '', callbacks: {} })
runtimeCall.mockClear()
await expect(
transport.sendInputAccepted?.(
'😀'.repeat(Math.floor(TERMINAL_INPUT_MAX_BYTES / 4) + 1),
'driving'
)
).resolves.toBe(false)
expect(runtimeCall).not.toHaveBeenCalled()
})
it('preserves literal LF input when sending remote PTY binary frames', async () => {
vi.useFakeTimers()
try {
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
await transport.connect({ url: '', callbacks: {} })
const { streamId } = latestSubscribePayload()
runtimeCall.mockClear()
subscriptionSendBinary.mockClear()
expect(transport.sendInput('echo one\necho two\r\n', 'driving')).toBe(true)
await vi.runOnlyPendingTimersAsync()
expect(runtimeCall).not.toHaveBeenCalled()
expect(subscriptionSendBinary).toHaveBeenCalledTimes(1)
const frame = decodeTerminalStreamFrame(subscriptionSendBinary.mock.calls[0][0])
expect(frame?.opcode).toBe(TerminalStreamOpcode.Input)
expect(frame?.streamId).toBe(streamId)
expect(frame ? decodeTerminalStreamText(frame.payload) : '').toBe('echo one\necho two\r\n')
} finally {
vi.useRealTimers()
}
})
it('coalesces rapid remote viewport updates before sending the latest size', async () => {
vi.useFakeTimers()
try {
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
await transport.connect({ url: '', callbacks: {} })
const { streamId } = latestSubscribePayload()
runtimeCall.mockClear()
subscriptionSendBinary.mockClear()
expect(transport.resize(80, 24)).toBe(true)
expect(transport.resize(120, 40)).toBe(true)
expect(runtimeCall).not.toHaveBeenCalled()
await vi.runOnlyPendingTimersAsync()
expect(runtimeCall).not.toHaveBeenCalled()
expect(subscriptionSendBinary).toHaveBeenCalledTimes(1)
const frame = decodeTerminalStreamFrame(subscriptionSendBinary.mock.calls[0][0])
expect(frame?.opcode).toBe(TerminalStreamOpcode.Resize)
expect(frame?.streamId).toBe(streamId)
expect(frame ? decodeTerminalStreamJson(frame.payload) : null).toEqual({
cols: 120,
rows: 40
})
} finally {
vi.useRealTimers()
}
})
it('sends an activity claim before the user input it sizes', async () => {
vi.useFakeTimers()
try {
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
await transport.connect({ url: '', callbacks: {} })
const { streamId } = latestSubscribePayload()
subscriptionSendBinary.mockClear()
expect(transport.claimViewport?.(101, 33)).toBe(true)
expect(transport.sendInput('x', 'driving')).toBe(true)
await vi.runOnlyPendingTimersAsync()
const frames = subscriptionSendBinary.mock.calls.map((call) =>
decodeTerminalStreamFrame(call[0])
)
expect(frames.map((frame) => frame?.opcode)).toEqual([
TerminalStreamOpcode.ClaimViewport,
TerminalStreamOpcode.Resize,
TerminalStreamOpcode.Input
])
expect(frames[0]?.streamId).toBe(streamId)
expect(frames[0] ? decodeTerminalStreamJson(frames[0].payload) : null).toEqual({
cols: 101,
rows: 33
})
} finally {
vi.useRealTimers()
}
})
it('bounds query replies buffered during a viewport claim', async () => {
runtimeSubscribe.mockImplementation(
async (_args: unknown, callbacks: typeof subscriptionCallbacks) => {
subscriptionCallbacks = callbacks
return { unsubscribe: vi.fn(), sendBinary: subscriptionSendBinary }
}
)
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
transport.attach({
existingPtyId: 'remote:terminal-1',
cols: 80,
rows: 24,
callbacks: {}
})
await vi.waitFor(() => expect(runtimeSubscribe).toHaveBeenCalled())
expect(transport.claimViewport?.(101, 33)).toBe(true)
for (let index = 0; index < 10_000; index += 1) {
expect(transport.sendInputImmediate(`\x1b[?${index};2c`)).toBe(true)
}
emitMultiplexReady()
await vi.waitFor(() => {
const input = subscriptionSendBinary.mock.calls
.map((call) => decodeTerminalStreamFrame(call[0]))
.filter((frame) => frame?.opcode === TerminalStreamOpcode.Input)
.map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : ''))
expect(input).toHaveLength(64)
expect(input.at(0)).toBe('\x1b[?9936;2c')
expect(input.at(-1)).toBe('\x1b[?9999;2c')
})
transport.destroy?.()
})
})
@@ -8,10 +8,7 @@ import type { ConnectPanePtySession } from '../../pty-connection/connect-pane-pt
import './recovery/remote-runtime-pty-recovery-state'
import { REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS } from './recovery/remote-runtime-pty-recovery-limits'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
createRemoteRuntimeTransportMocks,
readyHostSessionInventoryResponse
} from '../remote/remote-runtime-pty-transport-test-harness'
import { createRemoteRuntimeTransportMocks } from '../remote/remote-runtime-pty-transport-test-harness'
import type { MultiplexSubscriptionCallbacks } from '../remote/remote-runtime-pty-transport-stream-fixtures'
const appStore = vi.hoisted(() => ({
@@ -38,7 +35,6 @@ let resolvedPaneHandle = 'terminal-1'
const {
runtimeCall,
runtimeSubscribe,
latestSubscribePayload,
subscribeFrameCount,
inputFrameTexts,
@@ -55,12 +51,6 @@ const {
}
})
function unreachable(): Error {
return Object.assign(new Error('Remote Orca runtime closed the connection.'), {
code: 'remote_runtime_unavailable'
})
}
const callsTo = (method: string) => runtimeCall.mock.calls.filter(([r]) => r.method === method)
// Every exit from binding a remote pane must leave one owner: the host's answer, or the transport's own retry.
@@ -303,275 +293,4 @@ describe('remote runtime pane binding ownership', () => {
}
}
)
it.each([false, true])(
'resolves create refusal without replay (contact loss: %s)',
async (contactLoss) => {
vi.useFakeTimers()
const defaultCall = runtimeCall.getMockImplementation()
let reachable = !contactLoss
runtimeCall.mockImplementation(async (args: { method: string }) => {
if (args.method === 'terminal.create') {
return {
ok: false,
error: { code: 'runtime_error', message: 'terminal_pane_owner_changed' }
}
}
if (!reachable) {
throw unreachable()
}
return defaultCall?.(args)
})
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
const onError = vi.fn()
try {
const connecting = transport.connect({ url: '', callbacks: { onError } })
if (contactLoss) {
expect(await connecting).toBeUndefined()
await vi.advanceTimersByTimeAsync(REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS + 1)
expect(transport.getRecoveryState?.().phase).toBe('disconnected')
const { createPaneRecoveryReconnect } =
await import('./recovery/TerminalPaneRecoveryPortals')
reachable = true
const retryRecovery = transport.retryRecovery
let accepted: boolean | undefined
transport.retryRecovery = () => (accepted = retryRecovery?.() ?? false)
createPaneRecoveryReconnect(() => transport, null)()
expect(accepted).toBe(true)
}
await vi.waitFor(() => expect(latestSubscribePayload().terminal).toBe('terminal-1'))
emitSnapshot(latestSubscribePayload().streamId, 'recovered$ ')
if (!contactLoss) {
expect(await connecting).toMatchObject({ id: 'remote:env-1@@terminal-1' })
}
await vi.advanceTimersByTimeAsync(20)
expect(transport.isConnected()).toBe(true)
expect(transport.getRecoveryState?.().phase).toBe('connected')
expect(onError).not.toHaveBeenCalled()
expect(callsTo('terminal.create')).toHaveLength(1)
expect(callsTo('terminal.resolvePane')).toHaveLength(contactLoss ? 2 : 1)
} finally {
transport.destroy?.()
vi.useRealTimers()
}
}
)
it('settles an attach whose pane the host no longer knows instead of latching in connecting (#21344)', async () => {
const defaultCall = runtimeCall.getMockImplementation()
runtimeCall.mockImplementation(async (args: { method: string }) => {
if (args.method === 'terminal.resolvePane') {
return { ok: false, error: { code: 'runtime_error', message: 'terminal_not_found' } }
}
return defaultCall?.(args)
})
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const onPtyExit = vi.fn()
const onError = vi.fn()
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1',
onPtyExit
})
transport.attach({
existingPtyId: 'remote:env-1@@terminal-1',
cols: 80,
rows: 24,
callbacks: { onError }
})
await vi.waitFor(() => expect(onPtyExit).toHaveBeenCalled())
// Why -1: the host answered for its registry, but a restarting host can republish later.
expect(onPtyExit).toHaveBeenCalledWith('remote:env-1@@terminal-1', -1)
expect(onError).toHaveBeenCalledWith('Remote terminal was closed.')
expect(transport.getRecoveryState?.().phase).toBe('ended')
expect(transport.ownsRecovery?.()).toBe(false)
expect(transport.sendInput('typed after close', 'driving')).toBe(false)
})
it('retries an attach whose pane lookup lost contact instead of latching in connecting', async () => {
vi.useFakeTimers()
try {
let hostReachable = false
const defaultCall = runtimeCall.getMockImplementation()
runtimeCall.mockImplementation(async (args: { method: string }) => {
if (!hostReachable) {
throw unreachable()
}
return defaultCall?.(args)
})
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const onError = vi.fn()
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
transport.attach({
existingPtyId: 'remote:env-1@@terminal-1',
cols: 80,
rows: 24,
callbacks: { onError }
})
await vi.advanceTimersByTimeAsync(0)
expect(transport.getRecoveryState?.().phase).toBe('backoff')
expect(transport.ownsRecovery?.()).toBe(true)
expect(onError).not.toHaveBeenCalled()
// Typed while the host is unreachable: held for this pane's terminal, not dropped (#20802).
expect(transport.sendInput('echo held', 'driving')).toBe(true)
hostReachable = true
await vi.advanceTimersByTimeAsync(1_000)
await vi.waitFor(() => expect(runtimeSubscribe).toHaveBeenCalled())
emitSnapshot(latestSubscribePayload().streamId, 'prompt$ ')
await vi.advanceTimersByTimeAsync(20)
expect(transport.isConnected()).toBe(true)
expect(transport.getRecoveryState?.().phase).toBe('connected')
expect(transport.ownsRecovery?.()).toBe(false)
expect(inputFrameTexts().join('')).toBe('echo held')
expect(onError).not.toHaveBeenCalled()
transport.destroy?.()
} finally {
vi.useRealTimers()
}
})
it('reports owning recovery after a recoverable connect failure so the pane is not remounted (#21195)', async () => {
vi.useFakeTimers()
try {
runtimeCall.mockImplementation(async () => {
throw unreachable()
})
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
const result = await transport.connect({
url: '',
sessionId: 'remote:env-1@@',
callbacks: {}
})
expect(result).toBeUndefined()
expect(transport.getPtyId()).toBeNull()
expect(transport.ownsRecovery?.()).toBe(true)
transport.destroy?.()
expect(transport.ownsRecovery?.()).toBe(false)
} finally {
vi.useRealTimers()
}
})
it('delivers acknowledged input typed during a same-terminal recovery once it rebinds (#25784)', async () => {
const defaultCall = runtimeCall.getMockImplementation()
runtimeCall.mockImplementation(async (args: { method: string }) =>
args.method === 'terminal.send'
? { ok: true, result: { send: { accepted: true } } }
: defaultCall?.(args)
)
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'tab-1',
leafId: 'pane:1'
})
await transport.connect({ url: '', callbacks: {} })
await vi.waitFor(() => expect(runtimeSubscribe).toHaveBeenCalled())
emitSnapshot(latestSubscribePayload().streamId, 'prompt$ ')
await vi.waitFor(() => expect(transport.isConnected()).toBe(true))
const firstCallbacks = subscriptionCallbacks
firstCallbacks?.onError?.({
code: 'remote_runtime_unavailable',
message: 'Remote runtime connection closed.'
})
expect(transport.isConnected()).toBe(false)
const accepted = transport.sendInputAccepted?.('git status\r', 'driving')
await vi.waitFor(() => expect(subscriptionCallbacks).not.toBe(firstCallbacks))
await vi.waitFor(() => expect(latestSubscribePayload().terminal).toBe('terminal-1'))
emitSnapshot(latestSubscribePayload().streamId, 'prompt$ ')
await expect(accepted).resolves.toBe(true)
expect(runtimeCall).toHaveBeenCalledWith(
expect.objectContaining({
method: 'terminal.send',
params: expect.objectContaining({ terminal: 'terminal-1', text: 'git status\r' })
})
)
transport.destroy?.()
})
it('does not close a pane on an inventory that was already in flight before its leaf published (#20923)', async () => {
let releaseStaleInventory: () => void = () => {}
const staleInventory = new Promise<void>((resolve) => {
releaseStaleInventory = resolve
})
const siblingOnly = readyHostSessionInventoryResponse('terminal-sibling', 'host-tab-1')
// Why: rewrite the leaf so only a sibling of the requested pane is present.
const staleSnapshot = JSON.parse(JSON.stringify(siblingOnly).replaceAll('pane:1', 'pane:2'))
let listCalls = 0
const defaultCall = runtimeCall.getMockImplementation()
runtimeCall.mockImplementation(async (args: { method: string; params?: unknown }) => {
if (args.method === 'session.tabs.activate') {
return { ok: true, result: { tabs: [] } }
}
if (args.method === 'session.tabs.list') {
listCalls += 1
if (listCalls === 1) {
await staleInventory
return staleSnapshot
}
return readyHostSessionInventoryResponse('terminal-1', 'host-tab-1')
}
return defaultCall?.(args)
})
const { listRemoteRuntimeSessionTabsDeduped } =
await import('@/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight')
// Another pane's inventory request starts before this leaf is published.
const preexisting = listRemoteRuntimeSessionTabsDeduped({
environmentId: 'env-1',
worktreeId: 'wt-1',
load: async () => {
const response = await runtimeCall({ method: 'session.tabs.list' })
return { snapshot: response.result }
}
})
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const onError = vi.fn()
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'web-terminal-host-tab-1',
leafId: 'pane:1'
})
vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] })
try {
const connected = transport.connect({ url: '', callbacks: { onError } })
await vi.advanceTimersByTimeAsync(400)
releaseStaleInventory()
await preexisting
await expect(connected).resolves.toMatchObject({ id: 'remote:env-1@@terminal-1' })
expect(onError).not.toHaveBeenCalledWith('Remote terminal was closed.')
expect(listCalls).toBeGreaterThanOrEqual(2)
} finally {
releaseStaleInventory()
transport.destroy?.()
vi.useRealTimers()
}
})
})
@@ -1,261 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { ManagedPaneInternal } from '@/lib/pane-manager/pane-manager-types'
import '@/lib/pane-manager/pane-lifecycle'
import {
isPaneReplaying,
replayIntoTerminal,
replayIntoTerminalAsync,
type ReplayingPanesRef
} from './replay-guard'
import '@/lib/pane-manager/terminal-rendering/terminal-arabic-shaping-joiner'
import '@/lib/pane-manager/terminal-output/terminal-write-pipeline-health'
const mocks = vi.hoisted(() => ({
recordRendererCrashBreadcrumb: vi.fn()
}))
vi.mock('@/diagnostics/crash-reporting/crash-breadcrumb-recorder', () => ({
recordRendererCrashBreadcrumb: mocks.recordRendererCrashBreadcrumb
}))
beforeEach(() => {
mocks.recordRendererCrashBreadcrumb.mockClear()
})
afterEach(() => {
vi.useRealTimers()
})
function makeRef(): ReplayingPanesRef {
return { current: new Map() } as ReplayingPanesRef
}
type FakeTerminal = {
write: (data: string, cb?: () => void) => void
lastData: string[]
pendingCallbacks: (() => void)[]
rows: number
buffer: {
active: {
baseY: number
viewportY: number
}
}
_core: {
refresh: (start: number, end: number, sync?: boolean) => void
// Private flag read by isXtermInstanceDisposed.
_store?: { _isDisposed: boolean }
}
refresh: (start: number, end: number) => void
/** Like xterm 6: drops queued write callbacks and flags the private store. */
dispose: () => void
/** Flush all pending xterm write callbacks, simulating parse completion. */
flush: () => void
}
function makeFakePane(paneId: number): { pane: ManagedPaneInternal; terminal: FakeTerminal } {
const pendingCallbacks: (() => void)[] = []
const terminal: FakeTerminal = {
lastData: [],
pendingCallbacks,
rows: 24,
buffer: {
active: {
baseY: 0,
viewportY: 0
}
},
_core: {
refresh() {}
},
refresh() {},
dispose() {
pendingCallbacks.length = 0
terminal._core._store = { _isDisposed: true }
},
write(data: string, cb?: () => void) {
terminal.lastData.push(data)
if (cb) {
pendingCallbacks.push(cb)
}
},
flush() {
while (pendingCallbacks.length > 0) {
pendingCallbacks.shift()!()
}
}
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: replay reads only id/terminal; disposePane null-checks or try-wraps every other field it touches.
const pane = { id: paneId, terminal } as unknown as ManagedPaneInternal
return { pane, terminal }
}
describe('replay-guard', () => {
it('is replaying between write dispatch and xterm parse completion', () => {
const ref = makeRef()
const { pane, terminal } = makeFakePane(1)
replayIntoTerminal(pane, ref, 'hello')
// Keep the guard until parse completion so replay queries cannot emit shell input.
expect(isPaneReplaying(ref, 1)).toBe(true)
terminal.flush()
expect(isPaneReplaying(ref, 1)).toBe(false)
})
it('composes nested replays via a counter', () => {
const ref = makeRef()
const { pane, terminal } = makeFakePane(1)
// Queue cold-restore preamble, history and banner before any parse completion.
replayIntoTerminal(pane, ref, '\x1b[2J\x1b[3J\x1b[H')
replayIntoTerminal(pane, ref, 'scrollback bytes')
replayIntoTerminal(pane, ref, '--- session restored ---')
expect(isPaneReplaying(ref, 1)).toBe(true)
// The first completion cannot release later queued replay writes that may still auto-reply.
terminal.pendingCallbacks.shift()!()
expect(isPaneReplaying(ref, 1)).toBe(true)
terminal.pendingCallbacks.shift()!()
expect(isPaneReplaying(ref, 1)).toBe(true)
terminal.pendingCallbacks.shift()!()
expect(isPaneReplaying(ref, 1)).toBe(false)
})
it('keeps each pane independent', () => {
const ref = makeRef()
const a = makeFakePane(1)
const b = makeFakePane(2)
replayIntoTerminal(a.pane, ref, 'a')
expect(isPaneReplaying(ref, 1)).toBe(true)
expect(isPaneReplaying(ref, 2)).toBe(false)
replayIntoTerminal(b.pane, ref, 'b')
expect(isPaneReplaying(ref, 2)).toBe(true)
a.terminal.flush()
expect(isPaneReplaying(ref, 1)).toBe(false)
expect(isPaneReplaying(ref, 2)).toBe(true)
b.terminal.flush()
expect(isPaneReplaying(ref, 2)).toBe(false)
})
})
describe('replay-guard stall handling (probe-certified release)', () => {
it('releases when the probe parses but the replay completion was lost, and reports it', () => {
vi.useFakeTimers()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
try {
const ref = makeRef()
const { pane, terminal } = makeFakePane(1)
replayIntoTerminal(pane, ref, 'restored bytes', { stallCheckMs: 1_000 })
terminal.pendingCallbacks.shift() // xterm lost the replay's completion
vi.advanceTimersByTime(1_000) // stall check → probe enqueued
// Probe completion proves every earlier replay byte parsed, making release safe.
terminal.flush()
expect(isPaneReplaying(ref, 1)).toBe(false)
expect(mocks.recordRendererCrashBreadcrumb).toHaveBeenCalledWith(
'terminal_replay_guard_lost_completion',
{ paneId: 1 }
)
} finally {
errorSpy.mockRestore()
}
})
it('releases after the probe itself never parses (wedged pipeline) and reports it', () => {
vi.useFakeTimers()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
try {
const ref = makeRef()
const { pane } = makeFakePane(1)
replayIntoTerminal(pane, ref, 'restored bytes', { stallCheckMs: 1_000 })
vi.advanceTimersByTime(1_000) // stall check → probe enqueued
expect(isPaneReplaying(ref, 1)).toBe(true)
// A certified silent parser cannot emit query replies, so bounded wedge release cannot leak input.
vi.advanceTimersByTime(1_000)
expect(isPaneReplaying(ref, 1)).toBe(false)
expect(mocks.recordRendererCrashBreadcrumb).toHaveBeenCalledWith(
'terminal_replay_guard_wedged_release',
{ paneId: 1 }
)
} finally {
errorSpy.mockRestore()
}
})
it('releases immediately when the probe write throws (terminal disposed mid-replay)', () => {
vi.useFakeTimers()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
try {
const ref = makeRef()
const { pane, terminal } = makeFakePane(1)
replayIntoTerminal(pane, ref, 'restored bytes', { stallCheckMs: 1_000 })
terminal.write = () => {
throw new Error('terminal disposed')
}
vi.advanceTimersByTime(1_000)
expect(isPaneReplaying(ref, 1)).toBe(false)
expect(mocks.recordRendererCrashBreadcrumb).toHaveBeenCalledWith(
'terminal_replay_guard_wedged_release',
{ paneId: 1 }
)
} finally {
errorSpy.mockRestore()
}
})
it('keeps overlapping engagements independent through a lost completion', () => {
vi.useFakeTimers()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
try {
const ref = makeRef()
const { pane, terminal } = makeFakePane(1)
replayIntoTerminal(pane, ref, 'lost completion', { stallCheckMs: 1_000 })
replayIntoTerminal(pane, ref, 'healthy completion', { stallCheckMs: 60_000 })
terminal.pendingCallbacks.shift() // drop only the first completion
vi.advanceTimersByTime(1_000) // first engagement's probe enqueued
terminal.flush() // healthy completion + probe both parse
expect(isPaneReplaying(ref, 1)).toBe(false)
vi.advanceTimersByTime(120_000)
} finally {
errorSpy.mockRestore()
}
})
it('resolves replayIntoTerminalAsync via the wedged path so restore chains cannot hang', async () => {
vi.useFakeTimers()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
try {
const ref = makeRef()
const { pane } = makeFakePane(1)
const replayDone = replayIntoTerminalAsync(pane, ref, 'restored bytes', {
stallCheckMs: 1_000
})
let resolved = false
void replayDone.then(() => {
resolved = true
})
await vi.advanceTimersByTimeAsync(2_000)
expect(resolved).toBe(true)
expect(isPaneReplaying(ref, 1)).toBe(false)
} finally {
errorSpy.mockRestore()
}
})
})
@@ -3,15 +3,12 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useAppStore } from '@/store/index'
import 'sonner'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch'
import { executeWorktreeCreation } from './worktree-creation-flow-execute'
import './worktree-creation-flow'
import {
makeCreatedAgentWorktree,
seedEmptyActivatableWorktree
} from '../activation/worktree-activation-created-agent.test-fixture'
import type { StructuredLaunchAdmission } from '../../agent-session/launch/structured-agent-session-host-admission'
import type * as admissionModule from '../../agent-session/launch/structured-agent-session-host-admission'
import type * as launchModule from '../../agent-session/launch/structured-agent-session-launch-create-call'
import {
@@ -23,7 +20,6 @@ import {
drawTabsFromMain,
type TabsDrawnFromMain
} from '@/store/slices/tabs/tabs-drawn-from-main.test-fixture'
import { layoutApplyTestTransport } from '@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture'
import { clearNativeChatComposerDraftsForTests } from '@/components/native-chat/drafts/native-chat-draft-reset'
import {
readNativeChatComposerDraft,
@@ -38,7 +34,6 @@ import {
pendingCreationChatDraftScopeKey
} from './pending-worktree-creation'
import '../../agent-session/launch/structured-agent-session-launch-prompt'
import { hasStagedStructuredLaunchPrompt } from '../../agent-session/launch/structured-agent-session-staged-prompt'
import '@/components/native-chat/session/structured/delivery/structured-agent-session-pending-sends'
import { resetStructuredAgentSessionSendsForTests } from '@/components/native-chat/session/structured/delivery/structured-agent-session-message-sender'
import {
@@ -145,100 +140,6 @@ afterEach(() => {
})
describe('creation chat handoff', () => {
it.skipIf(!ORCA_LAYOUT_OWNER_IS_MAIN)(
'owns input through delayed provider creation and replacement tab publication',
async () => {
const emptyRequest = { ...request, quickPrompt: '' }
useAppStore.getState().updatePendingWorktreeCreation('creation-1', {
request: emptyRequest,
heldChatMessage: 'First message accepted before launch'
})
const scope = pendingCreationChatDraftScopeKey('creation-1')
updateNativeChatComposerDraft(scope, { text: 'Unsent follow-up', images: [] }, 'immediate')
layoutApplyTestTransport.answerWith((command) =>
command.type === 'openAgentSessionTab' ? 'pending' : 'apply'
)
const completion = executeWorktreeCreation('creation-1', emptyRequest)
await vi.waitFor(() => expect(mocks.createSession).toHaveBeenCalled())
const intent = mocks.createSession.mock.calls[0][0]
expect(hasStagedStructuredLaunchPrompt(intent.sessionId)).toBe(true)
expect(
readNativeChatComposerDraft(structuredAgentSessionDraftScopeKey(intent.sessionId)).text
).toBe('')
expect(readNativeChatComposerDraft(scope).text).toBe('Unsent follow-up')
expect(useAppStore.getState().activePendingCreationId).toBe('creation-1')
expect(
useAppStore.getState().pendingWorktreeCreations['creation-1']?.chatInputHandedOff
).toBe(true)
layoutApplyTestTransport.answerWith('apply')
layoutApplyTestTransport.answerPending()
await completion
expect(useAppStore.getState().pendingWorktreeCreations['creation-1']).toBeUndefined()
expect(
readNativeChatComposerDraft(structuredAgentSessionDraftScopeKey(intent.sessionId)).text
).toBe('Unsent follow-up')
}
)
it.skipIf(!ORCA_LAYOUT_OWNER_IS_MAIN)(
'waits for the answering layout frame even when provider creation fails first',
async () => {
layoutApplyTestTransport.answerWith((command) =>
command.type === 'openAgentSessionTab' ? 'pending' : 'apply'
)
mocks.createSession.mockRejectedValue(new StructuredAgentSessionCreateRefusalError('no'))
const completion = executeWorktreeCreation('creation-1', request)
await vi.waitFor(() => expect(layoutApplyTestTransport.pendingCount).toBe(1))
await vi.waitFor(() => expect(mocks.createSession).toHaveBeenCalled())
const intent = mocks.createSession.mock.calls[0][0]
await vi.waitFor(() =>
expect(getStructuredLaunchStateBySessionId(intent.sessionId)?.callers.outcome).toBe(
'failed'
)
)
expect(useAppStore.getState().activeWorktreeId).toBe('previous-worktree')
expect(useAppStore.getState().activePendingCreationId).toBe('creation-1')
layoutApplyTestTransport.answerWith('apply')
layoutApplyTestTransport.answerPending()
await completion
expect(useAppStore.getState().activeWorktreeId).toBe(worktree.id)
expect(useAppStore.getState().getActiveTab(worktree.id)?.contentType).toBe('agent-session')
expect(useAppStore.getState().pendingWorktreeCreations['creation-1']).toBeUndefined()
}
)
it.skipIf(!ORCA_LAYOUT_OWNER_IS_MAIN)(
'preserves the held first message in a terminal when layout refuses the chat',
async () => {
const emptyRequest = { ...request, quickPrompt: '' }
useAppStore.getState().updatePendingWorktreeCreation('creation-1', {
request: emptyRequest,
heldChatMessage: 'Recover this first message'
})
layoutApplyTestTransport.answerWith((command) =>
command.type === 'openAgentSessionTab'
? { ok: false, code: 'pane_structure_changed' }
: 'apply'
)
await executeWorktreeCreation('creation-1', emptyRequest)
await main.settle()
const state = useAppStore.getState()
expect(state.pendingWorktreeCreations['creation-1']).toBeUndefined()
expect(state.tabsByWorktree[worktree.id]).toHaveLength(1)
expect(state.getActiveTab(worktree.id)?.contentType).toBe('terminal')
const tabId = state.tabsByWorktree[worktree.id]![0]!.id
expect(state.pendingStartupByTabId[tabId]).toMatchObject({
command: expect.stringContaining('Recover this first message')
})
}
)
it('keeps a rich first message and unsent follow-up in the failed chat when its host declines', async () => {
const emptyRequest = { ...request, quickPrompt: '' }
const source = pendingCreationChatDraftScopeKey('creation-1')
@@ -341,20 +242,4 @@ describe('creation chat handoff', () => {
])
expect(readNativeChatComposerDraft(source).images).toEqual([])
})
it('dismisses a pending admission without opening a late chat', async () => {
const admission = Promise.withResolvers<StructuredLaunchAdmission>()
mocks.admission.mockReturnValue(admission.promise)
const completion = executeWorktreeCreation('creation-1', request)
await vi.waitFor(() => expect(mocks.admission).toHaveBeenCalled())
useAppStore.getState().removePendingWorktreeCreation('creation-1')
await completion
admission.resolve({ kind: 'admitted' })
await main.settle()
expect(useAppStore.getState().activeWorktreeId).toBe('previous-worktree')
expect(useAppStore.getState().unifiedTabsByWorktree[worktree.id] ?? []).toEqual([])
expect(mocks.createSession).not.toHaveBeenCalled()
})
})
@@ -1,676 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { RuntimeMobileSessionTabsResult } from '../../../../../../shared/runtime-session-contracts'
import { resetWebSessionTabsSyncTestState } from '../../../web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'
import {
ENVIRONMENT_ID,
deferred,
listResult,
makeSnapshot,
makeState,
pendingSurface
} from '../testing/web-session-terminal-orphan-recovery-regression-fixtures'
import {
clearWebSessionTerminalOrphanRecoveryForTests,
recoverWebSessionTerminalOrphansBeforeApply
} from '../web-session-terminal-orphan-recovery'
vi.mock('../../../../store/index', () => ({ useAppStore: { setState: vi.fn() } }))
vi.mock('@/hooks/agent-hook-completion-notifications', () => ({
observeAgentHookCompletionForNotification: vi.fn()
}))
describe('web session terminal orphan adoption regressions', () => {
beforeEach(() => {
clearWebSessionTerminalOrphanRecoveryForTests()
resetWebSessionTabsSyncTestState()
})
it('retries a transient thrown adoption on an unchanged semantic frame', async () => {
const worktree = 'repo::transient-adoption-retry'
const leaves = [{ leafId: 'leaf-1', handle: 'term-live' }]
const state = makeState(worktree, leaves)
const snapshot: RuntimeMobileSessionTabsResult = {
...makeSnapshot(worktree, 'transient-adoption', leaves),
tabs: [pendingSurface('host-tab', 'leaf-1', 'pty-live')] as never
}
let adoptionAttempts = 0
const call = vi.fn(async ({ method }: { method: string }) => {
if (method === 'terminal.list') {
return {
ok: true as const,
result: listResult(worktree, [
{
handle: 'term-live',
ptyId: 'pty-live',
incarnationId: 'inc-live',
orphaned: true
}
])
}
}
if (method === 'session.tabs.list') {
return {
ok: true as const,
result: {
...snapshot,
tabs: [pendingSurface('host-tab', 'leaf-1', 'pty-live', 'term-live')]
}
}
}
if (method !== 'terminal.adoptOrphans') {
throw new Error(`Unexpected method: ${method}`)
}
adoptionAttempts += 1
if (adoptionAttempts === 1) {
throw new Error('Remote runtime connection closed')
}
return {
ok: true as const,
result: {
adopted: true,
topologyRevision: 8,
snapshot: {
...snapshot,
publicationEpoch: 'adopted',
tabs: [
{
...pendingSurface('host-tab', 'leaf-1', 'pty-live', 'term-live'),
status: 'ready' as const,
terminal: 'term-live'
}
]
}
}
}
})
await recoverWebSessionTerminalOrphansBeforeApply(state, snapshot, ENVIRONMENT_ID, {
call: call as never
})
const recovered = await recoverWebSessionTerminalOrphansBeforeApply(
state,
snapshot,
ENVIRONMENT_ID,
{ call: call as never }
)
expect(recovered?.tabs[0]).toMatchObject({ status: 'ready', terminal: 'term-live' })
})
it.each([
{
failure: 'rpc-error',
expectedRuntimeId: 'origin-runtime',
reply: () => ({ ok: false, error: { code: 'unavailable', message: 'unavailable' } })
},
{
failure: 'throw',
expectedRuntimeId: 'origin-runtime',
reply: () => {
throw new Error('Remote runtime connection closed')
}
},
{
failure: 'invalid-snapshot',
expectedRuntimeId: 'origin-runtime',
reply: (snapshot: RuntimeMobileSessionTabsResult) => ({
ok: true,
_meta: { runtimeId: 'origin-runtime' },
result: { ...snapshot, tabs: [null] }
})
},
{
failure: 'wrong-worktree',
expectedRuntimeId: 'origin-runtime',
reply: (snapshot: RuntimeMobileSessionTabsResult) => ({
ok: true,
_meta: { runtimeId: 'origin-runtime' },
result: { ...snapshot, worktree: 'folder:other-host-workspace' }
})
},
{
failure: 'runtime-changed',
expectedRuntimeId: 'origin-runtime',
reply: (snapshot: RuntimeMobileSessionTabsResult) => ({
ok: true,
_meta: { runtimeId: 'replacement-runtime' },
result: snapshot
})
},
{
failure: 'runtime-missing',
expectedRuntimeId: 'origin-runtime',
reply: (snapshot: RuntimeMobileSessionTabsResult) => ({ ok: true, result: snapshot })
},
{
failure: 'runtime-changed-without-frame-id',
expectedRuntimeId: undefined,
reply: (snapshot: RuntimeMobileSessionTabsResult) => ({
ok: true,
_meta: { runtimeId: 'replacement-runtime' },
result: snapshot
})
}
])(
'retains the client epoch and retries when the post-adoption list has $failure',
async ({ expectedRuntimeId, reply }) => {
const worktree = 'folder:post-adoption-list'
const leaves = [{ leafId: 'leaf-1', handle: 'term-live' }]
const state = makeState(worktree, leaves)
const snapshot = makeSnapshot(worktree, 'renderer:host:client-navigation', leaves)
const adopted: RuntimeMobileSessionTabsResult = {
...snapshot,
publicationEpoch: 'renderer:host',
snapshotVersion: 2,
tabs: [pendingSurface('host-tab', 'leaf-1', 'pty-live', 'term-live')]
}
const projected = { ...adopted, publicationEpoch: 'renderer:host:client-navigation' }
let failNextList = true
const call = vi.fn(async ({ method }: { method: string }) => {
if (method === 'terminal.list') {
return {
ok: true,
result: listResult(worktree, [
{
handle: 'term-live',
ptyId: 'pty-live',
incarnationId: 'inc-live',
orphaned: true
}
])
}
}
if (method === 'terminal.adoptOrphans') {
return {
ok: true,
result: { adopted: true, topologyRevision: 8, snapshot: adopted },
_meta: { runtimeId: 'origin-runtime' }
}
}
if (method !== 'session.tabs.list') {
throw new Error(`Unexpected method: ${method}`)
}
if (failNextList) {
failNextList = false
return reply(projected)
}
return { ok: true, result: projected, _meta: { runtimeId: 'origin-runtime' } }
})
const options = { call: call as never, expectedRuntimeId }
const retained = await recoverWebSessionTerminalOrphansBeforeApply(
state,
snapshot,
ENVIRONMENT_ID,
options
)
expect(retained).toMatchObject({
worktree: 'folder:post-adoption-list',
publicationEpoch: 'renderer:host:client-navigation',
snapshotVersion: 1,
tabs: [
{
id: 'host-tab::leaf-1',
parentTabId: 'host-tab',
leafId: 'leaf-1',
status: 'ready',
terminal: 'term-live'
}
]
})
await expect(
recoverWebSessionTerminalOrphansBeforeApply(state, snapshot, ENVIRONMENT_ID, options)
).resolves.toMatchObject({
worktree: 'folder:post-adoption-list',
publicationEpoch: 'renderer:host:client-navigation',
snapshotVersion: 2,
tabs: [
{
id: 'host-tab::leaf-1',
parentTabId: 'host-tab',
leafId: 'leaf-1',
ptyId: 'pty-live',
status: 'ready',
terminal: 'term-live'
}
]
})
}
)
it.each([
{
failure: 'empty-row',
malform: (snapshot: RuntimeMobileSessionTabsResult) => ({ ...snapshot, tabs: [{}] })
},
{
failure: 'missing-selection',
malform: (snapshot: RuntimeMobileSessionTabsResult) => ({
...snapshot,
activeTabId: undefined
})
},
{
failure: 'malformed-groups',
malform: (snapshot: RuntimeMobileSessionTabsResult) => ({
...snapshot,
tabGroups: [{ id: 'group-1' }]
})
}
])(
'preserves prior terminal bindings after a post-adoption $failure and retries',
async ({ malform }) => {
const worktree = 'folder:malformed-post-adoption'
const state = makeState(worktree, [{ leafId: 'leaf-1', handle: 'term-live' }])
state.tabsByWorktree[worktree]!.push({
...state.tabsByWorktree[worktree]![0]!,
id: 'web-terminal-owned-tab',
ptyId: 'remote:remote-runtime@@term-owned'
})
state.terminalLayoutsByTabId['web-terminal-owned-tab'] = {
root: { type: 'leaf', leafId: 'leaf-owned' },
activeLeafId: 'leaf-owned',
expandedLeafId: null,
ptyIdsByLeafId: { 'leaf-owned': 'remote:remote-runtime@@term-owned' }
}
state.activeTabIdByWorktree[worktree] = null
const owned = pendingSurface('owned-tab', 'leaf-owned', 'pty-owned', 'term-owned')
const incoming: RuntimeMobileSessionTabsResult = {
...makeSnapshot(worktree, 'renderer:host:client-navigation', []),
snapshotVersion: 2,
tabs: [pendingSurface('host-tab', 'leaf-1', 'pty-live'), owned]
}
const projected: RuntimeMobileSessionTabsResult = {
...incoming,
snapshotVersion: 3,
tabs: [pendingSurface('host-tab', 'leaf-1', 'pty-live', 'term-live'), owned]
}
const malformed = malform(projected)
let failNextList = true
const call = vi.fn(async ({ method }: { method: string }) => {
const envelope = { id: method, ok: true as const, _meta: { runtimeId: 'host-runtime' } }
if (method === 'terminal.list') {
return {
...envelope,
result: listResult(worktree, [
{ handle: 'term-live', ptyId: 'pty-live', incarnationId: 'inc-live', orphaned: true }
])
}
}
if (method === 'terminal.adoptOrphans') {
return {
...envelope,
result: {
adopted: true,
topologyRevision: 8,
snapshot: { ...projected, publicationEpoch: 'renderer:host' }
}
}
}
if (method !== 'session.tabs.list') {
throw new Error(`Unexpected method: ${method}`)
}
if (failNextList) {
failNextList = false
return { ...envelope, result: malformed }
}
return { ...envelope, result: projected }
})
const retained = await recoverWebSessionTerminalOrphansBeforeApply(
state,
incoming,
ENVIRONMENT_ID,
{ call: call as never }
)
expect(retained).toMatchObject({
worktree: 'folder:malformed-post-adoption',
publicationEpoch: 'renderer:host:client-navigation',
snapshotVersion: 2,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: [
{
id: 'host-tab::leaf-1',
parentTabId: 'host-tab',
leafId: 'leaf-1',
ptyId: 'pty-live',
status: 'ready',
terminal: 'term-live'
},
{
id: 'owned-tab::leaf-owned',
parentTabId: 'owned-tab',
leafId: 'leaf-owned',
ptyId: 'pty-owned',
status: 'ready',
terminal: 'term-owned'
}
]
})
const retried = await recoverWebSessionTerminalOrphansBeforeApply(
state,
incoming,
ENVIRONMENT_ID,
{ call: call as never }
)
expect(retried).toMatchObject({
worktree: 'folder:malformed-post-adoption',
publicationEpoch: 'renderer:host:client-navigation',
snapshotVersion: 3,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: [
{
id: 'host-tab::leaf-1',
parentTabId: 'host-tab',
leafId: 'leaf-1',
ptyId: 'pty-live',
status: 'ready',
terminal: 'term-live'
},
{
id: 'owned-tab::leaf-owned',
parentTabId: 'owned-tab',
leafId: 'leaf-owned',
ptyId: 'pty-owned',
status: 'ready',
terminal: 'term-owned'
}
]
})
}
)
it.each([
{
verdict: 'retired',
projectedSibling: [],
retirementProofs: [
{
parentTabId: 'host-tab',
leafId: 'leaf-hold',
terminal: 'term-hold',
ptyId: 'pty-hold',
incarnationId: 'inc-hold'
}
],
expectedTabs: [
{ id: 'host-tab::leaf-claim', ptyId: 'pty-claim', status: 'ready', terminal: 'term-claim' }
],
expectedRetirements: [
{
parentTabId: 'host-tab',
leafId: 'leaf-hold',
terminal: 'term-hold',
ptyId: 'pty-hold',
incarnationId: 'inc-hold'
}
]
},
{
verdict: 'rebound',
projectedSibling: [
{
type: 'terminal' as const,
id: 'host-tab::leaf-hold',
parentTabId: 'host-tab',
leafId: 'leaf-hold',
title: 'leaf-hold',
ptyId: 'pty-new',
isActive: false,
status: 'ready' as const,
terminal: 'term-new'
}
],
retirementProofs: [],
expectedTabs: [
{ id: 'host-tab::leaf-claim', ptyId: 'pty-claim', status: 'ready', terminal: 'term-claim' },
{ id: 'host-tab::leaf-hold', ptyId: 'pty-new', status: 'ready', terminal: 'term-new' }
],
expectedRetirements: []
},
{
verdict: 'pending-without-proof',
projectedSibling: [
{
type: 'terminal' as const,
id: 'host-tab::leaf-hold',
parentTabId: 'host-tab',
leafId: 'leaf-hold',
title: 'leaf-hold',
ptyId: 'pty-new',
isActive: false,
status: 'pending-handle' as const,
terminal: null
}
],
retirementProofs: [],
expectedTabs: [
{ id: 'host-tab::leaf-claim', ptyId: 'pty-claim', status: 'ready', terminal: 'term-claim' },
{ id: 'host-tab::leaf-hold', ptyId: 'pty-hold', status: 'pending-handle', terminal: null }
],
expectedRetirements: []
}
])(
'merges host-projected $verdict sibling state after adoption without treating pending as exited',
async ({ projectedSibling, retirementProofs, expectedTabs, expectedRetirements }) => {
const worktree = 'folder:post-adoption-sibling'
const state = makeState(worktree, [
{ leafId: 'leaf-claim', handle: 'term-claim' },
{ leafId: 'leaf-hold', handle: 'term-hold' }
])
state.activeTabIdByWorktree[worktree] = null
const snapshot: RuntimeMobileSessionTabsResult = {
...makeSnapshot(worktree, 'renderer:host:client-navigation', []),
snapshotVersion: 2,
tabs: [
pendingSurface('host-tab', 'leaf-claim', 'pty-claim'),
pendingSurface('host-tab', 'leaf-hold', 'pty-hold')
]
}
const adopted: RuntimeMobileSessionTabsResult = {
...snapshot,
publicationEpoch: 'renderer:host',
snapshotVersion: 3,
tabs: [pendingSurface('host-tab', 'leaf-claim', 'pty-claim', 'term-claim')]
}
const projected: RuntimeMobileSessionTabsResult = {
...adopted,
publicationEpoch: 'renderer:host:client-navigation',
snapshotVersion: 4,
tabs: [
pendingSurface('host-tab', 'leaf-claim', 'pty-claim', 'term-claim'),
...projectedSibling
],
retiredTerminalSurfaces: retirementProofs
}
const call = vi.fn(async ({ method }: { method: string }) => {
if (method === 'terminal.list') {
return {
ok: true,
result: listResult(worktree, [
{
handle: 'term-claim',
ptyId: 'pty-claim',
incarnationId: 'inc-claim',
orphaned: true
}
])
}
}
if (method === 'terminal.adoptOrphans') {
return { ok: true, result: { adopted: true, topologyRevision: 8, snapshot: adopted } }
}
if (method !== 'session.tabs.list') {
throw new Error(`Unexpected method: ${method}`)
}
return { ok: true, result: projected }
})
const recovered = await recoverWebSessionTerminalOrphansBeforeApply(
state,
snapshot,
ENVIRONMENT_ID,
{ call: call as never }
)
expect(recovered).toMatchObject({
worktree: 'folder:post-adoption-sibling',
publicationEpoch: 'renderer:host:client-navigation',
snapshotVersion: 4,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: expectedTabs,
retiredTerminalSurfaces: expectedRetirements
})
}
)
it('does not apply an adoption result after the local tab closes while adoption is blocked', async () => {
const worktree = 'repo::local-close-during-adoption'
const leaves = [{ leafId: 'leaf-1', handle: 'term-live' }]
const stateBeforeClose = makeState(worktree, leaves)
const stateAfterClose = {
...stateBeforeClose,
tabsByWorktree: { ...stateBeforeClose.tabsByWorktree, [worktree]: [] },
terminalLayoutsByTabId: {},
activeTabIdByWorktree: { [worktree]: null }
}
let currentState = stateBeforeClose
const snapshot: RuntimeMobileSessionTabsResult = {
...makeSnapshot(worktree, 'local-close-during-adoption', leaves),
tabs: [pendingSurface('host-tab', 'leaf-1', 'pty-live')]
}
const adoption = deferred<unknown>()
const entered = deferred<void>()
const call = vi.fn(async ({ method }: { method: string }) => {
if (method === 'terminal.list') {
return {
ok: true as const,
result: listResult(worktree, [
{
handle: 'term-live',
ptyId: 'pty-live',
incarnationId: 'inc-live',
orphaned: true
}
])
}
}
if (method !== 'terminal.adoptOrphans') {
throw new Error(`Unexpected method: ${method}`)
}
entered.resolve(undefined)
return adoption.promise
})
const recovery = recoverWebSessionTerminalOrphansBeforeApply(
stateBeforeClose,
snapshot,
ENVIRONMENT_ID,
{ call: call as never, getCurrentState: () => currentState } as never
)
await entered.promise
currentState = stateAfterClose
adoption.resolve({
ok: true,
result: {
adopted: true,
topologyRevision: 8,
snapshot: {
...snapshot,
publicationEpoch: 'adopted-after-close',
tabs: [
{
...pendingSurface('host-tab', 'leaf-1', 'pty-live', 'term-live'),
status: 'ready' as const,
terminal: 'term-live'
}
]
}
}
})
await expect(recovery).resolves.toBeNull()
})
it('does not apply an adoption result after the local tab moves groups while adoption is blocked', async () => {
const worktree = 'repo::local-move-during-adoption'
const leaves = [{ leafId: 'leaf-1', handle: 'term-live' }]
const stateBeforeMove = makeState(worktree, leaves)
const localTabId = stateBeforeMove.tabsByWorktree[worktree]![0]!.id
const stateAfterMove = {
...stateBeforeMove,
activeGroupIdByWorktree: { [worktree]: 'group-moved' },
groupsByWorktree: {
[worktree]: [
{
id: 'group-moved',
worktreeId: worktree,
activeTabId: localTabId,
tabOrder: [localTabId]
}
]
},
layoutByWorktree: { [worktree]: { type: 'leaf' as const, groupId: 'group-moved' } }
}
let currentState = stateBeforeMove
const snapshot: RuntimeMobileSessionTabsResult = {
...makeSnapshot(worktree, 'local-move-during-adoption', leaves),
tabs: [pendingSurface('host-tab', 'leaf-1', 'pty-live')]
}
const adoption = deferred<unknown>()
const entered = deferred<void>()
const call = vi.fn(async ({ method }: { method: string }) => {
if (method === 'terminal.list') {
return {
ok: true as const,
result: listResult(worktree, [
{
handle: 'term-live',
ptyId: 'pty-live',
incarnationId: 'inc-live',
orphaned: true
}
])
}
}
if (method !== 'terminal.adoptOrphans') {
throw new Error(`Unexpected method: ${method}`)
}
entered.resolve(undefined)
return adoption.promise
})
const recovery = recoverWebSessionTerminalOrphansBeforeApply(
stateBeforeMove,
snapshot,
ENVIRONMENT_ID,
{ call: call as never, getCurrentState: () => currentState }
)
await entered.promise
currentState = stateAfterMove
adoption.resolve({
ok: true,
result: {
adopted: true,
topologyRevision: 8,
snapshot: {
...snapshot,
publicationEpoch: 'adopted-after-move',
tabs: [
{
...pendingSurface('host-tab', 'leaf-1', 'pty-live', 'term-live'),
status: 'ready' as const,
terminal: 'term-live'
}
]
}
}
})
await expect(recovery).resolves.toBeNull()
})
})
@@ -1,30 +1,19 @@
// @vitest-environment happy-dom
import { act, cleanup, render, renderHook, waitFor } from '@testing-library/react'
import { act, cleanup, render, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import type { Tab } from '../../../../../shared/tab-types'
import type { ExecutionHostId } from '../../../../../shared/execution-host'
import '../../../../../shared/global-settings-test-fixture'
import '../../../../../shared/ephemeral-setup-terminal-worktree-id'
import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire'
import type * as LayoutRouting from '@/store/terminals/tab-change-through-layout-owner'
import type * as LocalRuntimeCapabilities from '../../hosts/capabilities/local-runtime-capabilities'
import {
addWorkspace,
emptySession
} from '../../../../../shared/workspace-layout/workspace-layout-session.test-fixture'
import { loadWorkspaceLayoutWithoutReport } from '../../../../../shared/workspace-layout/workspace-layout-load'
import { nameBasedLoadContext } from '../../../../../shared/workspace-layout/workspace-layout-minted-ids'
import { renameTab } from '../../../../../shared/workspace-layout/workspace-layout-tab-rename'
import { saveWorkspaceLayout } from '../../../../../shared/workspace-layout/workspace-layout-save'
import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture'
import { makeUnifiedTab } from '@/store/slices/tabs/tab-group.test-fixture'
import { TEST_REPO } from '@/store/repos/repo.test-fixture'
import { makeFolderWorkspace } from '@/store/folder-workspaces/folder-workspace.test-fixture'
import { WorkspaceAttachmentOrigins } from '@/components/sidebar/workspace-card/review/WorkspaceAttachmentOrigins'
import { useAppStore } from '@/store/index'
import { installLegacyChatRenameMigration } from './legacy-chat-rename-migration'
import { uploadLegacyStructuredChatRename } from './structured-chat-rename'
import { readStructuredChatTabName } from './structured-chat-tab-name'
import '@/store/slices/tabs/closing/pinned-tab-close-guard'
import {
@@ -35,11 +24,6 @@ import { useLiveDashboardSnapshot } from '@/components/dashboard/useLiveDashboar
import { useAgentPaneThreads } from '@/components/activity/use-agent-pane-threads'
import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id'
import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target'
import { fetchWorkspaceSessionWithRuntimeHostOwners } from '@/lib/workspace/persistence/workspace-session-host-hydration'
import { buildPersistedUnifiedTabSessionData } from '@/lib/workspace/persistence/workspace-session-unified-tabs'
import { persistWorkspaceSessionByHost } from '@/lib/workspace/persistence/workspace-session-host-persistence'
import { sendMessageToAgent } from '@/lib/agent-session/messaging/agent-message-send'
import type { WorkspaceSessionState } from '../../../../../shared/workspace-session/workspace-session-state-types'
import '../../web-session-tabs-sync/snapshot-api'
import '../../web-session-tabs-sync/store-patch'
@@ -113,15 +97,6 @@ const chat = (extra: Partial<Tab> = {}): Tab =>
label: 'Codex Chat',
...extra
})
function loadChat(tab: Tab, owner: ExecutionHostId) {
const stored = addWorkspace(emptySession(), tab.worktreeId, [
{
id: 'group',
tabs: [{ id: tab.id, entityId: tab.entityId, kind: 'agent-session', entry: tab }]
}
])
return loadWorkspaceLayoutWithoutReport(owner, stored, nameBasedLoadContext())
}
function seed(tab: Tab) {
useAppStore.setState({
workspaceSessionReady: true,
@@ -130,16 +105,6 @@ function seed(tab: Tab) {
unifiedTabsByWorktree: { [tab.worktreeId]: [tab] }
})
}
function partitionedSessionApi(partitions: Record<string, WorkspaceSessionState>) {
return {
get: async (host?: string) => partitions[host ?? 'local'] ?? emptySession(),
set: async (session: WorkspaceSessionState, host?: string) => {
partitions[host ?? 'local'] = session
},
patch: async () => {},
flush: async () => {}
}
}
const stops: (() => void)[] = []
beforeEach(() => {
vi.spyOn(Date, 'now').mockReturnValue(1_700_000_000_000)
@@ -158,95 +123,6 @@ afterEach(() => {
vi.restoreAllMocks()
})
it('migrates an inactive restored alias after reconnect and clears both saved copies only after acknowledgment', async () => {
const alias = 'x'.repeat(5000)
const tab = chat({
worktreeId: 'folder:twin',
executionHostId: 'runtime:paired',
customLabel: alias
})
let loaded = loadChat(tab, 'runtime:paired')
mock.layout.mockImplementation((_state, target, change, _local, answers) => {
if (!target) {
throw new Error('Missing tab')
}
const command = change(target.id)
if (command.type !== 'renameTab') {
throw new Error('Unexpected layout command')
}
const result = renameTab(loaded.layout, { ...command, workspace: target.worktreeId })
if (!result.ok) {
throw new Error('Layout refused cleanup')
}
loaded = { ...loaded, layout: result.model }
answers?.shown?.()
return true
})
seedTwin(tab)
mock.rpc
.mockRejectedValueOnce(new Error('Disconnected'))
.mockResolvedValue({ name: 'x'.repeat(200), applied: true })
stops.push(installLegacyChatRenameMigration())
await waitFor(() => expect(mock.rpc).toHaveBeenCalledTimes(1))
expect(useAppStore.getState().unifiedTabsByWorktree[tab.worktreeId]?.[0]?.customLabel).toBe(alias)
mock.contacts.forEach((regained) => regained())
await waitFor(() =>
expect(
useAppStore.getState().unifiedTabsByWorktree[tab.worktreeId]?.[0]?.customLabel
).toBeNull()
)
expect(mock.rpc).toHaveBeenLastCalledWith(expect.anything(), 'agentSession.rename', {
sessionId: tab.entityId,
name: 'x'.repeat(200),
legacyAlias: true
})
expect(saveWorkspaceLayout(loaded).unifiedTabs?.[tab.worktreeId]?.[0]?.customLabel).toBeNull()
})
it('transfers an unstamped alias once its single local owner is known and reloads the canonical name', async () => {
const tab = chat({ worktreeId: 'folder:unique', customLabel: 'Legacy' })
seed(tab)
useAppStore.setState({
repos: [],
worktreesByRepo: {},
restoredRuntimeHostIdByWorkspaceSessionKey: { [tab.worktreeId]: 'runtime:storage-only' }
})
mock.snapshot.set(tab.entityId, name(tab, 'History name'))
mock.rpc.mockResolvedValue({ name: 'History name', applied: false })
stops.push(installLegacyChatRenameMigration())
expect(
await uploadLegacyStructuredChatRename(useAppStore.getState, tab, 'Legacy', 'Legacy')
).toBe(false)
expect(mock.rpc).not.toHaveBeenCalled()
const groups = saveWorkspaceLayout(loadChat(tab, 'local')).tabGroups?.[tab.worktreeId] ?? []
useAppStore.setState({ groupsByWorktree: { [tab.worktreeId]: groups } })
useAppStore.setState({
folderWorkspaces: [makeFolderWorkspace({ id: 'unique', executionHostId: 'local' })]
})
await waitFor(() =>
expect(useAppStore.getState().unifiedTabsByWorktree[tab.worktreeId][0].customLabel).toBeNull()
)
expect(mock.rpc).toHaveBeenCalledExactlyOnceWith({ kind: 'local' }, 'agentSession.rename', {
sessionId: tab.entityId,
name: 'Legacy',
legacyAlias: true
})
const saved = {
...emptySession(),
...buildPersistedUnifiedTabSessionData(useAppStore.getState())
}
const api = partitionedSessionApi({ local: emptySession() })
await persistWorkspaceSessionByHost(api, saved, useAppStore.getState())
const read = await fetchWorkspaceSessionWithRuntimeHostOwners(api, [])
useAppStore.getState().hydrateWorkspaceSession(read.session, read)
useAppStore.getState().hydrateTabsSession(read.session)
useAppStore.setState({ activeWorktreeId: 'elsewhere' })
const restored = useAppStore.getState().unifiedTabsByWorktree[tab.worktreeId][0]
expect(restored.executionHostId).toBeUndefined()
expect(restored.customLabel).toBeNull()
expect(readStructuredChatTabName(restored, useAppStore.getState())).toBe('History name')
})
function seedTwin(tab: Tab) {
seed(tab)
const folder = makeFolderWorkspace({ id: 'twin' })
@@ -372,146 +248,3 @@ it('shares qualified current names with live dashboard and attachments without a
expect(readStructuredChatTabName(replacement, useAppStore.getState())).toBe('Dormant rename')
expect(mock.activates).toHaveBeenCalledTimes(2)
})
it('traces legacy runtime storage movement, action routing and switch-away before inventory', async () => {
const tab = chat({ worktreeId: 'folder:twin', customLabel: 'Legacy paired' })
seedTwin(tab)
useAppStore.setState({ workspaceSessionReady: false })
const local = {
...emptySession(),
activeWorktreeId: tab.worktreeId,
activeWorkspaceKey: 'folder:twin' as const,
activeWorkspaceExecutionHostId: 'runtime:b' as const
}
const partitions: Record<string, WorkspaceSessionState> = {
local,
'runtime:b': {
...emptySession(),
unifiedTabs: { [tab.worktreeId]: [tab] },
tabGroups: {
[tab.worktreeId]: [
{ id: tab.groupId, worktreeId: tab.worktreeId, activeTabId: tab.id, tabOrder: [tab.id] }
]
}
}
}
const api = partitionedSessionApi(partitions)
const restored = await fetchWorkspaceSessionWithRuntimeHostOwners(
api,
[],
['runtime:a', 'runtime:b']
)
useAppStore.getState().hydrateWorkspaceSession(restored.session, restored)
useAppStore.getState().hydrateTabsSession(restored.session)
expect(useAppStore.getState().restoredRuntimeHostIdByWorkspaceSessionKey[tab.worktreeId]).toBe(
'runtime:b'
)
const current = () => useAppStore.getState().unifiedTabsByWorktree[tab.worktreeId][0]
expect(current().executionHostId).toBeUndefined()
const folder = makeFolderWorkspace({ id: 'twin' })
useAppStore.setState({
activeWorkspaceExecutionHostId: 'runtime:b',
folderWorkspaces: [
{ ...folder, executionHostId: 'runtime:a' },
{ ...folder, executionHostId: 'runtime:b' }
]
})
const payload = {
...restored.session,
...buildPersistedUnifiedTabSessionData(useAppStore.getState())
}
expect(payload.unifiedTabs?.[tab.worktreeId]?.[0]).toBe(current())
await persistWorkspaceSessionByHost(api, payload, useAppStore.getState())
expect(partitions['runtime:a'].unifiedTabs?.[tab.worktreeId]?.[0]).toBe(current())
const reloaded = await fetchWorkspaceSessionWithRuntimeHostOwners(
api,
[],
['runtime:a', 'runtime:b']
)
expect(reloaded.contestedPrimaryHostBySessionKey[tab.worktreeId]).toBe('runtime:a')
useAppStore.getState().hydrateWorkspaceSession(reloaded.session, reloaded)
useAppStore.getState().hydrateTabsSession(reloaded.session)
expect(current().executionHostId).toBeUndefined()
useAppStore.setState({
activeWorktreeId: tab.worktreeId,
activeWorkspaceExecutionHostId: 'runtime:a'
})
mock.send.mockReturnValue({ outcome: Promise.resolve('recorded') })
expect(
await sendMessageToAgent({
worktreeId: tab.worktreeId,
target: { kind: 'structured-session', sessionId: tab.entityId },
prompt: 'hello'
})
).toEqual({ status: 'sent' })
expect(mock.send).toHaveBeenCalledWith(
expect.objectContaining({ target: { kind: 'environment', environmentId: 'a' } })
)
mock.paired = new Map([[tab.entityId, name(tab, 'Legacy paired')]])
mock.rpc.mockResolvedValue({ name: 'Legacy paired', applied: true })
await useAppStore.getState().reconnectPersistedTerminals()
expect(useAppStore.getState().workspaceSessionReady).toBe(true)
stops.push(installLegacyChatRenameMigration())
expect(
await uploadLegacyStructuredChatRename(
useAppStore.getState,
current(),
'Legacy paired',
'Legacy paired'
)
).toBe(false)
expect(mock.rpc).not.toHaveBeenCalled()
expect(current().customLabel).toBe('Legacy paired')
expect(readStructuredChatTabName(current(), useAppStore.getState())).toBe('Legacy paired')
useAppStore.setState({ activeWorktreeId: 'elsewhere' })
expect(mock.rpc).not.toHaveBeenCalled()
expect(readStructuredChatTabName(current(), useAppStore.getState())).toBe('Legacy paired')
useAppStore.setState({
activeWorktreeId: tab.worktreeId,
activeWorkspaceExecutionHostId: 'runtime:b'
})
expect(mock.rpc).not.toHaveBeenCalled()
mock.paired.set(tab.entityId, name(tab, 'Explicit name'))
useAppStore.getState().setTabCustomTitle(current().id, ' Explicit name ')
// Navigation happens before the dynamic rename import resumes, with inventory still absent.
useAppStore.setState({
activeWorktreeId: 'elsewhere',
activeWorkspaceExecutionHostId: 'runtime:a'
})
await waitFor(() => expect(current().customLabel).toBe('Explicit name'))
expect(mock.rpc).toHaveBeenCalledExactlyOnceWith(
{ kind: 'environment', environmentId: 'b' },
'agentSession.rename',
{
sessionId: tab.entityId,
name: 'Explicit name'
}
)
expect(current().executionHostId).toBeUndefined()
expect(readStructuredChatTabName(current(), useAppStore.getState())).toBe('Explicit name')
await persistWorkspaceSessionByHost(
api,
{ ...reloaded.session, ...buildPersistedUnifiedTabSessionData(useAppStore.getState()) },
useAppStore.getState()
)
const renamed = await fetchWorkspaceSessionWithRuntimeHostOwners(
api,
[],
['runtime:a', 'runtime:b']
)
useAppStore.getState().hydrateWorkspaceSession(renamed.session, renamed)
useAppStore.getState().hydrateTabsSession(renamed.session)
useAppStore.setState({ activeWorktreeId: 'elsewhere' })
expect(current().executionHostId).toBeUndefined()
expect(readStructuredChatTabName(current(), useAppStore.getState())).toBe('Explicit name')
expect(mock.rpc).toHaveBeenCalledTimes(1)
// The existing migration retires the copy once catalog ownership is proved.
useAppStore.setState({ folderWorkspaces: [{ ...folder, executionHostId: 'runtime:b' }] })
await waitFor(() => expect(current().customLabel).toBeNull())
expect(mock.rpc).toHaveBeenLastCalledWith(
{ kind: 'environment', environmentId: 'b' },
'agentSession.rename',
{ sessionId: tab.entityId, name: 'Explicit name', legacyAlias: true }
)
expect(readStructuredChatTabName(current(), useAppStore.getState())).toBe('Explicit name')
})
@@ -44,11 +44,7 @@ import '@/store/slices/editor/file-ids/editor-file-ids'
import { replaceRuntimeEnvironmentRevisions } from '../../rpc/environment-revisions/runtime-environment-revision'
import '../../../../../shared/remote-runtime/remote-runtime-pty-id'
import '../terminal-handles/web-session-terminal-handle-events'
import {
_getWebSessionTabsReceiptTrackingCountsForTest,
_getWebSessionTabsTrackingCountsForTest,
resetWebSessionTabsSnapshotFreshnessForTests
} from '../tracking-lifecycle'
import { resetWebSessionTabsSnapshotFreshnessForTests } from '../tracking-lifecycle'
import { useWebSessionTabsSync } from '../use-web-session-tabs-sync'
import '../state'
import '../../../lib/window-activity/window-park-visibility'
@@ -3,14 +3,8 @@ import { cleanup } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useStore } from 'zustand'
import { createTestStore, mockApi, resetRemoteRuntimeMocks } from '../github-slice-test-harness'
import { mergeFetchedRepoCatalog, type FetchedRepoCatalog } from '../../repos/repo-catalog-merge'
import { projectHostSetupProjectionFromRepos } from '../../../../../shared/project-host-setup-projection'
import { createRepoUpdateActions } from '../../repos/repo-update'
import { findTaskPageDialogWorkItem } from '@/components/task-page/task-page-dialog-work-item'
import { getTaskPageRepoSourceContext } from '@/lib/work-items/task-repo-source-context'
import { taskPageGitHubResumeCache } from '@/components/task-page/github/task-page-github-resume-cache'
import { githubTaskBinding } from '@/lib/work-items/github/github-task-observation'
import type { AppState } from '../../types'
import { createGlobalSettingsFixture } from '../../../../../shared/global-settings-test-fixture'
import type { Repo } from '../../../../../shared/repo-types'
@@ -97,54 +91,6 @@ afterEach(() => {
})
describe('GitHub source collection lifetime', () => {
it('detaches old rows at the optimistic click and never publishes a pre-ack response', async () => {
const store = setup()
await store.getState().fetchWorkItems(repo.id, repo.path, 20, '')
const save = Promise.withResolvers<Repo>()
mockApi.repos.update.mockReturnValue(save.promise)
const pendingSave = store
.getState()
.setIssueSourcePreference(repo.id, repo.path, 'origin', 'local')
const detached = store.getState().getCachedWorkItems(repo.id, 20, '', repo.path)
const early = store.getState().fetchWorkItems(repo.id, repo.path, 20, '', { force: true })
await flush()
save.resolve({ ...repo, issueSourcePreference: 'origin' })
await pendingSave
expect(detached).toBeNull()
expect(await early).toBeUndefined()
expect(store.getState().getCachedWorkItems(repo.id, 20, '', repo.path)).toBeNull()
})
it('preserves the latest pressed value across intermediate A→B→A save replies', async () => {
const store = setup()
const catalog: FetchedRepoCatalog = {
repos: [repo],
reposAtRequest: [repo],
hostId: 'local',
projectHostSetupCompatibility: projectHostSetupProjectionFromRepos([repo]),
sourceOwner: store.getState().githubSourceCollections,
sourceWrites: store.getState().githubSourceCollections.catalogSnapshot()
}
const first = Promise.withResolvers<Repo>(),
last = Promise.withResolvers<Repo>()
mockApi.repos.update.mockReturnValueOnce(first.promise).mockReturnValueOnce(last.promise)
const b = store.getState().setIssueSourcePreference(repo.id, repo.path, 'origin', 'local')
const a = store.getState().setIssueSourcePreference(repo.id, repo.path, 'upstream', 'local')
first.resolve({ ...repo, issueSourcePreference: 'origin' })
await b
const intermediate = store.getState().repos[0].issueSourcePreference
expect(
mergeFetchedRepoCatalog(catalog, store.getState().repos).repos[0].issueSourcePreference
).toBe('upstream')
last.resolve({ ...repo, issueSourcePreference: 'upstream' })
await a
expect(intermediate).toBe('upstream')
expect(store.getState().repos[0].issueSourcePreference).toBe('upstream')
expect(
mergeFetchedRepoCatalog(catalog, store.getState().repos).repos[0].issueSourcePreference
).toBe('upstream')
})
it('rejects inverted A1/B/A2 list deliveries including page N', async () => {
const store = setup()
const a1 = Promise.withResolvers<ReturnType<typeof envelope>>()
@@ -171,249 +117,9 @@ describe('GitHub source collection lifetime', () => {
?.map((item) => item.url)
).toEqual([row('parent').url])
})
it('detaches only the selected host when two copies share both id and path', async () => {
const store = setup()
const ssh = { ...repo, executionHostId: 'ssh:box' as const, connectionId: 'box' }
store.setState({ repos: [repo, ssh] })
const localSource = getTaskPageRepoSourceContext(repo, 'github')
const sshSource = getTaskPageRepoSourceContext(ssh, 'github')
await store
.getState()
.fetchWorkItems(repo.id, repo.path, 20, '', { sourceContext: localSource })
await store.getState().fetchWorkItems(repo.id, repo.path, 20, '', { sourceContext: sshSource })
await store.getState().setIssueSourcePreference(ssh.id, ssh.path, 'origin', 'ssh:box')
expect(store.getState().getCachedWorkItems(ssh.id, 20, '', ssh.path, sshSource)).toBeNull()
expect(
store.getState().getCachedWorkItems(repo.id, 20, '', repo.path, localSource)
).toHaveLength(1)
})
it('returns obsolete for a served-source contradiction rather than wrong-source rows', async () => {
const store = setup()
await store.getState().setIssueSourcePreference(repo.id, repo.path, 'origin', 'local')
mockApi.gh.listWorkItems.mockResolvedValue(envelope('parent'))
expect(await store.getState().fetchWorkItemsAcrossRepos(args, 20, 20, '')).toBeUndefined()
})
it('terminates a failed save and failed resync, restores the acknowledged choice, and permits retry', async () => {
const store = setup()
mockApi.repos.update.mockRejectedValueOnce(new Error('save rejected'))
store.setState({ fetchReposForAllHosts: vi.fn().mockRejectedValue(new Error('resync failed')) })
await store.getState().setIssueSourcePreference(repo.id, repo.path, 'origin', 'local')
expect(store.getState().repos[0].issueSourcePreference).toBeUndefined()
mockApi.gh.listWorkItems.mockResolvedValueOnce(envelope('parent'))
expect(await store.getState().fetchWorkItems(repo.id, repo.path, 20, '')).toHaveLength(1)
await store.getState().setIssueSourcePreference(repo.id, repo.path, 'upstream', 'local')
expect(store.getState().repos[0].issueSourcePreference).toBe('upstream')
})
it('certifies Submit after a failed write only once the host row is read back', async () => {
const store = setup()
// The host may have committed origin although the acknowledgement was lost.
mockApi.repos.update.mockRejectedValueOnce(new Error('request timed out'))
const recovery = Promise.withResolvers<void>()
store.setState({ fetchReposForAllHosts: vi.fn().mockReturnValue(recovery.promise) })
const owner = store.getState().githubSourceCollections
await store.getState().setIssueSourcePreference(repo.id, repo.path, 'origin', 'local')
const waiting = owner.awaitSave(store.getState().repos[0])
await flush()
recovery.reject(new Error('catalog unreachable'))
const unverified = await waiting
expect(unverified !== 'save-failed' && unverified()).toBe(false)
const readBack = vi.fn(async () => {
const started = owner.catalogSnapshot()
store.setState((s) => ({ repos: s.repos.map((row) => owner.adopt({ ...row }, started)) }))
})
store.setState({ fetchReposForAllHosts: readBack })
const ready = await owner.awaitSave(store.getState().repos[0])
expect(ready !== 'save-failed' && ready()).toBe(true)
})
it('keeps another repository delivery current when one owner retires its mapping', async () => {
const store = setup()
const other = { ...repo, id: 'other', path: '/other' }
store.setState({ repos: [repo, other] })
await store.getState().fetchWorkItems(repo.id, repo.path, 20, '')
const held = Promise.withResolvers<ReturnType<typeof envelope>>()
mockApi.gh.listWorkItems.mockReturnValueOnce(held.promise)
const otherRows = store.getState().fetchWorkItems(other.id, other.path, 20, '')
await flush()
mockApi.gh.listWorkItems.mockResolvedValueOnce({
...envelope('parent'),
sources: { ...envelope('parent').sources, originCandidate: { owner: 'new-fork', repo: 'p' } }
})
await store.getState().fetchWorkItems(repo.id, repo.path, 20, 'label:new')
held.resolve(envelope('parent'))
expect(await otherRows).toHaveLength(1)
})
it('adopts a queued rename after an earlier queued account change replaced the owner', async () => {
const store = setup()
const bob = { host: 'github.com', user: 'bob' }
const account = Promise.withResolvers<Repo>()
mockApi.repos.update
.mockReturnValueOnce(account.promise)
.mockResolvedValueOnce({ ...repo, ghAccount: bob, displayName: 'New' })
const switching = store.getState().updateRepo(repo.id, { ghAccount: bob })
const renaming = store.getState().updateRepo(repo.id, { displayName: 'New' })
account.resolve({ ...repo, ghAccount: bob })
expect([await switching, await renaming]).toEqual([true, true])
expect(store.getState().repos[0].displayName).toBe('New')
})
it('retires removed owners and their cached pages', async () => {
const k = 3
const store = setup()
const gone = Array.from({ length: k }, (_, i) => ({
...repo,
id: `gone-${i}`,
path: `/g${i}`
}))
store.setState({ repos: [repo, ...gone] })
await store.getState().fetchWorkItems(repo.id, repo.path, 20, '')
await store.getState().fetchWorkItems(gone[0].id, gone[0].path, 20, '')
const owner = store.getState().githubSourceCollections
const goneCount = owner.countKey([owner.capture(gone[0]).scope], '', 20)
owner.answer(goneCount, [owner.capture(gone[0])], { totalCount: 1, totalPages: 1 }, '', 20)
taskPageGitHubResumeCache.write('gone', 1, [row('parent')], undefined, [owner.context(gone[0])])
const cache = store.getState().workItemsCache
store.setState({ repos: [repo, gone[0]] })
expect(store.getState().workItemsCache).toBe(cache)
store.setState({ repos: [repo] })
expect(Object.keys(store.getState().workItemsCache)).toHaveLength(1)
expect(owner.count(goneCount)).toBeUndefined()
expect(taskPageGitHubResumeCache.read('gone', 1)).toBeNull()
})
it('ends a held read whose owner is removed and re-added, but keeps an unbound read', async () => {
const store = setup()
const owner = store.getState().githubSourceCollections
const save = Promise.withResolvers<Repo>()
mockApi.repos.update.mockReturnValueOnce(save.promise)
const saving = store.getState().setIssueSourcePreference(repo.id, repo.path, 'origin', 'local')
const reading = owner.readCurrent(store.getState().repos, () =>
store.getState().fetchWorkItems(repo.id, repo.path, 20, '')
)
await flush()
store.setState({ repos: [] })
store.setState({ repos: [{ ...repo, issueSourcePreference: 'origin' }] })
save.resolve({ ...repo, issueSourcePreference: 'origin' })
await saving
expect(await reading).toBeUndefined()
expect(mockApi.gh.listWorkItems).not.toHaveBeenCalled()
expect(store.getState().workItemsCache).toEqual({})
const unbound = await owner.readCurrent([undefined], () =>
store.getState().fetchWorkItems('unregistered', '/unregistered', 20, '')
)
expect(unbound).toHaveLength(1)
})
it('follows superseding saves without spending reads, then reads once', async () => {
const store = setup()
const saves = [0, 1, 2].map(() => Promise.withResolvers<Repo>())
for (const save of saves) {
mockApi.repos.update.mockReturnValueOnce(save.promise)
}
mockApi.gh.listWorkItems.mockResolvedValue(envelope('fork'))
const set = () =>
store.getState().setIssueSourcePreference(repo.id, repo.path, 'origin', 'local')
const pending = [set()]
const reading = store
.getState()
.githubSourceCollections.readCurrent(store.getState().repos, () =>
store.getState().fetchWorkItems(repo.id, repo.path, 20, '')
)
for (let superseding = 0; superseding < 2; superseding++) {
await flush()
pending.push(set())
}
for (const save of saves) {
save.resolve({ ...repo, issueSourcePreference: 'origin' })
await flush()
}
await Promise.all(pending)
expect(await reading).toHaveLength(1)
})
it('opens the clicked current-binding row over an older binding copy of the same issue', async () => {
const store = setup()
mockApi.gh.listWorkItems.mockResolvedValueOnce({
...envelope('parent'),
items: [{ ...row('parent'), title: 'Old title' }]
})
await store.getState().fetchWorkItems(repo.id, repo.path, 20, '')
await store.getState().setIssueSourcePreference(repo.id, repo.path, 'upstream', 'local')
mockApi.gh.listWorkItems.mockResolvedValueOnce({
...envelope('parent'),
items: [{ ...row('parent'), title: 'Fresh title' }]
})
const [clicked] =
(await store.getState().fetchWorkItems(repo.id, repo.path, 20, '', { force: true })) ?? []
expect(
findTaskPageDialogWorkItem(
store.getState().workItemsCache,
clicked,
githubTaskBinding(store.getState().repos[0])
)?.title
).toBe('Fresh title')
})
})
describe('source mapping and estimate retirement', () => {
it('keeps unregistered legacy reads usable without certifying another repository estimate', async () => {
const store = setup()
mockApi.gh.listWorkItems.mockResolvedValueOnce({ ...envelope('parent'), items: [] })
await store.getState().fetchWorkItems('unregistered-a', '/unregistered-a', 20, '')
mockApi.gh.countWorkItems.mockResolvedValueOnce(40)
expect(
await store
.getState()
.countWorkItemsAcrossRepos([{ repoId: 'unregistered-b', path: '/unregistered-b' }], '', 20)
).toEqual({ totalCount: 40, totalPages: 2 })
})
it('joins an already running discovery without another list, retains known answers on opaque failure, and retires complete empty evidence', async () => {
const store = setup()
const held = Promise.withResolvers<ReturnType<typeof envelope>>()
mockApi.gh.listWorkItems.mockReturnValueOnce(held.promise)
mockApi.gh.countWorkItems.mockResolvedValue(60)
const counting = store.getState().countWorkItemsAcrossRepos(args, '', 20)
const list = store.getState().fetchWorkItems(repo.id, repo.path, 20, '')
await flush()
held.resolve(envelope('parent'))
await list
expect(await counting).toEqual({ totalCount: 60, totalPages: 3 })
const owner = store.getState().githubSourceCollections
const key = owner.countKey([owner.capture(store.getState().repos[0]).scope], '', 20)
mockApi.gh.countWorkItems.mockResolvedValue(0)
expect(await store.getState().countWorkItemsAcrossRepos(args, '', 20)).toBeUndefined()
expect(owner.count(key)?.totalCount).toBe(60)
mockApi.gh.countWorkItems.mockRejectedValueOnce(new Error('offline'))
expect(await store.getState().countWorkItemsAcrossRepos(args, '', 20)).toBeUndefined()
expect(owner.count(key)?.totalCount).toBe(60)
mockApi.gh.listWorkItems.mockResolvedValueOnce({
...envelope('parent'),
items: [],
errors: { issues: { type: 'unknown', message: 'partial' } }
})
await store.getState().fetchWorkItems(repo.id, repo.path, 20, '', { force: true })
mockApi.gh.countWorkItems.mockResolvedValueOnce(20)
expect(await store.getState().countWorkItemsAcrossRepos(args, '', 20)).toBeUndefined()
expect(owner.count(key)?.totalCount).toBe(60)
mockApi.gh.listWorkItems.mockResolvedValueOnce({ ...envelope('parent'), items: [] })
await store.getState().fetchWorkItems(repo.id, repo.path, 20, '', { force: true })
expect(owner.count(key)).toBeUndefined()
expect(await store.getState().countWorkItemsAcrossRepos(args, '', 20)).toEqual({
totalCount: 0,
totalPages: 0
})
})
it('retires every query and resume page when origin alone changes, and cannot revive a removed owner through a pending save', async () => {
const store = setup()
await store.getState().fetchWorkItems(repo.id, repo.path, 20, '')
@@ -1,712 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createTestStore } from '../testing/app-store-test-fixture'
import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types'
import type { ProjectGroup } from '../../../../shared/project-group-types'
import type { Project, ProjectHostSetup } from '../../../../shared/project-types'
import type { Repo } from '../../../../shared/repo-types'
import {
createCompatibleRuntimeStatusResponseIfNeeded,
type RuntimeEnvironmentCallRequest
} from '../../runtime/rpc/testing/runtime-compatibility-test-fixture'
import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '../../runtime/rpc/compatibility/runtime-compatibility-cache'
import { getSetupScriptPromptDismissalKey } from '../../runtime/repo-hooks/setup-script-prompt'
const localRepo: Repo = {
id: 'local-repo',
path: '/local',
displayName: 'Local',
badgeColor: '#000',
addedAt: 1
}
const remoteRepo: Repo = {
id: 'remote-repo',
path: '/srv/repo',
displayName: 'Remote',
badgeColor: '#000',
addedAt: 1
}
const localProject: Project = {
id: 'local-project',
displayName: 'Local project',
badgeColor: '#000',
sourceRepoIds: ['local-repo'],
createdAt: 1,
updatedAt: 1
}
const localProjectHostSetup: ProjectHostSetup = {
id: 'local-setup',
projectId: 'local-project',
hostId: 'local',
repoId: 'local-repo',
path: '/local',
displayName: 'Local setup',
setupState: 'setting-up',
setupMethod: 'imported-existing-folder',
createdAt: 1,
updatedAt: 1
}
const localProjectGroup: ProjectGroup = {
id: 'local-group',
name: 'Local group',
parentPath: '/local',
parentGroupId: null,
createdFrom: 'manual',
tabOrder: 0,
isCollapsed: false,
color: null,
createdAt: 1,
updatedAt: 1
}
const remoteProjectGroup: ProjectGroup = {
id: 'remote-group',
name: 'Remote group',
parentPath: '/srv',
parentGroupId: null,
createdFrom: 'manual',
tabOrder: 0,
isCollapsed: false,
color: null,
createdAt: 1,
updatedAt: 1
}
const localFolderWorkspace: FolderWorkspace = {
id: 'local-folder',
projectGroupId: 'local-group',
name: 'Local folder',
folderPath: '/local',
linkedTask: null,
comment: '',
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 1,
createdAt: 1,
updatedAt: 1
}
const remoteFolderWorkspace: FolderWorkspace = {
id: 'remote-folder',
projectGroupId: 'remote-group',
name: 'Remote folder',
folderPath: '/srv',
linkedTask: null,
comment: '',
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 1,
createdAt: 1,
updatedAt: 1
}
const reposList = vi.fn()
const projectsList = vi.fn()
const listHostSetups = vi.fn()
const projectGroupsList = vi.fn()
const folderWorkspacesList = vi.fn()
const runtimeEnvironmentsList = vi.fn()
const runtimeEnvironmentCall = vi.fn()
const runtimeEnvironmentTransportCall = vi.fn()
const dispatchEventMock = vi.fn()
beforeEach(() => {
clearRuntimeCompatibilityCacheForTests()
reposList.mockReset()
projectsList.mockReset()
listHostSetups.mockReset()
projectGroupsList.mockReset()
folderWorkspacesList.mockReset()
runtimeEnvironmentsList.mockReset()
runtimeEnvironmentCall.mockReset()
runtimeEnvironmentTransportCall.mockReset()
dispatchEventMock.mockReset()
reposList.mockResolvedValue([localRepo])
projectsList.mockResolvedValue([localProject])
listHostSetups.mockResolvedValue([localProjectHostSetup])
projectGroupsList.mockResolvedValue([localProjectGroup])
folderWorkspacesList.mockResolvedValue([localFolderWorkspace])
runtimeEnvironmentsList.mockResolvedValue([{ id: 'env-1', name: 'lobster' }])
runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => {
if (args.method === 'repo.list') {
return {
id: 'rpc-repo-list',
ok: true,
result: { repos: [remoteRepo] },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (args.method === 'projectGroup.list') {
return {
id: 'rpc-project-group-list',
ok: true,
result: { groups: [remoteProjectGroup] },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (args.method === 'folderWorkspace.list') {
return {
id: 'rpc-folder-workspace-list',
ok: true,
result: { folderWorkspaces: [remoteFolderWorkspace] },
_meta: { runtimeId: 'runtime-remote' }
}
}
return {
id: 'rpc-other',
ok: true,
result: { projects: [], setups: [] },
_meta: { runtimeId: 'runtime-remote' }
}
})
runtimeEnvironmentTransportCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => {
return createCompatibleRuntimeStatusResponseIfNeeded(args) ?? runtimeEnvironmentCall(args)
})
vi.stubGlobal('window', {
api: {
repos: { list: reposList },
projects: { list: projectsList, listHostSetups: listHostSetups },
projectGroups: { list: projectGroupsList },
folderWorkspaces: { list: folderWorkspacesList },
runtimeEnvironments: {
call: runtimeEnvironmentTransportCall,
list: runtimeEnvironmentsList
}
},
dispatchEvent: dispatchEventMock
})
})
function configureSharedProjectCompatibilityMocks(
options: {
localRepoHasProviderIdentity?: boolean
remoteProjectRuntimePreference?: Project['localWindowsRuntimePreference']
} = {}
): {
sharedProjectId: string
sharedRemoteProject: Project
} {
const sharedProjectId = 'github:stablyai/orca'
const localRepoForSharedProject: Repo =
options.localRepoHasProviderIdentity === false
? localRepo
: {
...localRepo,
upstream: { owner: 'stablyai', repo: 'orca' }
}
const remoteRepoWithIdentity: Repo = {
...remoteRepo,
upstream: { owner: 'stablyai', repo: 'orca' }
}
const sharedLocalProject: Project = {
id: sharedProjectId,
displayName: 'Orca',
badgeColor: '#000',
sourceRepoIds: ['local-repo'],
localWindowsRuntimePreference: { kind: 'windows-host' },
createdAt: 1,
updatedAt: 1
}
const sharedRemoteProject: Project = {
id: sharedProjectId,
displayName: 'Orca',
badgeColor: '#111',
sourceRepoIds: ['remote-repo'],
...(options.remoteProjectRuntimePreference
? { localWindowsRuntimePreference: options.remoteProjectRuntimePreference }
: {}),
createdAt: 2,
updatedAt: 2
}
const sharedLocalSetup: ProjectHostSetup = {
...localProjectHostSetup,
projectId: sharedProjectId
}
const sharedRemoteSetup: ProjectHostSetup = {
...localProjectHostSetup,
id: 'remote-setup',
projectId: sharedProjectId,
repoId: 'remote-repo',
path: '/srv/repo',
displayName: 'Remote setup'
}
reposList.mockResolvedValue([localRepoForSharedProject])
projectsList.mockResolvedValue([sharedLocalProject])
listHostSetups.mockResolvedValue([sharedLocalSetup])
runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => {
if (args.method === 'repo.list') {
return {
id: 'rpc-repo-list',
ok: true,
result: { repos: [remoteRepoWithIdentity] },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (args.method === 'project.list') {
return {
id: 'rpc-project-list',
ok: true,
result: { projects: [sharedRemoteProject] },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (args.method === 'projectHostSetup.list') {
return {
id: 'rpc-project-host-setup-list',
ok: true,
result: { setups: [sharedRemoteSetup] },
_meta: { runtimeId: 'runtime-remote' }
}
}
return {
id: 'rpc-other',
ok: true,
result: {},
_meta: { runtimeId: 'runtime-remote' }
}
})
return { sharedProjectId, sharedRemoteProject }
}
function expectSharedProjectMetadata(projects: readonly Project[], sharedProjectId: string): void {
const sharedProject = projects.find((project) => project.id === sharedProjectId)
expect([...(sharedProject?.sourceRepoIds ?? [])].sort()).toEqual(['local-repo', 'remote-repo'])
expect(sharedProject?.localWindowsRuntimePreference).toEqual({ kind: 'windows-host' })
}
function directSshRepo(targetId: string): Repo {
return {
...localRepo,
id: 're-adopted-repo',
connectionId: targetId,
executionHostId: `ssh:${targetId}`
}
}
const repoReadoption = {
oldTargetId: 'ssh-old',
newTargetId: 'ssh-new',
repoIds: ['re-adopted-repo']
}
describe('fetchReposForAllHosts', () => {
it('reconciles a targeted runtime response against the latest repo state', async () => {
const staleRepo = directSshRepo('ssh-old')
const liveRepo = directSshRepo('ssh-new')
let resolveRepoList!: (response: unknown) => void
const repoListResponse = new Promise((resolve) => (resolveRepoList = resolve))
runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => {
if (args.method === 'repo.list') {
return repoListResponse
}
return {
id: 'rpc-other',
ok: true,
result: { projects: [], setups: [] },
_meta: { runtimeId: 'runtime-remote' }
}
})
const store = createTestStore()
store.setState({
repos: [staleRepo],
pendingSshRepoReadoptions: [repoReadoption]
})
const load = store.getState().fetchRuntimeEnvironmentRepos('env-1')
store.setState({ repos: [staleRepo, liveRepo] })
resolveRepoList({
id: 'rpc-repo-list',
ok: true,
result: { repos: [remoteRepo] },
_meta: { runtimeId: 'runtime-remote' }
})
await load
expect(store.getState().repos).toEqual([
liveRepo,
{ ...remoteRepo, executionHostId: 'runtime:env-1' }
])
})
it('preserves runtime-owned project metadata during a local-only repo refresh', async () => {
const runtimeProject: Project = {
id: 'repo:remote-repo',
displayName: 'Runtime API project',
badgeColor: '#abc',
sourceRepoIds: ['remote-repo'],
createdAt: 3,
updatedAt: 4
}
const runtimeSetup: ProjectHostSetup = {
...localProjectHostSetup,
id: 'runtime-setup',
projectId: runtimeProject.id,
repoId: 'remote-repo',
path: '/srv/repo',
displayName: 'Runtime setup',
setupState: 'ready',
createdAt: 3,
updatedAt: 4
}
runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => {
if (args.method === 'repo.list') {
return {
id: 'rpc-repo-list',
ok: true,
result: { repos: [remoteRepo] },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (args.method === 'project.list') {
return {
id: 'rpc-project-list',
ok: true,
result: { projects: [runtimeProject] },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (args.method === 'projectHostSetup.list') {
return {
id: 'rpc-project-host-setup-list',
ok: true,
result: { setups: [runtimeSetup] },
_meta: { runtimeId: 'runtime-remote' }
}
}
return {
id: 'rpc-other',
ok: true,
result: {},
_meta: { runtimeId: 'runtime-remote' }
}
})
const store = createTestStore()
await store.getState().fetchReposForAllHosts()
await store.getState().fetchRepos({ runtimeEnvironmentId: null })
expect(
store
.getState()
.projects.map((project) => project.id)
.sort()
).toEqual(['local-project', 'repo:remote-repo'])
expect(store.getState().projects.find((project) => project.id === runtimeProject.id)).toEqual(
expect.objectContaining({
displayName: runtimeProject.displayName,
badgeColor: runtimeProject.badgeColor
})
)
})
it('preserves shared project metadata when the same project id is fetched from multiple hosts', async () => {
const { sharedProjectId } = configureSharedProjectCompatibilityMocks()
const store = createTestStore()
store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never })
await store.getState().fetchReposForAllHosts()
expectSharedProjectMetadata(store.getState().projects, sharedProjectId)
const setups = store.getState().projectHostSetups
expect(setups).toHaveLength(2)
expect(setups).toEqual(
expect.arrayContaining([
expect.objectContaining({
projectId: sharedProjectId,
hostId: 'local',
repoId: 'local-repo'
}),
expect.objectContaining({
projectId: sharedProjectId,
hostId: 'runtime:env-1',
repoId: 'remote-repo'
})
])
)
})
it('keeps local Windows runtime preference when remote project metadata has its own preference', async () => {
const { sharedProjectId } = configureSharedProjectCompatibilityMocks({
remoteProjectRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' }
})
const store = createTestStore()
store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never })
await store.getState().fetchReposForAllHosts()
expect(
store.getState().projects.find((project) => project.id === sharedProjectId)
?.localWindowsRuntimePreference
).toEqual({ kind: 'windows-host' })
})
it('keeps the local side of a shared project when a runtime refresh removes its repos', async () => {
const { sharedProjectId } = configureSharedProjectCompatibilityMocks()
const store = createTestStore()
store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never })
await store.getState().fetchReposForAllHosts()
runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => {
if (args.method === 'repo.list') {
return {
id: 'rpc-repo-list-empty',
ok: true,
result: { repos: [] },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (args.method === 'project.list') {
return {
id: 'rpc-project-list-empty',
ok: true,
result: { projects: [] },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (args.method === 'projectHostSetup.list') {
return {
id: 'rpc-project-host-setup-list-empty',
ok: true,
result: { setups: [] },
_meta: { runtimeId: 'runtime-remote' }
}
}
return {
id: 'rpc-other',
ok: true,
result: {},
_meta: { runtimeId: 'runtime-remote' }
}
})
await store.getState().fetchRuntimeEnvironmentRepos('env-1')
const sharedProject = store
.getState()
.projects.find((project) => project.id === sharedProjectId)
expect(sharedProject?.sourceRepoIds).toEqual(['local-repo'])
expect(sharedProject?.localWindowsRuntimePreference).toEqual({ kind: 'windows-host' })
expect(store.getState().projectHostSetups).toEqual([
expect.objectContaining({
projectId: sharedProjectId,
hostId: 'local',
repoId: 'local-repo'
})
])
})
it('preserves API-owned local shared projects when repo identity cannot re-derive them', async () => {
const { sharedProjectId } = configureSharedProjectCompatibilityMocks({
localRepoHasProviderIdentity: false
})
const store = createTestStore()
store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never })
await store.getState().fetchReposForAllHosts()
expectSharedProjectMetadata(store.getState().projects, sharedProjectId)
runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => {
if (args.method === 'repo.list') {
return {
id: 'rpc-repo-list-empty',
ok: true,
result: { repos: [] },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (args.method === 'project.list') {
return {
id: 'rpc-project-list-empty',
ok: true,
result: { projects: [] },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (args.method === 'projectHostSetup.list') {
return {
id: 'rpc-project-host-setup-list-empty',
ok: true,
result: { setups: [] },
_meta: { runtimeId: 'runtime-remote' }
}
}
return {
id: 'rpc-other',
ok: true,
result: {},
_meta: { runtimeId: 'runtime-remote' }
}
})
await store.getState().fetchRuntimeEnvironmentRepos('env-1')
expect(store.getState().projects.map((project) => project.id)).toEqual([sharedProjectId])
expect(
store.getState().projects.find((project) => project.id === sharedProjectId)?.sourceRepoIds
).toEqual(['local-repo'])
expect(store.getState().projectHostSetups).toEqual([
expect.objectContaining({
projectId: sharedProjectId,
hostId: 'local',
repoId: 'local-repo'
})
])
})
it('drops refreshed-host source ownership when that repo no longer matches a shared project', async () => {
const { sharedProjectId } = configureSharedProjectCompatibilityMocks()
const store = createTestStore()
store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never })
await store.getState().fetchReposForAllHosts()
runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => {
if (args.method === 'repo.list') {
return {
id: 'rpc-repo-list-reassigned',
ok: true,
result: { repos: [remoteRepo] },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (args.method === 'project.list') {
return {
id: 'rpc-project-list-empty',
ok: true,
result: { projects: [] },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (args.method === 'projectHostSetup.list') {
return {
id: 'rpc-project-host-setup-list-empty',
ok: true,
result: { setups: [] },
_meta: { runtimeId: 'runtime-remote' }
}
}
return {
id: 'rpc-other',
ok: true,
result: {},
_meta: { runtimeId: 'runtime-remote' }
}
})
await store.getState().fetchRuntimeEnvironmentRepos('env-1')
expect(
store.getState().projects.find((project) => project.id === sharedProjectId)?.sourceRepoIds
).toEqual(['local-repo'])
expect(
store
.getState()
.projects.map((project) => project.id)
.sort()
).toEqual(['github:stablyai/orca', 'repo:remote-repo'])
expect(store.getState().projectHostSetups).toEqual(
expect.arrayContaining([
expect.objectContaining({
projectId: sharedProjectId,
hostId: 'local',
repoId: 'local-repo'
}),
expect.objectContaining({
projectId: 'repo:remote-repo',
hostId: 'runtime:env-1',
repoId: 'remote-repo'
})
])
)
})
it('drops stale runtime repo ownership when project metadata lags behind repo removal', async () => {
const { sharedProjectId, sharedRemoteProject } = configureSharedProjectCompatibilityMocks()
const store = createTestStore()
store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never })
await store.getState().fetchReposForAllHosts()
runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => {
if (args.method === 'repo.list') {
return {
id: 'rpc-repo-list-empty',
ok: true,
result: { repos: [] },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (args.method === 'project.list') {
return {
id: 'rpc-project-list-stale',
ok: true,
result: { projects: [sharedRemoteProject] },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (args.method === 'projectHostSetup.list') {
return {
id: 'rpc-project-host-setup-list-empty',
ok: true,
result: { setups: [] },
_meta: { runtimeId: 'runtime-remote' }
}
}
return {
id: 'rpc-other',
ok: true,
result: {},
_meta: { runtimeId: 'runtime-remote' }
}
})
await store.getState().fetchRuntimeEnvironmentRepos('env-1')
expect(
store.getState().projects.find((project) => project.id === sharedProjectId)?.sourceRepoIds
).toEqual(['local-repo'])
})
it('preserves remote repo filters during first-paint local catalog refresh', async () => {
const store = createTestStore()
const remoteDismissalKey = getSetupScriptPromptDismissalKey('runtime:env-1\0remote-repo')
const staleDismissalKey = getSetupScriptPromptDismissalKey('local\0stale-repo')
store.setState({
activeRepoId: 'remote-repo',
filterRepoIds: ['remote-repo', 'stale-repo'],
setupScriptPromptDismissedRepoIds: [remoteDismissalKey, staleDismissalKey],
trustedOrcaHooks: {
'remote-repo': { all: { approvedAt: 1 } },
'stale-repo': { all: { approvedAt: 2 } }
}
})
await store.getState().fetchReposForAllHosts({ remoteHosts: 'skip' })
expect(store.getState().activeRepoId).toBe('remote-repo')
expect(store.getState().filterRepoIds).toEqual(['remote-repo', 'stale-repo'])
expect(store.getState().setupScriptPromptDismissedRepoIds).toEqual([
remoteDismissalKey,
staleDismissalKey
])
expect(store.getState().trustedOrcaHooks).toEqual({
'remote-repo': { all: { approvedAt: 1 } },
'stale-repo': { all: { approvedAt: 2 } }
})
await store.getState().fetchReposForAllHosts()
expect(store.getState().activeRepoId).toBe('remote-repo')
expect(store.getState().filterRepoIds).toEqual(['remote-repo'])
expect(store.getState().setupScriptPromptDismissedRepoIds).toEqual([remoteDismissalKey])
expect(store.getState().trustedOrcaHooks).toEqual({
'remote-repo': { all: { approvedAt: 1 } }
})
})
})
@@ -11,7 +11,6 @@ import type { Repo } from '../../../../../shared/repo-types'
import type { Worktree } from '../../../../../shared/worktree/types'
import '../../../../../shared/execution-host'
import { createTestStore } from '../../testing/app-store-test-fixture'
import { selectWorktreeDiffCommentsOrEmpty } from './worktree-diff-comments-selector'
vi.mock('../../../runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => ({
...(await importOriginal<typeof RuntimeRpcCallModule>()),
@@ -86,23 +85,6 @@ function rowNotes(store: ReturnType<typeof createTwinStore>, hostId: string): st
return (row?.diffComments ?? []).map((comment) => comment.body)
}
function addNote(store: ReturnType<typeof createTwinStore>) {
return addNoteFor(store, capturedOwner(store, WT))
}
function addNoteFor(store: ReturnType<typeof createTwinStore>, owner: DiffCommentOwner | null) {
if (!owner) {
throw new Error('no workspace')
}
return store.getState().addDiffComment(owner, {
worktreeId: WT,
filePath: 'README.md',
lineNumber: 1,
body: 'ssh note',
side: 'modified'
})
}
beforeEach(() => {
vi.mocked(callRuntimeRpc).mockClear()
vi.mocked(toast.error).mockClear()
@@ -111,123 +93,6 @@ beforeEach(() => {
updateMeta.mockResolvedValue({})
})
describe('diff comments on twin worktrees', () => {
it('saves to the open twin and names its host', async () => {
const store = createTwinStore('ssh:box')
expect(await addNote(store)).not.toBeNull()
expect(rowNotes(store, 'ssh:box')).toEqual(['ssh note'])
expect(rowNotes(store, 'local')).toEqual([])
// What the notes panel and diff gutters render.
expect(selectWorktreeDiffCommentsOrEmpty(store.getState(), WT).map((c) => c.body)).toEqual([
'ssh note'
])
expect(updateMeta).toHaveBeenCalledWith(
expect.objectContaining({ worktreeId: WT, executionHostId: 'ssh:box' })
)
})
it('rolls back only the twin it wrote', async () => {
const store = createTwinStore('ssh:box')
store.setState({
worktreesByRepo: {
[REPO]: [worktree('local', [note('l1', 'local note')]), worktree('ssh:box')]
}
})
updateMeta.mockRejectedValueOnce(new Error('write failed'))
expect(await addNote(store)).toBeNull()
expect(rowNotes(store, 'ssh:box')).toEqual([])
expect(rowNotes(store, 'local')).toEqual(['local note'])
})
it('drops a queued save whose twin left, instead of writing the other copy under its host', async () => {
const store = createTwinStore('ssh:box')
store.setState({
worktreesByRepo: {
[REPO]: [worktree('local', [note('l1', 'local note')]), worktree('ssh:box')]
}
})
const pending = addNote(store)
store.setState({ worktreesByRepo: { [REPO]: [worktree('local', [note('l1', 'local note')])] } })
expect(await pending).toBeNull()
expect(updateMeta).not.toHaveBeenCalled()
expect(rowNotes(store, 'local')).toEqual(['local note'])
})
it('keeps one queue for a copy when its twin leaves between saves', async () => {
const store = createTwinStore('ssh:box')
updateMeta.mockRejectedValue(new Error('write failed'))
const first = addNote(store)
// The local copy goes before the second save, so the SSH copy is the only row left.
store.setState({ worktreesByRepo: { [REPO]: [store.getState().worktreesByRepo[REPO][1]] } })
const second = addNote(store)
expect(await first).toBeNull()
expect(await second).toBeNull()
expect(rowNotes(store, 'ssh:box')).toEqual([])
})
it('writes every duplicated row of one copy, so reads see the note', async () => {
const store = createTwinStore(null)
store.setState({ worktreesByRepo: { [REPO]: [worktree('local'), worktree('local')] } })
expect(await addNote(store)).not.toBeNull()
expect(
store
.getState()
.getDiffComments(WT)
.map((c) => c.body)
).toEqual(['ssh note'])
})
it('rolls a failed burst back to disk when a listing stamps the row mid-burst', async () => {
const store = createTwinStore('local')
store.setState({ worktreesByRepo: { [REPO]: [worktree(undefined)] } })
updateMeta.mockRejectedValue(new Error('write failed'))
const first = addNote(store)
const [row] = store.getState().worktreesByRepo[REPO]
store.setState({ worktreesByRepo: { [REPO]: [{ ...row, hostId: 'local' }] } })
const second = addNote(store)
expect(await first).toBeNull()
expect(await second).toBeNull()
expect(rowNotes(store, 'local')).toEqual([])
})
it('reports a save main refused as failed and rolls it back', async () => {
const store = createTwinStore('ssh:box')
updateMeta.mockResolvedValueOnce(null)
expect(await addNote(store)).toBeNull()
expect(rowNotes(store, 'ssh:box')).toEqual([])
})
it('refuses a note-id change on an unstamped twin rather than route it by the open one', async () => {
const store = createTwinStore('ssh:box')
store.setState({
worktreesByRepo: {
[REPO]: [worktree(undefined, [note('u1', 'unstamped')]), worktree('ssh:box')]
}
})
await store.getState().deleteDiffComment(capturedOwner(store, WT), 'u1')
expect(updateMeta).not.toHaveBeenCalled()
expect(store.getState().worktreesByRepo[REPO][0].diffComments?.map((c) => c.body)).toEqual([
'unstamped'
])
})
})
function capturedOwner(store: { getState: () => AppState }, worktreeId: string): DiffCommentOwner {
const { owner } = selectDiffCommentView(store.getState(), worktreeId, 'selection')
if (!owner) {
@@ -6,17 +6,13 @@ import type { DiffComment } from '../../../../../shared/diff-comment-types'
import type { FolderWorkspace } from '../../../../../shared/folder-workspaces/folder-workspace-types'
import type { ProjectGroup } from '../../../../../shared/project-group-types'
import { folderWorkspaceKey } from '../../../../../shared/workspace-scope'
import type { PublicKnownRuntimeEnvironment } from '../../../../../shared/remote-runtime/host-catalog/runtime-environments'
import { SELF_LOCAL_AUTHORITY } from '../../../../../shared/host-authority'
import {
createCompatibleRuntimeStatusResponseIfNeeded,
type RuntimeEnvironmentCallRequest
} from '../../../runtime/rpc/testing/runtime-compatibility-test-fixture'
import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '../../../runtime/rpc/compatibility/runtime-compatibility-cache'
import {
clearRuntimeEnvironmentConnectionGenerations as clearRuntimeEnvironmentConnectionGenerationsForTests,
setRuntimeEnvironmentConnectionGenerationForTests
} from '../runtime-status/runtime-status-connection-generation'
import { clearRuntimeEnvironmentConnectionGenerations as clearRuntimeEnvironmentConnectionGenerationsForTests } from '../runtime-status/runtime-status-connection-generation'
import { createDiffCommentsSlice } from './create-diff-comments-slice'
import { makeProjectGroup } from '@/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit-fixtures'
@@ -92,31 +88,6 @@ function addNote(
})
}
function folderNote(worktreeId: string, body: string): DiffComment {
return {
id: body,
worktreeId,
filePath: 'README.md',
lineNumber: 1,
body,
createdAt: 1,
side: 'modified'
}
}
function savedServer(id: string): PublicKnownRuntimeEnvironment {
return {
id,
name: id,
createdAt: 1,
updatedAt: 1,
lastUsedAt: null,
runtimeId: id,
endpoints: [{ id: 'ws', kind: 'websocket', label: 'WebSocket', endpoint: 'ws://server' }],
preferredEndpointId: 'ws'
}
}
function bodies(store: ReturnType<typeof createTestStore>, workspaceKey: string): string[] {
return store
.getState()
@@ -134,59 +105,6 @@ beforeEach(() => {
})
describe('folder workspace diff comments', () => {
it('preserves a second note while the first write is in flight', async () => {
const store = createTestStore()
const folderWorkspace = seedLocalFolderWorkspace(store)
let releaseFirstWrite: (() => void) | undefined
const firstWrite = new Promise<void>((resolve) => {
releaseFirstWrite = resolve
})
folderWorkspacesUpdate.mockImplementation(async ({ updates }) => {
if (folderWorkspacesUpdate.mock.calls.length === 1) {
await firstWrite
}
return { ...folderWorkspace, ...updates }
})
const addFirst = store
.getState()
.addDiffComment(capturedOwner(store, folderWorkspaceKey(folderWorkspace.id)), {
worktreeId: folderWorkspaceKey(folderWorkspace.id),
filePath: 'README.md',
source: 'markdown',
lineNumber: 1,
body: 'first note',
side: 'modified'
})
await vi.waitFor(() => expect(folderWorkspacesUpdate).toHaveBeenCalledTimes(1))
const addSecond = store
.getState()
.addDiffComment(capturedOwner(store, folderWorkspaceKey(folderWorkspace.id)), {
worktreeId: folderWorkspaceKey(folderWorkspace.id),
filePath: 'README.md',
source: 'markdown',
lineNumber: 2,
body: 'second note',
side: 'modified'
})
releaseFirstWrite?.()
await Promise.all([addFirst, addSecond])
expect(store.getState().getDiffComments(folderWorkspaceKey(folderWorkspace.id))).toEqual([
expect.objectContaining({ body: 'first note' }),
expect.objectContaining({ body: 'second note' })
])
expect(folderWorkspacesUpdate).toHaveBeenLastCalledWith({
folderWorkspaceId: folderWorkspace.id,
updates: {
diffComments: [
expect.objectContaining({ body: 'first note' }),
expect.objectContaining({ body: 'second note' })
]
}
})
})
it.each([false, true])(
'keeps inherited same-id writes scoped to their original hosts, reversed=%s',
async (reverse) => {
@@ -304,144 +222,6 @@ describe('folder workspace diff comment rollback convergence', () => {
errSpy.mockRestore()
})
it('converges to disk when two consecutive writes fail', async () => {
const store = createTestStore()
const folderWorkspace = seedLocalFolderWorkspace(store)
const key = folderWorkspaceKey(folderWorkspace.id)
let rejectFirst!: (err: Error) => void
folderWorkspacesUpdate.mockImplementation(() => {
if (folderWorkspacesUpdate.mock.calls.length === 1) {
return new Promise((_resolve, reject) => {
rejectFirst = reject
})
}
return Promise.reject(new Error('disk full'))
})
const addA = addNote(store, key, 'note A', 1)
await vi.waitFor(() => expect(folderWorkspacesUpdate).toHaveBeenCalledTimes(1))
const addB = addNote(store, key, 'note B', 2)
rejectFirst(new Error('disk full'))
await expect(Promise.all([addA, addB])).resolves.toEqual([null, null])
expect(folderWorkspacesUpdate).toHaveBeenCalledTimes(2)
expect(store.getState().getDiffComments(key)).toEqual([])
})
it('keeps a durably saved note when a coalesced write succeeds before a later failure', async () => {
const store = createTestStore()
const folderWorkspace = seedLocalFolderWorkspace(store)
const key = folderWorkspaceKey(folderWorkspace.id)
folderWorkspacesUpdate.mockImplementation(async ({ updates }) => {
if (folderWorkspacesUpdate.mock.calls.length > 1) {
throw new Error('disk full')
}
return { ...folderWorkspace, ...updates }
})
// Why: both mutations land before the first write dequeues, so write 1 coalesces and persists [A,B].
const addA = addNote(store, key, 'note A', 1)
const addB = addNote(store, key, 'note B', 2)
await Promise.all([addA, addB])
expect(folderWorkspacesUpdate).toHaveBeenNthCalledWith(1, {
folderWorkspaceId: folderWorkspace.id,
updates: {
diffComments: [
expect.objectContaining({ body: 'note A' }),
expect.objectContaining({ body: 'note B' })
]
}
})
expect(bodies(store, key)).toEqual(['note A', 'note B'])
})
it('converges to the partially-written list when only the first write landed', async () => {
const store = createTestStore()
const folderWorkspace = seedLocalFolderWorkspace(store)
const key = folderWorkspaceKey(folderWorkspace.id)
let releaseFirst!: () => void
folderWorkspacesUpdate.mockImplementation(async ({ updates }) => {
if (folderWorkspacesUpdate.mock.calls.length === 1) {
await new Promise<void>((resolve) => {
releaseFirst = resolve
})
return { ...folderWorkspace, ...updates }
}
throw new Error('disk full')
})
const addA = addNote(store, key, 'note A', 1)
await vi.waitFor(() => expect(folderWorkspacesUpdate).toHaveBeenCalledTimes(1))
const addB = addNote(store, key, 'note B', 2)
releaseFirst()
await Promise.all([addA, addB])
// Why: write 1 persisted only [A], so [A] is the floor B's failure converges to.
expect(bodies(store, key)).toEqual(['note A'])
})
it('rolls back to the list the queue drained on, not a stale burst floor', async () => {
const store = createTestStore()
const folderWorkspace = seedLocalFolderWorkspace(store)
const key = folderWorkspaceKey(folderWorkspace.id)
folderWorkspacesUpdate.mockImplementation(() => Promise.reject(new Error('disk full')))
await Promise.all([addNote(store, key, 'A', 1), addNote(store, key, 'B', 2)])
// Why: the drained queue must not carry its floor into the next burst.
const hydrated = [
{
id: 'h1',
worktreeId: key,
filePath: 'README.md',
lineNumber: 9,
body: 'hydrated',
createdAt: 1,
side: 'modified'
} as DiffComment
]
store.setState({ folderWorkspaces: [{ ...folderWorkspace, diffComments: hydrated }] })
await addNote(store, key, 'D', 4)
expect(store.getState().getDiffComments(key)).toBe(hydrated)
})
it('keeps an out-of-band replacement when a later mutation in the same burst fails', async () => {
const store = createTestStore()
const folderWorkspace = seedLocalFolderWorkspace(store)
const key = folderWorkspaceKey(folderWorkspace.id)
let rejectFirst!: (err: Error) => void
folderWorkspacesUpdate.mockImplementation(() => {
if (folderWorkspacesUpdate.mock.calls.length === 1) {
return new Promise((_resolve, reject) => {
rejectFirst = reject
})
}
return Promise.reject(new Error('disk full'))
})
const addA = addNote(store, key, 'note A', 1)
await vi.waitFor(() => expect(folderWorkspacesUpdate).toHaveBeenCalledTimes(1))
const hydrated = [
{
id: 'h1',
worktreeId: key,
filePath: 'README.md',
lineNumber: 9,
body: 'hydrated',
createdAt: 1,
side: 'modified'
} as DiffComment
]
store.setState({ folderWorkspaces: [{ ...folderWorkspace, diffComments: hydrated }] })
const addE = addNote(store, key, 'note E', 2)
rejectFirst(new Error('disk full'))
await Promise.all([addA, addE])
expect(bodies(store, key)).toEqual(['hydrated'])
})
it('keeps an out-of-band replacement when the in-flight write succeeds', async () => {
const store = createTestStore()
const folderWorkspace = seedLocalFolderWorkspace(store)
@@ -478,158 +258,6 @@ describe('folder workspace diff comment rollback convergence', () => {
await Promise.all([addA, addE])
expect(bodies(store, key)).toEqual(['hydrated'])
})
it('keeps a successful write that straddles a chain break as the floor', async () => {
const store = createTestStore()
const folderWorkspace = seedLocalFolderWorkspace(store)
const key = folderWorkspaceKey(folderWorkspace.id)
folderWorkspacesUpdate.mockImplementation(async ({ updates }) => {
if (folderWorkspacesUpdate.mock.calls.length > 1) {
throw new Error('disk full')
}
return { ...folderWorkspace, ...updates }
})
// Why: no await, so the replacement + E land before A dequeues — A's payload already carries `hydrated`.
const addA = addNote(store, key, 'note A', 1)
const hydrated = [
{
id: 'h1',
worktreeId: key,
filePath: 'README.md',
lineNumber: 9,
body: 'hydrated',
createdAt: 1,
side: 'modified'
} as DiffComment
]
store.setState({ folderWorkspaces: [{ ...folderWorkspace, diffComments: hydrated }] })
const addE = addNote(store, key, 'note E', 2)
await Promise.all([addA, addE])
// Why: write #1 put ['hydrated', 'note E'] on disk, so E's failure must not roll back past it.
expect(bodies(store, key)).toEqual(['hydrated', 'note E'])
expect(folderWorkspacesUpdate.mock.calls[0][0].updates.diffComments).toEqual([
expect.objectContaining({ body: 'hydrated' }),
expect.objectContaining({ body: 'note E' })
])
})
it('rolls back a runtime note whose server was replaced while the write was in flight', async () => {
const store = createTestStore()
const runtimeWorkspace = makeFolderWorkspace({
executionHostId: 'runtime:env-owner',
connectionId: 'nested-box'
})
const key = folderWorkspaceKey(runtimeWorkspace.id)
store.setState({
activeWorktreeId: key,
activeWorkspaceExecutionHostId: 'runtime:env-owner',
folderWorkspaces: [runtimeWorkspace]
})
runtimeEnvironmentCall.mockImplementation(async (args: { params: { updates: object } }) => {
// Why: the reply may come from the old runtime; whether the write landed is unknown.
setRuntimeEnvironmentConnectionGenerationForTests('env-owner', 1)
return {
id: 'rpc-folder-update',
ok: true,
result: {
folderWorkspace: {
...runtimeWorkspace,
...args.params.updates
}
},
_meta: { runtimeId: 'remote-runtime' }
}
})
await expect(addNote(store, key, 'A', 1)).resolves.toBeNull()
expect(runtimeEnvironmentCall).toHaveBeenCalledWith(
expect.objectContaining({ selector: 'env-owner', method: 'folderWorkspace.update' })
)
expect(store.getState().getDiffComments(key)).toEqual([])
expect(folderWorkspacesUpdate).not.toHaveBeenCalled()
})
it('drops a queued folder save once its catalog endpoint is replaced, touching no other copy', async () => {
Object.assign(globalThis, { __ORCA_WEB_CLIENT__: true })
try {
const store = createTestStore()
const key = folderWorkspaceKey('folder-1')
const folder = makeFolderWorkspace({ diffComments: [folderNote(key, 'hub A')] })
store.setState({
activeWorktreeId: key,
activeWorkspaceExecutionHostId: 'local',
runtimeEnvironments: [savedServer('hub-a')],
folderWorkspaces: [folder]
})
const owner = capturedOwner(store, key)
expect(owner).toMatchObject({ runtimeEnvironmentId: 'hub-a' })
const pending = store.getState().addDiffComment(owner, {
worktreeId: key,
filePath: 'README.md',
lineNumber: 2,
body: 'added',
side: 'modified'
})
const replacement = { ...folder, diffComments: [folderNote(key, 'hub B')] }
store.setState({
runtimeEnvironments: [savedServer('hub-b')],
folderWorkspaces: [replacement]
})
expect(await pending).toBeNull()
expect(runtimeEnvironmentCall).not.toHaveBeenCalledWith(
expect.objectContaining({ method: 'folderWorkspace.update' })
)
expect(folderWorkspacesUpdate).not.toHaveBeenCalled()
expect(store.getState().folderWorkspaces).toEqual([replacement])
} finally {
Reflect.deleteProperty(globalThis, '__ORCA_WEB_CLIENT__')
}
})
it('keeps a failing burst scoped to its own execution host', async () => {
const store = createTestStore()
const workspaceId = 'shared-folder-id'
const key = folderWorkspaceKey(workspaceId)
const localWorkspace = makeFolderWorkspace({ id: workspaceId, projectGroupId: 'local-group' })
const runtimeWorkspace = makeFolderWorkspace({
id: workspaceId,
projectGroupId: 'runtime-group',
executionHostId: 'runtime:env-owner'
})
store.setState({
activeWorktreeId: key,
activeWorkspaceExecutionHostId: 'runtime:env-owner',
folderWorkspaces: [localWorkspace, runtimeWorkspace]
})
runtimeEnvironmentCall.mockImplementation(async (args: RuntimeEnvironmentCallRequest) => ({
id: 'rpc-folder-update',
ok: true,
result: {
folderWorkspace: {
...runtimeWorkspace,
...(
args as RuntimeEnvironmentCallRequest & {
params: { updates?: Partial<FolderWorkspace> }
}
).params.updates
}
},
_meta: { runtimeId: 'remote-runtime' }
}))
folderWorkspacesUpdate.mockImplementation(() => Promise.reject(new Error('disk full')))
await addNote(store, key, 'runtime note', 1)
store.setState({ activeWorkspaceExecutionHostId: 'local' })
await Promise.all([addNote(store, key, 'local A', 2), addNote(store, key, 'local B', 3)])
expect(store.getState().getDiffComments(key)).toEqual([])
store.setState({ activeWorkspaceExecutionHostId: 'runtime:env-owner' })
expect(bodies(store, key)).toEqual(['runtime note'])
})
})
function capturedOwner(store: { getState: () => AppState }, worktreeId: string): DiffCommentOwner {
@@ -17,7 +17,6 @@ import {
type TabsDrawnFromMain
} from '../../tabs/tabs-drawn-from-main.test-fixture'
import { contentRekeyOutcome } from '@/runtime/workspace-layout/intents/layout-owner-content-rekeys'
import { hasPendingEntityTab } from '@/runtime/workspace-layout/intents/layout-owner-pending-tabs'
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) =>
(
@@ -65,42 +64,6 @@ beforeEach(async () => {
afterEach(() => main.close())
function editorTabsAndFiles(worktreeId = WT) {
const state = useAppStore.getState()
const fileIds = new Set(state.openFiles.map((file) => file.id))
return (state.unifiedTabsByWorktree[worktreeId] ?? []).map((tab) => ({
kind: tab.contentType,
entity: tab.entityId,
hasFile: fileIds.has(tab.entityId)
}))
}
/** Non-empty groups only: an emptied group is never saved. */
function windowView(worktreeId: string) {
const state = useAppStore.getState()
const tabs = state.unifiedTabsByWorktree[worktreeId] ?? []
return (state.groupsByWorktree[worktreeId] ?? [])
.filter((group) => group.tabOrder.length > 0)
.map((group) => ({
group: group.id,
tabs: group.tabOrder.map((tabId) => {
const tab = tabs.find((entry) => entry.id === tabId)!
return { id: tab.id, entity: tab.entityId }
})
}))
}
function mainView(worktreeId: string) {
const workspace = layoutApplyTestTransport.mainModel!.workspaces[worktreeId]
return (workspace?.groups ?? []).map((group) => ({
group: group.id,
tabs: group.tabOrder.map((tabId) => {
const tab = workspace!.tabs.find((entry) => entry.id === tabId)!
return { id: tab.id, entity: tab.entityId }
})
}))
}
function openEdit(worktreeId: string, filePath: string, relativePath: string): string {
return useAppStore.getState().openFile(
{
@@ -119,232 +82,7 @@ function localMoveOwner(worktreeId: string | undefined): EditorMoveOwner {
return editorMoveOwnerFromContext({ target: { kind: 'local' } }, worktreeId)
}
describe.runIf(ORCA_LAYOUT_OWNER_IS_MAIN)('editor records under frames, layout-owner build', () => {
it('draws every editor tab main keeps, each with its file record', async () => {
const state = useAppStore.getState()
state.openFile(
{
filePath: '/repo-a/a.md',
relativePath: 'a.md',
worktreeId: WT,
runtimeEnvironmentId: null,
language: 'markdown',
mode: 'edit'
},
{ suppressActiveRuntimeFallback: true }
)
state.openDiff(WT, '/repo-a/b.ts', 'b.ts', 'typescript', false)
state.openMarkdownPreview({
filePath: '/repo-a/a.md',
relativePath: 'a.md',
worktreeId: WT,
runtimeEnvironmentId: null,
language: 'markdown'
})
await main.settle()
expect(editorTabsAndFiles()).toEqual([
{ kind: 'editor', entity: '/repo-a/a.md', hasFile: true },
{ kind: 'diff', entity: expect.any(String), hasFile: true },
{ kind: 'editor', entity: expect.any(String), hasFile: true }
])
// A diff or preview is kept by the view its open sent, not by the window's record.
expect(
layoutApplyTestTransport
.sentOfType('openEditorTab')
.map((command) => [command.contentType, command.view?.view.mode ?? null])
).toEqual([
['editor', null],
['diff', 'diff'],
['editor', 'markdown-preview']
])
})
it('drops a diff record with the tab main closed, and keeps a record no tab shows', async () => {
useAppStore.getState().openDiff(WT, '/repo-a/b.ts', 'b.ts', 'typescript', false)
await main.settle()
const diffTab = useAppStore.getState().unifiedTabsByWorktree[WT]![0]!
// A conflict review's selected file has no tab of its own.
useAppStore.setState({
openFiles: [
...useAppStore.getState().openFiles,
{
id: '/repo-a/c.ts',
filePath: '/repo-a/c.ts',
relativePath: 'c.ts',
worktreeId: WT,
language: 'typescript',
isDirty: false,
mode: 'edit'
}
]
})
// Main closes the diff tab (another client's close).
await layoutApplyTestTransport.call({
command: { type: 'closeTabs', workspace: WT, tabIds: [diffTab.id], force: true }
})
await main.settle()
expect(editorTabsAndFiles()).toEqual([])
expect(useAppStore.getState().openFiles.map((file) => file.id)).toEqual(['/repo-a/c.ts'])
})
})
describe.runIf(ORCA_LAYOUT_OWNER_IS_MAIN)('closing every editor, layout-owner build', () => {
it("keeps the files' content until main's frame drops their tabs", async () => {
const a = openEdit(WT, '/repo-a/a.ts', 'a.ts')
openEdit(WT, '/repo-a/b.ts', 'b.ts')
await main.settle()
useAppStore.getState().setEditorDraft(a, 'unsaved')
useAppStore.getState().closeAllFiles()
expect(useAppStore.getState().openFiles.map((file) => file.id)).toEqual([a, '/repo-a/b.ts'])
expect(useAppStore.getState().editorDrafts).toEqual({ [a]: 'unsaved' })
await main.settle()
const state = useAppStore.getState()
expect(editorTabsAndFiles()).toEqual([])
expect(state.openFiles).toEqual([])
expect(state.editorDrafts).toEqual({})
expect(state.recentlyClosedEditorTabsByWorktree[WT]?.map((entry) => entry.filePath)).toEqual([
'/repo-a/a.ts',
'/repo-a/b.ts'
])
})
it('cleans a file up once when it is closed again while its close is in flight', async () => {
const a = openEdit(WT, '/repo-a/a.ts', 'a.ts')
await main.settle()
useAppStore.getState().setEditorDraft(a, 'unsaved')
// A repeat close reaches main after the first emptied the workspace, which main refuses.
let closes = 0
layoutApplyTestTransport.answerWith(() =>
closes++ === 0 ? 'pending' : { ok: false, code: 'workspace_not_found' }
)
useAppStore.getState().closeFile(a)
useAppStore.getState().closeFile(a)
await main.settle()
layoutApplyTestTransport.answerWith('apply')
layoutApplyTestTransport.answerPending()
await main.settle()
const state = useAppStore.getState()
expect(editorTabsAndFiles()).toEqual([])
expect(state.openFiles).toEqual([])
expect(state.editorDrafts).toEqual({})
expect(state.recentlyClosedEditorTabsByWorktree[WT]?.map((entry) => entry.filePath)).toEqual([
'/repo-a/a.ts'
])
expect(layoutApplyTestTransport.sentOfType('closeTabs')).toHaveLength(1)
})
it("cleans a file up when it is closed during a bulk close's close of its tab", async () => {
const keep = openEdit(WT, '/repo-a/keep.ts', 'keep.ts')
const a = openEdit(WT, '/repo-a/a.ts', 'a.ts')
await main.settle()
useAppStore.getState().setEditorDraft(a, 'unsaved')
const keepTab = useAppStore
.getState()
.unifiedTabsByWorktree[WT]?.find((tab) => tab.entityId === keep)
layoutApplyTestTransport.answerWith('pending')
// "Close others" closes a's tab with no file cleanup; a closeFile lands while it is in flight.
useAppStore.getState().closeOtherTabs(keepTab?.id ?? '')
useAppStore.getState().closeFile(a)
layoutApplyTestTransport.answerWith('apply')
layoutApplyTestTransport.answerPending()
await main.settle()
const state = useAppStore.getState()
expect(editorTabsAndFiles().map((tab) => tab.entity)).toEqual([keep])
expect(state.openFiles.map((file) => file.id)).toEqual([keep])
expect(state.editorDrafts).toEqual({})
expect(layoutApplyTestTransport.sentOfType('closeTabs')).toHaveLength(1)
})
it('settles an open whose selection threw: its waiters run and nothing stays pending', async () => {
const activateTab = useAppStore.getState().activateTab
useAppStore.setState({
activateTab: () => {
throw new Error('selection failed')
}
})
const shown: unknown[] = []
useAppStore.getState().openFileForLink(
{
filePath: '/repo-a/a.ts',
relativePath: 'a.ts',
worktreeId: WT,
runtimeEnvironmentId: null,
language: 'typescript',
mode: 'edit'
},
undefined,
null,
(result) => shown.push(result)
)
await main.settle()
useAppStore.setState({ activateTab })
expect(shown).toEqual([expect.objectContaining({ fileId: '/repo-a/a.ts' })])
expect(hasPendingEntityTab(WT, '/repo-a/a.ts')).toBe(false)
})
it('keeps every file whose close main refused', async () => {
const a = openEdit(WT, '/repo-a/a.ts', 'a.ts')
await main.settle()
useAppStore.getState().setEditorDraft(a, 'unsaved')
layoutApplyTestTransport.answerWith({ refuse: 'tab_not_found' })
useAppStore.getState().closeAllFiles()
await main.settle()
expect(editorTabsAndFiles()).toEqual([{ kind: 'editor', entity: a, hasFile: true }])
expect(useAppStore.getState().editorDrafts).toEqual({ [a]: 'unsaved' })
})
})
describe.runIf(ORCA_LAYOUT_OWNER_IS_MAIN)('open files renamed on disk, layout-owner build', () => {
it("rekeys main's tabs and file records under the window's ids", async () => {
const plain = openEdit(WT, '/repo-a/src/a.ts', 'src/a.ts')
// The same path in a sibling workspace gets an owner-qualified id.
const owned = openEdit(SIBLING, '/repo-a/src/a.ts', 'src/a.ts')
useAppStore.getState().openDiff(WT, '/repo-a/src/a.ts', 'src/a.ts', 'typescript', false)
await main.settle()
expect(owned).toMatch(/^editor:/)
const sentBefore = layoutApplyTestTransport.sent.length
const result = remapOpenEditorTabsForPathChange({
fromPath: '/repo-a/src',
toPath: '/repo-a/lib',
worktreePath: '/repo-a',
worktreeId: WT,
owner: localMoveOwner(WT)
})
expect(result).toEqual({ ok: true })
await main.settle()
const commands = layoutApplyTestTransport.sent.slice(sentBefore)
// One command: main renames both workspaces' tabs or neither.
expect(
commands.map((command) => [
command.type,
command.workspace,
command.type === 'renameEditorFiles' ? command.alsoIn?.map((entry) => entry.workspace) : []
])
).toEqual([['renameEditorFiles', WT, [SIBLING]]])
expect(editorTabsAndFiles().map((tab) => tab.entity)).not.toContain(plain)
for (const worktreeId of [WT, SIBLING]) {
expect(mainView(worktreeId)).toEqual(windowView(worktreeId))
expect(layoutApplyTestTransport.mainModel!.workspaces[worktreeId]!.editorFiles).toEqual([
expect.objectContaining({ filePath: '/repo-a/lib/a.ts', relativePath: 'lib/a.ts' })
])
}
expect(editorTabsAndFiles(WT).every((tab) => tab.hasFile)).toBe(true)
expect(editorTabsAndFiles(SIBLING).every((tab) => tab.hasFile)).toBe(true)
})
it('changes neither workspace when main refuses the rename in one of them', async () => {
openEdit(WT, '/repo-a/src/a.ts', 'src/a.ts')
openEdit(SIBLING, '/repo-a/src/a.ts', 'src/a.ts')
@@ -421,176 +159,4 @@ describe.runIf(ORCA_LAYOUT_OWNER_IS_MAIN)('open files renamed on disk, layout-ow
])
expect(state.editorDrafts).toEqual({ '/repo-a/lib/a.ts': 'unsaved' })
})
it('changes nothing when main refuses the rename', async () => {
const oldId = openEdit(WT, '/repo-a/src/a.ts', 'src/a.ts')
await main.settle()
useAppStore.getState().setEditorDraft(oldId, 'unsaved')
const before = useAppStore.getState()
layoutApplyTestTransport.answerWith({ refuse: 'invalid_params' })
remapOpenEditorTabsForPathChange({
fromPath: '/repo-a/src',
toPath: '/repo-a/lib',
worktreePath: '/repo-a',
worktreeId: WT,
owner: localMoveOwner(WT),
moveOperationId: 'move-1'
})
expect(await contentRekeyOutcome([oldId])).toBe(false)
await main.settle()
const after = useAppStore.getState()
expect(after.openFiles).toEqual(before.openFiles)
expect(after.editorDrafts).toEqual({ [oldId]: 'unsaved' })
expect(after.unifiedTabsByWorktree).toEqual(before.unifiedTabsByWorktree)
})
it('settles a rename whose content rekey threw, so the move does not wait forever', async () => {
openEdit(WT, '/repo-a/b.ts', 'b.ts')
await main.settle()
// A conflict review's selected file has no tab: main's answer rekeys it.
useAppStore.setState({
openFiles: [
...useAppStore.getState().openFiles,
{
id: '/repo-a/src/c.ts',
filePath: '/repo-a/src/c.ts',
relativePath: 'src/c.ts',
worktreeId: WT,
language: 'typescript',
isDirty: false,
mode: 'edit'
}
]
})
const unsubscribe = useAppStore.subscribe((state) => {
if (state.openFiles.some((file) => file.filePath === '/repo-a/lib/c.ts')) {
throw new Error('a subscriber threw')
}
})
remapOpenEditorTabsForPathChange({
fromPath: '/repo-a/src',
toPath: '/repo-a/lib',
worktreePath: '/repo-a',
worktreeId: WT,
owner: localMoveOwner(WT)
})
const outcomes: boolean[] = []
void contentRekeyOutcome(['/repo-a/src/c.ts']).then((ok) => outcomes.push(ok))
await main.settle()
unsubscribe()
expect(outcomes).toEqual([false])
})
it("gives a renamed view tab's published view the file's new path", async () => {
useAppStore.getState().openDiff(WT, '/repo-a/src/a.ts', 'src/a.ts', 'typescript', false)
await main.settle()
remapOpenEditorTabsForPathChange({
fromPath: '/repo-a/src',
toPath: '/repo-a/lib',
worktreePath: '/repo-a',
worktreeId: WT,
owner: localMoveOwner(WT)
})
await main.settle()
const views = Object.values(layoutApplyTestTransport.mainModel!.workspaces[WT]!.editorViews!)
expect(views).toEqual([
expect.objectContaining({
file: expect.objectContaining({ filePath: '/repo-a/lib/a.ts', relativePath: 'lib/a.ts' })
})
])
expect(editorTabsAndFiles()).toEqual([
{ kind: 'diff', entity: expect.stringContaining('lib/a.ts'), hasFile: true }
])
})
})
describe.runIf(ORCA_LAYOUT_OWNER_IS_MAIN)(
'a resolved deleted-side conflict, layout-owner build',
() => {
it("closes the placeholder's tab in main, and the frame drops it", async () => {
const entry = {
path: 'gone.ts',
status: 'deleted' as const,
area: 'unstaged' as const,
conflictKind: 'deleted_by_us' as const,
conflictStatus: 'unresolved' as const,
conflictStatusSource: 'git' as const
}
useAppStore.getState().setGitStatus(WT, { entries: [entry], conflictOperation: 'merge' })
useAppStore.getState().openConflictFile(WT, '/repo-a', entry, 'typescript')
await main.settle()
expect(editorTabsAndFiles()).toEqual([
{ kind: 'editor', entity: '/repo-a/gone.ts', hasFile: true }
])
expect(layoutApplyTestTransport.mainModel!.workspaces[WT]!.tabs).toHaveLength(1)
const sentBefore = layoutApplyTestTransport.sent.length
useAppStore.getState().setGitStatus(WT, { entries: [], conflictOperation: 'merge' })
expect(
layoutApplyTestTransport.sent.slice(sentBefore).map((command) => command.type)
).toEqual(['closeTabs'])
await main.settle()
expect(layoutApplyTestTransport.mainModel!.workspaces[WT]?.tabs ?? []).toEqual([])
expect(editorTabsAndFiles()).toEqual([])
expect(useAppStore.getState().openFiles).toEqual([])
})
}
)
describe.runIf(ORCA_LAYOUT_OWNER_IS_MAIN)(
'a runtime-owned file the window opens, layout-owner build',
() => {
const FILE = '/repo-a/src/remote.ts'
const openRuntimeOwned = (onShown: (result: unknown) => void) =>
useAppStore.getState().openFileForLink(
{
filePath: FILE,
relativePath: 'src/remote.ts',
worktreeId: WT,
runtimeEnvironmentId: 'env-1',
language: 'typescript',
mode: 'edit'
},
undefined,
null,
onShown
)
it('keeps one id through frames, so its reveal runs and a rename reaches main', async () => {
const shown: unknown[] = []
openRuntimeOwned((result) => shown.push(result))
await main.settle()
const fileId = useAppStore.getState().openFiles[0]?.id
expect(shown).toEqual([expect.objectContaining({ fileId })])
expect(editorTabsAndFiles()).toEqual([{ kind: 'editor', entity: fileId, hasFile: true }])
expect(mainView(WT)).toEqual(windowView(WT))
remapOpenEditorTabsForPathChange({
fromPath: '/repo-a/src',
toPath: '/repo-a/lib',
worktreePath: '/repo-a',
worktreeId: WT,
owner: editorMoveOwnerFromContext(
{ target: { kind: 'environment', environmentId: 'env-1' } },
WT
)
})
expect(await contentRekeyOutcome([fileId ?? ''])).toBe(true)
await main.settle()
expect(layoutApplyTestTransport.mainModel?.workspaces[WT]?.editorFiles).toEqual([
expect.objectContaining({ filePath: '/repo-a/lib/remote.ts' })
])
expect(mainView(WT)).toEqual(windowView(WT))
expect(editorTabsAndFiles()).toEqual([
{ kind: 'editor', entity: expect.stringContaining('remote.ts'), hasFile: true }
])
})
}
)
@@ -1,638 +0,0 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { createTestStore } from '../../testing/app-store-test-fixture'
import { makeWorktree } from '../worktrees/worktree.test-fixture'
import type { AppState } from '../../types'
import type { WorktreeLineage } from '../../../../../shared/worktree/lineage-types'
import type { PublicKnownRuntimeEnvironment } from '../../../../../shared/remote-runtime/host-catalog/runtime-environments'
import { toast } from 'sonner'
import {
MIN_COMPATIBLE_RUNTIME_SERVER_VERSION,
MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION,
RUNTIME_PROTOCOL_VERSION
} from '../../../../../shared/protocol-version'
import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '../../../runtime/rpc/compatibility/runtime-compatibility-cache'
import {
RUNTIME_CATALOG_STALE_MS,
resetRuntimeCatalogListingForTests
} from '../runtime-status/runtime-status-hydration'
vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn(), info: vi.fn() } }))
vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>()
return {
...actual,
detectAgentStatusFromTitle: vi.fn().mockReturnValue(null)
}
})
const runtimeEnvironmentCall = vi.fn()
const runtimeEnvironmentGetStatus = vi.fn()
const settingsSet = vi.fn().mockResolvedValue(undefined)
const settingsGet = vi.fn()
const runtimeEnvironmentList = vi.fn()
const setActiveRuntimeEnvironmentPreference = vi.fn().mockResolvedValue(undefined)
const worktreesListDetected = vi.fn()
const env2Lineage: WorktreeLineage = {
worktreeId: 'repo-env-2::/env-2/repo',
worktreeInstanceId: 'env-2-instance',
parentWorktreeId: 'repo-env-2::/env-2/parent',
parentWorktreeInstanceId: 'env-2-parent-instance',
origin: 'manual',
capture: { source: 'manual-action', confidence: 'explicit' },
createdAt: 1
}
function makeRuntimeEnvironment(id: string): PublicKnownRuntimeEnvironment {
const endpointId = `ws-${id}`
return {
id,
name: id,
createdAt: 1,
updatedAt: 1,
lastUsedAt: null,
runtimeId: null,
endpoints: [{ id: endpointId, kind: 'websocket', label: 'WebSocket', endpoint: 'ws://x' }],
preferredEndpointId: endpointId
}
}
function deferred<T>() {
let resolve: (value: T) => void = () => {}
let reject: (reason?: unknown) => void = () => {}
const promise = new Promise<T>((promiseResolve, promiseReject) => {
resolve = promiseResolve
reject = promiseReject
})
return { promise, resolve, reject }
}
beforeEach(() => {
delete (globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__
clearRuntimeCompatibilityCacheForTests()
resetRuntimeCatalogListingForTests()
vi.clearAllMocks()
runtimeEnvironmentGetStatus.mockResolvedValue({
id: 'status-rpc-1',
ok: true,
result: {
runtimeId: 'runtime-2',
graphStatus: 'ready',
runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION,
minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION
},
_meta: { runtimeId: 'runtime-2' }
})
settingsGet.mockResolvedValue({ notifications: {} })
runtimeEnvironmentList.mockResolvedValue([])
runtimeEnvironmentCall.mockImplementation(
({ method, params }: { method: string; params?: { repo?: string } }) => {
const detectedRepoId = params?.repo ?? 'repo-env-2'
const detectedPath = detectedRepoId === 'repo-env-1' ? '/env-1/repo' : '/env-2/repo'
const result =
method === 'status.get'
? {
runtimeId: 'runtime-2',
graphStatus: 'ready',
runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION,
minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION
}
: method === 'repo.list'
? {
repos: [
{
id: 'repo-env-2',
path: '/env-2/repo',
displayName: 'Env 2',
badgeColor: 'blue',
addedAt: 1
}
]
}
: method === 'worktree.list'
? {
worktrees: [
makeWorktree({
id: 'repo-env-2::/env-2/repo',
repoId: 'repo-env-2',
path: '/env-2/repo'
})
],
totalCount: 1,
truncated: false
}
: method === 'worktree.detectedList'
? {
repoId: detectedRepoId,
authoritative: true,
source: 'git',
worktrees: [
{
...makeWorktree({
id: `${detectedRepoId}::${detectedPath}`,
repoId: detectedRepoId,
path: detectedPath
}),
ownership: 'orca-managed',
selectedCheckout: true,
visible: true
}
]
}
: method === 'browser.profileList'
? { profiles: [] }
: method === 'projectGroup.list'
? { groups: [] }
: method === 'worktree.lineageList'
? { lineage: { [env2Lineage.worktreeId]: env2Lineage } }
: method === 'settings.get'
? { settings: {} }
: {}
return Promise.resolve({ id: 'rpc-1', ok: true, result, _meta: { runtimeId: 'runtime-2' } })
}
)
worktreesListDetected.mockResolvedValue({
repoId: 'repo-env-1',
authoritative: true,
source: 'git',
worktrees: [
{
...makeWorktree({
id: 'repo-env-1::/env-1/repo',
repoId: 'repo-env-1',
path: '/env-1/repo'
}),
ownership: 'orca-managed',
selectedCheckout: true,
visible: true
}
]
})
vi.stubGlobal('window', {
api: {
settings: { get: settingsGet, set: settingsSet, setActiveRuntimeEnvironmentPreference },
runtimeEnvironments: {
call: runtimeEnvironmentCall,
getStatus: runtimeEnvironmentGetStatus,
list: runtimeEnvironmentList
},
worktrees: { listDetected: worktreesListDetected }
}
})
})
describe('createSettingsSlice runtime switching', () => {
it('preserves existing host state while loading the selected environment', async () => {
const store = createTestStore()
store.setState({
settings: { activeRuntimeEnvironmentId: 'env-1' } as AppState['settings'],
repos: [
{
id: 'repo-env-1',
path: '/env-1/repo',
displayName: 'Env 1',
executionHostId: 'runtime:env-1'
} as never
],
projectGroups: [
{
id: 'group-env-1',
name: 'Env 1 Group',
parentPath: '/env-1',
parentGroupId: null,
createdFrom: 'manual',
tabOrder: 0,
isCollapsed: false,
color: null,
createdAt: 1,
updatedAt: 1
}
],
worktreesByRepo: {
'repo-env-1': [makeWorktree({ id: 'repo-env-1::/env-1/repo', repoId: 'repo-env-1' })]
},
worktreeLineageById: {
'repo-env-1::/env-1/repo': {
...env2Lineage,
worktreeId: 'repo-env-1::/env-1/repo',
parentWorktreeId: 'repo-env-1::/env-1/parent'
}
},
activeWorktreeId: 'repo-env-1::/env-1/repo',
openFiles: [{ id: '/env-1/repo/a.md', worktreeId: 'repo-env-1::/env-1/repo' } as never],
ptyIdsByTabId: { tab1: ['remote:env-1@@terminal-a'] },
terminalLayoutsByTabId: {
tab1: {
root: null,
activeLeafId: null,
expandedLeafId: null,
ptyIdsByLeafId: { 'pane:1': 'remote:legacy-terminal' }
}
},
browserTabsByWorktree: { 'repo-env-1::/env-1/repo': [{ id: 'browser-env-1' }] as never },
browserPagesByWorkspace: {
'browser-env-1': [{ id: 'page-env-1', worktreeId: 'repo-env-1::/env-1/repo' }] as never
},
remoteBrowserPageHandlesByPageId: {
'page-env-1': { environmentId: 'env-1', remotePageId: 'remote-page-1' }
},
editorDrafts: { '/env-1/repo/stale.md': 'stale' },
markdownViewMode: { '/env-1/repo/stale.md': 'rich' },
editorViewMode: { '/env-1/repo/stale.md': 'changes' },
markdownFrontmatterVisible: { '/env-1/repo/stale.md': false },
editorCursorLine: { '/env-1/repo/stale.md': 4 },
showDotfilesByWorktree: { 'repo-env-1::/env-1/repo': false },
gitIgnoredPathsByWorktree: { 'repo-env-1::/env-1/repo': ['dist/'] },
prCache: { '/env-1/repo::main': { data: null, fetchedAt: Date.now() } },
linearIssueCache: { 'LIN-1': { data: { id: 'LIN-1' } as never, fetchedAt: Date.now() } },
jiraIssueCache: { 'JIRA-1': { data: { key: 'JIRA-1' } as never, fetchedAt: Date.now() } }
})
await expect(store.getState().setActiveRuntimeEnvironmentPreference('env-2')).resolves.toBe(
true
)
expect(setActiveRuntimeEnvironmentPreference).toHaveBeenCalledWith({ environmentId: 'env-2' })
expect(runtimeEnvironmentGetStatus).toHaveBeenCalledWith({
selector: 'env-2',
timeoutMs: 15_000
})
expect(runtimeEnvironmentCall).toHaveBeenCalledWith(
expect.objectContaining({ selector: 'env-2', method: 'status.get' })
)
expect(runtimeEnvironmentCall).toHaveBeenCalledWith(
expect.objectContaining({ selector: 'env-2', method: 'repo.list' })
)
expect(runtimeEnvironmentCall).toHaveBeenCalledWith(
expect.objectContaining({ selector: 'env-2', method: 'worktree.lineageList' })
)
expect(runtimeEnvironmentCall).not.toHaveBeenCalledWith(
expect.objectContaining({ selector: 'env-1', method: 'terminal.close' })
)
expect(runtimeEnvironmentCall).not.toHaveBeenCalledWith(
expect.objectContaining({ selector: 'env-1', method: 'browser.tabClose' })
)
expect(store.getState().repos.map((repo) => repo.id)).toEqual(['repo-env-1', 'repo-env-2'])
expect(store.getState().repos.find((repo) => repo.id === 'repo-env-2')?.executionHostId).toBe(
'runtime:env-2'
)
expect(store.getState().worktreeVisibilityDefaultsByHost['runtime:env-2']).toBeNull()
expect(store.getState().projectGroups.map((group) => group.id)).toEqual(['group-env-1'])
expect(store.getState().worktreesByRepo['repo-env-1']?.map((worktree) => worktree.id)).toEqual([
'repo-env-1::/env-1/repo'
])
expect(store.getState().worktreesByRepo['repo-env-2']?.map((worktree) => worktree.id)).toEqual([
'repo-env-2::/env-2/repo'
])
expect(store.getState().worktreeLineageById).toEqual({
'repo-env-1::/env-1/repo': {
...env2Lineage,
worktreeId: 'repo-env-1::/env-1/repo',
parentWorktreeId: 'repo-env-1::/env-1/parent'
},
[env2Lineage.worktreeId]: env2Lineage
})
expect(store.getState().activeWorktreeId).toBe('repo-env-1::/env-1/repo')
expect(store.getState().openFiles).toEqual([
{ id: '/env-1/repo/a.md', worktreeId: 'repo-env-1::/env-1/repo' }
])
expect(store.getState().editorDrafts).toEqual({ '/env-1/repo/stale.md': 'stale' })
expect(store.getState().markdownViewMode).toEqual({ '/env-1/repo/stale.md': 'rich' })
expect(store.getState().editorViewMode).toEqual({ '/env-1/repo/stale.md': 'changes' })
expect(store.getState().markdownFrontmatterVisible).toEqual({
'/env-1/repo/stale.md': false
})
expect(store.getState().editorCursorLine).toEqual({ '/env-1/repo/stale.md': 4 })
expect(store.getState().showDotfilesByWorktree).toEqual({ 'repo-env-1::/env-1/repo': false })
expect(store.getState().gitIgnoredPathsByWorktree).toEqual({
'repo-env-1::/env-1/repo': ['dist/']
})
expect(store.getState().ptyIdsByTabId).toEqual({ tab1: ['remote:env-1@@terminal-a'] })
expect(store.getState().browserTabsByWorktree).toEqual({
'repo-env-1::/env-1/repo': [{ id: 'browser-env-1' }]
})
expect(store.getState().prCache).toEqual({
'/env-1/repo::main': expect.objectContaining({ data: null })
})
expect(store.getState().linearIssueCache).toEqual({
'LIN-1': expect.objectContaining({ data: { id: 'LIN-1' } })
})
expect(store.getState().jiraIssueCache).toEqual({
'JIRA-1': expect.objectContaining({ data: { key: 'JIRA-1' } })
})
})
it('keeps the previous host live terminal and browser resources intact on switch (multi-host keepalive)', async () => {
const store = createTestStore()
store.setState({
settings: { activeRuntimeEnvironmentId: 'env-1' } as AppState['settings'],
repos: [
{
id: 'repo-env-1',
path: '/env-1/repo',
displayName: 'Env 1',
executionHostId: 'runtime:env-1'
} as never
],
worktreesByRepo: {
'repo-env-1': [makeWorktree({ id: 'repo-env-1::/env-1/repo', repoId: 'repo-env-1' })]
},
activeWorktreeId: 'repo-env-1::/env-1/repo',
tabsByWorktree: {
'repo-env-1::/env-1/repo': [
{
id: 'host-tab-1',
ptyId: 'remote:env-1@@terminal-a',
worktreeId: 'repo-env-1::/env-1/repo',
title: 'Terminal 1',
defaultTitle: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
ptyIdsByTabId: { 'host-tab-1': ['remote:env-1@@terminal-a'] },
terminalLayoutsByTabId: {
'host-tab-1': {
root: null,
activeLeafId: null,
expandedLeafId: null,
ptyIdsByLeafId: { 'pane:1': 'remote:env-1@@terminal-a' }
}
},
browserPagesByWorkspace: {
'browser-env-1': [{ id: 'page-env-1', worktreeId: 'repo-env-1::/env-1/repo' }] as never
},
remoteBrowserPageHandlesByPageId: {
'page-env-1': { environmentId: 'env-1', remotePageId: 'remote-page-1' }
}
})
await expect(store.getState().setActiveRuntimeEnvironmentPreference('env-2')).resolves.toBe(
true
)
expect(runtimeEnvironmentCall).not.toHaveBeenCalledWith(
expect.objectContaining({ selector: 'env-1', method: 'terminal.close' })
)
expect(runtimeEnvironmentCall).not.toHaveBeenCalledWith(
expect.objectContaining({ selector: 'env-1', method: 'browser.tabClose' })
)
expect(store.getState().tabsByWorktree).toEqual({
'repo-env-1::/env-1/repo': [
{
id: 'host-tab-1',
ptyId: 'remote:env-1@@terminal-a',
worktreeId: 'repo-env-1::/env-1/repo',
title: 'Terminal 1',
defaultTitle: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
})
expect(store.getState().ptyIdsByTabId).toEqual({
'host-tab-1': ['remote:env-1@@terminal-a']
})
expect(store.getState().terminalLayoutsByTabId).toEqual({
'host-tab-1': {
root: null,
activeLeafId: null,
expandedLeafId: null,
ptyIdsByLeafId: { 'pane:1': 'remote:env-1@@terminal-a' }
}
})
expect(store.getState().browserPagesByWorkspace).toEqual({
'browser-env-1': [{ id: 'page-env-1', worktreeId: 'repo-env-1::/env-1/repo' }]
})
expect(store.getState().remoteBrowserPageHandlesByPageId).toEqual({
'page-env-1': { environmentId: 'env-1', remotePageId: 'remote-page-1' }
})
})
it('allows switching focus while editor tabs have unsaved state', async () => {
const store = createTestStore()
store.setState({
settings: { activeRuntimeEnvironmentId: 'env-1' } as AppState['settings'],
openFiles: [
{
id: '/env-1/repo/dirty.md',
worktreeId: 'repo-env-1::/env-1/repo',
isDirty: true
} as never
],
editorDrafts: { '/env-1/repo/dirty.md': 'draft' }
})
await expect(store.getState().setActiveRuntimeEnvironmentPreference('env-2')).resolves.toBe(
true
)
expect(setActiveRuntimeEnvironmentPreference).toHaveBeenCalledWith({ environmentId: 'env-2' })
expect(runtimeEnvironmentCall).toHaveBeenCalledWith(
expect.objectContaining({ selector: 'env-2', method: 'repo.list' })
)
expect(store.getState().settings?.activeRuntimeEnvironmentId).toBe('env-2')
expect(store.getState().openFiles).toHaveLength(1)
expect(store.getState().editorDrafts).toEqual({ '/env-1/repo/dirty.md': 'draft' })
expect(toast.error).not.toHaveBeenCalled()
})
it('keeps the current environment when the selected remote server is unreachable', async () => {
runtimeEnvironmentGetStatus.mockRejectedValueOnce(
new Error('Remote Orca runtime closed the connection.')
)
const store = createTestStore()
store.setState({
settings: { activeRuntimeEnvironmentId: 'env-1' } as AppState['settings'],
repos: [{ id: 'repo-env-1', path: '/env-1/repo', displayName: 'Env 1' } as never],
openFiles: [],
ptyIdsByTabId: { tab1: ['remote:env-1@@terminal-a'] }
})
await expect(store.getState().setActiveRuntimeEnvironmentPreference('env-2')).resolves.toBe(
false
)
expect(setActiveRuntimeEnvironmentPreference).not.toHaveBeenCalled()
expect(runtimeEnvironmentGetStatus).toHaveBeenCalledWith({
selector: 'env-2',
timeoutMs: 15_000
})
expect(runtimeEnvironmentCall).not.toHaveBeenCalled()
expect(runtimeEnvironmentCall).not.toHaveBeenCalledWith(
expect.objectContaining({ selector: 'env-1', method: 'terminal.close' })
)
expect(store.getState().settings?.activeRuntimeEnvironmentId).toBe('env-1')
expect(store.getState().repos.map((repo) => repo.id)).toEqual(['repo-env-1'])
expect(store.getState().ptyIdsByTabId).toEqual({ tab1: ['remote:env-1@@terminal-a'] })
expect(toast.error).toHaveBeenCalledWith('Failed to switch servers', {
description: 'Remote Orca runtime closed the connection.'
})
})
it('keeps the current environment when the selected server is protocol-incompatible', async () => {
runtimeEnvironmentGetStatus.mockResolvedValueOnce({
id: 'status-rpc-old',
ok: true,
result: {
runtimeId: 'runtime-old',
graphStatus: 'ready',
runtimeProtocolVersion: MIN_COMPATIBLE_RUNTIME_SERVER_VERSION - 1,
minCompatibleRuntimeClientVersion: 0
},
_meta: { runtimeId: 'runtime-old' }
})
const store = createTestStore()
store.setState({
settings: { activeRuntimeEnvironmentId: 'env-1' } as AppState['settings'],
repos: [{ id: 'repo-env-1', path: '/env-1/repo', displayName: 'Env 1' } as never],
openFiles: []
})
await expect(store.getState().setActiveRuntimeEnvironmentPreference('env-old')).resolves.toBe(
false
)
expect(setActiveRuntimeEnvironmentPreference).not.toHaveBeenCalled()
expect(runtimeEnvironmentGetStatus).toHaveBeenCalledWith({
selector: 'env-old',
timeoutMs: 15_000
})
expect(runtimeEnvironmentCall).not.toHaveBeenCalled()
expect(toast.error).toHaveBeenCalledWith('Failed to switch servers', {
description: expect.stringContaining('server is too old')
})
})
})
describe('fetchSettings runtime catalog probe', () => {
// A failed settings read must still settle runtime catalog discovery or skill badges spin forever without retry.
it('still probes the runtime catalog when the settings read fails', async () => {
settingsGet.mockRejectedValueOnce(new Error('unreadable settings.json'))
const store = createTestStore()
await store.getState().fetchSettings()
await vi.waitFor(() => expect(runtimeEnvironmentList).toHaveBeenCalled())
expect(store.getState().settings).toBeNull()
expect(store.getState().runtimeEnvironmentCatalogSettled).toBe(true)
})
it('coalesces concurrent settings refreshes into one all-host sweep', async () => {
const environments = [makeRuntimeEnvironment('env-a'), makeRuntimeEnvironment('env-b')]
const catalog = deferred<PublicKnownRuntimeEnvironment[]>()
runtimeEnvironmentList.mockReturnValueOnce(catalog.promise)
const store = createTestStore()
await Promise.all(Array.from({ length: 10 }, () => store.getState().fetchSettings()))
expect(settingsGet).toHaveBeenCalledTimes(10)
expect(runtimeEnvironmentList).toHaveBeenCalledTimes(1)
expect(runtimeEnvironmentGetStatus).not.toHaveBeenCalled()
catalog.resolve(environments)
await vi.waitFor(() => expect(runtimeEnvironmentGetStatus).toHaveBeenCalledTimes(2))
await vi.waitFor(() => expect(store.getState().runtimeStatusByEnvironmentId.size).toBe(2))
await store.getState().fetchSettings()
expect(settingsGet).toHaveBeenCalledTimes(11)
expect(runtimeEnvironmentList).toHaveBeenCalledTimes(1)
expect(runtimeEnvironmentGetStatus).toHaveBeenCalledTimes(2)
})
it('treats an offline result as checked on later settings refreshes', async () => {
const environments = [makeRuntimeEnvironment('env-a'), makeRuntimeEnvironment('env-b')]
runtimeEnvironmentList.mockResolvedValue(environments)
runtimeEnvironmentGetStatus.mockImplementation(({ selector }: { selector: string }) =>
selector === 'env-b'
? Promise.reject(new Error('offline'))
: Promise.resolve({
id: 'status-rpc-a',
ok: true,
result: {
runtimeId: 'runtime-a',
graphStatus: 'ready',
runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION,
minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION
},
_meta: { runtimeId: 'runtime-a' }
})
)
const store = createTestStore()
await store.getState().fetchSettings()
await vi.waitFor(() =>
expect(store.getState().runtimeStatusByEnvironmentId.get('env-b')?.status).toBeNull()
)
await store.getState().fetchSettings()
expect(settingsGet).toHaveBeenCalledTimes(2)
expect(runtimeEnvironmentList).toHaveBeenCalledTimes(1)
expect(runtimeEnvironmentGetStatus).toHaveBeenCalledTimes(2)
})
it('retries a failed catalog read on the next settings refresh', async () => {
const firstCatalog = deferred<PublicKnownRuntimeEnvironment[]>()
runtimeEnvironmentList
.mockReturnValueOnce(firstCatalog.promise)
.mockResolvedValueOnce([makeRuntimeEnvironment('env-a')])
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined)
const store = createTestStore()
try {
await store.getState().fetchSettings()
firstCatalog.reject(new Error('unreadable environments.json'))
await vi.waitFor(() => expect(store.getState().runtimeEnvironmentCatalogSettled).toBe(true))
expect(store.getState().runtimeEnvironmentCatalogHydrated).toBe(false)
await store.getState().fetchSettings()
await vi.waitFor(() => expect(store.getState().runtimeEnvironmentCatalogHydrated).toBe(true))
await vi.waitFor(() => expect(runtimeEnvironmentGetStatus).toHaveBeenCalledTimes(1))
await store.getState().fetchSettings()
expect(settingsGet).toHaveBeenCalledTimes(3)
expect(runtimeEnvironmentList).toHaveBeenCalledTimes(2)
expect(runtimeEnvironmentGetStatus).toHaveBeenCalledTimes(1)
} finally {
consoleError.mockRestore()
}
})
it('picks up an externally added host once the listing goes stale', async () => {
runtimeEnvironmentList.mockResolvedValue([makeRuntimeEnvironment('env-a')])
const store = createTestStore()
const now = vi.spyOn(Date, 'now').mockReturnValue(1_000_000)
try {
await store.getState().fetchSettings()
await vi.waitFor(() => expect(store.getState().runtimeStatusByEnvironmentId.size).toBe(1))
// Another client adds a host; coverage still matches, so only staleness can reveal it.
runtimeEnvironmentList.mockResolvedValue([
makeRuntimeEnvironment('env-a'),
makeRuntimeEnvironment('env-b')
])
await store.getState().fetchSettings()
expect(runtimeEnvironmentList).toHaveBeenCalledTimes(1)
expect(store.getState().runtimeEnvironments.map(({ id }) => id)).toEqual(['env-a'])
now.mockReturnValue(1_000_000 + RUNTIME_CATALOG_STALE_MS + 1)
await store.getState().fetchSettings()
await vi.waitFor(() =>
expect(store.getState().runtimeEnvironments.map(({ id }) => id)).toEqual(['env-a', 'env-b'])
)
await vi.waitFor(() =>
expect(store.getState().runtimeStatusByEnvironmentId.has('env-b')).toBe(true)
)
expect(runtimeEnvironmentList).toHaveBeenCalledTimes(2)
} finally {
now.mockRestore()
}
})
})
@@ -1,23 +1,11 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { AppState } from '../../../types'
import type { Tab } from '../../../../../../shared/tab-types'
import type { RuntimeEnvironmentCallRequest } from '../../../../runtime/rpc/testing/runtime-compatibility-test-fixture'
import { WORKTREE_REFRESH_CONCURRENCY } from './worktree-slice-constants'
import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../../../shared/constants'
import { folderWorkspaceKey } from '../../../../../../shared/workspace-scope'
import { makeDetectedResult, qualifyDetectedResult } from './worktrees-detected-listing-fixtures'
import { purgeHydratedWorktrees } from './hydrated-worktree-purge'
import { worktreeCatalogVersionKey } from './worktree-catalog-version-state'
import { makeTab } from '../../../terminals/terminal-tab.test-fixture'
import { makeFolderWorkspace } from '../../../folder-workspaces/folder-workspace.test-fixture'
import { makeWorktree } from '../worktree.test-fixture'
import {
createTestStore,
mockApi,
resetRemoteRuntimeMocks,
resetWorktreeSliceModuleMemory,
runtimeEnvironmentCall,
runtimeEnvironmentTransportCall,
worktreeListMock
} from '../worktrees-slice-test-harness'
@@ -61,205 +49,6 @@ describe('fetchAllWorktrees hydration-time purge (design §4.4)', () => {
addedAt: 0
}
it('reuses unchanged startup scan evidence after restoring saved session', async () => {
const store = createTestStore()
const live = makeWorktree({ id: 'repoA::/a/live', repoId: 'repoA', path: '/a/live' })
mockApi.worktrees.listDetected.mockImplementationOnce(async (args) =>
qualifyDetectedResult(
args,
makeDetectedResult(repoA.id, [live], {
catalogVersion: { epoch: 'startup', sequence: 1 }
})
)
)
store.setState({
repos: [repoA],
hydrationSucceeded: false,
workspaceSessionReady: false
})
const results = await store.getState().fetchAllWorktrees({
visibilityOwnerHostId: 'local',
hydrationPurge: 'defer'
})
expect(store.getState().hasHydratedWorktreePurge).toBe(false)
store.setState({
hydrationSucceeded: true,
workspaceSessionReady: true,
tabsByWorktree: {
'repoA::/a/stale': [makeTab({ id: 'saved', worktreeId: 'repoA::/a/stale' })]
}
})
purgeHydratedWorktrees(store.setState, store.getState, results)
expect(store.getState().hasHydratedWorktreePurge).toBe(true)
expect(store.getState().tabsByWorktree['repoA::/a/stale']).toBeUndefined()
})
it('defers saved-session purge after newer catalog', async () => {
const store = createTestStore()
const live = makeWorktree({ id: 'repoA::/a/live', repoId: 'repoA', path: '/a/live' })
mockApi.worktrees.listDetected.mockImplementationOnce(async (args) =>
qualifyDetectedResult(
args,
makeDetectedResult(repoA.id, [live], {
catalogVersion: { epoch: 'startup', sequence: 1 }
})
)
)
store.setState({
repos: [repoA],
hydrationSucceeded: false,
workspaceSessionReady: false
})
const results = await store.getState().fetchAllWorktrees({
visibilityOwnerHostId: 'local',
hydrationPurge: 'defer'
})
expect(store.getState().hasHydratedWorktreePurge).toBe(false)
store.setState({
hydrationSucceeded: true,
workspaceSessionReady: true,
tabsByWorktree: {
'repoA::/a/stale': [makeTab({ id: 'saved', worktreeId: 'repoA::/a/stale' })]
}
})
store.setState({
worktreeCatalogVersionByRepoHost: {
[worktreeCatalogVersionKey(repoA.id, 'local')]: { epoch: 'startup', sequence: 2 }
}
})
purgeHydratedWorktrees(store.setState, store.getState, results)
expect(store.getState().hasHydratedWorktreePurge).toBe(false)
expect(store.getState().tabsByWorktree['repoA::/a/stale']).toEqual([
expect.objectContaining({ id: 'saved', worktreeId: 'repoA::/a/stale' })
])
})
it('defers saved-session purge after new owner', async () => {
const store = createTestStore()
const live = makeWorktree({ id: 'repoA::/a/live', repoId: 'repoA', path: '/a/live' })
mockApi.worktrees.listDetected.mockImplementationOnce(async (args) =>
qualifyDetectedResult(
args,
makeDetectedResult(repoA.id, [live], {
catalogVersion: { epoch: 'startup', sequence: 1 }
})
)
)
store.setState({
repos: [repoA],
hydrationSucceeded: false,
workspaceSessionReady: false
})
const results = await store.getState().fetchAllWorktrees({
visibilityOwnerHostId: 'local',
hydrationPurge: 'defer'
})
expect(store.getState().hasHydratedWorktreePurge).toBe(false)
store.setState({
hydrationSucceeded: true,
workspaceSessionReady: true,
tabsByWorktree: {
'repoA::/a/stale': [makeTab({ id: 'saved', worktreeId: 'repoA::/a/stale' })]
}
})
store.setState({ repos: [repoA, repoB] })
purgeHydratedWorktrees(store.setState, store.getState, results)
expect(store.getState().hasHydratedWorktreePurge).toBe(false)
expect(store.getState().tabsByWorktree['repoA::/a/stale']).toEqual([
expect.objectContaining({ id: 'saved', worktreeId: 'repoA::/a/stale' })
])
})
it('defers saved-session purge after unloaded runtime', async () => {
const store = createTestStore()
const live = makeWorktree({ id: 'repoA::/a/live', repoId: 'repoA', path: '/a/live' })
mockApi.worktrees.listDetected.mockImplementationOnce(async (args) =>
qualifyDetectedResult(
args,
makeDetectedResult(repoA.id, [live], {
catalogVersion: { epoch: 'startup', sequence: 1 }
})
)
)
store.setState({
repos: [repoA],
hydrationSucceeded: false,
workspaceSessionReady: false
})
const results = await store.getState().fetchAllWorktrees({
visibilityOwnerHostId: 'local',
hydrationPurge: 'defer'
})
expect(store.getState().hasHydratedWorktreePurge).toBe(false)
store.setState({
hydrationSucceeded: true,
workspaceSessionReady: true,
tabsByWorktree: {
'repoA::/a/stale': [makeTab({ id: 'saved', worktreeId: 'repoA::/a/stale' })]
}
})
store.setState({
restoredRuntimeHostIdByWorkspaceSessionKey: {
'remote-repo::/remote/saved': 'runtime:offline'
}
})
purgeHydratedWorktrees(store.setState, store.getState, results)
expect(store.getState().hasHydratedWorktreePurge).toBe(false)
expect(store.getState().tabsByWorktree['repoA::/a/stale']).toEqual([
expect.objectContaining({ id: 'saved', worktreeId: 'repoA::/a/stale' })
])
})
// D1b-7a: hydration keeps only a moved project's chats, which stay on this computer.
it("keeps a moved project's chats through the purge, and still purges a stale worktree", async () => {
const store = createTestStore()
const live = makeWorktree({ id: 'repoA::/a/live', repoId: 'repoA', path: '/a/live' })
mockApi.worktrees.listDetected.mockImplementationOnce(async (args) =>
qualifyDetectedResult(args, makeDetectedResult(repoA.id, [live]))
)
store.setState({ repos: [repoA], hydrationSucceeded: false, workspaceSessionReady: false })
const results = await store.getState().fetchAllWorktrees({
visibilityOwnerHostId: 'local',
hydrationPurge: 'defer'
})
const moved = 'moved-repo::\\\\wsl.localhost\\Ubuntu\\home\\dev\\app'
const chat: Tab = {
id: 'chat',
entityId: 'agent-session-1',
groupId: 'group-1',
worktreeId: moved,
contentType: 'agent-session',
label: 'Claude',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 0
}
store.setState({
hydrationSucceeded: true,
workspaceSessionReady: true,
wslMovedProjects: [
{
kind: 'repo',
id: 'moved-repo',
displayName: 'app',
path: '\\\\wsl.localhost\\Ubuntu\\home\\dev\\app',
distro: 'Ubuntu'
}
],
tabsByWorktree: {
'repoA::/a/stale': [makeTab({ id: 'saved', worktreeId: 'repoA::/a/stale' })],
[moved]: []
},
unifiedTabsByWorktree: { [moved]: [chat] }
})
purgeHydratedWorktrees(store.setState, store.getState, results)
expect(store.getState().hasHydratedWorktreePurge).toBe(true)
expect(store.getState().tabsByWorktree['repoA::/a/stale']).toBeUndefined()
expect(store.getState().tabsByWorktree[moved]).toEqual([])
expect(store.getState().unifiedTabsByWorktree[moved]).toEqual([chat])
})
it('defers the purge when a sibling repo fetch fails (F1 regression)', async () => {
const store = createTestStore()
const wtA = makeWorktree({ id: 'repoA::/a/wt1', repoId: 'repoA', path: '/a/wt1' })
@@ -306,259 +95,6 @@ describe('fetchAllWorktrees hydration-time purge (design §4.4)', () => {
})
})
it('defers the purge when every repo succeeds but none returns worktrees (empty-sibling safety)', async () => {
const store = createTestStore()
// Empty valid-id union (both repos newly-cloned, empty) isn't authoritative — defer instead of wiping tabsByWorktree.
worktreeListMock.mockResolvedValue([])
store.setState({
repos: [repoA, repoB],
tabsByWorktree: {
'repoA::/a/wt1': [{ id: 'tab-A', worktreeId: 'repoA::/a/wt1' }]
}
} as unknown as Partial<AppState>)
await store.getState().fetchAllWorktrees()
expect(store.getState().hasHydratedWorktreePurge).toBe(false)
expect(store.getState().tabsByWorktree).toEqual({
'repoA::/a/wt1': [{ id: 'tab-A', worktreeId: 'repoA::/a/wt1' }]
})
})
it('fires the purge once when every repo returns successfully with ≥1 worktree', async () => {
const store = createTestStore()
const wtA = makeWorktree({ id: 'repoA::/a/wt1', repoId: 'repoA', path: '/a/wt1' })
const wtB = makeWorktree({ id: 'repoB::/b/wt1', repoId: 'repoB', path: '/b/wt1' })
const folderWorkspace = makeFolderWorkspace({ id: 'folder-keep' })
const folderKey = folderWorkspaceKey(folderWorkspace.id)
worktreeListMock.mockImplementation(async ({ repoId }: { repoId: string }) =>
repoId === 'repoA' ? [wtA] : [wtB]
)
store.setState({
repos: [repoA, repoB],
folderWorkspaces: [folderWorkspace],
tabsByWorktree: {
'repoA::/a/wt1': [{ id: 'tab-A', worktreeId: 'repoA::/a/wt1' }],
'repoA::/a/zombie': [{ id: 'tab-zombie', worktreeId: 'repoA::/a/zombie' }],
'repoB::/b/wt1': [{ id: 'tab-B', worktreeId: 'repoB::/b/wt1' }],
[folderKey]: [{ id: 'tab-folder', worktreeId: folderKey }]
},
gitIgnoredPathsByWorktree: {
'repoA::/a/wt1': ['dist/'],
'repoA::/a/zombie': ['coverage/'],
'repoB::/b/wt1': ['build/'],
[folderKey]: ['tmp/']
}
} as unknown as Partial<AppState>)
await store.getState().fetchAllWorktrees()
expect(store.getState().hasHydratedWorktreePurge).toBe(true)
expect(worktreeListMock).toHaveBeenCalledTimes(2)
expect(store.getState().tabsByWorktree).toEqual({
'repoA::/a/wt1': [{ id: 'tab-A', worktreeId: 'repoA::/a/wt1' }],
'repoB::/b/wt1': [{ id: 'tab-B', worktreeId: 'repoB::/b/wt1' }],
[folderKey]: [{ id: 'tab-folder', worktreeId: folderKey }]
})
expect(store.getState().gitIgnoredPathsByWorktree).toEqual({
'repoA::/a/wt1': ['dist/'],
'repoB::/b/wt1': ['build/'],
[folderKey]: ['tmp/']
})
// Second call must not re-run the purge even if new stale ids appear.
store.setState({
tabsByWorktree: {
...store.getState().tabsByWorktree,
'repoA::/a/new-zombie': [{ id: 'tab-new-zombie', worktreeId: 'repoA::/a/new-zombie' }]
}
} as unknown as Partial<AppState>)
await store.getState().fetchAllWorktrees()
expect(worktreeListMock).toHaveBeenCalledTimes(4)
expect(store.getState().tabsByWorktree['repoA::/a/new-zombie']).toBeDefined()
})
it('does not consume the one-shot purge before clean workspace session hydration', async () => {
const store = createTestStore()
const wtA = makeWorktree({ id: 'repoA::/a/wt1', repoId: 'repoA', path: '/a/wt1' })
const wtB = makeWorktree({ id: 'repoB::/b/wt1', repoId: 'repoB', path: '/b/wt1' })
worktreeListMock.mockImplementation(async ({ repoId }: { repoId: string }) =>
repoId === 'repoA' ? [wtA] : [wtB]
)
store.setState({
workspaceSessionReady: false,
hydrationSucceeded: false,
repos: [repoA, repoB],
tabsByWorktree: {
'repoA::/a/wt1': [{ id: 'tab-A', worktreeId: 'repoA::/a/wt1' }],
'repoA::/a/zombie': [{ id: 'tab-zombie', worktreeId: 'repoA::/a/zombie' }],
'repoB::/b/wt1': [{ id: 'tab-B', worktreeId: 'repoB::/b/wt1' }]
}
} as unknown as Partial<AppState>)
await store.getState().fetchAllWorktrees()
expect(store.getState().hasHydratedWorktreePurge).toBe(false)
expect(store.getState().tabsByWorktree['repoA::/a/zombie']).toBeDefined()
store.setState({ workspaceSessionReady: true } as Partial<AppState>)
await store.getState().fetchAllWorktrees()
expect(store.getState().hasHydratedWorktreePurge).toBe(false)
expect(store.getState().tabsByWorktree['repoA::/a/zombie']).toBeDefined()
store.setState({ hydrationSucceeded: true } as Partial<AppState>)
await store.getState().fetchAllWorktrees()
expect(store.getState().hasHydratedWorktreePurge).toBe(true)
expect(store.getState().tabsByWorktree).toEqual({
'repoA::/a/wt1': [{ id: 'tab-A', worktreeId: 'repoA::/a/wt1' }],
'repoB::/b/wt1': [{ id: 'tab-B', worktreeId: 'repoB::/b/wt1' }]
})
})
it('preserves sibling host worktrees during hydrated refresh when repo ids are duplicated', async () => {
const store = createTestStore()
const localRepo = {
id: 'same-repo',
path: '/repos/local',
displayName: 'same local',
badgeColor: '#000',
addedAt: 0,
executionHostId: 'local'
}
const runtimeRepo = {
id: 'same-repo',
path: '/repos/remote',
displayName: 'same remote',
badgeColor: '#111',
addedAt: 1,
executionHostId: 'runtime:env-1'
}
const localWorktree = makeWorktree({
id: 'same-repo::/local/wt',
repoId: 'same-repo',
path: '/local/wt'
})
const staleRemoteWorktree = makeWorktree({
id: 'same-repo::/remote/stale',
repoId: 'same-repo',
path: '/remote/stale',
hostId: 'runtime:env-1'
})
const refreshedRemoteWorktree = makeWorktree({
id: 'same-repo::/remote/fresh',
repoId: 'same-repo',
path: '/remote/fresh',
hostId: 'local'
})
mockApi.worktrees.listDetected.mockResolvedValueOnce(
makeDetectedResult('same-repo', [localWorktree])
)
runtimeEnvironmentCall.mockResolvedValue({
id: 'rpc-duplicate-worktrees',
ok: true,
result: makeDetectedResult('same-repo', [refreshedRemoteWorktree]),
_meta: { runtimeId: 'runtime-remote' }
})
store.setState({
hasHydratedWorktreePurge: true,
repos: [localRepo, runtimeRepo],
worktreesByRepo: {
'same-repo': [localWorktree, staleRemoteWorktree]
},
detectedWorktreesByRepo: {
'same-repo': makeDetectedResult('same-repo', [localWorktree, staleRemoteWorktree])
}
} as unknown as Partial<AppState>)
await store.getState().fetchAllWorktrees()
const refreshed = store.getState().worktreesByRepo['same-repo'] ?? []
expect(refreshed).toHaveLength(2)
expect(refreshed).toEqual(
expect.arrayContaining([
localWorktree,
{
...refreshedRemoteWorktree,
hostId: 'runtime:env-1',
runtimeOwnerEnvironmentId: 'env-1'
}
])
)
expect(refreshed.map((worktree) => worktree.id)).not.toContain(staleRemoteWorktree.id)
expect(store.getState().detectedWorktreesByRepo['same-repo']?.worktrees).toEqual(
expect.arrayContaining([
expect.objectContaining({ id: localWorktree.id }),
expect.objectContaining({ id: refreshedRemoteWorktree.id, hostId: 'runtime:env-1' })
])
)
expect(mockApi.worktrees.listDetected).toHaveBeenCalledWith(
expect.objectContaining({
repoId: 'same-repo',
executionHostId: 'local'
})
)
expect(runtimeEnvironmentCall).toHaveBeenCalledWith({
selector: 'env-1',
method: 'worktree.detectedList',
params: { repo: 'same-repo' },
timeoutMs: 15_000
})
})
it('reuses an offline runtime preflight across hydrated all-worktree refresh repos', async () => {
const store = createTestStore()
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
const repos = Array.from({ length: WORKTREE_REFRESH_CONCURRENCY + 2 }, (_, index) => ({
id: `runtime-repo-${index}`,
path: `/remote/repos/${index}`,
displayName: `runtime-repo-${index}`,
badgeColor: '#000',
addedAt: 0,
executionHostId: 'runtime:env-offline'
}))
runtimeEnvironmentTransportCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => {
if (args.method === 'status.get') {
return Promise.resolve({
id: 'status',
ok: false,
error: { code: 'runtime_unavailable', message: 'offline' },
_meta: { runtimeId: 'runtime-offline' }
})
}
return runtimeEnvironmentCall(args)
})
try {
store.setState({
hasHydratedWorktreePurge: true,
repos
} as unknown as Partial<AppState>)
await store.getState().fetchAllWorktrees()
} finally {
consoleError.mockRestore()
}
expect(runtimeEnvironmentTransportCall.mock.calls.map((call) => call[0].method)).toEqual([
'status.get'
])
expect(runtimeEnvironmentCall).not.toHaveBeenCalled()
expect(mockApi.worktrees.listDetected).not.toHaveBeenCalled()
})
it('preserves floating workspace state while purging a real stale worktree', async () => {
const store = createTestStore()
const wtA = makeWorktree({ id: 'repoA::/a/wt1', repoId: 'repoA', path: '/a/wt1' })
@@ -45,296 +45,6 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
shutdownBufferCaptures.clear()
})
it('does not commit sleep state when exact runtime stop post-check is inconclusive', async () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
mockApi.runtimeEnvironments.call.mockImplementation((args: { method: string }) =>
Promise.resolve(
createCompatibleRuntimeStatusResponseIfNeeded(args) ?? {
id: 'rpc-default',
ok: true,
result:
args.method === 'terminal.stopExact'
? {
stoppedPtyIds: ['pty-1'],
livePtyIds: ['pty-1'],
postStopVerified: false,
postStopFailure: 'terminal_liveness_unavailable'
}
: {},
_meta: { runtimeId: 'remote-runtime' }
}
)
)
seedStore(store, {
settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: 'runtime-1' },
worktreesByRepo: {
repo1: [makeRuntimeOwnedWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' })]
},
ptyIdsByTabId: { 'tab-1': [] }
})
store.getState().setAgentStatus(
'tab-1:live',
{
state: 'done',
prompt: 'resume live',
agentType: 'codex'
},
'Codex',
{ updatedAt: 1000, stateStartedAt: 1000 },
{ tabId: 'tab-1', worktreeId: wt },
{ providerSession: { key: 'session_id', id: 'live-session' } }
)
await expect(
store.getState().shutdownWorktreeTerminals(wt, {
keepIdentifiers: true,
sleepingPaneKeys: ['tab-1:live'],
expectedRuntimePtyIds: ['pty-1']
})
).rejects.toThrow('terminal_liveness_unavailable')
// Inconclusive stop restores the done agent’s live recovery anchor, never worktree-sleep (#9454).
expect(store.getState().sleepingAgentSessionsByPaneKey['tab-1:live']).toMatchObject({
origin: 'live',
agent: 'codex',
providerSession: { key: 'session_id', id: 'live-session' }
})
expect(store.getState().agentStatusByPaneKey['tab-1:live']).toBeDefined()
expect(store.getState().suppressedPtyExitIds['pty-1']).toBeUndefined()
expect(mockApi.pty.kill).not.toHaveBeenCalled()
})
it('clears exact-stop exit suppression when a slept PTY ID wakes live again', async () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
mockApi.runtimeEnvironments.call.mockImplementation((args: { method: string }) =>
Promise.resolve(
createCompatibleRuntimeStatusResponseIfNeeded(args) ?? {
id: 'rpc-default',
ok: true,
result:
args.method === 'terminal.stopExact'
? { stoppedPtyIds: ['pty-1'], livePtyIds: ['pty-1'], postStopVerified: true }
: {},
_meta: { runtimeId: 'remote-runtime' }
}
)
)
seedStore(store, {
settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: 'runtime-1' },
worktreesByRepo: {
repo1: [makeRuntimeOwnedWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' })]
},
ptyIdsByTabId: { 'tab-1': ['remote:runtime-1@@pty-1'] }
})
store.getState().setAgentStatus(
'tab-1:live',
{
state: 'done',
prompt: 'resume live',
agentType: 'codex'
},
'Codex',
{ updatedAt: 1000, stateStartedAt: 1000 },
{ tabId: 'tab-1', worktreeId: wt },
{ providerSession: { key: 'session_id', id: 'live-session' } }
)
await store.getState().shutdownWorktreeTerminals(wt, {
keepIdentifiers: true,
sleepingPaneKeys: ['tab-1:live'],
expectedRuntimePtyIds: ['pty-1']
})
expect(store.getState().suppressedPtyExitIds['remote:runtime-1@@pty-1']).toBe(true)
expect(store.getState().suppressedPtyExitIds['pty-1']).toBeUndefined()
store.getState().updateTabPtyId('tab-1', 'remote:runtime-1@@pty-1')
expect(store.getState().suppressedPtyExitIds['remote:runtime-1@@pty-1']).toBeUndefined()
})
it('suppresses only the scoped remote PTY identity before exact runtime stop resolves', async () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
let sawWrappedSuppressedDuringStop = false
let sawRawSuppressedDuringStop = false
mockApi.runtimeEnvironments.call.mockImplementation((args: { method: string }) => {
const compatible = createCompatibleRuntimeStatusResponseIfNeeded(args)
if (compatible) {
return Promise.resolve(compatible)
}
if (args.method === 'terminal.stopExact') {
sawWrappedSuppressedDuringStop = store
.getState()
.consumeSuppressedPtyExit('remote:env-1@@terminal-1')
sawRawSuppressedDuringStop = store.getState().consumeSuppressedPtyExit('terminal-1')
return Promise.resolve({
id: 'rpc-default',
ok: true,
result: {
stoppedPtyIds: ['terminal-1'],
livePtyIds: ['terminal-1'],
postStopVerified: true
},
_meta: { runtimeId: 'remote-runtime' }
})
}
return Promise.resolve({
id: 'rpc-default',
ok: true,
result: {},
_meta: { runtimeId: 'remote-runtime' }
})
})
seedStore(store, {
settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: 'runtime-1' },
worktreesByRepo: {
repo1: [makeRuntimeOwnedWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' })]
},
ptyIdsByTabId: { 'tab-1': ['remote:env-1@@terminal-1'] }
})
store.getState().setAgentStatus(
'tab-1:live',
{
state: 'done',
prompt: 'resume live',
agentType: 'codex'
},
'Codex',
{ updatedAt: 1000, stateStartedAt: 1000 },
{ tabId: 'tab-1', worktreeId: wt },
{ providerSession: { key: 'session_id', id: 'live-session' } }
)
await store.getState().shutdownWorktreeTerminals(wt, {
keepIdentifiers: true,
sleepingPaneKeys: ['tab-1:live'],
expectedRuntimePtyIds: ['terminal-1']
})
expect(sawWrappedSuppressedDuringStop).toBe(true)
expect(store.getState().suppressedPtyExitIds['remote:runtime-1@@terminal-1']).toBeUndefined()
expect(sawRawSuppressedDuringStop).toBe(false)
expect(mockUnregisterPtyDataHandlers).toHaveBeenCalledWith(['remote:env-1@@terminal-1'])
expect(mockUnregisterPtyDataHandlers).not.toHaveBeenCalledWith(['terminal-1'])
})
it('still kills a local renderer PTY whose id matches a remote exact-stop handle', async () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
mockApi.runtimeEnvironments.call.mockImplementation((args: { method: string }) =>
Promise.resolve(
createCompatibleRuntimeStatusResponseIfNeeded(args) ?? {
id: 'rpc-default',
ok: true,
result:
args.method === 'terminal.stopExact'
? {
stoppedPtyIds: ['terminal-1'],
livePtyIds: ['terminal-1'],
postStopVerified: true
}
: {},
_meta: { runtimeId: 'remote-runtime' }
}
)
)
seedStore(store, {
settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: 'runtime-1' },
worktreesByRepo: {
repo1: [makeRuntimeOwnedWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt })]
},
ptyIdsByTabId: {
'tab-1': ['remote:runtime-1@@terminal-1', 'terminal-1']
}
})
await store.getState().shutdownWorktreeTerminals(wt, {
expectedRuntimePtyIds: ['terminal-1']
})
expect(mockApi.pty.kill).toHaveBeenCalledWith('terminal-1', { keepHistory: false })
expect(mockUnregisterPtyDataHandlers).toHaveBeenCalledWith([
'remote:runtime-1@@terminal-1',
'terminal-1'
])
})
it('commits the pre-stop sleeping record when exact-stop exit clears live status', async () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
const now = Date.now()
mockApi.runtimeEnvironments.call.mockImplementation((args: { method: string }) => {
if (args.method === 'terminal.stopExact') {
store.getState().removeAgentStatus('tab-1:live')
return Promise.resolve({
id: 'rpc-default',
ok: true,
result: { stoppedPtyIds: ['pty-1'], livePtyIds: ['pty-1'], postStopVerified: true },
_meta: { runtimeId: 'remote-runtime' }
})
}
return Promise.resolve(
createCompatibleRuntimeStatusResponseIfNeeded(args) ?? {
id: 'rpc-default',
ok: true,
result: {},
_meta: { runtimeId: 'remote-runtime' }
}
)
})
seedStore(store, {
settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: 'runtime-1' },
worktreesByRepo: {
repo1: [makeRuntimeOwnedWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' })]
},
ptyIdsByTabId: { 'tab-1': [] }
})
store.getState().setAgentStatus(
'tab-1:live',
{
state: 'working',
prompt: 'resume live',
agentType: 'codex'
},
'Codex',
{ updatedAt: now, stateStartedAt: now },
{ tabId: 'tab-1', worktreeId: wt },
{ providerSession: { key: 'session_id', id: 'live-session' } }
)
await store.getState().shutdownWorktreeTerminals(wt, {
keepIdentifiers: true,
sleepingPaneKeys: ['tab-1:live'],
expectedRuntimePtyIds: ['pty-1']
})
expect(store.getState().sleepingAgentSessionsByPaneKey['tab-1:live']).toMatchObject({
origin: 'worktree-sleep',
providerSession: { key: 'session_id', id: 'live-session' }
})
})
it('commits pre-stop retained evidence when exact-stop clears live status during hibernation', async () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
@@ -399,184 +109,4 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
}
})
})
it('does not commit stale pre-stop evidence when exact-stop changes live status', async () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
mockApi.runtimeEnvironments.call.mockImplementation((args: { method: string }) => {
if (args.method === 'terminal.stopExact') {
store.getState().setAgentStatus(
'tab-1:live',
{
state: 'working',
prompt: 'still active',
agentType: 'codex'
},
'Codex',
{ updatedAt: 1500, stateStartedAt: 1500 },
{ tabId: 'tab-1', worktreeId: wt },
{ providerSession: { key: 'session_id', id: 'live-session' } }
)
return Promise.resolve({
id: 'rpc-default',
ok: true,
result: { stoppedPtyIds: ['pty-1'], livePtyIds: ['pty-1'], postStopVerified: true },
_meta: { runtimeId: 'remote-runtime' }
})
}
return Promise.resolve(
createCompatibleRuntimeStatusResponseIfNeeded(args) ?? {
id: 'rpc-default',
ok: true,
result: {},
_meta: { runtimeId: 'remote-runtime' }
}
)
})
seedStore(store, {
settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: 'runtime-1' },
worktreesByRepo: {
repo1: [makeRuntimeOwnedWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' })]
},
ptyIdsByTabId: { 'tab-1': [] }
})
store.getState().setAgentStatus(
'tab-1:live',
{
state: 'done',
prompt: 'stale done',
agentType: 'codex'
},
'Codex',
{ updatedAt: 1000, stateStartedAt: 1000 },
{ tabId: 'tab-1', worktreeId: wt },
{ providerSession: { key: 'session_id', id: 'live-session' } }
)
await store.getState().shutdownWorktreeTerminals(wt, {
keepIdentifiers: true,
shutdownReason: 'auto-hibernate-completed-agent',
sleepingPaneKeys: ['tab-1:live'],
expectedRuntimePtyIds: ['pty-1']
})
expect(store.getState().agentStatusByPaneKey['tab-1:live']).toBeUndefined()
expect(store.getState().retainedAgentsByPaneKey['tab-1:live']).toBeUndefined()
expect(store.getState().retentionSuppressedPaneKeys['tab-1:live']).toBe(true)
})
it('does not commit sleep state when exact runtime stop fails', async () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
mockApi.runtimeEnvironments.call.mockImplementation((args: { method: string }) => {
const compatible = createCompatibleRuntimeStatusResponseIfNeeded(args)
if (compatible) {
return Promise.resolve(compatible)
}
if (args.method === 'terminal.stopExact') {
return Promise.reject(new Error('stop failed'))
}
return Promise.resolve({
id: 'rpc-default',
ok: true,
result: {},
_meta: { runtimeId: 'remote-runtime' }
})
})
seedStore(store, {
settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: 'runtime-1' },
worktreesByRepo: {
repo1: [makeRuntimeOwnedWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' })]
},
ptyIdsByTabId: { 'tab-1': [] }
})
store.getState().setAgentStatus(
'tab-1:live',
{
state: 'done',
prompt: 'resume live',
agentType: 'codex'
},
'Codex',
{ updatedAt: 1000, stateStartedAt: 1000 },
{ tabId: 'tab-1', worktreeId: wt },
{ providerSession: { key: 'session_id', id: 'live-session' } }
)
await expect(
store.getState().shutdownWorktreeTerminals(wt, {
keepIdentifiers: true,
sleepingPaneKeys: ['tab-1:live'],
expectedRuntimePtyIds: ['pty-1']
})
).rejects.toThrow('stop failed')
// Failed stop restores the done agent’s live recovery anchor, never worktree-sleep (#9454).
expect(store.getState().sleepingAgentSessionsByPaneKey['tab-1:live']).toMatchObject({
origin: 'live',
agent: 'codex',
providerSession: { key: 'session_id', id: 'live-session' }
})
expect(store.getState().agentStatusByPaneKey['tab-1:live']).toBeDefined()
expect(mockUnregisterPtyDataHandlers).not.toHaveBeenCalledWith(['pty-1'])
expect(mockApi.pty.kill).not.toHaveBeenCalled()
})
it('does not commit sleep state when exact runtime stop returns the wrong set', async () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
mockApi.runtimeEnvironments.call.mockImplementation((args: { method: string }) =>
Promise.resolve(
createCompatibleRuntimeStatusResponseIfNeeded(args) ?? {
id: 'rpc-default',
ok: true,
result:
args.method === 'terminal.stopExact'
? {
stoppedPtyIds: ['pty-1'],
livePtyIds: ['pty-1', 'pty-shell'],
postStopVerified: true
}
: {},
_meta: { runtimeId: 'remote-runtime' }
}
)
)
seedStore(store, {
settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: 'runtime-1' },
worktreesByRepo: {
repo1: [makeRuntimeOwnedWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' })]
},
ptyIdsByTabId: { 'tab-1': [] }
})
store.getState().setAgentStatus('tab-1:live', {
state: 'done',
prompt: 'resume live',
agentType: 'codex'
})
await expect(
store.getState().shutdownWorktreeTerminals(wt, {
keepIdentifiers: true,
sleepingPaneKeys: ['tab-1:live'],
expectedRuntimePtyIds: ['pty-1']
})
).rejects.toThrow('exact_terminal_stop_mismatch')
expect(store.getState().sleepingAgentSessionsByPaneKey['tab-1:live']).toBeUndefined()
expect(store.getState().agentStatusByPaneKey['tab-1:live']).toBeDefined()
expect(mockApi.pty.kill).not.toHaveBeenCalled()
})
})
@@ -1,10 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type * as AgentStatusModule from '@/lib/agent-status/aggregation/worktree-agent-status'
import { getDefaultSettings } from '../../../../shared/constants'
import { createCompatibleRuntimeStatusResponseIfNeeded } from '../../runtime/rpc/testing/runtime-compatibility-test-fixture'
import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '../../runtime/rpc/compatibility/runtime-compatibility-cache'
import { createTestStore, seedStore } from '../testing/app-store-test-fixture'
import { makeRuntimeOwnedWorktree } from '../slices/worktrees/worktree-owner.test-fixture'
import { makeTab } from './terminal-tab.test-fixture'
import { makeWorktree } from '../slices/worktrees/worktree.test-fixture'
import { shutdownBufferCaptures } from '@/components/terminal-pane/snapshots/shutdown-buffer-captures'
@@ -149,438 +146,4 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
expect(state.pendingIssueCommandSplitByTabId['tab-1']).toBeDefined()
expect(dropByWorktree).not.toHaveBeenCalled()
})
it('aborts pane hibernation without side effects when no resume record can be captured', async () => {
// No capturable resume record means the pane could never wake, so shutdown throws before any suppression or kill.
const store = createTestStore()
const wt = 'repo1::/path/wt1'
const targetLeaf = '11111111-1111-4111-8111-111111111111'
const siblingLeaf = '22222222-2222-4222-8222-222222222222'
const targetPaneKey = `tab-1:${targetLeaf}`
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex', ptyId: 'pty-agent' })]
},
terminalLayoutsByTabId: {
'tab-1': {
root: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', leafId: targetLeaf },
second: { type: 'leaf', leafId: siblingLeaf }
},
activeLeafId: siblingLeaf,
expandedLeafId: null,
ptyIdsByLeafId: { [targetLeaf]: 'pty-agent', [siblingLeaf]: 'pty-shell' }
}
},
ptyIdsByTabId: { 'tab-1': ['pty-agent', 'pty-shell'] }
})
// A done agent with no provider session yields no resumable sleeping record.
store
.getState()
.setAgentStatus(
targetPaneKey,
{ state: 'done', prompt: 'resume target', agentType: 'codex' },
'Codex',
{ updatedAt: 2000, stateStartedAt: 1000 },
{ tabId: 'tab-1', worktreeId: wt }
)
await expect(
store.getState().shutdownCompletedAgentPaneForHibernation(wt, {
paneKey: targetPaneKey,
tabId: 'tab-1',
leafId: targetLeaf,
ptyId: 'pty-agent'
})
).rejects.toThrow('agent_hibernation_capture_missing')
const state = store.getState()
expect(mockApi.pty.kill).not.toHaveBeenCalled()
expect(state.suppressedPtyExitIds['pty-agent']).toBeUndefined()
expect(state.sleepingAgentSessionsByPaneKey[targetPaneKey]).toBeUndefined()
expect(state.ptyIdsByTabId['tab-1']).toEqual(['pty-agent', 'pty-shell'])
expect(state.agentStatusByPaneKey[targetPaneKey]).toBeDefined()
})
it('persists the sleeping record and suppression before issuing the hibernation kill', async () => {
// pty:exit can beat the kill promise back; the record must be in the store before the kill or the wake never arms.
const store = createTestStore()
const wt = 'repo1::/path/wt1'
const targetLeaf = '11111111-1111-4111-8111-111111111111'
const targetPaneKey = `tab-1:${targetLeaf}`
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Claude', ptyId: 'pty-agent' })]
},
terminalLayoutsByTabId: {
'tab-1': {
root: { type: 'leaf', leafId: targetLeaf },
activeLeafId: targetLeaf,
expandedLeafId: null,
ptyIdsByLeafId: { [targetLeaf]: 'pty-agent' }
}
},
ptyIdsByTabId: { 'tab-1': ['pty-agent'] }
})
store
.getState()
.setAgentStatus(
targetPaneKey,
{ state: 'done', prompt: 'resume target', agentType: 'claude' },
'Claude',
{ updatedAt: 2000, stateStartedAt: 1000 },
{ tabId: 'tab-1', worktreeId: wt },
{ providerSession: { key: 'session_id', id: 'sess-ordering-1' } }
)
let recordAtKillTime: unknown = null
let suppressionAtKillTime: boolean | undefined
mockApi.pty.kill.mockImplementationOnce(async () => {
const atKill = store.getState()
recordAtKillTime = atKill.sleepingAgentSessionsByPaneKey[targetPaneKey]
suppressionAtKillTime = atKill.suppressedPtyExitIds['pty-agent']
})
await store.getState().shutdownCompletedAgentPaneForHibernation(wt, {
paneKey: targetPaneKey,
tabId: 'tab-1',
leafId: targetLeaf,
ptyId: 'pty-agent'
})
expect(mockApi.pty.kill).toHaveBeenCalledWith('pty-agent', { keepHistory: true })
expect(recordAtKillTime).toMatchObject({
paneKey: targetPaneKey,
providerSession: { key: 'session_id', id: 'sess-ordering-1' }
})
expect(suppressionAtKillTime).toBe(true)
const state = store.getState()
expect(state.sleepingAgentSessionsByPaneKey[targetPaneKey]).toBeDefined()
})
it('does not commit pane sleep state when local target kill fails', async () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
const targetLeaf = '11111111-1111-4111-8111-111111111111'
const siblingLeaf = '22222222-2222-4222-8222-222222222222'
const targetPaneKey = `tab-1:${targetLeaf}`
const handlerSnapshots = [{ ptyId: 'pty-agent' }]
mockApi.pty.kill.mockRejectedValueOnce(new Error('kill failed'))
mockUnregisterPtyDataHandlers.mockReturnValueOnce(handlerSnapshots)
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex', ptyId: 'pty-agent' })]
},
terminalLayoutsByTabId: {
'tab-1': {
root: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', leafId: targetLeaf },
second: { type: 'leaf', leafId: siblingLeaf }
},
activeLeafId: siblingLeaf,
expandedLeafId: null,
ptyIdsByLeafId: { [targetLeaf]: 'pty-agent', [siblingLeaf]: 'pty-shell' }
}
},
ptyIdsByTabId: { 'tab-1': ['pty-agent', 'pty-shell'] }
})
store
.getState()
.setAgentStatus(
targetPaneKey,
{ state: 'done', prompt: 'resume target', agentType: 'codex' },
'Codex',
{ updatedAt: 2000, stateStartedAt: 1000 },
{ tabId: 'tab-1', worktreeId: wt },
{ providerSession: { key: 'session_id', id: 'target-session' } }
)
await expect(
store.getState().shutdownCompletedAgentPaneForHibernation(wt, {
paneKey: targetPaneKey,
tabId: 'tab-1',
leafId: targetLeaf,
ptyId: 'pty-agent'
})
).rejects.toThrow('kill failed')
const state = store.getState()
expect(state.ptyIdsByTabId['tab-1']).toEqual(['pty-agent', 'pty-shell'])
// Failed kill restores the done agent’s live recovery anchor, never worktree-sleep (#9454).
expect(state.sleepingAgentSessionsByPaneKey[targetPaneKey]).toMatchObject({
origin: 'live',
agent: 'codex',
providerSession: { key: 'session_id', id: 'target-session' }
})
expect(state.agentStatusByPaneKey[targetPaneKey]).toBeDefined()
expect(state.suppressedPtyExitIds['pty-agent']).toBeUndefined()
expect(mockRestorePtyDataHandlersAfterFailedShutdown).toHaveBeenCalledWith(handlerSnapshots)
})
it('uses target-only runtime stop for automatic pane hibernation', async () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
const targetLeaf = '11111111-1111-4111-8111-111111111111'
const siblingLeaf = '22222222-2222-4222-8222-222222222222'
const targetPaneKey = `tab-1:${targetLeaf}`
mockApi.runtimeEnvironments.call.mockImplementation((args: { method: string }) =>
Promise.resolve(
createCompatibleRuntimeStatusResponseIfNeeded(args) ?? {
id: 'rpc-default',
ok: true,
result:
args.method === 'terminal.stopExact'
? {
stoppedPtyIds: ['terminal-1'],
livePtyIds: ['terminal-1', 'terminal-2'],
postStopVerified: true,
remainingLivePtyIds: ['terminal-2']
}
: {},
_meta: { runtimeId: 'remote-runtime' }
}
)
)
seedStore(store, {
settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: 'runtime-1' },
worktreesByRepo: {
repo1: [makeRuntimeOwnedWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' })]
},
terminalLayoutsByTabId: {
'tab-1': {
root: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', leafId: targetLeaf },
second: { type: 'leaf', leafId: siblingLeaf }
},
activeLeafId: siblingLeaf,
expandedLeafId: null,
ptyIdsByLeafId: {
[targetLeaf]: 'remote:env-1@@terminal-1',
[siblingLeaf]: 'remote:env-1@@terminal-2'
}
}
},
ptyIdsByTabId: {
'tab-1': ['remote:env-1@@terminal-1', 'remote:env-1@@terminal-2', 'terminal-1']
}
})
store
.getState()
.setAgentStatus(
targetPaneKey,
{ state: 'done', prompt: 'resume target', agentType: 'codex' },
'Codex',
{ updatedAt: 2000, stateStartedAt: 1000 },
{ tabId: 'tab-1', worktreeId: wt },
{ providerSession: { key: 'session_id', id: 'target-session' } }
)
await store.getState().shutdownCompletedAgentPaneForHibernation(wt, {
paneKey: targetPaneKey,
tabId: 'tab-1',
leafId: targetLeaf,
ptyId: 'remote:env-1@@terminal-1',
expectedRuntimePtyId: 'terminal-1'
})
expect(mockApi.runtimeEnvironments.call).toHaveBeenCalledWith(
expect.objectContaining({
selector: 'runtime-1',
method: 'terminal.stopExact',
params: expect.objectContaining({
expectedPtyIds: ['terminal-1'],
keepHistory: true,
targetOnly: true
})
})
)
expect(mockApi.runtimeEnvironments.call).not.toHaveBeenCalledWith(
expect.objectContaining({ method: 'terminal.stop' })
)
expect(mockApi.runtimeEnvironments.call).not.toHaveBeenCalledWith(
expect.objectContaining({ method: 'terminal.sleep' })
)
expect(store.getState().ptyIdsByTabId['tab-1']).toEqual([
'remote:env-1@@terminal-2',
'terminal-1'
])
expect(mockUnregisterPtyDataHandlers).toHaveBeenCalledWith(['remote:env-1@@terminal-1'])
expect(mockUnregisterPtyDataHandlers).not.toHaveBeenCalledWith(['terminal-1'])
expect(store.getState().suppressedPtyExitIds['remote:env-1@@terminal-1']).toBe(true)
expect(store.getState().suppressedPtyExitIds['remote:runtime-1@@terminal-1']).toBeUndefined()
expect(store.getState().suppressedPtyExitIds['terminal-1']).toBeUndefined()
expect(mockApi.pty.kill).not.toHaveBeenCalled()
})
it('does not retain stale completion evidence when pane status changes during hibernation', async () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
const targetLeaf = '11111111-1111-4111-8111-111111111111'
const targetPaneKey = `tab-1:${targetLeaf}`
mockApi.pty.kill.mockImplementationOnce(async () => {
store
.getState()
.setAgentStatus(
targetPaneKey,
{ state: 'working', prompt: 'still running', agentType: 'codex' },
'Codex',
{ updatedAt: 3000, stateStartedAt: 3000 },
{ tabId: 'tab-1', worktreeId: wt },
{ providerSession: { key: 'session_id', id: 'target-session' } }
)
})
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex', ptyId: 'pty-agent' })]
},
terminalLayoutsByTabId: {
'tab-1': {
root: { type: 'leaf', leafId: targetLeaf },
activeLeafId: targetLeaf,
expandedLeafId: null,
ptyIdsByLeafId: { [targetLeaf]: 'pty-agent' }
}
},
ptyIdsByTabId: { 'tab-1': ['pty-agent'] }
})
store.getState().setAgentStatus(
targetPaneKey,
{
state: 'done',
prompt: 'stale done',
agentType: 'codex',
lastAssistantMessage: 'old done'
},
'Codex',
{ updatedAt: 2000, stateStartedAt: 1000 },
{ tabId: 'tab-1', worktreeId: wt },
{ providerSession: { key: 'session_id', id: 'target-session' } }
)
await store.getState().shutdownCompletedAgentPaneForHibernation(wt, {
paneKey: targetPaneKey,
tabId: 'tab-1',
leafId: targetLeaf,
ptyId: 'pty-agent'
})
expect(store.getState().agentStatusByPaneKey[targetPaneKey]).toBeUndefined()
expect(store.getState().retainedAgentsByPaneKey[targetPaneKey]).toBeUndefined()
expect(store.getState().retentionSuppressedPaneKeys[targetPaneKey]).toBe(true)
})
it('rolls back target suppressions when target-only runtime stop fails', async () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
const targetLeaf = '11111111-1111-4111-8111-111111111111'
const siblingLeaf = '22222222-2222-4222-8222-222222222222'
const targetPaneKey = `tab-1:${targetLeaf}`
mockApi.runtimeEnvironments.call.mockImplementation((args: { method: string }) =>
Promise.resolve(
createCompatibleRuntimeStatusResponseIfNeeded(args) ?? {
id: 'rpc-default',
ok: true,
result:
args.method === 'terminal.stopExact'
? {
stoppedPtyIds: ['terminal-1'],
livePtyIds: ['terminal-1', 'terminal-2'],
postStopVerified: false,
postStopFailure: 'target_still_live'
}
: {},
_meta: { runtimeId: 'remote-runtime' }
}
)
)
seedStore(store, {
settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: 'runtime-1' },
worktreesByRepo: {
repo1: [makeRuntimeOwnedWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
tabsByWorktree: {
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' })]
},
terminalLayoutsByTabId: {
'tab-1': {
root: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', leafId: targetLeaf },
second: { type: 'leaf', leafId: siblingLeaf }
},
activeLeafId: siblingLeaf,
expandedLeafId: null,
ptyIdsByLeafId: {
[targetLeaf]: 'remote:env-1@@terminal-1',
[siblingLeaf]: 'remote:env-1@@terminal-2'
}
}
},
ptyIdsByTabId: {
'tab-1': ['remote:env-1@@terminal-1', 'remote:env-1@@terminal-2']
}
})
store
.getState()
.setAgentStatus(
targetPaneKey,
{ state: 'done', prompt: 'resume target', agentType: 'codex' },
'Codex',
{ updatedAt: 2000, stateStartedAt: 1000 },
{ tabId: 'tab-1', worktreeId: wt },
{ providerSession: { key: 'session_id', id: 'target-session' } }
)
await expect(
store.getState().shutdownCompletedAgentPaneForHibernation(wt, {
paneKey: targetPaneKey,
tabId: 'tab-1',
leafId: targetLeaf,
ptyId: 'remote:env-1@@terminal-1',
expectedRuntimePtyId: 'terminal-1'
})
).rejects.toThrow('target_still_live')
const state = store.getState()
expect(state.ptyIdsByTabId['tab-1']).toEqual([
'remote:env-1@@terminal-1',
'remote:env-1@@terminal-2'
])
expect(state.suppressedPtyExitIds['remote:env-1@@terminal-1']).toBeUndefined()
expect(state.suppressedPtyExitIds['terminal-1']).toBeUndefined()
// Failed target stop restores the done agent’s live recovery anchor, never worktree-sleep (#9454).
expect(state.sleepingAgentSessionsByPaneKey[targetPaneKey]).toMatchObject({
origin: 'live',
agent: 'codex',
providerSession: { key: 'session_id', id: 'target-session' }
})
expect(state.agentStatusByPaneKey[targetPaneKey]).toBeDefined()
})
})