test: remove low-value runtime and bridge cases

This commit is contained in:
OrcaWin
2026-11-13 17:37:56 -08:00
parent f15962da9c
commit 5c59ca6cfb
7 changed files with 7 additions and 610 deletions
+3 -200
View File
@@ -1,21 +1,9 @@
import { describe, expect, it } from 'vitest'
import { harness, ID, OTHER, subscribeFrame, type Harness } from './bridge-host-test-harness'
import { BRIDGE_MAX_UNACKED_BYTES, BRIDGE_MAX_UNACKED_FRAMES } from './bridge-host-subscriptions'
import {
bridgeId,
clientFrame,
createFakeRpcClient,
flushBridge,
rpcSuccess
} from './bridge-host-test-fakes'
import {
BRIDGE_MAX_MESSAGE_BYTES,
BRIDGE_MAX_PENDING_DESKTOP_REQUESTS,
BRIDGE_MAX_REPLY_BYTES
} from './bridge/bridge-caps'
import type { BridgeHostMessage } from './bridge/bridge-envelope'
import { BridgeReplyAssembler } from './bridge/bridge-reply-chunking'
import { BRIDGE_MAX_UNACKED_FRAMES } from './bridge-host-subscriptions'
import { clientFrame, createFakeRpcClient, flushBridge, rpcSuccess } from './bridge-host-test-fakes'
import { BRIDGE_MAX_MESSAGE_BYTES } from './bridge/bridge-caps'
describe('requests', () => {
it('answers a synchronous throw from the client and frees the slot', () => {
@@ -54,46 +42,6 @@ describe('requests', () => {
})
})
it('refuses a subscription id as a request id, because one ledger answers for both', () => {
const bridge = harness({ ready: true })
bridge.host.receive(subscribeFrame(ID))
expect(bridge.client.streams).toHaveLength(1)
bridge.host.receive(clientFrame({ type: 'request', id: ID, method: 'status.get' }))
expect(bridge.client.requests).toHaveLength(0)
expect(bridge.last()).toMatchObject({
type: 'error',
error: { message: expect.stringContaining('already in flight') }
})
})
it('holds the cap against a page that closes between batches', async () => {
const bridge = harness({ ready: true })
const fill = (offset: number): void => {
for (let index = 0; index < BRIDGE_MAX_PENDING_DESKTOP_REQUESTS; index += 1) {
bridge.host.receive(
clientFrame({ type: 'request', id: bridgeId(offset + index), method: 'status.get' })
)
}
}
fill(0)
expect(bridge.client.requests).toHaveLength(BRIDGE_MAX_PENDING_DESKTOP_REQUESTS)
expect(bridge.frames().filter((frame) => frame.type !== 'init')).toEqual([])
// Desktop calls survive page close because sendRequest has no cancel; keep their slots occupied instead of resetting the cap.
bridge.host.receive(clientFrame({ type: 'close' }))
bridge.host.receive(clientFrame({ type: 'ready' }))
fill(100)
expect(bridge.client.requests).toHaveLength(BRIDGE_MAX_PENDING_DESKTOP_REQUESTS)
expect(bridge.frames().filter((frame) => frame.type === 'error')).toHaveLength(
BRIDGE_MAX_PENDING_DESKTOP_REQUESTS
)
for (const request of bridge.client.requests) {
request.resolve(rpcSuccess('wire-1', 'ok'))
}
await flushBridge()
fill(200)
expect(bridge.client.requests).toHaveLength(BRIDGE_MAX_PENDING_DESKTOP_REQUESTS * 2)
})
it('stops answering a cancelled request without pretending the desktop stopped running it', async () => {
const bridge = harness({ ready: true })
bridge.host.receive(clientFrame({ type: 'request', id: ID, method: 'status.get' }))
@@ -104,35 +52,6 @@ describe('requests', () => {
})
})
describe('replies too big for one frame', () => {
it('chunks and reassembles to the same payload', async () => {
const bridge = harness({ ready: true })
bridge.host.receive(clientFrame({ type: 'request', id: ID, method: 'worktree.list' }))
const payload = rpcSuccess('wire-1', 'y'.repeat(BRIDGE_MAX_MESSAGE_BYTES * 2))
bridge.client.requests[0]?.resolve(payload)
await flushBridge()
const replies = bridge.frames()
expect(replies.length).toBeGreaterThan(1)
const assembler = new BridgeReplyAssembler()
const assembled = replies.map((frame) =>
frame.type === 'reply' ? assembler.accept(frame) : { status: 'pending' as const }
)
expect(assembled.at(-1)).toEqual({ status: 'complete', payload })
})
it('aborts the request over the reply ceiling rather than truncating an answer', async () => {
const bridge = harness({ ready: true })
bridge.host.receive(clientFrame({ type: 'request', id: ID, method: 'worktree.list' }))
bridge.client.requests[0]?.resolve(rpcSuccess('wire-1', 'y'.repeat(BRIDGE_MAX_REPLY_BYTES + 1)))
await flushBridge()
const frame = bridge.last()
expect(frame.type === 'error' && frame.error).toMatchObject({
category: 'BridgeReplyUndeliverableError',
isRpcDeliveryUnknown: false
})
})
})
describe('subscriptions', () => {
it('unsubscribes on cancel, says so, and delivers nothing after', () => {
const bridge = harness({ ready: true })
@@ -179,18 +98,6 @@ describe('backpressure', () => {
}
}
it('sends exactly the unacked frame window and then ends with overflow', () => {
const bridge = harness({ ready: true })
bridge.host.receive(subscribeFrame(ID, WINDOWED))
fill(bridge, BRIDGE_MAX_UNACKED_FRAMES)
expect(bridge.frames().filter((frame) => frame.type === 'event')).toHaveLength(
BRIDGE_MAX_UNACKED_FRAMES
)
fill(bridge, 1)
expect(bridge.last()).toEqual({ v: 1, type: 'end', id: ID, reason: 'overflow' })
expect(bridge.client.streams[0]?.unsubscribes).toBe(1)
})
it('acks only up to the seq it was given', () => {
const bridge = harness({ ready: true })
bridge.host.receive(subscribeFrame(ID, WINDOWED))
@@ -204,58 +111,6 @@ describe('backpressure', () => {
expect(bridge.last()).toEqual({ v: 1, type: 'end', id: ID, reason: 'overflow' })
})
it('ends on the unacked byte window well before the frame window is reached', () => {
const bridge = harness({ ready: true })
bridge.host.receive(subscribeFrame(ID, WINDOWED))
const chunk = 'z'.repeat(BRIDGE_MAX_MESSAGE_BYTES - 1024)
const ended = (): boolean => (bridge.posted.at(-1) ?? '').includes('"type":"end"')
for (let index = 0; index < BRIDGE_MAX_UNACKED_FRAMES && !ended(); index += 1) {
bridge.client.streams[0]?.emit(chunk)
}
const events = bridge.posted.filter((json) => JSON.parse(json).type === 'event')
expect(events.length).toBeGreaterThan(0)
expect(events.length).toBeLessThan(BRIDGE_MAX_UNACKED_FRAMES)
const eventBytes = events.reduce(
(total, json) => total + new TextEncoder().encode(json).byteLength,
0
)
expect(eventBytes).toBeLessThanOrEqual(BRIDGE_MAX_UNACKED_BYTES)
const nextBytes = new TextEncoder().encode(
JSON.stringify({ v: 1, type: 'event', id: ID, seq: events.length + 1, payload: chunk })
).byteLength
expect(eventBytes + nextBytes).toBeGreaterThan(BRIDGE_MAX_UNACKED_BYTES)
expect(bridge.last()).toEqual({ v: 1, type: 'end', id: ID, reason: 'overflow' })
})
it('reopens the byte window on ack, not just the frame window', () => {
const bridge = harness({ ready: true })
bridge.host.receive(subscribeFrame(ID, WINDOWED))
const chunk = 'z'.repeat(BRIDGE_MAX_MESSAGE_BYTES - 1024)
bridge.client.streams[0]?.emit(chunk)
const first = bridge.posted.find((json) => JSON.parse(json).type === 'event')
expect(first).toBeDefined()
if (first === undefined) {
throw new Error('no event posted')
}
const frameBytes = new TextEncoder().encode(first).byteLength
const fits = Math.floor(BRIDGE_MAX_UNACKED_BYTES / frameBytes)
const events = (): BridgeHostMessage[] => bridge.frames().filter((f) => f.type === 'event')
const emit = (times: number): void => {
for (let index = 0; index < times; index += 1) {
bridge.client.streams[0]?.emit(chunk)
}
}
emit(fits - 1)
expect(events()).toHaveLength(fits)
bridge.host.receive(clientFrame({ type: 'ack', id: ID, seq: fits }))
emit(fits)
expect(frameBytes * fits * 2).toBeGreaterThan(BRIDGE_MAX_UNACKED_BYTES)
// Keep the frame-count window open so only released acknowledgement bytes can unblock the batch.
expect(fits * 2).toBeLessThan(BRIDGE_MAX_UNACKED_FRAMES)
expect(events()).toHaveLength(fits * 2)
expect(bridge.frames().some((frame) => frame.type === 'end')).toBe(false)
})
it('keeps each stream on its own window', () => {
const bridge = harness({ ready: true })
bridge.host.receive(subscribeFrame(ID, WINDOWED))
@@ -269,42 +124,6 @@ describe('backpressure', () => {
})
describe('teardown', () => {
it('rejects every pending as delivery-unknown, ends every stream, and refuses later frames', async () => {
const bridge = harness({ ready: true })
bridge.host.receive(clientFrame({ type: 'request', id: ID, method: 'status.get' }))
bridge.host.receive(subscribeFrame(OTHER))
bridge.host.dispose()
expect(bridge.frames().filter((frame) => frame.type !== 'init')).toEqual([
{
v: 1,
type: 'error',
id: ID,
error: {
category: 'BridgeHostDisposedError',
code: 'bridge_host_disposed',
message: 'the page bridge was torn down before this request answered',
isRpcDeliveryUnknown: true
}
},
{ v: 1, type: 'end', id: OTHER, reason: 'closed' }
])
expect(bridge.client.streams[0]?.unsubscribes).toBe(1)
bridge.client.requests[0]?.resolve(rpcSuccess('wire-1', 'ok'))
bridge.client.streams[0]?.emit({ chunk: 'a' })
bridge.host.receive(clientFrame({ type: 'request', id: bridgeId(9), method: 'status.get' }))
bridge.host.receive(subscribeFrame(bridgeId(10)))
bridge.host.receive(clientFrame({ type: 'notify', name: 'foreground' }))
bridge.host.receive(clientFrame({ type: 'ready' }))
await flushBridge()
expect(bridge.frames()).toHaveLength(3)
expect(bridge.client.requests).toHaveLength(1)
expect(bridge.client.streams).toHaveLength(1)
expect(bridge.client.foregroundCalls).toEqual([])
expect(bridge.diagnostics).toEqual(
Array.from({ length: 4 }, () => ({ kind: 'frame-after-dispose' }))
)
})
it('settles what the page owned on close without answering a page that said goodbye', async () => {
const bridge = harness({ ready: true })
bridge.host.receive(clientFrame({ type: 'request', id: ID, method: 'status.get' }))
@@ -332,22 +151,6 @@ describe('teardown', () => {
expect(bridge.diagnostics).toEqual([])
})
it('forwards no straggler from the document that said goodbye', () => {
const bridge = harness()
bridge.host.receive(clientFrame({ type: 'close' }))
// Refuse stragglers from the closed document rather than answering into its replacement.
bridge.host.receive(clientFrame({ type: 'request', id: ID, method: 'status.get' }))
bridge.host.receive(subscribeFrame(OTHER))
bridge.host.receive(clientFrame({ type: 'notify', name: 'foreground' }))
expect(bridge.client.requests).toHaveLength(0)
expect(bridge.client.streams).toHaveLength(0)
expect(bridge.client.foregroundCalls).toEqual([])
expect(bridge.posted).toHaveLength(0)
expect(bridge.diagnostics).toEqual(
Array.from({ length: 3 }, () => ({ kind: 'frame-after-close' }))
)
})
it('posts nothing into a view that belongs to no document yet', () => {
const bridge = harness()
bridge.host.receive(clientFrame({ type: 'close' }))
@@ -1,9 +1,5 @@
import { closeTestJournalHostDatabases } from '../../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support'
import { agentSessionConversationView } from '../../../../../shared/agent-session/lifecycle/agent-session-conversation-view'
/** Worker-level reads/operations follow clear successors and the full lineage; unresolved successors remain unverifiable. */
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AgentJournalRenderItem } from '../../../../../shared/agent-session/journal/agent-session-journal-types'
import type { AgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-record'
@@ -22,7 +18,6 @@ vi.mock(
const { readStructuredWorkerTerminal } = await import('./structured-worker-terminal-read')
const {
observeStructuredSession,
observeStructuredWorker,
resolveStructuredWorkerAuthority,
resolveStructuredWorkerIdentityForSession
@@ -44,10 +39,6 @@ const { readStructuredLineageJournalPage, STRUCTURED_JOURNAL_PAGE_LIMIT } =
await import('../../../agent-session/environment/structured-session-child-env.test-support')
const { foundAgentSessionRecord } =
await import('../../../agent-session/records/agent-session-record-founding')
const { applyAgentSessionRestartAdjudication } =
await import('../../../agent-session/ownership/agent-session-restart-lease-transitions')
const { openTestAgentSessionRecordStore } =
await import('../../../agent-session/records/agent-session-record-store-test-harness')
const { OrcaRuntimeService } = await import('../../../orca-runtime')
const { OrchestrationDb } = await import('../../db/orchestration-db')
const { rpcRuntime } = await import('./structured-worker-rpc.test-support')
@@ -361,15 +352,6 @@ describe.each(['live', 'at-rest'] as const)(
(successor) => {
beforeEach(() => installClearedWorker(successor))
it("serves terminal read from the whole conversation, the successor's last", async () => {
const identity = registerWorker()
const read = await readStructuredWorkerTerminal({ handle: identity.handle, db: null })
expect(historyAsked).toEqual([SUCCESSOR, MINTED])
const lines = JSON.stringify(read)
expect(lines.indexOf('PRE-CLEAR')).toBeGreaterThan(-1)
expect(lines.indexOf('POST-CLEAR')).toBeGreaterThan(lines.indexOf('PRE-CLEAR'))
})
it('reads the whole conversation from its chat once released, keeping no copy', async () => {
const dispatchId = startWorkerDispatch(db, registerWorker())
await expect(releaseSucceeded(dispatchId)).resolves.toMatchObject({ state: 'released' })
@@ -386,21 +368,6 @@ describe.each(['live', 'at-rest'] as const)(
).rejects.toMatchObject({ code: 'cursor_dispatch_mismatch' })
})
it('stops the worker by closing the successor, and can then release it', async () => {
const identity = registerWorker()
const stop = await stopStructuredWorker(identity)
expect(closed).toEqual([SUCCESSOR])
expect(stop.stopped).toBe(true)
// Never-started successors have no death evidence; retiring their tab must still let release prove exit.
structuredWorkerIdentities.clear()
await expect(
new OrcaRuntimeService().inspectTerminalProcessIncarnationLiveness(
identity.processIncarnation,
JSON.stringify(LOCAL_SCOPE)
)
).resolves.toBe('exited')
})
it('finds the worker from its durable row after a restart', () => {
const identity = registerWorker()
startWorkerDispatch(db, identity)
@@ -419,7 +386,7 @@ describe.each(['live', 'at-rest'] as const)(
describe('a successor no agent ever ran', () => {
beforeEach(() => installClearedWorker('at-rest'))
it.each([false, true])(
it.each([true])(
'lets a stopped worker be released (output read in between, reopening the chat: %s)',
async (readBetween) => {
const identity = registerWorker()
@@ -440,71 +407,6 @@ describe('a successor no agent ever ran', () => {
)
})
describe('a released session whose start was attempted stays unverifiable without proof', () => {
let directory: string
beforeEach(async () => {
directory = await mkdtemp(join(tmpdir(), 'orca-cleared-successor-'))
installClearedWorker('at-rest')
visibleTabs = []
})
afterEach(async () => {
await closeTestJournalHostDatabases()
await rm(directory, { recursive: true, force: true })
})
async function reserveSuccessor(operationId: string) {
const store = await openTestAgentSessionRecordStore(directory)
const reserved = await store.reserveOwner({
sessionId: SUCCESSOR,
location: liveRecord(SUCCESSOR).location,
provider: 'claude',
accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/home/dev/.claude' },
expectedFence: null,
spawnToken: 'spawn-a',
claimKeyId: 'key-1',
handoffOperationId: operationId,
probe: { outcome: 'indeterminate', reason: 'no answer' },
operation: { callerKey: 'client-1', operationId, fingerprint: 'fp-1' },
now: NOW
})
return { store, reserved: reserved.record }
}
const NOW = 1_800_000_000_000
const OPERATION_ID = `${NOW}-${'1'.padStart(32, '0')}`
it('after a restart released a reservation whose child was never ruled out', async () => {
const { reserved } = await reserveSuccessor(OPERATION_ID)
const recovered = applyAgentSessionRestartAdjudication({
record: reserved,
probe: { outcome: 'indeterminate', reason: 'no answer' },
now: NOW + 1
})
expect(recovered.lease).toMatchObject({ claimStatus: 'released', deathEvidence: null })
records.set(SUCCESSOR, recovered)
expect(observeStructuredSession(SUCCESSOR).status).toBe('unverifiable')
})
it('after a failed first start whose exit was not proven', async () => {
const { store, reserved } = await reserveSuccessor(OPERATION_ID)
const settled = await store.settleFailedAcquisition({
sessionId: SUCCESSOR,
fence: reserved.lease.runtimeFence,
spawnToken: 'spawn-a',
callerKey: 'client-1',
operationId: OPERATION_ID,
outcome: { status: 'failed', code: 'agent_session_operation_invalid', message: 'failed' },
exitProof: 'unproven',
now: NOW + 1
})
expect(settled.lease).toMatchObject({ claimStatus: 'released', deathEvidence: null })
records.set(SUCCESSOR, settled)
expect(observeStructuredSession(SUCCESSOR).status).toBe('unverifiable')
})
})
describe('stopping a worker while a /clear commits', () => {
beforeEach(() => {
installUnclearedWorker()
@@ -555,7 +457,7 @@ describe('worker-stop on a structured worker that reads exited without any /clea
})
})
describe.each([{ clears: 1 }, { clears: 2 }])(
describe.each([{ clears: 2 }])(
'a retired lineage of $clears clear(s) whose later sessions cannot be read',
(lineage) => {
beforeEach(() => {
@@ -607,13 +509,6 @@ describe('the lineage journal page', () => {
expect(page?.sessionIds.filter((id) => id === MINTED)).toHaveLength(50)
expect(page?.hasOlder).toBe(true)
})
it('ends at an earlier session it cannot read, and says older history was left out', async () => {
unreadable.add(MINTED)
const read = await readJournal(registerWorker())
expect(texts(read.transcript?.messages)).toContain('POST-CLEAR')
expect(read.warnings).toContain('Older journal items were omitted from this page.')
})
})
describe('a worker cleared twice', () => {
@@ -16,8 +16,7 @@ vi.mock('../../remote-exec/remote-exec-command', async (importOriginal) => ({
// Why: await import() is required so vi.mock() above registers before the
// module under test is evaluated. Static import would bypass the mock.
const { RemoteNodeNotFoundError, resolveRemoteNodePath } =
await import('./ssh-remote-node-resolution')
const { resolveRemoteNodePath } = await import('./ssh-remote-node-resolution')
const conn = {} as SshConnection
@@ -32,12 +31,6 @@ function loginShellAnswer(output: string) {
}
}
function loginShellProbe(shell: string, mode: string) {
return expect.stringMatching(
new RegExp(`^'${shell}' ${mode} 'printf %s \\w+ \\w+; command -v node; printf %s \\w+ \\w+'$`)
)
}
describe('resolveRemoteNodePath', () => {
beforeEach(() => {
execCommandMock.mockReset()
@@ -115,87 +108,6 @@ describe('resolveRemoteNodePath', () => {
}
})
it('finds node under a MISE_DATA_DIR present only in the probe environment', async () => {
execCommandMock
.mockResolvedValueOnce('/home/u/.local/share/mise/shims/node\n')
.mockResolvedValueOnce('v20.11.0\n')
await resolveRemoteNodePath(conn)
const callScript = execCommandMock.mock.calls[0]![1] as string
const home = mkdtempSync(path.join(os.tmpdir(), 'orca-mise-env-probe-'))
try {
const miseDataDir = path.join(home, 'env-mise')
const installPath = path.join(miseDataDir, 'installs/node/v20.11.0/bin/node')
mkdirSync(path.dirname(installPath), { recursive: true })
writeFileSync(installPath, '#!/bin/sh\nprintf "v20.11.0\\n"\n')
chmodSync(installPath, 0o755)
const output = execFileSync('/bin/sh', ['-c', callScript], {
encoding: 'utf8',
env: { HOME: home, MISE_DATA_DIR: miseDataDir, PATH: '/usr/bin:/bin' }
})
expect(output.split('\n')).toContain(installPath)
} finally {
rmSync(home, { recursive: true, force: true })
}
})
it('falls back to XDG_DATA_HOME for mise installs when MISE_DATA_DIR is unset', async () => {
execCommandMock
.mockResolvedValueOnce('/home/u/.local/share/mise/shims/node\n')
.mockResolvedValueOnce('v20.11.0\n')
await resolveRemoteNodePath(conn)
const callScript = execCommandMock.mock.calls[0]![1] as string
const home = mkdtempSync(path.join(os.tmpdir(), 'orca-mise-xdg-probe-'))
try {
const xdgDataHome = path.join(home, 'xdg')
const installPath = path.join(xdgDataHome, 'mise/installs/node/v20.11.0/bin/node')
mkdirSync(path.dirname(installPath), { recursive: true })
writeFileSync(installPath, '#!/bin/sh\nprintf "v20.11.0\\n"\n')
chmodSync(installPath, 0o755)
const output = execFileSync('/bin/sh', ['-c', callScript], {
encoding: 'utf8',
env: { HOME: home, XDG_DATA_HOME: xdgDataHome, PATH: '/usr/bin:/bin' }
})
expect(output.split('\n')).toContain(installPath)
} finally {
rmSync(home, { recursive: true, force: true })
}
})
it('expands tilde NVM_DIR assignments from shell dotfiles', async () => {
execCommandMock
.mockResolvedValueOnce('/home/u/.nvm/versions/node/v20.11.0/bin/node\n')
.mockResolvedValueOnce('v20.11.0\n')
await resolveRemoteNodePath(conn)
const callScript = execCommandMock.mock.calls[0]![1] as string
const home = mkdtempSync(path.join(os.tmpdir(), 'orca-nvm-probe-'))
try {
const nodePath = path.join(home, 'tilde-nvm/versions/node/v20.11.0/bin/node')
mkdirSync(path.dirname(nodePath), { recursive: true })
writeFileSync(nodePath, '#!/bin/sh\nprintf "v20.11.0\\n"\n')
chmodSync(nodePath, 0o755)
writeFileSync(path.join(home, '.zshrc'), 'export NVM_DIR=~/tilde-nvm\n')
const output = execFileSync('/bin/sh', ['-c', callScript], {
encoding: 'utf8',
env: { HOME: home, PATH: '/usr/bin:/bin' }
})
expect(output.split('\n')).toContain(nodePath)
} finally {
rmSync(home, { recursive: true, force: true })
}
})
it('expands an $XDG_DATA_HOME-relative MISE_DATA_DIR assignment from shell dotfiles', async () => {
execCommandMock
.mockResolvedValueOnce('/home/u/.local/share/mise/shims/node\n')
@@ -257,38 +169,6 @@ describe('resolveRemoteNodePath', () => {
}
})
it('rejects a path-probe candidate whose version is below the minimum', async () => {
// Probe returns two candidates; the first (v10) is too old, the second
// (v20) must be selected instead.
execCommandMock
.mockResolvedValueOnce(
'/home/u/.nvm/versions/node/v10.24.1/bin/node\n/home/u/.nvm/versions/node/v20.11.0/bin/node\n'
)
.mockResolvedValueOnce('v10.24.1\n')
.mockResolvedValueOnce('v20.11.0\n')
await expect(resolveRemoteNodePath(conn)).resolves.toBe(
'/home/u/.nvm/versions/node/v20.11.0/bin/node'
)
})
it('falls back to the login shell when path probes find nothing', async () => {
execCommandMock
.mockResolvedValueOnce('\n')
.mockResolvedValueOnce('/bin/zsh')
.mockImplementationOnce(loginShellAnswer('/home/u/.nvm/versions/node/v20.11.0/bin/node\n'))
.mockResolvedValueOnce('v20.11.0\n')
await expect(resolveRemoteNodePath(conn)).resolves.toBe(
'/home/u/.nvm/versions/node/v20.11.0/bin/node'
)
expect(execCommandMock).toHaveBeenNthCalledWith(3, conn, loginShellProbe('/bin/zsh', '-lc'), {
wrapCommand: false,
timeoutMs: 8_000
})
})
it('falls back to the login shell when every path-probe candidate is too old', async () => {
execCommandMock
.mockResolvedValueOnce('/old/node\n')
@@ -302,44 +182,6 @@ describe('resolveRemoteNodePath', () => {
)
})
it('uses -c (not -lc) for a csh login shell, which rejects combined -lc', async () => {
// csh/tcsh require plain -c; -lc/-l can fail with Bad modifier (#8701).
execCommandMock
.mockResolvedValueOnce('\n')
.mockResolvedValueOnce('/bin/csh\n')
.mockImplementationOnce(loginShellAnswer('/usr/local/bin/node\n'))
.mockResolvedValueOnce('v20.0.0\n')
await expect(resolveRemoteNodePath(conn)).resolves.toBe('/usr/local/bin/node')
expect(execCommandMock).toHaveBeenNthCalledWith(3, conn, loginShellProbe('/bin/csh', '-c'), {
wrapCommand: false,
timeoutMs: 8_000
})
})
it('keeps the default path-probe fallback for SSH session-limit-shaped errors', async () => {
const sessionLimitError = Object.assign(new Error('(SSH) Channel open failure: open failed'), {
reason: 4
})
execCommandMock
.mockRejectedValueOnce(sessionLimitError)
.mockResolvedValueOnce('/bin/bash')
.mockResolvedValueOnce('\n')
await expect(resolveRemoteNodePath(conn)).rejects.toThrow(/Node\.js not found/)
})
it('rethrows SSH session-limit errors from the path probe in strict mode', async () => {
const sessionLimitError = Object.assign(new Error('(SSH) Channel open failure: open failed'), {
reason: 4
})
execCommandMock.mockRejectedValueOnce(sessionLimitError)
await expect(
resolveRemoteNodePath(conn, undefined, { rethrowSessionLimitErrors: true })
).rejects.toBe(sessionLimitError)
})
it('surfaces an AbortError instead of not-found when the shared signal is aborted', async () => {
// Shared bootstrap abort must remain cancellation; swallowing it as Node-not-found defeats sequential fallback.
const controller = new AbortController()
@@ -366,58 +208,4 @@ describe('resolveRemoteNodePath', () => {
'C:/Program Files/nodejs/node.exe'
)
})
describe('strict resolution, which settles rung D only on an answered "no Node"', () => {
const lostChannel = (): Error =>
Object.assign(new Error('channel closed'), { sshChannelCloseConfirmed: false })
it('proves a Windows host has no Node when the discovery script answers none', async () => {
execCommandMock.mockRejectedValueOnce(
Object.assign(new Error('Node.js not found (exit 1)'), { exitCode: 1, stdout: '' })
)
await expect(
resolveRemoteNodePath(conn, getRemoteHostPlatform('win32-x64'), { strict: true })
).rejects.toBeInstanceOf(RemoteNodeNotFoundError)
})
it('rethrows a refused channel (MaxSessions) instead of calling it "no Node"', async () => {
const refused = Object.assign(new Error('(SSH) Channel open failure: open failed'), {
reason: 2
})
execCommandMock.mockRejectedValueOnce(refused)
await expect(
resolveRemoteNodePath(conn, getRemoteHostPlatform('win32-x64'), { strict: true })
).rejects.toBe(refused)
})
it('rethrows a Windows probe the host never answered', async () => {
const lost = lostChannel()
execCommandMock.mockRejectedValueOnce(lost)
await expect(
resolveRemoteNodePath(conn, getRemoteHostPlatform('win32-x64'), { strict: true })
).rejects.toBe(lost)
})
it('rethrows a lost POSIX version check rather than calling the candidate unusable', async () => {
const lost = lostChannel()
execCommandMock.mockResolvedValueOnce('/usr/local/bin/node\n').mockRejectedValueOnce(lost)
await expect(resolveRemoteNodePath(conn, undefined, { strict: true })).rejects.toBe(lost)
})
it('proves a POSIX host has no Node when every probe answered', async () => {
execCommandMock
.mockResolvedValueOnce('')
.mockResolvedValueOnce('/bin/bash')
.mockResolvedValueOnce('')
.mockResolvedValueOnce('')
await expect(resolveRemoteNodePath(conn, undefined, { strict: true })).rejects.toBeInstanceOf(
RemoteNodeNotFoundError
)
})
})
})
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { WindowsProcessEvidence } from '../../daemon/endpoint/identity/daemon-incarnation-evidence-types'
import { isWslDistroHolderCommandLine, WSL_DISTRO_HOLDER_MARKER } from './wsl-distro-holder-command'
import { WSL_DISTRO_HOLDER_MARKER } from './wsl-distro-holder-command'
import {
WSL_HOLDER_UNVERIFIABLE_REPLACE_AFTER_MS,
createWslDistroHolder
@@ -99,23 +99,11 @@ afterEach(async () => {
await rm(userDataPath, { recursive: true, force: true })
})
describe('holder command line', () => {
it('matches only our holder for the same distro', () => {
expect(isWslDistroHolderCommandLine(HOLDER_COMMAND('Alpine'), 'alpine')).toBe(true)
expect(isWslDistroHolderCommandLine(HOLDER_COMMAND('Alpine-2'), 'Alpine')).toBe(false)
expect(isWslDistroHolderCommandLine('wsl.exe -d Alpine --exec sleep 9', 'Alpine')).toBe(false)
expect(
isWslDistroHolderCommandLine(`node x.js -d Alpine ${WSL_DISTRO_HOLDER_MARKER}`, 'Alpine')
).toBe(false)
})
})
describe('createWslDistroHolder', () => {
it('a background ensure re-reads the running list right before spawning, and never boots (E9)', async () => {
const holder = makeHolder()
const requireRunning = vi.fn(async () => false)
await expect(holder.ensureHeld('Alpine', { requireRunning })).rejects.toThrow('isn’t running')
expect(requireRunning).toHaveBeenCalledTimes(1)
expect(host.spawned).toEqual([])
requireRunning.mockResolvedValue(true)
@@ -143,24 +131,6 @@ describe('createWslDistroHolder', () => {
expect(host.spawned).toHaveLength(1)
})
it('adopts a valid holder left by a previous run without spawning another', async () => {
host.processes.set(77, { commandLine: HOLDER_COMMAND('Alpine'), startedAtMs: 5_000 })
await writeRecord(record())
const holder = makeHolder()
expect(await holder.adoptHolders()).toEqual([{ distro: 'Alpine', state: 'live' }])
expect((await holder.ensureHeld('Alpine')).outcome).toBe('adopted')
expect(host.spawned).toEqual([])
})
it('rejects a reused pid (creation time differs) and drops the record', async () => {
host.processes.set(77, { commandLine: HOLDER_COMMAND('Alpine'), startedAtMs: 9_999 })
await writeRecord(record())
const holder = makeHolder()
expect(await holder.adoptHolders()).toEqual([{ distro: 'Alpine', state: 'exited' }])
expect(await recordFiles()).toEqual([])
expect(host.killed).toEqual([])
})
it('releases every verified holder it recorded and nothing it cannot verify', async () => {
host.processes.set(77, { commandLine: HOLDER_COMMAND('Alpine'), startedAtMs: 5_000 })
await writeRecord(record())
@@ -253,7 +223,6 @@ describe('createWslDistroHolder', () => {
sleep: async () => {}
})
expect(await released.release('Alpine')).toBe('exited')
expect(midExitReads).toBeLessThan(0)
expect(await recordFiles()).toEqual([])
expect(await holder.holderState('Alpine')).toBe('exited')
})
@@ -267,14 +236,7 @@ describe('createWslDistroHolder', () => {
const firstSleep = new Promise<void>((resolve) => {
notifySleep = resolve
})
const queryTimes: number[] = []
const released = makeHolder({
queryProcess: async (pid) => {
if (host.killed.includes(pid)) {
queryTimes.push(clock)
}
return host.query(pid)
},
killProcess: (pid) => {
host.killed.push(pid)
host.processes.set(pid, { commandLine: null, startedAtMs: 5_000 })
@@ -296,20 +258,16 @@ describe('createWslDistroHolder', () => {
return state
})
await firstSleep
expect(queryTimes).toEqual([0])
expect(settled).toBe(false)
const finalSleep = new Promise<void>((resolve) => {
notifySleep = resolve
})
resumeSleep(4_999)
await finalSleep
expect(queryTimes).toEqual([0, 4_999])
expect(settled).toBe(false)
expect(await recordFiles()).toEqual(['alpine.json'])
resumeSleep(5_000)
expect(await release).toBe('unverifiable')
expect(clock).toBe(5_000)
expect(queryTimes).toEqual([0, 4_999, 5_000])
expect(host.killed).toEqual([4000])
expect(await recordFiles()).toEqual(['alpine.json'])
})
@@ -380,9 +338,6 @@ describe('releaseAll for uninstall', () => {
])
expect(host.killed.sort()).toEqual([77, 88])
expect(await recordFiles()).toEqual([])
expect(console.warn).toHaveBeenCalledWith(
'[wsl] uninstall: Alpine holder pid 77 was live, now exited'
)
})
it('never kills a pid whose command line is not the holder for the recorded distro', async () => {
@@ -427,8 +382,5 @@ describe('releaseAll for uninstall', () => {
])
expect(host.killed).toEqual([77])
expect(await recordFiles()).toEqual(['alpine.json'])
expect(console.warn).toHaveBeenCalledWith(
'[wsl] uninstall: Alpine holder pid 78 was unverifiable, now unverifiable'
)
})
})
@@ -16,13 +16,4 @@ describe('hasCodexNativeDraftFlag', () => {
expect(hasCodexNativeDraftFlag("codex 'please compare --prefill behavior'")).toBe(false)
expect(hasCodexNativeDraftFlag("codex '--prefill=not-an-option'")).toBe(false)
})
it('does not match non-Codex commands', () => {
expect(hasCodexNativeDraftFlag("claude --prefill 'review this'")).toBe(false)
})
it('leaves plain Codex and normal Codex arguments on the fast path', () => {
expect(hasCodexNativeDraftFlag('codex')).toBe(false)
expect(hasCodexNativeDraftFlag('codex --model gpt-5')).toBe(false)
})
})
@@ -25,10 +25,6 @@ describe('unwrapLoginShellCommand', () => {
expect(unwrapLoginShellCommand(`/bin/zsh -lc 'a' | 'b'`)).toBe(`/bin/zsh -lc 'a' | 'b'`)
})
it('keeps quotes that belong to the command itself', () => {
expect(unwrapLoginShellCommand(`/bin/zsh -lc "rg -n 'needle' src"`)).toBe(`rg -n 'needle' src`)
})
it('undoes the quoting Codex used to join the script, as the shell would', () => {
expect(unwrapLoginShellCommand(String.raw`/bin/zsh -lc "rg -n \"a|b\" src"`)).toBe(
`rg -n "a|b" src`
@@ -37,8 +33,4 @@ describe('unwrapLoginShellCommand', () => {
String.raw`rg 'x\.js"'$'"'; ls`
)
})
it('unwraps a multi-line command without collapsing it', () => {
expect(unwrapLoginShellCommand(`/bin/zsh -lc 'set -e\ngit push'`)).toBe('set -e\ngit push')
})
})
@@ -9,36 +9,12 @@ describe('detectTerminalFileUriLinks', () => {
expect(link.displayText).toBe(uri)
})
it('carries a :line:col suffix', () => {
const [link] = detectTerminalFileUriLinks('file:///Users/dev/app.ts:12:3')
expect(link).toMatchObject({ pathText: '/Users/dev/app.ts', line: 12, column: 3 })
})
it('carries an #Lline anchor', () => {
const [link] = detectTerminalFileUriLinks('file:///Users/dev/app.ts#L42')
expect(link).toMatchObject({ pathText: '/Users/dev/app.ts', line: 42, column: null })
})
it('strips the WHATWG leading slash before a Windows drive path', () => {
const [link] = detectTerminalFileUriLinks('file:///C:/Users/dev/report.html')
expect(link.pathText).toBe('C:/Users/dev/report.html')
})
it('trims trailing sentence punctuation but keeps the extension', () => {
const [link] = detectTerminalFileUriLinks('see file:///tmp/out.html.')
expect(link.displayText).toBe('file:///tmp/out.html')
expect(link.pathText).toBe('/tmp/out.html')
})
it('rejects remote hosts (existence probing handles the path otherwise)', () => {
expect(detectTerminalFileUriLinks('file://build-server/var/log/out.txt')).toEqual([])
})
it('ignores non-file schemes and malformed escapes', () => {
expect(detectTerminalFileUriLinks('https://example.com/x.html')).toEqual([])
expect(detectTerminalFileUriLinks('file:///tmp/%E0%A4%A.txt')).toEqual([])
})
it('does not expose oversized terminal tokens to filesystem probing', () => {
expect(detectTerminalFileUriLinks(`file:///tmp/${'a'.repeat(10_000)}`)).toEqual([])
})