test: remove low-value transport and shared suites (#42026)

* test: remove low-value automation and shared suites

* test: retire stale gate references and stabilize retained fixture date

---------

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-13 05:43:27 -08:00
committed by GitHub
co-authored by OrcaWin
parent e9d5b35d64
commit a5854aec6e
32 changed files with 78 additions and 2708 deletions
-2
View File
@@ -214,7 +214,6 @@
1 test-no-real-time-wait:src/renderer/src/lib/agent-session/resume/cli-fork/native-chat-cli-fork-preparation.test.ts
2 test-no-real-time-wait:src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-removal-preflight.test.ts
2 test-no-real-time-wait:src/shared/__tests__/process-host/windows-tree-kill-late-taskkill.win32.test.ts
1 test-no-real-time-wait:src/shared/darwin-process-table-capture.test.ts
1 test-no-real-time-wait:src/shared/darwin-terminal-names-real-ps.test.ts
1 test-no-real-time-wait:src/shared/darwin-terminal-names.test.ts
1 test-no-real-time-wait:src/shared/git/status/git-branch-line-total-soft-deadline.test.ts
@@ -628,7 +627,6 @@
1 test-timeout-needs-reason:src/renderer/src/hooks/agent-hook-completion-notifications.test.ts
1 test-timeout-needs-reason:src/renderer/src/lib/source-control/checks/check-run-details-log-normalization-performance.test.ts
1 test-timeout-needs-reason:src/shared/__tests__/process-host/windows-tree-kill-late-taskkill.win32.test.ts
1 test-timeout-needs-reason:src/shared/dsh-real-cli.test.ts
1 test-timeout-needs-reason:src/shared/wsl-login-shell-command.test.ts
1 test-timeout-needs-reason:tests/e2e/active-view-restart-restore.spec.ts
1 test-timeout-needs-reason:tests/e2e/agent-send-picker-reveal.spec.ts
-1
View File
@@ -20,7 +20,6 @@
1 src/renderer/src/components/activity/use-agent-pane-threads.ts
4 src/renderer/src/components/agent/AgentSettingsDialog.tsx
1 src/renderer/src/components/automations/authoring/use-automations-page-destination-form.ts
1 src/renderer/src/components/automations/automations-page-fixtures.ts
1 src/renderer/src/components/automations/hosts/automation-host-client.ts
1 src/renderer/src/components/automations/use-automations-page-controller.ts
1 src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.tsx
File diff suppressed because one or more lines are too long
+10 -60
View File
@@ -18,10 +18,10 @@ const reply = (result: unknown) =>
`${JSON.stringify({ id: 'request-1', ok: true, result, _meta: { runtimeId: 'runtime-1' } })}\n`
class TestSocket extends EventEmitter {
setEncoding = vi.fn()
write = vi.fn()
end = vi.fn()
destroy = vi.fn()
setEncoding = (): void => {}
write = (): void => {}
end = (): void => {}
destroy = (): void => {}
}
let socket: TestSocket
@@ -30,50 +30,16 @@ beforeEach(() => {
createConnection.mockReturnValue(socket)
})
afterEach(() => {
vi.restoreAllMocks()
vi.useRealTimers()
})
describe('CLI runtime response framing', () => {
it.each([1, 7, 256, 4096])(
'reads a fragmented response with %i-character chunks',
async (size) => {
const result = { data: '界😀'.repeat(10000) }
const encoded = reply(result)
const pending = sendRequest(metadata, 'terminal.read', {}, 30000)
for (let offset = 0; offset < encoded.length; offset += size) {
socket.emit('data', encoded.slice(offset, offset + size))
}
await expect(pending).resolves.toMatchObject({ result })
expect(socket.setEncoding).toHaveBeenCalledExactlyOnceWith('utf8')
expect(socket.end).toHaveBeenCalledOnce()
}
)
it('searches each fragment once without rescanning the accumulated reply', async () => {
const encoded = reply({ data: 'x'.repeat(1024 * 1024) })
it('reads a response split across chunks without losing its payload', async () => {
const encoded = reply({ data: '界😀done' })
const pending = sendRequest(metadata, 'terminal.read', {}, 30000)
const originalIndexOf = String.prototype.indexOf
let searchedCharacters = 0
const search = vi.spyOn(String.prototype, 'indexOf').mockImplementation(function (
this: string,
value,
position
) {
if (value === '\n') {
searchedCharacters += this.length - (position ?? 0)
}
return originalIndexOf.call(this, value, position)
})
try {
for (let offset = 0; offset < encoded.length; offset += 256) {
socket.emit('data', encoded.slice(offset, offset + 256))
}
} finally {
search.mockRestore()
}
await expect(pending).resolves.toMatchObject({ ok: true })
expect(searchedCharacters).toBe(encoded.length)
socket.emit('data', encoded.slice(0, 7))
socket.emit('data', encoded.slice(7))
await expect(pending).resolves.toMatchObject({ result: { data: '界😀done' } })
})
it('refreshes keepalives across chunks and ignores blanks and data after the final frame', async () => {
@@ -86,13 +52,10 @@ describe('CLI runtime response framing', () => {
socket.emit('data', `${reply({ data: 'done' })}invalid JSON\n`)
socket.emit('data', 'more ignored data')
await expect(pending).resolves.toMatchObject({ result: { data: 'done' } })
expect(socket.end).toHaveBeenCalledOnce()
expect(vi.getTimerCount()).toBe(0)
})
it.each([
['broken JSON\n', 'invalid_runtime_response'],
['{}\n', 'invalid_runtime_response'],
['{"id":"other","ok":true,"result":{}}\n', 'invalid_runtime_response'],
[
'{"id":"request-1","ok":true,"result":{},"_meta":{"runtimeId":"other"}}\n',
@@ -105,29 +68,18 @@ describe('CLI runtime response framing', () => {
socket.emit('data', line.slice(0, 2))
socket.emit('data', line.slice(2) + reply({ data: 'ignored' }))
await expect(pending).rejects.toMatchObject({ code })
expect(socket.end).toHaveBeenCalledOnce()
}
)
it('preserves terminal failure envelopes', async () => {
const pending = sendRequest(metadata, 'terminal.read', {}, 30000)
socket.emit('data', '{"id":"request-1","ok":false,"error":{"code":"bad","message":"no"}}\n')
await expect(pending).resolves.toMatchObject({
ok: false,
error: { code: 'bad', message: 'no' }
})
})
it('rejects close with an incomplete frame and does not parse later data', async () => {
const pending = sendRequest(metadata, 'terminal.read', {}, 30000)
socket.emit('data', '{"id":')
socket.emit('close')
socket.emit('data', reply({ data: 'ignored' }))
await expect(pending).rejects.toMatchObject({ code: 'runtime_unavailable' })
expect(socket.end).toHaveBeenCalledOnce()
})
it('destroys a timed out socket holding an incomplete frame', async () => {
it('rejects a timed out incomplete frame and ignores a late reply', async () => {
vi.useFakeTimers()
const pending = sendRequest(metadata, 'terminal.read', {}, 100)
const rejected = expect(pending).rejects.toMatchObject({ code: 'runtime_timeout' })
@@ -135,7 +87,5 @@ describe('CLI runtime response framing', () => {
await vi.advanceTimersByTimeAsync(100)
socket.emit('data', reply({ data: 'ignored' }))
await rejected
expect(socket.destroy).toHaveBeenCalledOnce()
expect(vi.getTimerCount()).toBe(0)
})
})
-263
View File
@@ -1,263 +0,0 @@
import { createServer, type Server } from 'node:http'
import 'node:fs'
import 'node:os'
import 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { WebSocketServer } from 'ws'
import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing'
import type { RuntimeStatus } from '../../shared/runtime-types'
import {
decrypt,
deriveSharedKey,
encrypt,
generateKeyPair,
publicKeyToBase64
} from '../../shared/remote-runtime/e2ee/node/e2ee-crypto'
import './websocket-transport'
import '../../shared/remote-runtime/requests/remote-runtime-prepared-request-admission'
import { RuntimeClient } from './client'
import '../workspaces/worktree-removal-request'
import { launchOrcaApp } from './launch'
import './environments'
import {
MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION,
RUNTIME_PROTOCOL_VERSION
} from '../../shared/protocol-version'
vi.mock('./launch', () => ({
launchOrcaApp: vi.fn()
}))
type TestRuntime = {
endpoint: string
publicKeyB64: string
deviceToken: string
authFrames: Record<string, unknown>[]
requestMethods: string[]
requestParams: unknown[]
connectionCount: () => number
close: () => Promise<void>
}
describe('CLI remote WebSocket transport', () => {
const servers: TestRuntime[] = []
afterEach(async () => {
vi.mocked(launchOrcaApp).mockClear()
await Promise.all(servers.splice(0).map((server) => server.close()))
})
it('blocks remote RPCs when the server protocol is too old', async () => {
const runtime = await startTestRuntime('runtime-old', { runtimeProtocolVersion: 1 })
servers.push(runtime)
const client = new RuntimeClient(
'/tmp/unused',
5_000,
encodePairingOffer({
v: 2,
endpoint: runtime.endpoint,
deviceToken: runtime.deviceToken,
publicKeyB64: runtime.publicKeyB64
})
)
await expect(client.call('repo.list')).rejects.toMatchObject({
code: 'incompatible_runtime',
message: expect.stringContaining('server is too old')
})
expect(runtime.connectionCount()).toBe(1)
expect(runtime.authFrames).toHaveLength(1)
expect(runtime.requestMethods).toEqual(['status.get'])
})
})
async function startTestRuntime(
runtimeId: string,
statusOverrides: {
runtimeProtocolVersion?: number
minCompatibleRuntimeClientVersion?: number
desktopWindowStatus?: 'available' | 'openable' | 'initializing' | 'blocked'
appVersion?: string
remoteUpdateSupport?: {
installMode: 'unsupported-headless-serve'
automatic: false
reason: 'manual-service-update-required'
}
capabilities?: string[]
malformed?: boolean
failure?: boolean
hold?: string
onRequest?: (method: string) => void
disconnect?: boolean
mutationDisconnect?: boolean
rejectAuth?: boolean
degradations?: RuntimeStatus['degradations']
} = {}
): Promise<TestRuntime> {
const serverKeyPair = generateKeyPair()
const deviceToken = `token-${runtimeId}`
const httpServer = createServer()
const wss = new WebSocketServer({ server: httpServer })
const authFrames: Record<string, unknown>[] = []
const requestMethods: string[] = []
const requestParams: unknown[] = []
let connectionCount = 0
wss.on('connection', (ws) => {
let sharedKey: Uint8Array | null = null
let authenticated = false
ws.on('message', (data) => {
const frame = data.toString()
if (!sharedKey) {
const hello = JSON.parse(frame) as Record<string, unknown> & {
type?: string
publicKeyB64?: string
}
if (!hello.publicKeyB64) {
// Legacy-only host: refuses a v2 hello the way hosts before v2 do.
ws.close(4001, 'Invalid e2ee_hello')
return
}
connectionCount += 1
const clientPublicKey = Buffer.from(hello.publicKeyB64 ?? '', 'base64')
sharedKey = deriveSharedKey(serverKeyPair.secretKey, clientPublicKey)
ws.send(JSON.stringify({ type: 'e2ee_ready' }))
return
}
const plaintext = decrypt(frame, sharedKey)
if (!plaintext) {
ws.close(4003, 'decrypt failed')
return
}
if (!authenticated) {
const auth = JSON.parse(plaintext) as Record<string, unknown> & {
type?: string
deviceToken?: string
}
authFrames.push(auth)
if (
auth.type !== 'e2ee_auth' ||
auth.deviceToken !== deviceToken ||
statusOverrides.rejectAuth
) {
ws.send(encrypt(JSON.stringify({ type: 'e2ee_error' }), sharedKey))
ws.close(4001, 'auth failed')
return
}
authenticated = true
ws.send(encrypt(JSON.stringify({ type: 'e2ee_authenticated' }), sharedKey))
return
}
const request: { id: string; method: string; params?: unknown } = JSON.parse(plaintext)
requestMethods.push(request.method)
requestParams.push(request.params)
statusOverrides.onRequest?.(request.method)
if (request.method === statusOverrides.hold) {
return
}
if (request.method === 'status.get' && statusOverrides.disconnect) {
ws.close()
return
}
if (request.method === 'worktree.rm' && statusOverrides.mutationDisconnect) {
ws.close()
return
}
const response =
request.method === 'status.get' && statusOverrides.failure
? {
id: request.id,
ok: false,
error: { code: 'runtime_unavailable', message: 'status failed' },
_meta: { runtimeId }
}
: request.method === 'worktree.rm'
? { id: request.id, ok: true, result: { removed: true }, _meta: { runtimeId } }
: request.method === 'status.get'
? {
id: request.id,
ok: true,
result: statusOverrides.malformed
? { capabilities: 42 }
: {
runtimeId,
rendererGraphEpoch: 1,
graphStatus: 'ready',
authoritativeWindowId: null,
desktopWindowStatus: statusOverrides.desktopWindowStatus,
liveTabCount: 0,
liveLeafCount: 0,
runtimeProtocolVersion:
statusOverrides.runtimeProtocolVersion ?? RUNTIME_PROTOCOL_VERSION,
minCompatibleRuntimeClientVersion:
statusOverrides.minCompatibleRuntimeClientVersion ??
MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION,
appVersion: statusOverrides.appVersion,
remoteUpdateSupport: statusOverrides.remoteUpdateSupport,
capabilities: statusOverrides.capabilities,
degradations: statusOverrides.degradations
},
_meta: { runtimeId }
}
: {
id: request.id,
ok: false,
error: { code: 'method_not_found', message: 'Unknown method' },
_meta: { runtimeId }
}
ws.send(encrypt(JSON.stringify(response), sharedKey))
})
})
await listen(httpServer)
const address = httpServer.address()
if (!address || typeof address === 'string') {
throw new Error('Expected TCP test server')
}
return {
endpoint: `ws://127.0.0.1:${address.port}`,
publicKeyB64: publicKeyToBase64(serverKeyPair.publicKey),
deviceToken,
authFrames,
requestMethods,
requestParams,
connectionCount: () => connectionCount,
close: async () => {
await new Promise<void>((resolve) => {
wss.close(() => resolve())
for (const client of wss.clients) {
client.close()
}
})
await closeHttpServer(httpServer)
}
}
}
async function listen(server: Server): Promise<void> {
await new Promise<void>((resolve, reject) => {
server.once('error', reject)
server.listen(0, '127.0.0.1', () => {
server.off('error', reject)
resolve()
})
})
}
async function closeHttpServer(server: Server): Promise<void> {
await new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error) {
reject(error)
return
}
resolve()
})
})
}
@@ -1,4 +0,0 @@
// @vitest-environment happy-dom
import './AutomationsPage.escape-precedence.spec'
import './AutomationsPage.external-scope.spec'
import './AutomationsPage.refresh-selection.spec'
@@ -1,72 +0,0 @@
// @vitest-environment happy-dom
/** Window capture runs before Radix document capture; preventing Escape here would veto dismissal of an overlaid dialog (STA-5207). */
import { describe, expect, it, vi } from 'vitest'
import {
installAutomationsPageHarness,
mocks,
renderPage,
settleHostQueries
} from './automations-page-test-harness'
function pressEscape(target: EventTarget): KeyboardEvent {
const event = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })
target.dispatchEvent(event)
return event
}
async function renderWithCloseSpy(): Promise<ReturnType<typeof vi.fn>> {
const closeAutomationsPage = vi.fn()
mocks.state.closeAutomationsPage = closeAutomationsPage
await renderPage()
await settleHostQueries()
return closeAutomationsPage
}
describe('automations page Escape precedence', () => {
installAutomationsPageHarness()
it('closes the page when nothing is layered above it', async () => {
const closeAutomationsPage = await renderWithCloseSpy()
const event = pressEscape(document.body)
expect(event.defaultPrevented).toBe(true)
expect(closeAutomationsPage).toHaveBeenCalledTimes(1)
})
it('leaves Escape to a store modal opened over the page', async () => {
mocks.state.activeModal = 'new-workspace-composer'
const closeAutomationsPage = await renderWithCloseSpy()
const input = document.createElement('input')
document.body.appendChild(input)
const event = pressEscape(input)
expect(event.defaultPrevented).toBe(false)
expect(closeAutomationsPage).not.toHaveBeenCalled()
})
it('leaves Escape to a store modal even when focus is on page chrome', async () => {
mocks.state.activeModal = 'worktree-palette'
const closeAutomationsPage = await renderWithCloseSpy()
const event = pressEscape(document.body)
expect(event.defaultPrevented).toBe(false)
expect(closeAutomationsPage).not.toHaveBeenCalled()
})
it('leaves Escape to a visible overlay that the store does not track', async () => {
const closeAutomationsPage = await renderWithCloseSpy()
const overlay = document.createElement('div')
overlay.setAttribute('role', 'dialog')
document.body.appendChild(overlay)
const event = pressEscape(document.body)
expect(event.defaultPrevented).toBe(false)
expect(closeAutomationsPage).not.toHaveBeenCalled()
})
})
@@ -1,69 +0,0 @@
// @vitest-environment happy-dom
/** Drive the page’s scope producer and inspect IPC; client tests with pre-narrowed scopes cannot verify which hosts the page asks. */
import { describe, expect, it } from 'vitest'
import {
api,
installAutomationsPageHarness,
mocks,
renderPage,
settleHostQueries
} from './automations-page-test-harness'
import { listedExternalEntries } from './automations-page-listed-items'
import { makeExternalManager } from './automations-page-fixtures'
const DESKTOP_SELF_FILTER = {
kind: 'host' as const,
host: { authority: { kind: 'desktop' as const }, selector: { kind: 'self' as const } }
}
function sshFilter(targetId: string): unknown {
return {
kind: 'host',
host: { authority: { kind: 'desktop' }, selector: { kind: 'ssh', targetId } }
}
}
/** Registered SSH targets, each with the generation that makes it fenceable. */
function withSshHosts(...targetIds: string[]): void {
mocks.state.sshTargetLabels = new Map(targetIds.map((targetId) => [targetId, targetId]))
mocks.state.sshTargetGenerations = new Map(targetIds.map((targetId) => [targetId, 1]))
mocks.state.sshConnectionStates = new Map(
targetIds.map((targetId) => [targetId, { status: 'connected' }])
)
}
function openclawOnly(): void {
api.automations.listExternalManagerForOwner.mockImplementation(
async ({ provider }: { provider: string }) =>
provider === 'openclaw'
? { manager: makeExternalManager(), error: null, updatedAt: 1 }
: { manager: null, error: null, updatedAt: 1 }
)
}
describe('AutomationsPage external manager probes', () => {
installAutomationsPageHarness()
it('drops the previous host rows when the selection moves, not when the new probe lands', async () => {
withSshHosts('staging')
mocks.state.automationHostFilter = DESKTOP_SELF_FILTER
openclawOnly()
const { rerender } = await renderPage()
await settleHostQueries()
expect(listedExternalEntries().length).toBeGreaterThan(0)
// The new host never answers, so anything still listed belongs to the old one.
api.automations.listExternalManagerForOwner.mockImplementation(
async () => await new Promise(() => undefined)
)
mocks.state.automationHostFilter = sshFilter('staging')
await rerender()
await settleHostQueries()
expect(listedExternalEntries()).toEqual([])
})
})
@@ -1,133 +0,0 @@
// @vitest-environment happy-dom
/** Refresh reaches one authority at a time; deriving selection/history from that answer would drop or mislabel other hosts’ rows under All hosts. */
import { act } from 'react'
import { describe, expect, it, vi } from 'vitest'
import {
api,
installAutomationsPageHarness,
mocks,
refreshOnFocus,
renderPage,
RUNTIME_SELF_FILTER,
runtimeHost,
scopedList,
SELF_PRECONDITION,
settleHostQueries
} from './automations-page-test-harness'
import { listedRows } from './automations-page-listed-items'
import { makeAutomation, makeRun } from './automations-page-fixtures'
async function openAutomationRow(container: HTMLElement, name: string): Promise<void> {
const row = [
...container.querySelectorAll<HTMLButtonElement>('[data-testid="automation-row"]')
].find((candidate) => candidate.textContent === name)
expect(row).toBeTruthy()
await act(async () => row?.click())
await settleHostQueries()
}
describe('AutomationsPage selection', () => {
installAutomationsPageHarness()
it('fetches the newly selected automation runs when the selection changes', async () => {
scopedList([
makeAutomation({ id: 'a-1', name: 'Nightly' }),
makeAutomation({ id: 'a-2', name: 'Weekly' })
])
const { container, rerender } = await renderPage()
api.automations.listRuns.mockClear()
mocks.state.selectedAutomationId = 'a-2'
await rerender()
await openAutomationRow(container, 'Weekly')
// Fence history reads too so moved rows refuse rather than answer from a former host.
expect(api.automations.listRuns).toHaveBeenCalledWith({
automationId: 'a-2',
expectedOwner: SELF_PRECONDITION,
preview: true
})
expect(mocks.detailPane?.selected?.id).toBe('a-2')
})
})
describe('AutomationsPage multi-host selection', () => {
installAutomationsPageHarness()
it('keeps a selection that lives on another host when the window regains focus', async () => {
runtimeHost([makeAutomation({ id: 'a-remote', name: 'Remote nightly' })], [])
const desktop = makeAutomation({ id: 'a-desktop', name: 'Desktop nightly' })
scopedList([desktop])
api.automations.list.mockResolvedValue([desktop])
const setSelectedAutomationId = vi.fn((id: string | null) => {
mocks.state.selectedAutomationId = id
})
mocks.state.selectedAutomationId = 'a-remote'
mocks.state.setSelectedAutomationId = setSelectedAutomationId
const { container, rerender } = await renderPage()
await settleHostQueries()
await refreshOnFocus()
await rerender()
// One authority’s refresh cannot decide whether another authority’s selected row still exists.
expect(setSelectedAutomationId).not.toHaveBeenCalled()
await openAutomationRow(container, 'Remote nightly')
expect(container.querySelector('[data-testid="detail-name"]')?.textContent).toBe(
'Remote nightly'
)
})
it('shows the selected host’s runs when another authority holds the same id', async () => {
runtimeHost(
[makeAutomation({ id: 'a-1', name: 'Remote nightly' })],
[makeRun({ id: 'run-remote', automationId: 'a-1' })]
)
// IDs can collide across authorities; desktop remains independently reachable.
api.automations.list.mockResolvedValue([makeAutomation({ id: 'a-1', name: 'Desktop nightly' })])
api.automations.listRuns.mockResolvedValue([
makeRun({ id: 'run-desktop', automationId: 'a-1' })
])
scopedList([])
mocks.state.automationHostFilter = RUNTIME_SELF_FILTER
mocks.state.selectedAutomationId = 'a-1'
const { container } = await renderPage()
await settleHostQueries()
await refreshOnFocus()
await openAutomationRow(container, 'Remote nightly')
expect(mocks.detailPane?.selected?.name).toBe('Remote nightly')
expect(mocks.detailPane?.selectedRuns.map((run) => run.id)).toEqual(['run-remote'])
})
it('keeps both authorities’ rows on screen and selectable under All hosts', async () => {
runtimeHost(
[makeAutomation({ id: 'a-1', name: 'Remote nightly' })],
[makeRun({ id: 'run-remote', automationId: 'a-1' })]
)
scopedList([makeAutomation({ id: 'a-1', name: 'Desktop nightly' })])
// The stored id names the record; only the row key can say whose copy.
mocks.state.selectedAutomationId = 'a-1'
const { container } = await renderPage()
await settleHostQueries()
// Two stored records, not one row and a silent drop into #44's empty state.
expect(
[...container.querySelectorAll('[data-testid="automation-row"]')].map(
(row) => row.textContent
)
).toEqual(['Desktop nightly', 'Remote nightly'])
const remote = listedRows().find((row) => row.automation.name === 'Remote nightly')
await act(async () => {
mocks.listPanel?.selectAutomationRow(remote?.key ?? '')
})
expect(mocks.detailPane?.selected?.name).toBe('Remote nightly')
})
})
@@ -1,159 +0,0 @@
import { EVERY_AGENT_CHAT } from '../../../../shared/native-chat/every-agent-chat.test-fixture'
import {
addRuntimeProject,
api,
mocks,
renderPage,
runtimeHost,
RUNTIME_ID,
RUNTIME_SELF_FILTER,
scopedList,
settleHostQueries
} from './automations-page-test-harness'
import { RUNTIME_REPO_ID, RUNTIME_WORKSPACE_ID } from './automations-page-runtime-fixtures'
import { act } from 'react'
import { expect, vi } from 'vitest'
import { checkRuntimeHooks, type HookCheckResult } from '@/runtime/repo-hooks/runtime-hooks-client'
import { loadHostStructuredAgents } from '@/runtime/native-chat/agent-catalogs/host-structured-agents'
import { getDefaultSettings } from '../../../../shared/constants'
import type { Automation } from '../../../../shared/automations/automation-definition'
import type { AutomationDraft } from './authoring/AutomationEditorDialog'
import {
AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY as LIST_HOST_SCOPE,
AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY as OWNER_FENCING,
AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY as CREATE_IDEMPOTENCY,
AUTOMATION_SURFACE_RUNTIME_CAPABILITY,
AUTOMATION_EXTRA_AGENT_ARGS_RUNTIME_CAPABILITY
} from '../../../../shared/automations/automation-runtime-capabilities'
import {
STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY,
STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY
} from '../../../../shared/agent-session/agent-session-runtime-capabilities'
import { STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY } from '../../../../shared/agent-session/structured-agent-session-surface-capabilities'
import { makeAutomation } from './automations-page-fixtures'
export const CHAT_CAPABILITIES = [
LIST_HOST_SCOPE,
OWNER_FENCING,
CREATE_IDEMPOTENCY,
AUTOMATION_SURFACE_RUNTIME_CAPABILITY,
AUTOMATION_EXTRA_AGENT_ARGS_RUNTIME_CAPABILITY,
STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY,
STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY,
STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY
]
export function draftRecord(current: unknown): object {
if (current === null || typeof current !== 'object') {
throw new Error('Missing editor draft')
}
return current
}
/** The runtime answers a create; without this the RPC double returns an empty result. */
export function runtimeCreateReturns(automation: Automation): void {
const previous = mocks.callRuntimeRpc.getMockImplementation()
mocks.callRuntimeRpc.mockImplementation(
async (target: unknown, method: string, params: unknown, options: unknown) => {
if (method === 'automation.create') {
return { automation }
}
return await previous?.(target, method, params, options)
}
)
}
export async function save(): Promise<void> {
await act(async () => {
mocks.editorDialog?.onSave()
})
}
export function createRpcCalls(): unknown[][] {
return mocks.callRuntimeRpc.mock.calls.filter((call) => call[1] === 'automation.create')
}
export const REGISTERED_CHAT_CAPABILITIES = [
...CHAT_CAPABILITIES,
STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY
]
export function observeRuntimeIncarnation(
runtimeId: string,
capabilities = REGISTERED_CHAT_CAPABILITIES
): void {
const status = { runtimeId, capabilities }
mocks.state.runtimeStatusByEnvironmentId = new Map([[RUNTIME_ID, { status }]])
mocks.getRuntimeEnvironmentStatus.mockResolvedValue(status)
}
export async function learnRuntimeAgents(runtimeId: string, agents: string[]): Promise<void> {
const previous = mocks.callRuntimeRpc.getMockImplementation()
mocks.callRuntimeRpc.mockImplementation(async (target, method, params, options) =>
method === 'agentSession.agents'
? { agents: agents.map((agent) => ({ agent, capabilities: {} })) }
: await previous?.(target, method, params, options)
)
try {
await loadHostStructuredAgents(`runtime:${RUNTIME_ID}`, REGISTERED_CHAT_CAPABILITIES, runtimeId)
} finally {
mocks.callRuntimeRpc.mockImplementation(previous ?? (() => ({})))
}
}
export async function openCreateDialogFor(projectId: string, workspaceId: string): Promise<void> {
await act(async () => {
mocks.listPanel?.openCreateDialog()
})
await act(async () => {
mocks.editorDialog?.onDraftChange((current) => ({
...draftRecord(current),
name: 'Sweep',
prompt: 'Do the sweep',
projectId,
workspaceMode: 'existing',
workspaceId
}))
})
}
export async function holdRuntimeSave(
draft: Partial<AutomationDraft> = {},
initialAgents = ['pi']
) {
api.automations.list.mockResolvedValue([])
scopedList([])
runtimeHost([], [])
addRuntimeProject()
mocks.state.settings = { ...getDefaultSettings('/tmp'), nativeChatProviders: EVERY_AGENT_CHAT }
mocks.state.automationHostFilter = RUNTIME_SELF_FILTER
observeRuntimeIncarnation('A')
await learnRuntimeAgents('A', initialAgents)
runtimeCreateReturns(makeAutomation({ id: 'a-new' }))
const held = Promise.withResolvers<HookCheckResult>()
vi.mocked(checkRuntimeHooks).mockReturnValue(held.promise)
const page = await renderPage()
await settleHostQueries()
await openCreateDialogFor(RUNTIME_REPO_ID, RUNTIME_WORKSPACE_ID)
await act(async () => {
mocks.editorDialog?.onDraftChange((current) => ({
...draftRecord(current),
agentId: 'pi',
workspaceMode: 'new_per_run',
workspaceId: '',
...draft
}))
})
await save()
expect(checkRuntimeHooks).toHaveBeenCalledWith(`runtime:${RUNTIME_ID}`, RUNTIME_REPO_ID, {})
expect(createRpcCalls()).toHaveLength(0)
return {
page,
async release() {
await act(async () => {
held.resolve({ status: 'ok', hasHooks: false, hooks: null, mayNeedUpdate: false })
})
await settleHostQueries()
}
}
}
@@ -1,65 +0,0 @@
import type { AutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref'
import type { Automation } from '../../../../shared/automations/automation-definition'
import type { Worktree } from '../../../../shared/worktree/types'
import type { AutomationHostCatalogView } from './hosts/use-automation-host-catalog'
import type { AutomationCreateDestinationControl } from './authoring/use-automation-create-destination'
import type { ExternalAutomationListEntry } from './external/external-automation-list-entries'
import type { AutomationListRow } from './listing/automation-list-row-identity'
import type { AutomationListViewItem } from './listing/automation-list-view'
import type { AutomationTemplate } from './authoring/automation-templates'
export type ListPanelProps = {
sortedListItems: readonly AutomationListViewItem[]
selectedExternal: ExternalAutomationListEntry | null
externalActionKey: string | null
requestExternalAction: (
manager: ExternalAutomationListEntry['manager'],
job: ExternalAutomationListEntry['job'],
action: 'run' | 'pause' | 'resume' | 'delete',
scope: ExternalAutomationListEntry['scope']
) => void
hasListItems: boolean
hasFilteredListItems: boolean
selectedRowKey: string | null
selectedExternalKey: string | null
hostCatalog: AutomationHostCatalogView
searchCounts: { hostRowCount: number; visibleRowCount: number; searchActive: boolean }
externalManagersUncheckedNotice: string | null
isActionEnabled: (row: AutomationListRow, action: string) => boolean
onSelectHost: (filter: unknown) => void
selectAutomationRow: (rowKey: string | null) => void
selectExternalKey: (entryKey: string | null) => void
onOpenDetail: () => void
onRefresh: () => void
onOpenRuns: () => void
runNow: (row: AutomationListRow) => void
openEditDialog: (row: AutomationListRow) => void
toggleAutomation: (row: AutomationListRow) => void
requestDeleteAutomation: (row: AutomationListRow) => void
openCreateDialog: () => void
canCreateAutomation: boolean
}
export type EditorDialogProps = {
launchAuthority?: AutomationAuthorityRef
open: boolean
isEditing: boolean
isSaving: boolean
createDestination?: AutomationCreateDestinationControl
editDestination?: AutomationCreateDestinationControl
notice?: { message: string; recovery: string | null } | null
onNoticeRecover?: (action: string) => void
repos?: { id: string }[]
worktrees: Worktree[]
draft?: { projectId: string; workspaceId: string }
canSave?: boolean
onSave: () => void
onProjectChange: (projectId: string) => void
onDraftChange: (updater: (current: unknown) => unknown) => void
onApplyTemplate: (template: AutomationTemplate) => void
}
export type DeleteDialogProps = {
deleteTarget: Automation | null
onConfirm: () => void
}
@@ -1,69 +0,0 @@
import { mocks, RUNTIME_ID } from './automations-page-test-harness'
import { CHAT_CAPABILITIES } from './automations-page-actions-test-harness'
import type { Repo } from '../../../../shared/repo-types'
import { hostStableKey } from '../../../../shared/automations/ownership/automation-owner-key'
export function observeRuntimeChat(capabilities: string[] | null): void {
mocks.state.runtimeStatusByEnvironmentId = new Map(
capabilities === null ? [] : [[RUNTIME_ID, { status: { capabilities } }]]
)
}
export function capableChatDestination(): void {
observeRuntimeChat(CHAT_CAPABILITIES)
mocks.getRuntimeEnvironmentStatus.mockResolvedValue({ capabilities: CHAT_CAPABILITIES })
}
export const SSH_TARGET_ID = 'ssh-target-1'
export const SSH_REPO_ID = 'repo-ssh'
export const SSH_HOST_KEY = hostStableKey({
authority: { kind: 'desktop' },
selector: { kind: 'ssh', targetId: SSH_TARGET_ID }
})
export const DESKTOP_SELF_KEY = hostStableKey({
authority: { kind: 'desktop' },
selector: { kind: 'self' }
})
export const RUNTIME_SELF_KEY = hostStableKey({
authority: { kind: 'runtime', environmentId: RUNTIME_ID },
selector: { kind: 'self' }
})
/** A desktop-registered SSH host, with the generation that makes it fenceable. */
export function addSshHost(): void {
mocks.state.sshTargetLabels = new Map([[SSH_TARGET_ID, 'openclaw']])
mocks.state.sshTargetGenerations = new Map([[SSH_TARGET_ID, 1]])
mocks.state.sshConnectionStates = new Map([[SSH_TARGET_ID, { status: 'connected' }]])
}
/** A project checked out on that SSH host rather than locally. */
export function addSshProject(): void {
const repo: Repo = {
id: SSH_REPO_ID,
displayName: 'orca',
path: '/repos/orca',
badgeColor: '#222222',
addedAt: 1,
worktreeBaseRef: 'main',
connectionId: SSH_TARGET_ID
}
mocks.state.repos = [...(mocks.state.repos as Repo[]), repo]
mocks.repoMap.set(SSH_REPO_ID, repo)
// The host needs a ready setup or save refuses the project before choosing a destination.
mocks.state.projectHostSetups = [
...mocks.state.projectHostSetups,
{
id: 'setup-ssh',
projectId: 'project-ssh',
hostId: `ssh:${SSH_TARGET_ID}`,
repoId: SSH_REPO_ID,
path: '/repos/orca',
displayName: 'orca',
setupState: 'ready',
setupMethod: 'legacy-repo',
createdAt: 1,
updatedAt: 1
}
]
}
@@ -1,29 +1,14 @@
/** Default to runnable local records so Run Now reaches its handler; cases needing refusal override the relevant fields. */
import type { Automation } from '../../../../shared/automations/automation-definition'
import type {
AutomationRun,
AutomationRunUsage
} from '../../../../shared/automations/history/automation-run'
import type { ExternalAutomationManager } from '../../../../shared/automations/external/external-automation'
import type { ProjectHostSetup } from '../../../../shared/project-types'
import type { AutomationHostCatalogEntry } from './hosts/automation-host-catalog-types'
import type { AppState } from '@/store/types'
import type { Repo } from '../../../../shared/repo-types'
import type { Worktree } from '../../../../shared/worktree/types'
import type {
ExternalAutomationScope,
ScopedExternalAutomationManager
} from './external/external-automation-scope-client'
import {
automationListRowKey,
type AutomationListRow
} from './listing/automation-list-row-identity'
import { ALL_AUTOMATION_HOSTS_FILTER } from '../../../../shared/automations/ownership/automation-host-filter'
import { getDefaultSettings } from '../../../../shared/constants'
export const REPO_ID = 'repo-1'
export const WORKSPACE_ID = 'workspace-1'
export function makeAutomation(overrides: Partial<Automation> = {}): Automation {
return {
@@ -114,186 +99,3 @@ export function makeRunUsage(overrides: Partial<AutomationRunUsage> = {}): Autom
...overrides
}
}
export function makeExternalManager(
overrides: Partial<ExternalAutomationManager> = {}
): ExternalAutomationManager {
return {
id: 'openclaw:local',
provider: 'openclaw',
label: 'OpenClaw',
targetLabel: 'This computer',
target: { type: 'local' },
status: 'available',
error: null,
canManage: true,
jobs: [
{
id: 'job-1',
managerId: 'openclaw:local',
provider: 'openclaw',
name: 'OpenClaw job',
schedule: 'Daily at 09:00',
rawSchedule: '0 9 * * *',
enabled: true,
state: 'active',
prompt: null,
promptPreview: 'Sweep',
nextRunAt: null,
lastRunAt: null,
lastStatus: null,
lastError: null,
workdir: null,
runCount: 0,
runs: []
}
],
...overrides
}
}
/** The desktop-self scope every manager fixture is discovered under by default. */
export function makeExternalAutomationScope(
overrides: Partial<ExternalAutomationScope> = {}
): ExternalAutomationScope {
return {
owner: {
authority: { kind: 'desktop' },
selector: { kind: 'self' }
},
provider: 'openclaw',
...overrides
}
}
export function makeScopedExternalManager(
overrides: Partial<ExternalAutomationManager> = {},
scope: ExternalAutomationScope = makeExternalAutomationScope()
): ScopedExternalAutomationManager {
return { scope, manager: makeExternalManager(overrides) }
}
function makeRepo(): Repo {
return {
id: REPO_ID,
displayName: 'orca',
path: '/repos/orca',
badgeColor: '#000000',
addedAt: 1,
worktreeBaseRef: 'main'
}
}
/** Ready and local, so the editor can build a run context and state a Self destination. */
function makeProjectHostSetup(): ProjectHostSetup {
return {
id: 'setup-1',
projectId: 'project-1',
hostId: 'local',
repoId: REPO_ID,
path: '/repos/orca',
displayName: 'orca',
setupState: 'ready',
setupMethod: 'legacy-repo',
createdAt: 1,
updatedAt: 1
}
}
export function makeWorktree(overrides: Partial<Worktree> = {}): Worktree {
return {
id: WORKSPACE_ID,
repoId: REPO_ID,
displayName: 'main',
path: '/repos/orca',
branch: 'main',
head: 'abc123',
isBare: false,
isMainWorktree: true,
comment: '',
linkedIssue: null,
linkedPR: null,
linkedLinearIssue: null,
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 0,
...overrides
}
}
export type AutomationsPageFixtureState = Record<string, unknown> &
Pick<AppState, 'repos' | 'projectHostSetups' | 'worktreesByRepo'>
export type AutomationsPageStoreFixtures = {
state: AutomationsPageFixtureState
repoMap: Map<string, Repo>
worktreeMap: Map<string, Worktree>
}
/** A store shaped like the page's reads; actions are spies so nothing escapes the test. */
export function makeStoreState(): AutomationsPageStoreFixtures {
const repo = makeRepo()
const worktree = makeWorktree()
const noop = (): void => undefined
return {
state: {
repos: [repo],
projectHostSetups: [makeProjectHostSetup()],
worktreesByRepo: { [REPO_ID]: [worktree] },
unifiedTabsByWorktree: {},
terminalLayoutsByTabId: {},
ptyIdsByTabId: {},
activeWorktreeId: null,
fetchWorktrees: noop,
fetchAllWorktrees: noop,
fetchRuntimeEnvironmentRepos: async () => [],
startupWorktreeRefreshCompleted: true,
updateSettings: noop,
openSettingsPage: noop,
openSettingsTarget: noop,
closeAutomationsPage: noop,
activeModal: 'none',
sshConnectionStates: new Map(),
sshTargetLabels: new Map(),
removedSshTargetLabels: new Map(),
// Hydrated absence proves no desktop SSH targets; the catalog should project only Self.
sshTargetsHydrated: true,
sshStateByEnvironment: new Map(),
runtimeEnvironments: [],
runtimeEnvironmentCatalogSettled: true,
runtimeStatusByEnvironmentId: new Map(),
automationHostFilter: ALL_AUTOMATION_HOSTS_FILTER,
setAutomationHostFilter: noop,
settings: getDefaultSettings('/tmp'),
preflightStatus: null,
preflightStatusChecked: true,
preflightStatusContextKey: null,
refreshPreflightStatus: noop,
selectedAutomationId: null,
setSelectedAutomationId: noop,
pendingAutomationRunNavigation: null,
setPendingAutomationRunNavigation: noop,
hydratePersistedUI: noop,
recordFeatureInteraction: noop,
allWorktrees: () => [worktree],
getKnownWorktreeById: () => worktree
},
repoMap: new Map([[REPO_ID, repo]]),
worktreeMap: new Map([[WORKSPACE_ID, worktree]])
}
}
export type DetailPaneProps = {
selected: Automation | null
selectedHostEntry: AutomationHostCatalogEntry | null
selectedRuns: AutomationRun[]
selectedRunsNotice: { message: string } | null
runNow: (automation: Automation) => void
toggleAutomation: (automation: Automation) => void
requestDeleteAutomation: (automation: Automation) => void
openEditDialog: (automation: Automation) => void
openAutomationRunPage: (run: AutomationRun) => void
recoverSelectedRuns: (action: 'retry') => void
}
@@ -1,27 +0,0 @@
/** Read authority-qualified row keys and render order from the mocked list panel, matching real clicks rather than synthesizing identity. */
import type { AutomationListRow } from './listing/automation-list-row-identity'
import type { ExternalAutomationListEntry } from './external/external-automation-list-entries'
import { mocks } from './automations-page-test-harness'
function listedItems() {
return mocks.listPanel?.sortedListItems ?? []
}
/** Local rows the page listed, in render order. */
export function listedRows(): readonly AutomationListRow[] {
return listedItems().flatMap((item) => (item.kind === 'local' ? [item.row] : []))
}
/** External entries the page listed, in render order. */
export function listedExternalEntries(): readonly ExternalAutomationListEntry[] {
return listedItems().flatMap((item) => (item.kind === 'external' ? [item.entry] : []))
}
export function listedRow(automationId: string): AutomationListRow {
const row = listedRows().find((entry) => entry.automation.id === automationId)
if (!row) {
throw new Error(`no listed row for ${automationId}`)
}
return row
}
@@ -1,66 +0,0 @@
import type { AutomationsPageFixtureState } from './automations-page-fixtures'
import type { Automation } from '../../../../shared/automations/automation-definition'
import type { ProjectHostSetup } from '../../../../shared/project-types'
import type { Repo } from '../../../../shared/repo-types'
import type { Worktree } from '../../../../shared/worktree/types'
export const RUNTIME_REPO_ID = 'repo-2'
export const RUNTIME_WORKSPACE_ID = 'workspace-2'
/** Builds the host-scoped response used by the page harness. */
export function selfScopedList(automations: Automation[]): Record<string, unknown> {
return {
automations,
items: automations.map((automation) => ({
automationId: automation.id,
selector: { kind: 'self' }
})),
orphanCount: 0
}
}
type RuntimeFixtureMocks = {
state: AutomationsPageFixtureState
repoMap: Map<string, unknown>
worktreeMap: Map<string, unknown>
}
/** Adds a runtime-owned project whose id is ambiguous in a flat repo lookup. */
export function addRuntimeProject(mocks: RuntimeFixtureMocks, runtimeId: string): void {
const repo = {
id: RUNTIME_REPO_ID,
displayName: 'gpu-orca',
path: '/repos/gpu-orca',
badgeColor: '#111111',
addedAt: 1,
worktreeBaseRef: 'main',
executionHostId: `runtime:${runtimeId}`
} as Repo
const worktree = {
id: RUNTIME_WORKSPACE_ID,
repoId: RUNTIME_REPO_ID,
displayName: 'main',
path: '/repos/gpu-orca',
branch: 'main'
} as Worktree
const setup: ProjectHostSetup = {
id: 'setup-2',
projectId: 'project-2',
hostId: `runtime:${runtimeId}`,
repoId: RUNTIME_REPO_ID,
path: '/repos/gpu-orca',
displayName: 'gpu-orca',
setupState: 'ready',
setupMethod: 'legacy-repo',
createdAt: 1,
updatedAt: 1
}
const repos = mocks.state.repos as Repo[]
const setups = mocks.state.projectHostSetups
const worktreesByRepo = mocks.state.worktreesByRepo as Record<string, Worktree[]>
mocks.state.repos = [...repos, repo]
mocks.state.projectHostSetups = [...setups, setup]
mocks.state.worktreesByRepo = { ...worktreesByRepo, [RUNTIME_REPO_ID]: [worktree] }
mocks.repoMap.set(RUNTIME_REPO_ID, repo)
mocks.worktreeMap.set(RUNTIME_WORKSPACE_ID, worktree)
}
@@ -1,399 +0,0 @@
import type {
ListPanelProps,
EditorDialogProps,
DeleteDialogProps
} from './automations-page-child-props.test-fixture'
import { resetHostStructuredAgentsForTests } from '@/runtime/native-chat/agent-catalogs/host-structured-agents'
import { setLocalRuntimeCapabilitiesForTests } from '@/runtime/hosts/capabilities/local-runtime-capabilities'
/** Record child props to test page orchestration rather than presentation. Import this harness first so shared vi.mock registrations precede AutomationsPage loading. */
import { act, createElement, StrictMode, type ReactNode } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, type Mock, vi } from 'vitest'
import type { Automation } from '../../../../shared/automations/automation-definition'
import type { AutomationRun } from '../../../../shared/automations/history/automation-run'
import {
AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY as LIST_HOST_SCOPE,
AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY as OWNER_FENCING,
AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY as CREATE_IDEMPOTENCY
} from '../../../../shared/automations/automation-runtime-capabilities'
import type { AppState } from '@/store/types'
import { AutomationDestinationField } from './authoring/AutomationDestinationField'
import { TooltipProvider } from '@/components/ui/tooltip'
import { resetAutomationCapabilityProbes } from './hosts/automation-capability-probe'
import {
addRuntimeProject as addRuntimeProjectFixture,
selfScopedList
} from './automations-page-runtime-fixtures'
type AutomationsPageMocks = {
state: AutomationsPageFixtureState
repoMap: Map<string, unknown>
worktreeMap: Map<string, unknown>
listPanel: ListPanelProps | null
detailPane: DetailPaneProps | null
editorDialog: EditorDialogProps | null
deleteDialog: DeleteDialogProps | null
callRuntimeRpc: Mock
getRuntimeEnvironmentStatus: Mock
setAutomationHostFilter: Mock
toastError: Mock
toastSuccess: Mock
toastMessage: Mock
setPendingRunNavigation: Mock
}
// Mock factories only close over this exported binding; vi.hoisted bindings cannot be exported.
export const mocks: AutomationsPageMocks = {
state: { repos: [], projectHostSetups: [], worktreesByRepo: {} },
repoMap: new Map<string, unknown>(),
worktreeMap: new Map<string, unknown>(),
listPanel: null,
detailPane: null,
editorDialog: null,
deleteDialog: null,
callRuntimeRpc: vi.fn(),
getRuntimeEnvironmentStatus: vi.fn(),
setAutomationHostFilter: vi.fn(),
toastError: vi.fn(),
toastSuccess: vi.fn(),
toastMessage: vi.fn(),
setPendingRunNavigation: vi.fn()
}
vi.mock('@/store/index', () => {
const useAppStore = (selector: (state: Partial<AppState>) => unknown): unknown =>
selector(mocks.state as Partial<AppState>)
useAppStore.getState = (): Partial<AppState> => mocks.state as Partial<AppState>
return { useAppStore }
})
vi.mock('@/store/repos/use-repository-catalog', () => ({
useRepoMap: () => mocks.repoMap
}))
vi.mock('@/store/slices/worktrees/listing/use-worktree-catalog', () => ({
useWorktreeMap: () => mocks.worktreeMap
}))
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({
callRuntimeRpc: (...args: unknown[]) => mocks.callRuntimeRpc(...args)
}))
vi.mock('@/runtime/rpc/compatibility/runtime-compatibility-probe', () => ({
getRuntimeEnvironmentStatus: (...args: unknown[]) => mocks.getRuntimeEnvironmentStatus(...args)
}))
vi.mock('sonner', () => ({
toast: {
error: (...args: unknown[]) => mocks.toastError(...args),
success: (...args: unknown[]) => mocks.toastSuccess(...args),
message: (...args: unknown[]) => mocks.toastMessage(...args)
}
}))
vi.mock('@/lib/window-activity/window-visibility-interval', () => ({
installWindowVisibilityInterval: () => () => undefined
}))
vi.mock('@/components/contextual-tours/use-contextual-tour', () => ({
useContextualTour: () => undefined
}))
vi.mock('@/components/ui/tooltip', () => ({
TooltipProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
TooltipContent: () => null
}))
vi.mock('@/runtime/repo-hooks/runtime-hooks-client', () => ({
checkRuntimeHooks: vi.fn(async () => ({ hooks: null, ok: true }))
}))
vi.mock('@/runtime/repo-hooks/ensure-hooks-confirmed', () => ({
ensureHooksConfirmed: vi.fn(async () => 'inherit'),
ensureHooksApproved: vi.fn(async () => ({ decision: 'run' }))
}))
vi.mock('@/lib/workspace/activation/worktree-activation', () => ({
activateAndRevealWorktree: vi.fn()
}))
vi.mock('./listing/AutomationsListPanel', () => ({
AutomationsListPanel: (props: ListPanelProps) => {
const selectAutomationRow = (rowKey: string | null): void => {
props.selectAutomationRow(rowKey)
props.onOpenDetail()
}
mocks.listPanel = { ...props, selectAutomationRow }
return (
<div data-testid="list-panel">
<button aria-label="Refresh automations" onClick={props.onRefresh} />
<button onClick={props.onOpenRuns}>Runs</button>
{props.sortedListItems.map((item) =>
item.kind === 'local' ? (
<button
type="button"
data-testid="automation-row"
key={item.id}
onClick={() => selectAutomationRow(item.id)}
>
{item.row.automation.name}
</button>
) : (
<button
type="button"
data-testid="external-row"
key={item.id}
onClick={() => {
props.selectAutomationRow(null)
props.selectExternalKey(item.id)
props.onOpenDetail()
}}
>
{item.entry.job.name}
</button>
)
)}
{props.hasListItems ? null : <div data-testid="empty-state" />}
</div>
)
}
}))
vi.mock('./details/AutomationsDetailPane', () => ({
AutomationsDetailPane: (props: DetailPaneProps) => {
mocks.detailPane = props
return (
<div data-testid="detail-pane">
<span data-testid="detail-name">{props.selected?.name ?? 'none'}</span>
<span data-testid="detail-run-count">{props.selectedRuns.length}</span>
</div>
)
}
}))
vi.mock('./authoring/AutomationEditorDialog', () => ({
AutomationEditorDialog: (props: EditorDialogProps) => {
mocks.editorDialog = props
return (
<div data-testid="editor-dialog">
{props.open ? 'open' : 'closed'}
{props.open && props.editDestination ? (
<TooltipProvider>
<AutomationDestinationField control={props.editDestination} />
<button data-testid="editor-save" disabled={!props.canSave} onClick={props.onSave}>
Save changes
</button>
</TooltipProvider>
) : null}
</div>
)
}
}))
vi.mock('./authoring/AutomationDeleteDialogs', () => ({
AutomationDeleteDialog: (props: DeleteDialogProps) => {
mocks.deleteDialog = props
return null
},
ExternalAutomationDeleteDialog: () => null
}))
import AutomationsPage from './AutomationsPage'
import {
makeAutomation,
makeRun,
makeStoreState,
type AutomationsPageFixtureState,
type DetailPaneProps
} from './automations-page-fixtures'
function mockGroup<K extends string>(...names: K[]): Record<K, Mock> {
return Object.fromEntries(names.map((name) => [name, vi.fn()])) as Record<K, Mock>
}
export const api = {
automations: mockGroup(
'list',
'listRuns',
'create',
'update',
'delete',
'runNow',
'listScoped',
'listExternalManagerForOwner',
'runExternalActionForOwner',
'retainExternalScopes'
),
ssh: mockGroup('listTargets', 'connect'),
runtimeEnvironments: mockGroup('connect'),
ui: mockGroup('get')
}
/** The precondition a Desktop + Self row captures; every fenced request repeats it. */
export const SELF_PRECONDITION = { selector: { kind: 'self' } }
/** The owner the catalog projects for Desktop + Self, which every scoped call names. */
export const DESKTOP_SELF_OWNER = { authority: { kind: 'desktop' }, selector: { kind: 'self' } }
export const RUNTIME_ID = 'gpu'
/** A runtime that advertises both automation capabilities, so its rows carry owners. */
const RUNTIME_CAPABILITIES = [LIST_HOST_SCOPE, OWNER_FENCING, CREATE_IDEMPOTENCY]
export const RUNTIME_SELF_FILTER = {
kind: 'host' as const,
host: {
authority: { kind: 'runtime' as const, environmentId: RUNTIME_ID },
selector: { kind: 'self' as const }
}
}
/** Serve desktop-local RPCs from the programmable API mocks and runtime-target RPCs from runtimeHost state. */
async function answerAutomationRpc(
target: unknown,
method: string,
params?: unknown
): Promise<unknown> {
if ((target as { kind?: string } | null)?.kind === 'environment') {
const answers = mocks.state.runtimeAnswers as
| { automations: Automation[]; runs: AutomationRun[] }
| undefined
if (method === 'automation.list') {
return selfScopedList(answers?.automations ?? [])
}
return method === 'automation.runs' ? { runs: answers?.runs ?? [] } : {}
}
const args = params as Record<string, unknown> | undefined
switch (method) {
case 'automation.list':
return args?.selector
? await api.automations.listScoped({ selector: args.selector })
: { automations: await api.automations.list() }
case 'automation.runs':
return { runs: await api.automations.listRuns(args) }
case 'automation.create':
return { automation: await api.automations.create(args) }
case 'automation.update':
return { automation: await api.automations.update(args) }
case 'automation.delete':
return await api.automations.delete(args).then(() => ({}))
case 'automation.runNow':
return { run: await api.automations.runNow(args) }
default:
return {}
}
}
/** Puts a reachable, capable second authority in the catalog and answers for it. */
export function runtimeHost(automations: Automation[], runs: AutomationRun[]): void {
mocks.state.runtimeEnvironments = [
{ id: RUNTIME_ID, name: 'GPU box', createdAt: 1, pairingRevision: 4 }
]
mocks.state.runtimeStatusByEnvironmentId = new Map([
[RUNTIME_ID, { status: { capabilities: RUNTIME_CAPABILITIES } }]
])
mocks.getRuntimeEnvironmentStatus.mockResolvedValue({ capabilities: RUNTIME_CAPABILITIES })
mocks.state.runtimeAnswers = { automations, runs }
}
export const addRuntimeProject = (): void => addRuntimeProjectFixture(mocks, RUNTIME_ID)
/** Answers the host-scoped read, which is where the list's rows and owners come from. */
export function scopedList(automations: Automation[]): void {
api.automations.listScoped.mockResolvedValue(selfScopedList(automations))
}
const roots: Root[] = []
export async function renderPage(options?: { strict?: boolean }): Promise<{
container: HTMLDivElement
rerender: () => Promise<void>
}> {
const container = document.createElement('div')
document.body.appendChild(container)
const root = createRoot(container)
roots.push(root)
const rerender = async (): Promise<void> => {
await act(async () => {
// StrictMode doubles effects to expose dispose-without-revive controller bugs.
const page = options?.strict
? createElement(StrictMode, null, createElement(AutomationsPage))
: createElement(AutomationsPage)
root.render(page)
})
}
await rerender()
return { container, rerender }
}
/** Lets the per-host queries, their capability probes, and the history read settle. */
export async function settleHostQueries(): Promise<void> {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0))
})
}
/** The alt-tab-back trigger: one of the two events bound to the page refresh. */
export async function refreshOnFocus(): Promise<void> {
await act(async () => {
window.dispatchEvent(new Event('focus'))
await new Promise((resolve) => setTimeout(resolve, 0))
})
}
export function rows(container: HTMLElement, testId: string): string[] {
return [...container.querySelectorAll(`[data-testid="${testId}"]`)].map(
(node) => node.textContent ?? ''
)
}
/** Registers the per-case store reset and renderer cleanup for the current suite. */
export function installAutomationsPageHarness(): void {
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
vi.clearAllMocks()
setLocalRuntimeCapabilitiesForTests([])
// Confirmed capabilities are module-level and must not leak between tests.
resetAutomationCapabilityProbes()
resetHostStructuredAgentsForTests()
// A prior test's wholesale mockImplementation must not leak forward.
mocks.callRuntimeRpc.mockReset()
mocks.callRuntimeRpc.mockImplementation(answerAutomationRpc)
mocks.listPanel = null
mocks.detailPane = null
mocks.editorDialog = null
mocks.deleteDialog = null
const fixtures = makeStoreState()
mocks.state = fixtures.state
mocks.state.folderWorkspaces = []
mocks.state.setAutomationHostFilter = mocks.setAutomationHostFilter
mocks.repoMap = fixtures.repoMap
mocks.worktreeMap = fixtures.worktreeMap
api.automations.list.mockResolvedValue([makeAutomation()])
api.automations.listRuns.mockResolvedValue([])
api.automations.listExternalManagerForOwner.mockResolvedValue({
manager: null,
error: null,
updatedAt: 0
})
api.automations.retainExternalScopes.mockResolvedValue(undefined)
api.automations.listScoped.mockResolvedValue(selfScopedList([makeAutomation()]))
api.automations.create.mockResolvedValue(makeAutomation())
api.automations.update.mockResolvedValue(makeAutomation())
api.automations.delete.mockResolvedValue(undefined)
api.automations.runNow.mockResolvedValue(makeRun())
api.ui.get.mockResolvedValue({})
// @ts-expect-error test window mock
globalThis.window.api = api
})
afterEach(async () => {
await act(async () => {
roots.splice(0).forEach((root) => root.unmount())
})
document.body.innerHTML = ''
setLocalRuntimeCapabilitiesForTests(null)
})
}
@@ -1,124 +0,0 @@
import type { GrokStartupTraceChunk } from './grok-startup-pty-trace'
/**
* Recorded PTY output of `grok --no-alt-screen`, grok's inline (non
* alternate-screen) rendering mode — also reachable via `--minimal` and
* `[ui] screen_mode = "minimal"` in ~/.grok/config.toml.
*
* Recorded from: grok 1.0.0 (3cd0d0cbcebe) [stable] on macOS (darwin 25.3.0),
* xterm-256color 120x30 via node-pty, cwd = an Orca git worktree, 10s of output
* from spawn.
*
* This mode emits NO alternate-screen switch, so the composer-glyph marker never
* anchors and the 2004-anchored quiet window is the only delivery path. Elision
* follows the alt-screen fixture: entries without `data` are marker-free render
* frames kept only as timestamp + byte count.
*/
export const GROK_INLINE_STARTUP_PTY_TRACE: GrokStartupTraceChunk[] = [
{
t: 279,
data: '\u001b]0;grok\u0007\u001b[?1000h\u001b[?1002h\u001b[?1003h\u001b[?1015h\u001b[?1006h\u001b[?1004h\u001b[?2004h\u001b[?25l\u001b]12;rgb:c8/c8'
},
{ t: 279, bytes: 8 },
{ t: 2280, bytes: 11 },
{ t: 2587, bytes: 5 },
{ t: 2612, bytes: 825 },
{ t: 2612, bytes: 925 },
{ t: 2612, bytes: 928 },
{ t: 2612, bytes: 958 },
{ t: 2612, bytes: 810 },
{ t: 2613, bytes: 1000 },
{
t: 2613,
data: ';80;80;88;48;2;20;20;20m╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\u001b[39;48;2;20;20;20m \u001b[26;1H \u001b[38;2;80;80;88;48;2;20;20;20m│\u001b[38;2;225;225;225;48;2;20;20;20m \u001b[38;2;200;200;200;48;2;20;20;20m❯ \u001b[38;2;225;225;225;48;2;20;20;20m \u001b[38;2;80;80;88;48;2;20;20;20m│\u001b[39;48;2;20;20;20m \u001b[27;1H \u001b[38;2;80;80;88;48;2;20;20;20m╰─────────────────────────────────────────────────────────────────────────────── \u001b[38;2;128;128;128;48;2;20;20;20mGrok 4.'
},
{
t: 2613,
data: '5 (high)\u001b[38;2;88;88;88;48;2;20;20;20m · \u001b[38;2;108;108;108;48;2;20;20;20malways-approve\u001b[38;2;80;80;88;48;2;20;20;20m ─╯\u001b[39;48;2;20;20;20m \u001b[28;1H \u001b[29;1H \u001b[38;2;108;108;108;48;2;20;20;20m[stable]\u001b[39;48;2;20;20;20m \u001b[30;1H \u001b[39m\u001b[49m\u001b[59m\u001b[0m\u001b[26;7H\u001b[?25h\u001b[?2026l'
},
{ t: 2614, bytes: 169 },
{ t: 2676, bytes: 158 },
{ t: 2697, bytes: 158 },
{ t: 2772, bytes: 586 },
{ t: 2781, bytes: 410 },
{ t: 2866, bytes: 971 },
{ t: 2866, bytes: 69 },
{ t: 2878, bytes: 970 },
{ t: 2878, bytes: 308 },
{ t: 2951, bytes: 970 },
{ t: 2951, bytes: 784 },
{ t: 3036, bytes: 970 },
{ t: 3036, bytes: 968 },
{ t: 3036, bytes: 417 },
{ t: 3121, bytes: 948 },
{ t: 3121, bytes: 954 },
{ t: 3121, bytes: 792 },
{ t: 3207, bytes: 966 },
{ t: 3207, bytes: 964 },
{ t: 3207, bytes: 837 },
{ t: 3291, bytes: 970 },
{ t: 3291, bytes: 966 },
{ t: 3291, bytes: 956 },
{ t: 3291, bytes: 195 },
{ t: 3376, bytes: 968 },
{ t: 3376, bytes: 962 },
{ t: 3376, bytes: 785 },
{ t: 3461, bytes: 944 },
{ t: 3461, bytes: 912 },
{ t: 3461, bytes: 79 },
{ t: 3546, bytes: 962 },
{ t: 3546, bytes: 568 },
{ t: 3630, bytes: 839 },
{ t: 3630, bytes: 40 },
{ t: 3715, bytes: 424 },
{ t: 3800, bytes: 168 },
{ t: 3885, bytes: 218 },
{ t: 4139, bytes: 219 },
{ t: 4394, bytes: 219 },
{ t: 4732, bytes: 219 },
{ t: 5582, bytes: 219 },
{ t: 5922, bytes: 219 },
{ t: 6177, bytes: 219 },
{ t: 6432, bytes: 219 },
{ t: 6602, bytes: 219 },
{ t: 6686, bytes: 158 },
{ t: 6771, bytes: 410 },
{ t: 6857, bytes: 878 },
{ t: 6857, bytes: 463 },
{ t: 6941, bytes: 970 },
{ t: 6941, bytes: 718 },
{ t: 7026, bytes: 970 },
{ t: 7026, bytes: 968 },
{ t: 7026, bytes: 292 },
{ t: 7110, bytes: 964 },
{ t: 7110, bytes: 962 },
{ t: 7110, bytes: 549 },
{ t: 7195, bytes: 964 },
{ t: 7195, bytes: 969 },
{ t: 7195, bytes: 967 },
{ t: 7195, bytes: 306 },
{ t: 7279, bytes: 970 },
{ t: 7279, bytes: 968 },
{ t: 7279, bytes: 961 },
{ t: 7279, bytes: 103 },
{ t: 7364, bytes: 968 },
{ t: 7364, bytes: 956 },
{ t: 7364, bytes: 795 },
{ t: 7449, bytes: 964 },
{ t: 7450, bytes: 962 },
{ t: 7450, bytes: 316 },
{ t: 7535, bytes: 954 },
{ t: 7535, bytes: 550 },
{ t: 7621, bytes: 960 },
{ t: 7621, bytes: 94 },
{ t: 7704, bytes: 438 },
{ t: 7789, bytes: 168 },
{ t: 7874, bytes: 83 },
{ t: 8043, bytes: 219 },
{ t: 8381, bytes: 219 },
{ t: 8635, bytes: 219 },
{ t: 8890, bytes: 219 },
{ t: 9144, bytes: 219 },
{ t: 9398, bytes: 219 },
{ t: 9738, bytes: 219 }
]
@@ -1,163 +0,0 @@
/**
* Recorded PTY output of a `grok` launch, used to pin when the draft-paste
* readiness scanner would deliver a launch draft.
*
* Recorded from: grok 1.0.0 (3cd0d0cbcebe) [stable] on macOS (darwin 25.3.0),
* xterm-256color 120x30 via node-pty, cwd = an Orca git worktree, 10s of output
* from spawn.
*
* Entries without `data` are grok logo-shimmer render frames, verified to hold
* none of DECSET 1049h / 2004h, DECTCEM show-cursor, or the composer glyphs
* U+276F / U+203A. Only their timestamp and byte count are kept so the fixture
* stays small; the replay substitutes filler of the recorded length. Timings are
* what the scanner reacts to, so they are preserved verbatim.
*/
export type GrokStartupTraceChunk = {
/** ms after spawn */
t: number
data?: string
/** Length of an elided, marker-free animation frame. */
bytes?: number
}
export const GROK_STARTUP_PTY_TRACE: GrokStartupTraceChunk[] = [
{
t: 274,
data: '\u001b]0;grok\u0007\u001b[?1049h\u001b[?1000h\u001b[?1002h\u001b[?1003h\u001b[?1015h\u001b[?1006h\u001b[?1004h\u001b[?2004h\u001b[?25l'
},
{ t: 274, bytes: 18 },
{ t: 582, bytes: 5 },
{ t: 607, bytes: 825 },
{ t: 607, bytes: 925 },
{ t: 607, bytes: 928 },
{ t: 607, bytes: 958 },
{ t: 607, bytes: 810 },
{ t: 607, bytes: 1000 },
{
t: 607,
data: ';80;80;88;48;2;20;20;20m╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\u001b[39;48;2;20;20;20m \u001b[26;1H \u001b[38;2;80;80;88;48;2;20;20;20m│\u001b[38;2;225;225;225;48;2;20;20;20m \u001b[38;2;200;200;200;48;2;20;20;20m❯ \u001b[38;2;225;225;225;48;2;20;20;20m \u001b[38;2;80;80;88;48;2;20;20;20m│\u001b[39;48;2;20;20;20m \u001b[27;1H \u001b[38;2;80;80;88;48;2;20;20;20m╰─────────────────────────────────────────────────────────────────────────────── \u001b[38;2;128;128;128;48;2;20;20;20mGrok 4.'
},
{
t: 607,
data: '5 (high)\u001b[38;2;88;88;88;48;2;20;20;20m · \u001b[38;2;108;108;108;48;2;20;20;20malways-approve\u001b[38;2;80;80;88;48;2;20;20;20m ─╯\u001b[39;48;2;20;20;20m \u001b[28;1H \u001b[29;1H \u001b[38;2;108;108;108;48;2;20;20;20m[stable]\u001b[39;48;2;20;20;20m \u001b[30;1H \u001b[39m\u001b[49m\u001b[59m\u001b[0m\u001b[26;7H\u001b[?25h\u001b[?2026l'
},
{ t: 613, bytes: 169 },
{ t: 664, bytes: 158 },
{ t: 691, bytes: 158 },
{ t: 762, bytes: 410 },
{ t: 776, bytes: 586 },
{ t: 861, bytes: 971 },
{ t: 861, bytes: 69 },
{ t: 945, bytes: 970 },
{ t: 945, bytes: 784 },
{ t: 1031, bytes: 970 },
{ t: 1031, bytes: 968 },
{ t: 1031, bytes: 417 },
{ t: 1109, bytes: 948 },
{ t: 1110, bytes: 954 },
{ t: 1110, bytes: 792 },
{ t: 1115, bytes: 972 },
{ t: 1115, bytes: 968 },
{ t: 1115, bytes: 336 },
{ t: 1200, bytes: 964 },
{ t: 1200, bytes: 964 },
{ t: 1200, bytes: 962 },
{ t: 1200, bytes: 62 },
{ t: 1286, bytes: 970 },
{ t: 1286, bytes: 966 },
{ t: 1286, bytes: 956 },
{ t: 1286, bytes: 195 },
{ t: 1370, bytes: 968 },
{ t: 1370, bytes: 962 },
{ t: 1370, bytes: 785 },
{ t: 1455, bytes: 944 },
{ t: 1455, bytes: 912 },
{ t: 1455, bytes: 79 },
{ t: 1540, bytes: 962 },
{ t: 1540, bytes: 568 },
{ t: 1625, bytes: 839 },
{ t: 1625, bytes: 40 },
{ t: 1710, bytes: 424 },
{ t: 1795, bytes: 168 },
{ t: 1879, bytes: 218 },
{ t: 2134, bytes: 219 },
{ t: 2389, bytes: 219 },
{ t: 2728, bytes: 219 },
{ t: 3579, bytes: 219 },
{ t: 3918, bytes: 219 },
{ t: 4172, bytes: 219 },
{ t: 4425, bytes: 219 },
{ t: 4594, bytes: 219 },
{ t: 4680, bytes: 158 },
{ t: 4764, bytes: 410 },
{ t: 4850, bytes: 878 },
{ t: 4850, bytes: 463 },
{ t: 4934, bytes: 970 },
{ t: 4934, bytes: 718 },
{ t: 5019, bytes: 970 },
{ t: 5019, bytes: 968 },
{ t: 5019, bytes: 292 },
{ t: 5103, bytes: 964 },
{ t: 5103, bytes: 962 },
{ t: 5103, bytes: 549 },
{ t: 5188, bytes: 964 },
{ t: 5188, bytes: 969 },
{ t: 5188, bytes: 967 },
{ t: 5188, bytes: 306 },
{ t: 5272, bytes: 970 },
{ t: 5272, bytes: 968 },
{ t: 5272, bytes: 961 },
{ t: 5272, bytes: 103 },
{ t: 5358, bytes: 968 },
{ t: 5358, bytes: 956 },
{ t: 5358, bytes: 795 },
{ t: 5442, bytes: 964 },
{ t: 5442, bytes: 962 },
{ t: 5442, bytes: 316 },
{ t: 5527, bytes: 954 },
{ t: 5527, bytes: 550 },
{ t: 5612, bytes: 960 },
{ t: 5612, bytes: 94 },
{ t: 5696, bytes: 438 },
{ t: 5781, bytes: 168 },
{ t: 5866, bytes: 83 },
{ t: 6120, bytes: 219 },
{ t: 6375, bytes: 219 },
{ t: 6631, bytes: 219 },
{ t: 6884, bytes: 219 },
{ t: 7139, bytes: 219 },
{ t: 7393, bytes: 219 },
{ t: 7732, bytes: 219 },
{ t: 8580, bytes: 219 },
{ t: 8664, bytes: 158 },
{ t: 8750, bytes: 410 },
{ t: 8835, bytes: 796 },
{ t: 8919, bytes: 908 },
{ t: 8919, bytes: 861 },
{ t: 9004, bytes: 966 },
{ t: 9004, bytes: 894 },
{ t: 9090, bytes: 970 },
{ t: 9090, bytes: 968 },
{ t: 9090, bytes: 768 },
{ t: 9175, bytes: 964 },
{ t: 9175, bytes: 969 },
{ t: 9175, bytes: 967 },
{ t: 9175, bytes: 306 },
{ t: 9260, bytes: 970 },
{ t: 9260, bytes: 968 },
{ t: 9260, bytes: 958 },
{ t: 9260, bytes: 291 },
{ t: 9344, bytes: 960 },
{ t: 9344, bytes: 956 },
{ t: 9344, bytes: 605 },
{ t: 9430, bytes: 952 },
{ t: 9430, bytes: 936 },
{ t: 9430, bytes: 377 },
{ t: 9515, bytes: 960 },
{ t: 9515, bytes: 775 },
{ t: 9600, bytes: 914 },
{ t: 9600, bytes: 427 },
{ t: 9684, bytes: 618 },
{ t: 9770, bytes: 180 },
{ t: 9855, bytes: 219 }
]
-45
View File
@@ -1,45 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { BundledSkillOp, BundledSkillPlan } from './bundled-skill-plan'
import { bundledSkillNudgeKey, summarizeBundledSkillPlan } from './bundled-skill-summary'
const folder = { kind: 'folder', entries: ['SKILL.md:file'], skillDigest: 'a'.repeat(64) } as const
function op(fields: Partial<BundledSkillOp>): BundledSkillOp {
return {
kind: 'keep',
path: '/home/me/.agents/skills/x',
role: 'shared',
agents: [],
observed: folder,
cleanup: [],
...fields
}
}
/** A plan as a paired server returns it: planned on the server's disk against the server's own bundle. */
const serverPlan = (ops: BundledSkillOp[]): BundledSkillPlan => ({
scope: 'global',
homeDirectory: '/home/me',
skills: [{ name: 'orca-cli', digest: 'b'.repeat(64), ops }],
planDigest: 'c'.repeat(64)
})
describe('another Orca build’s copy in a planned host’s plan', () => {
it('reads as current and is never offered as an update', () => {
const plan = serverPlan([
op({ kind: 'leave', reason: 'other-build', replaceable: true }),
op({
path: '/home/me/.claude/skills/x',
role: 'agent',
observed: { kind: 'link', target: 'x' }
})
])
expect(summarizeBundledSkillPlan(plan)).toMatchObject({
badge: null,
hasWork: false,
skills: [{ name: 'orca-cli', state: 'current' }]
})
expect(bundledSkillNudgeKey('runtime:server-1', plan)).toBeNull()
})
})
+26 -104
View File
@@ -1,12 +1,9 @@
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it } from 'vitest'
import type {
AgentSessionExecutionClaim,
AgentSessionSurfaceBinding
} from './agent-session/agent-session-host-authority'
import {
ClaimedAgentPtyOwnerRegistry,
MAX_CLAIMED_AGENT_PTY_OWNER_ENTRIES
} from './claimed-agent-pty-owner'
import { ClaimedAgentPtyOwnerRegistry } from './claimed-agent-pty-owner'
function claim(
identityDigest = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
@@ -49,25 +46,7 @@ describe('ClaimedAgentPtyOwnerRegistry', () => {
).rejects.toThrow('agent_session_conflict')
})
it('does not find an owner through another worktree scope', async () => {
const registry = new ClaimedAgentPtyOwnerRegistry()
await registry.ensure({
claim: claim(),
surface,
spawn: async () => ({ ptyId: 'pty-1' })
})
expect(
registry.find(
claim(
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'ccccccccccccccccccccccccccccccccccccccccccc'
)
)
).toBeNull()
})
it('generation-guards release across a replacement owner', async () => {
it('ignores a stale release generation and releases the matching owner', async () => {
const registry = new ClaimedAgentPtyOwnerRegistry()
const first = await registry.ensure({
claim: claim(),
@@ -76,7 +55,7 @@ describe('ClaimedAgentPtyOwnerRegistry', () => {
})
registry.release('pty-1', 'stale-generation')
expect(registry.find(claim())?.generation).toBe(first.owner.generation)
expect(registry.find(claim())).toMatchObject({ ptyId: 'pty-1' })
registry.release('pty-1', first.owner.generation)
expect(registry.find(claim())).toBeNull()
@@ -134,70 +113,6 @@ describe('ClaimedAgentPtyOwnerRegistry', () => {
})
})
it('rejects a recovered owner that reuses only one half of its generation identity', () => {
const registry = new ClaimedAgentPtyOwnerRegistry()
const owner = {
claim: claim(),
generation: 'generation-1',
phase: 'live' as const,
ptyId: 'pty-1',
surface
}
registry.register(owner)
expect(() => registry.register({ ...owner, ptyId: 'pty-2' })).toThrow('agent_session_conflict')
expect(() => registry.register({ ...owner, generation: 'generation-2' })).toThrow(
'agent_session_conflict'
)
})
it('retains only allowlisted owner fields', () => {
const registry = new ClaimedAgentPtyOwnerRegistry()
const owner = {
claim: { ...claim(), unknownPayload: 'claim payload' },
generation: 'generation-1',
phase: 'live' as const,
ptyId: 'pty-1',
surface: { ...surface, unknownPayload: 'surface payload' },
unknownPayload: 'owner payload'
}
registry.register(owner)
expect(registry.list()).toEqual([
{
claim: claim(),
generation: 'generation-1',
phase: 'live',
ptyId: 'pty-1',
surface
}
])
})
it('fails closed when recovered owner evidence reaches the process-wide cap', () => {
const registry = new ClaimedAgentPtyOwnerRegistry()
const owners = Array.from({ length: MAX_CLAIMED_AGENT_PTY_OWNER_ENTRIES }, (_, index) => ({
claim: claim(`identity-${index}`),
generation: `generation-${index}`,
phase: 'live' as const,
ptyId: `pty-${index}`,
surface
}))
registry.reconcileAuthoritative(owners)
expect(() =>
registry.register({
claim: claim('one-more-identity'),
generation: 'one-more-generation',
phase: 'live',
ptyId: 'one-more-pty',
surface
})
).toThrow('execution_owner_unavailable')
expect(registry.list()).toHaveLength(MAX_CLAIMED_AGENT_PTY_OWNER_ENTRIES)
})
it('atomically converges from conflicting provider evidence to one owner', async () => {
const registry = new ClaimedAgentPtyOwnerRegistry()
const ownerA = {
@@ -226,7 +141,10 @@ describe('ClaimedAgentPtyOwnerRegistry', () => {
spawn: async () => ({ ptyId: 'unexpected' }),
isLive: (owner) => owner.generation === ownerB.generation
})
).resolves.toMatchObject({ disposition: 'adopted', owner: ownerB })
).resolves.toMatchObject({
disposition: 'adopted',
owner: { ptyId: 'pty-b', generation: 'generation-b' }
})
})
it('prunes an advertised generation when an authoritative snapshot omits it', async () => {
@@ -241,12 +159,11 @@ describe('ClaimedAgentPtyOwnerRegistry', () => {
registry.reconcileAuthoritative([recovered])
registry.reconcileAuthoritative([])
const spawn = vi.fn(async () => ({ ptyId: 'pty-new' }))
const spawn = async () => ({ ptyId: 'pty-new' })
await expect(registry.ensure({ claim: claim(), surface, spawn })).resolves.toMatchObject({
disposition: 'created',
owner: { ptyId: 'pty-new' }
})
expect(spawn).toHaveBeenCalledOnce()
})
it('replaces a reused PTY id with the exact newly advertised generation', async () => {
@@ -261,7 +178,7 @@ describe('ClaimedAgentPtyOwnerRegistry', () => {
const newOwner = { ...oldOwner, generation: 'generation-new' }
registry.reconcileAuthoritative([oldOwner])
registry.reconcileAuthoritative([newOwner])
const isLive = vi.fn((owner: typeof newOwner) => owner.generation === 'generation-new')
const isLive = (owner: typeof newOwner) => owner.generation === 'generation-new'
await expect(
registry.ensure({
@@ -270,27 +187,32 @@ describe('ClaimedAgentPtyOwnerRegistry', () => {
spawn: async () => ({ ptyId: 'unexpected' }),
isLive
})
).resolves.toMatchObject({ disposition: 'adopted', owner: newOwner })
expect(isLive).toHaveBeenCalledWith(expect.objectContaining({ generation: 'generation-new' }))
).resolves.toMatchObject({
disposition: 'adopted',
owner: { ptyId: 'pty-reused', generation: 'generation-new' }
})
})
it('does not let reconciliation erase an in-flight reservation', async () => {
const registry = new ClaimedAgentPtyOwnerRegistry()
let finish!: (result: { ptyId: string }) => void
const spawn = vi.fn(
() =>
new Promise<{ ptyId: string }>((resolve) => {
finish = resolve
})
)
const spawn = () =>
new Promise<{ ptyId: string }>((resolve) => {
finish = resolve
})
const first = registry.ensure({ claim: claim(), surface, spawn })
registry.reconcileAuthoritative([])
const second = registry.ensure({ claim: claim(), surface, spawn })
finish({ ptyId: 'pty-reserved' })
await expect(first).resolves.toMatchObject({ disposition: 'created' })
await expect(second).resolves.toMatchObject({ disposition: 'adopted' })
expect(spawn).toHaveBeenCalledOnce()
await expect(first).resolves.toMatchObject({
disposition: 'created',
owner: { ptyId: 'pty-reserved' }
})
await expect(second).resolves.toMatchObject({
disposition: 'adopted',
owner: { ptyId: 'pty-reserved' }
})
})
})
+1 -27
View File
@@ -13,35 +13,9 @@ function controlResponseLine(models: unknown[]): string {
}
describe('parseClaudeModelList', () => {
it('skips init noise, CRLF endings, and duplicate values', () => {
const stdout =
'{"type":"system","subtype":"init","model":"claude-sonnet-5"}\r\n' +
'not json at all\r\n' +
`${controlResponseLine([
{ value: 'sonnet', displayName: 'Sonnet' },
{ value: 'sonnet', displayName: 'Sonnet (duplicate)' },
{ value: ' ', displayName: 'Blank' }
])}\r\n`
expect(parseClaudeModelList(stdout)).toEqual([
{ id: 'sonnet', label: 'Sonnet', effortLevels: [], supportsFastMode: false }
])
})
it('drops the disabled placeholder row the CLI advertises for a model it cannot run', () => {
// Captured from `claude` 2.1.237: Fable 5.1 is announced but gated on 2.1.255+.
const parsed = parseClaudeModelList(
controlResponseLine([
{ value: 'sonnet', displayName: 'Sonnet' },
{
value: 'cc-update-required-1',
resolvedModel: 'cc-update-required-1',
displayName: 'Fable 5.1 (disabled)',
description: 'Update to 2.1.255+ to use Fable 5.1',
supportsEffort: true,
supportedEffortLevels: ['low', 'medium', 'high', 'xhigh', 'max'],
disabled: true
}
])
controlResponseLine([{ value: 'sonnet' }, { value: 'disabled-model', disabled: true }])
)
expect(parsed.map(({ id }) => id)).toEqual(['sonnet'])
})
+6 -143
View File
@@ -1,20 +1,13 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { afterEach, describe, expect, it } from 'vitest'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import {
createCodexSubagentTranscriptState,
hasTrackedCodexTranscriptSubagents,
reconcileCodexSubagentTranscript
} from './codex-subagent-transcript'
import {
codexRosterToSnapshots,
queueCodexSubagentIdentity,
retryPendingCodexSubagentIdentities,
upsertCodexSubagent,
type CodexSubagentRoster
} from './codex-subagent-roster'
import { codexRosterToSnapshots, type CodexSubagentRoster } from './codex-subagent-roster'
const CHILD_ID = '019fa65f-3144-7151-9c02-cff7a28f316f'
@@ -52,47 +45,10 @@ describe('Codex subagent transcript reconciliation', () => {
dirs.length = 0
})
it('adds a child from the parent rollout and removes it after task completion', () => {
const dir = mkdtempSync(join(tmpdir(), 'codex-subagent-transcript-'))
dirs.push(dir)
const parentPath = join(dir, 'rollout-parent.jsonl')
const childPath = join(dir, `rollout-child-${CHILD_ID}.jsonl`)
writeFileSync(parentPath, jsonl([activity('started')]))
writeFileSync(childPath, jsonl([{ type: 'event_msg', payload: { type: 'task_started' } }]))
const state = createCodexSubagentTranscriptState()
const roster: CodexSubagentRoster = new Map()
reconcileCodexSubagentTranscript(state, roster, parentPath)
expect(hasTrackedCodexTranscriptSubagents(state)).toBe(true)
expect(codexRosterToSnapshots(roster)).toEqual([
{
id: CHILD_ID,
description: 'sidebar_repro',
state: 'working',
startedAt: 1234,
agentType: undefined,
model: undefined
}
])
writeFileSync(
childPath,
jsonl([
{ type: 'event_msg', payload: { type: 'task_started' } },
{ type: 'event_msg', payload: { type: 'task_complete' } }
])
)
reconcileCodexSubagentTranscript(state, roster, parentPath)
expect(hasTrackedCodexTranscriptSubagents(state)).toBe(false)
expect(codexRosterToSnapshots(roster)).toBeUndefined()
})
it('resolves a child rollout filed under a later session day than the parent', () => {
const root = mkdtempSync(join(tmpdir(), 'codex-subagent-transcript-'))
dirs.push(root)
const childStartedAt = Date.now()
const childStartedAt = 1_767_225_600_000
const parentDir = dayDirectory(root, childStartedAt - 24 * 60 * 60 * 1000)
const childDir = dayDirectory(root, childStartedAt)
mkdirSync(parentDir, { recursive: true })
@@ -115,87 +71,7 @@ describe('Codex subagent transcript reconciliation', () => {
reconcileCodexSubagentTranscript(state, roster, parentPath)
// Why: only a cross-day lookup can observe the completion; the parent-directory scan never finds this file.
expect(roster.size).toBe(0)
expect(hasTrackedCodexTranscriptSubagents(state)).toBe(false)
})
it('retires a child whose rollout never becomes readable', () => {
vi.useFakeTimers()
try {
const dir = mkdtempSync(join(tmpdir(), 'codex-subagent-transcript-'))
dirs.push(dir)
const parentPath = join(dir, 'rollout-parent.jsonl')
writeFileSync(parentPath, jsonl([activity('started')]))
const state = createCodexSubagentTranscriptState()
const roster: CodexSubagentRoster = new Map()
reconcileCodexSubagentTranscript(state, roster, parentPath)
expect(roster.size).toBe(1)
// Why: within the grace window a slow-to-appear rollout must not drop a live child.
vi.advanceTimersByTime(30_000)
reconcileCodexSubagentTranscript(state, roster, parentPath)
expect(roster.size).toBe(1)
vi.advanceTimersByTime(31_000)
reconcileCodexSubagentTranscript(state, roster, parentPath)
expect(roster.size).toBe(0)
expect(hasTrackedCodexTranscriptSubagents(state)).toBe(false)
} finally {
vi.useRealTimers()
}
})
it('names a hook-only worker child from its own rollout once the hook read missed it', () => {
const dir = mkdtempSync(join(tmpdir(), 'codex-subagent-transcript-'))
dirs.push(dir)
const parentPath = join(dir, 'rollout-parent.jsonl')
const childPath = join(dir, `rollout-child-${CHILD_ID}.jsonl`)
writeFileSync(parentPath, '')
const state = createCodexSubagentTranscriptState()
const roster: CodexSubagentRoster = new Map()
// SubagentStart carries only the role; a session_meta past 64 KiB (large tool lists) used to stay unread.
upsertCodexSubagent(roster, CHILD_ID, { agentType: 'worker', state: 'working' }, 1234)
writeFileSync(
childPath,
jsonl([
{
type: 'session_meta',
payload: {
id: CHILD_ID,
base_instructions: { text: 'x'.repeat(100 * 1024) },
source: {
subagent: {
thread_spawn: { agent_path: null, agent_nickname: 'Planck', agent_role: 'worker' }
}
}
}
}
])
)
reconcileCodexSubagentTranscript(state, roster, parentPath)
expect(retryPendingCodexSubagentIdentities(roster)).toBe(true)
expect(codexRosterToSnapshots(roster)).toEqual([
expect.objectContaining({ id: CHILD_ID, agentType: 'worker', description: 'Planck' })
])
})
it('keeps a task path the parent supplied over a queued header read', () => {
const dir = mkdtempSync(join(tmpdir(), 'codex-subagent-transcript-'))
dirs.push(dir)
const childPath = join(dir, `rollout-child-${CHILD_ID}.jsonl`)
writeFileSync(
childPath,
jsonl([{ type: 'session_meta', payload: { id: CHILD_ID, agent_nickname: 'Planck' } }])
)
const roster: CodexSubagentRoster = new Map()
upsertCodexSubagent(roster, CHILD_ID, { agentType: 'worker', state: 'working' }, 1234)
queueCodexSubagentIdentity(roster, CHILD_ID, childPath)
upsertCodexSubagent(roster, CHILD_ID, { description: 'pr_review', state: 'working' }, 1234)
expect(retryPendingCodexSubagentIdentities(roster)).toBe(false)
expect(codexRosterToSnapshots(roster)?.[0]).toMatchObject({ description: 'pr_review' })
expect(codexRosterToSnapshots(roster)).toBeUndefined()
})
it('removes a child when Codex reports it interrupted', () => {
@@ -210,8 +86,7 @@ describe('Codex subagent transcript reconciliation', () => {
writeFileSync(parentPath, jsonl([activity('started'), activity('interrupted')]))
reconcileCodexSubagentTranscript(state, roster, parentPath)
expect(hasTrackedCodexTranscriptSubagents(state)).toBe(false)
expect(roster.size).toBe(0)
expect(codexRosterToSnapshots(roster)).toBeUndefined()
})
describe('child model identity', () => {
@@ -237,17 +112,6 @@ describe('Codex subagent transcript reconciliation', () => {
return { parentPath, childPath }
}
it('reports the model from the child rollout, not the parent model', () => {
const { parentPath } = seedPair([started(), turnContext('gpt-5.6-terra')])
const state = createCodexSubagentTranscriptState()
const roster: CodexSubagentRoster = new Map()
reconcileCodexSubagentTranscript(state, roster, parentPath)
// The parent runs sol; only the child's own turn_context may set its model.
expect(codexRosterToSnapshots(roster)?.[0]?.model).toBe('gpt-5.6-terra')
})
it('keeps the discovered model when a later poll carries no turn_context', () => {
const { parentPath, childPath } = seedPair([started(), turnContext('gpt-5.6-terra')])
const state = createCodexSubagentTranscriptState()
@@ -293,8 +157,7 @@ describe('Codex subagent transcript reconciliation', () => {
reconcileCodexSubagentTranscript(state, roster, parentPath)
expect(roster.size).toBe(0)
expect(hasTrackedCodexTranscriptSubagents(state)).toBe(false)
expect(codexRosterToSnapshots(roster)).toBeUndefined()
})
})
})
@@ -1,26 +0,0 @@
import { describe, expect, it } from 'vitest'
import { createCommandCodeOutputStatusDetector } from './command-code-output-status'
function heapAfterGc(): number {
if (!('gc' in globalThis) || typeof globalThis.gc !== 'function') {
throw new Error('The test runner must enable --expose-gc')
}
globalThis.gc()
globalThis.gc()
return process.memoryUsage().heapUsed
}
describe('Command Code output retention', () => {
it('keeps small boundary carries without pinning oversized output on ordinary panes', () => {
const before = heapAfterGc()
const detectors = Array.from({ length: 8 }, (_value, index) => {
const detector = createCommandCodeOutputStatusDetector({ onWorking: () => {} })
detector.observe(`${index}:${'x'.repeat(4 * 1024 * 1024)}`)
return detector
})
expect(heapAfterGc() - before).toBeLessThan(2 * 1024 * 1024)
for (const detector of detectors) {
expect(detector.observe('\nordinary shell output\n')).toBe(false)
}
})
})
+1 -74
View File
@@ -1,37 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import { createCommandCodeOutputStatusDetector } from './command-code-output-status'
afterEach(() => {
vi.restoreAllMocks()
})
describe('createCommandCodeOutputStatusDetector', () => {
it('marks Command Code working with the submitted prompt when the TUI starts thinking', () => {
const onWorking = vi.fn()
const detector = createCommandCodeOutputStatusDetector({
startupCommand: 'command-code --trust',
onWorking
})
expect(detector.observe('❯ Fix the yellow spinner\r\n\x1b[35m✻ Thinking...\x1b[0m')).toBe(true)
expect(onWorking).toHaveBeenCalledWith('Fix the yellow spinner')
})
it('waits for the Command Code banner before trusting generic status text', () => {
const onWorking = vi.fn()
const detector = createCommandCodeOutputStatusDetector({
startupCommand: null,
onWorking
})
expect(detector.observe('Thinking about unrelated shell output')).toBe(false)
expect(detector.observe('# Command Code v0.27.2\r\n')).toBe(false)
expect(detector.observe('⌘ Parsing...')).toBe(true)
expect(onWorking).toHaveBeenCalledWith('')
})
it('detects the Command Code banner across PTY chunk boundaries', () => {
const onWorking = vi.fn()
const detector = createCommandCodeOutputStatusDetector({
@@ -46,22 +16,6 @@ describe('createCommandCodeOutputStatusDetector', () => {
expect(onWorking).toHaveBeenCalledWith('')
})
it('detects the banner after chunks that carry no banner characters at all', () => {
const onWorking = vi.fn()
const detector = createCommandCodeOutputStatusDetector({
startupCommand: null,
onWorking
})
// Ordinary agent output with no '#': the raw prefilter skips these without building a window.
expect(detector.observe('Codex is editing the file and rendering a diff\r\n')).toBe(false)
expect(detector.observe('Codex wrote 12 lines\r\n')).toBe(false)
expect(detector.observe('# Command Code v0.27.2\r\n')).toBe(false)
expect(detector.observe('⌘ Parsing...')).toBe(true)
expect(onWorking).toHaveBeenCalledWith('')
})
it('detects the Command Code banner when ANSI styling splits the words', () => {
const onWorking = vi.fn()
const detector = createCommandCodeOutputStatusDetector({
@@ -172,30 +126,3 @@ describe('createCommandCodeOutputStatusDetector', () => {
expect(onWorking).not.toHaveBeenCalled()
})
})
describe('terminal control stripping', () => {
function promptFrom(raw: string): string | null {
let captured: string | null = null
const detector = createCommandCodeOutputStatusDetector({
startupCommand: 'command-code',
onWorking: (prompt) => {
captured = prompt
}
})
detector.observe(raw)
return captured
}
it('strips control bytes wherever they sit around the prompt text', () => {
expect(promptFrom('❯ plain prompt\r\n\x1b[35m✻ Thinking...\x1b[0m')).toBe('plain prompt')
expect(promptFrom('\x07❯ leading control\r\n\x1b[35m✻ Thinking...\x1b[0m')).toBe(
'leading control'
)
expect(promptFrom('❯ trailing control\x07\r\n\x1b[35m✻ Thinking...\x1b[0m')).toBe(
'trailing control'
)
expect(promptFrom('❯ adjacent\x07\x01\x02controls\r\n\x1b[35m✻ Thinking...\x1b[0m')).toBe(
'adjacentcontrols'
)
})
})
-79
View File
@@ -1,7 +1,6 @@
import { describe, expect, it } from 'vitest'
import {
formatCrashReportText,
sanitizeCrashReportDetails,
sanitizeCrashReportString,
type CrashReportRecord
} from './crash-reporting'
@@ -27,14 +26,6 @@ function notesReport(overrides: Partial<CrashReportRecord> = {}): CrashReportRec
}
}
/** Notes are emitted indented inside the fence; mirror that when asserting. */
function indentNote(note: string): string {
return note
.split('\n')
.map((line) => ` ${line}`)
.join('\n')
}
describe('crash-reporting shared helpers', () => {
it('redacts paths and common secret-shaped strings', () => {
const text =
@@ -53,60 +44,6 @@ describe('crash-reporting shared helpers', () => {
)
})
it('keeps details on a strict primitive allowlist', () => {
const longStack = [
'Error: boom',
...Array.from(
{ length: 200 },
(_, index) => `at Component${index} (/Users/alice/project/src/file-${index}.tsx:1:1)`
)
].join('\n')
expect(
sanitizeCrashReportDetails({
name: 'GPU /home/alice/repo',
code: 9,
crashed: true,
missing: null,
error_stack: longStack,
minidumpPath: '/Users/alice/Library/Application Support/Orca/reports/abc.dmp',
nested: { nope: true },
infinite: Number.POSITIVE_INFINITY
})
).toEqual({
name: 'GPU [redacted-path]',
code: 9,
crashed: true,
missing: null,
error_stack: expect.stringContaining('[redacted-path]'),
minidumpPath: '[redacted-path]'
})
expect(
String(sanitizeCrashReportDetails({ error_stack: longStack }).error_stack).length
).toBeGreaterThan(240)
expect(String(sanitizeCrashReportDetails({ errorStack: longStack }).errorStack).length).toBe(
4_003
)
expect(
String(sanitizeCrashReportDetails({ componentStack: longStack }).componentStack).length
).toBe(4_003)
expect(String(sanitizeCrashReportDetails({ description: longStack }).description).length).toBe(
243
)
})
it('keeps a user note longer than the 240-char detail cap intact', () => {
// A real 1.4.184 note was cut mid-word by the telemetry detail budget.
const note =
`My phone is connected. ${'The Claude terminal never came back. '.repeat(20)}`.trim()
const text = formatCrashReportText(notesReport(), note)
expect(note.length).toBeGreaterThan(240)
expect(text).toContain(`--- begin user notes ---\n${indentNote(note)}\n--- end user notes ---`)
expect(text).not.toContain('...')
})
it('still redacts paths and secrets far past the old 240-char cap', () => {
const note = [
'a'.repeat(1_000),
@@ -123,22 +60,6 @@ describe('crash-reporting shared helpers', () => {
expect(text).not.toContain('ghp_abcdefghijklmnopqrstuvwxyz')
})
it('keeps user notes when the report is truncated to the endpoint cap', () => {
// Tail truncation must remove reproducible machine data before user notes.
const text = formatCrashReportText(
notesReport({
details: Object.fromEntries(
Array.from({ length: 400 }, (_, index) => [`detail_${index}`, 'x'.repeat(240)])
)
}),
'the sidebar went blank'
)
expect(text.length).toBeLessThanOrEqual(64_000)
expect(text).toContain('[Crash report truncated to fit feedback endpoint limits.]')
expect(text).toContain('--- begin user notes ---\n the sidebar went blank')
})
it.each([
['POSIX', '/home/alice/orca/app.log then recovered.'],
['Windows', 'C:\\Users\\alice\\Orca\\app.log then recovered.'],
@@ -7,7 +7,6 @@ import {
captureDarwinProcessTable,
resetDarwinProcessTableCaptureForTests
} from './darwin-process-table-capture'
import { PS_ARGS } from './process-table-snapshot'
const raw = '123 1 123 123 S+ 16/9 Fri Oct 9 12:34:56 2026 /bin/zsh\n'
const canonical = raw.replace('16/9', 'ttys009')
@@ -43,13 +42,7 @@ describe('Darwin translation deadline', () => {
await vi.advanceTimersByTimeAsync(100)
await rejected
expect(signal?.aborted).toBe(true)
expect(capture.mock.calls.map(([args]) => args)).toEqual([
['-axo', PS_ARGS[1].replace('tty=', 'tdev=')]
])
for (let index = 0; index < 5; index++) {
expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical)
}
expect(naming).toHaveBeenCalledTimes(1)
expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical)
finish(raw.replace('16/9', 'stale-name'))
await pending
@@ -58,24 +51,6 @@ describe('Darwin translation deadline', () => {
expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(
raw.replace('16/9', 'fresh-name')
)
expect(naming).toHaveBeenCalledTimes(2)
expect(vi.getTimerCount()).toBe(0)
})
it('does not start naming after the capture has consumed its budget', async () => {
const lateCapture = vi.fn(async (args: readonly string[]) => {
if (args[1].includes('tdev=')) {
await new Promise((resolve) => setTimeout(resolve, 100))
return raw
}
return canonical
})
const first = captureDarwinProcessTable(lateCapture, validate, 100)
const rejected = expect(first).rejects.toThrow('capture_over_budget')
await vi.advanceTimersByTimeAsync(100)
await rejected
expect(naming).not.toHaveBeenCalled()
})
it('rejects late successful names even when Promise completion beats the overdue timer', async () => {
@@ -90,23 +65,5 @@ describe('Darwin translation deadline', () => {
await expect(captureDarwinProcessTable(capture, validate, 100)).rejects.toThrow(
'capture_over_budget'
)
expect(capture).toHaveBeenCalledTimes(1)
expect(vi.getTimerCount()).toBe(0)
})
it('rejects expiry during output validation without another capture', async () => {
let clock = 0
vi.spyOn(performance, 'now').mockImplementation(() => clock)
naming.mockResolvedValue(canonical)
const slowValidation = (stdout: string): string => {
clock = 101
return stdout
}
await expect(captureDarwinProcessTable(capture, slowValidation, 100)).rejects.toThrow(
'capture_over_budget'
)
expect(capture).toHaveBeenCalledTimes(1)
expect(vi.getTimerCount()).toBe(0)
})
})
@@ -48,7 +48,7 @@ describe('Darwin inventory drain admission', () => {
if (path === candidatePath) {
return missingCandidate()
}
if (lstatMock.mock.calls.length === 2) {
if (path === '/dev/entry-0') {
throw new Error('stat invocation failed')
}
return pending.promise
@@ -60,19 +60,15 @@ describe('Darwin inventory drain admission', () => {
})
await vi.advanceTimersByTimeAsync(0)
expect(settled).toBe(false)
expect(lstatMock).toHaveBeenCalledTimes(3)
expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical)
expect(opendirMock).toHaveBeenCalledTimes(1)
const stat = { rdev: 0x10000009n, isCharacterDevice: () => true }
lstatMock.mockResolvedValue(stat)
pending.resolve(stat)
expect(await first).toBe(raw.replace('16/9', 'entry-1'))
expect(lstatMock).toHaveBeenCalledTimes(3)
expect(vi.getTimerCount()).toBe(0)
})
it('holds admission until its one uncancelable stat drains and admits no later reads', async () => {
it('uses canonical fallback until expired inventory drains, then admits fresh names', async () => {
opendirMock.mockResolvedValue(
Array.from({ length: 12 }, (_, index) => ({ name: `entry-${index}` }))
)
@@ -88,51 +84,18 @@ describe('Darwin inventory drain admission', () => {
const rejected = expect(first).rejects.toThrow('capture_over_budget')
await vi.advanceTimersByTimeAsync(100)
await rejected
expect(lstatMock).toHaveBeenCalledTimes(2)
const stat = { rdev: 0x10000009n, isCharacterDevice: () => true }
for (let index = 0; index < 5; index++) {
expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical)
}
expect(opendirMock).toHaveBeenCalledTimes(1)
expect(lstatMock).toHaveBeenCalledTimes(2)
expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical)
pending.resolve(stat)
await vi.advanceTimersByTimeAsync(0)
expect(lstatMock).toHaveBeenCalledTimes(2)
lstatMock.mockImplementation(async (path: string) =>
path === candidatePath ? missingCandidate() : stat
)
expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(
raw.replace('16/9', 'entry-0')
)
expect(opendirMock).toHaveBeenCalledTimes(2)
expect(vi.getTimerCount()).toBe(0)
})
it('holds admission while an expired pty candidate stat drains', async () => {
const pending = deferred<{
rdev: bigint
isCharacterDevice: () => boolean
}>()
lstatMock.mockReturnValue(pending.promise)
const first = captureDarwinProcessTable(capture, validate, 100)
const rejected = expect(first).rejects.toThrow('capture_over_budget')
await vi.advanceTimersByTimeAsync(100)
await rejected
expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical)
expect(lstatMock).toHaveBeenCalledTimes(1)
expect(opendirMock).not.toHaveBeenCalled()
const stat = { rdev: 0x10000009n, isCharacterDevice: () => true }
pending.resolve(stat)
await vi.advanceTimersByTimeAsync(0)
lstatMock.mockResolvedValue(stat)
expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical)
expect(lstatMock).toHaveBeenCalledTimes(2)
expect(opendirMock).not.toHaveBeenCalled()
expect(vi.getTimerCount()).toBe(0)
})
it('closes a directory that opens after expiry and holds admission until its close drains', async () => {
@@ -157,9 +120,7 @@ describe('Darwin inventory drain admission', () => {
opened.resolve(entries())
await vi.advanceTimersByTimeAsync(0)
expect(closeStarted).toBe(true)
expect(lstatMock.mock.calls).toEqual([[candidatePath, { bigint: true }]])
expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical)
expect(opendirMock).toHaveBeenCalledTimes(1)
close.resolve()
await vi.advanceTimersByTimeAsync(0)
@@ -172,7 +133,5 @@ describe('Darwin inventory drain admission', () => {
expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(
raw.replace('16/9', 'fresh-name')
)
expect(opendirMock).toHaveBeenCalledTimes(2)
expect(vi.getTimerCount()).toBe(0)
})
})
@@ -51,21 +51,4 @@ describe.runIf(process.platform === 'darwin')('nameDarwinTerminals against real
)
expect(ttyByPid(named).get(terminalPid)).toMatch(/^ttys\d{3,}$/)
})
it('matches ps terminal names for every process present in both captures', async () => {
// Retry once: a terminal can close between the two ps runs.
let mismatches: string[] = []
for (let attempt = 0; attempt < 2; attempt += 1) {
const raw = execFileSync('ps', RAW_ARGS, { encoding: 'utf8' })
const canonical = ttyByPid(execFileSync('ps', [...PS_ARGS], { encoding: 'utf8' }))
const named = ttyByPid(await nameDarwinTerminals(raw))
mismatches = [...named]
.filter(([pid, tty]) => canonical.has(pid) && canonical.get(pid) !== tty)
.map(([pid, tty]) => `${pid}: ${tty} != ${canonical.get(pid)}`)
if (mismatches.length === 0) {
break
}
}
expect(mismatches).toEqual([])
})
})
+25 -89
View File
@@ -7,24 +7,14 @@ type DeviceEntry = {
rdev: bigint
kind?: 'character' | 'symlink' | 'file'
delayMs?: number
error?: Error
}
class TestDeviceDirectory {
entries: DeviceEntry[] = []
openedPaths: string[] = []
readPaths: string[] = []
closedDirectories = 0
peakReads = 0
openError?: Error
enumerationError?: Error
private activeReads = 0
openDirectory = async (path: string): Promise<AsyncIterable<{ name: string }>> => {
this.openedPaths.push(path)
if (this.openError) {
throw this.openError
}
openDirectory = async (): Promise<AsyncIterable<{ name: string }>> => {
return this.enumerate()
}
@@ -44,24 +34,14 @@ class TestDeviceDirectory {
readDevice = async (
path: string
): Promise<{ rdev: bigint; isCharacterDevice: () => boolean }> => {
this.readPaths.push(path)
const entry = this.entries.find((candidate) => join('/dev', candidate.name) === path)
if (!entry) {
throw new Error('device disappeared')
}
this.activeReads += 1
this.peakReads = Math.max(this.peakReads, this.activeReads)
try {
await new Promise((resolve) => setTimeout(resolve, entry.delayMs ?? 1))
if (entry.error) {
throw entry.error
}
return {
rdev: entry.rdev,
isCharacterDevice: () => (entry.kind ?? 'character') === 'character'
}
} finally {
this.activeReads -= 1
await new Promise((resolve) => setTimeout(resolve, entry.delayMs ?? 1))
return {
rdev: entry.rdev,
isCharacterDevice: () => (entry.kind ?? 'character') === 'character'
}
}
}
@@ -85,7 +65,6 @@ describe('nameDarwinTerminals', () => {
expect(await nameDarwinTerminals(darwinRow('16/9'), directory)).toBe(darwinRow('??'))
directory.entries = [{ name: 'ttys009', rdev: 0x10000009n }]
expect(await nameDarwinTerminals(darwinRow('16/9'), directory)).toBe(darwinRow('ttys009'))
expect(directory.openedPaths).toEqual(['/dev', '/dev'])
})
it('updates a known device name after a rename between captures', async () => {
@@ -95,9 +74,6 @@ describe('nameDarwinTerminals', () => {
directory.entries = [{ name: 'cu.after', rdev: 0x1600002an }]
expect(await nameDarwinTerminals(darwinRow('22/42'), directory)).toBe(darwinRow('cu.after'))
expect(directory.readPaths).toEqual(
['ttys042', 'cu.before', 'ttys042', 'cu.after'].map((name) => join('/dev', name))
)
})
it('scans until a serial name resolves while excluding links and files', async () => {
@@ -113,14 +89,9 @@ describe('nameDarwinTerminals', () => {
expect(await nameDarwinTerminals(darwinRow('22/42'), directory)).toBe(
darwinRow('cu.serial-adapter')
)
expect(directory.readPaths).toEqual(
['ttys042', 'tty-link', 'tty-file', 'null', 'cu.serial-adapter'].map((name) =>
join('/dev', name)
)
)
})
it('stops scheduling stats after cancellation while draining all active reads', async () => {
it('drains an active inventory read and closes its directory on cancellation', async () => {
const directory = new TestDeviceDirectory()
directory.entries = Array.from({ length: 20 }, (_, index) => ({
name: `entry-${index}`,
@@ -140,16 +111,13 @@ describe('nameDarwinTerminals', () => {
void rejection.catch(() => {})
try {
await vi.advanceTimersByTimeAsync(2)
expect(directory.readPaths).toHaveLength(2)
controller.abort()
await vi.advanceTimersByTimeAsync(0)
expect(settled).toBe(false)
await vi.advanceTimersByTimeAsync(8)
expect(directory.readPaths).toHaveLength(2)
await rejection
expect(directory.closedDirectories).toBe(1)
expect(directory.peakReads).toBe(1)
} finally {
controller.abort()
try {
@@ -161,20 +129,6 @@ describe('nameDarwinTerminals', () => {
}
})
it('bounds large inventories and closes the directory without admitting device reads', async () => {
const directory = new TestDeviceDirectory()
directory.entries = Array.from({ length: 20_000 }, (_, index) => ({
name: `entry-${index}-${'x'.repeat(240)}`,
rdev: 0n
}))
await expect(nameDarwinTerminals(darwinRow('16/9'), directory)).rejects.toThrow(
'Directory listing is too large'
)
expect(directory.readPaths).toEqual([join('/dev', 'ttys009')])
expect(directory.closedDirectories).toBe(1)
})
it('closes an interrupted directory iterator and rejects partial inventories', async () => {
const directory = new TestDeviceDirectory()
directory.entries = [{ name: 'cu.device', rdev: 0x10000009n }]
@@ -184,26 +138,19 @@ describe('nameDarwinTerminals', () => {
'directory enumeration failed'
)
expect(directory.closedDirectories).toBe(1)
expect(directory.readPaths).toEqual([join('/dev', 'ttys009')])
})
it.each([
'123 1 S+ node 16/9\n',
'not-pid 1 123 123 S+ 16/9 tail\n',
'123 nope 123 123 S+ 16/9 tail\n',
'123 1 nope 123 S+ 16/9 tail\n',
'123 1 123 nope S+ 16/9 tail\n',
'PID PPID PGID TPGID STAT TDEV STARTED COMMAND\n',
'123 1 123 123 S+ 16/9 \t\r\n'
])('rejects unsupported row framing without a device scan (%s)', async (row) => {
const directory = new TestDeviceDirectory()
await expect(nameDarwinTerminals(darwinRow('16/9') + row, directory)).rejects.toThrow(
'malformed_darwin_device_row'
)
expect(directory.openedPaths).toEqual([])
})
it.each(['123 1 S+ node 16/9\n', 'not-pid 1 123 123 S+ 16/9 tail\n'])(
'rejects unsupported row framing (%s)',
async (row) => {
const directory = new TestDeviceDirectory()
await expect(nameDarwinTerminals(darwinRow('16/9') + row, directory)).rejects.toThrow(
'malformed_darwin_device_row'
)
}
)
it('rejects undecodable filenames and closes the directory before any stat reads', async () => {
it('rejects undecodable filenames and closes the directory', async () => {
const directory = new TestDeviceDirectory()
directory.entries = [
{ name: 'cu.device', rdev: 0x10000009n },
@@ -213,7 +160,6 @@ describe('nameDarwinTerminals', () => {
'undecodable_device_name'
)
expect(directory.closedDirectories).toBe(1)
expect(directory.readPaths).toEqual([join('/dev', 'ttys009')])
})
it('accepts signed and sign-extended device numbers while ignoring arbitrary wide rdev', async () => {
@@ -243,24 +189,19 @@ describe('nameDarwinTerminals', () => {
]
expect(await nameDarwinTerminals(darwinRow('16/9'), directory)).toBe(darwinRow('cu.alias'))
expect(directory.openedPaths).toEqual(['/dev'])
})
it.each(['symlink', 'file'] as const)(
'rejects a %s pty candidate and falls back to a character device',
async (kind) => {
const directory = new TestDeviceDirectory()
directory.entries = [
{ name: 'ttys009', rdev: 0x10000009n, kind },
{ name: 'cu.real', rdev: 0x10000009n }
]
it('rejects a symlink pty candidate and falls back to a character device', async () => {
const directory = new TestDeviceDirectory()
directory.entries = [
{ name: 'ttys009', rdev: 0x10000009n, kind: 'symlink' },
{ name: 'cu.real', rdev: 0x10000009n }
]
expect(await nameDarwinTerminals(darwinRow('16/9'), directory)).toBe(darwinRow('cu.real'))
expect(directory.openedPaths).toEqual(['/dev'])
}
)
expect(await nameDarwinTerminals(darwinRow('16/9'), directory)).toBe(darwinRow('cu.real'))
})
it('stops candidate stats after cancellation and rejects once the active read drains', async () => {
it('rejects cancellation after its active candidate read drains', async () => {
const directory = new TestDeviceDirectory()
directory.entries = [1, 2, 3].map((minor) => ({
name: `ttys00${minor}`,
@@ -281,16 +222,11 @@ describe('nameDarwinTerminals', () => {
void rejection.catch(() => {})
try {
await vi.advanceTimersByTimeAsync(2)
expect(directory.readPaths).toEqual([join('/dev', 'ttys001')])
controller.abort()
await vi.advanceTimersByTimeAsync(0)
expect(settled).toBe(false)
await vi.advanceTimersByTimeAsync(8)
expect(directory.readPaths).toEqual([join('/dev', 'ttys001')])
await rejection
expect(directory.openedPaths).toEqual([])
expect(directory.peakReads).toBe(1)
} finally {
controller.abort()
try {
@@ -1,58 +0,0 @@
// Replay alt-screen and inline grok startup captures: ~12Hz logo shimmer defeats the 1.5s quiet window, causing 8s timeout delays/dropped drafts. Preserve both marker and quiet-floor paths.
import { describe, expect, it } from 'vitest'
import { createDraftPasteReadyScanner } from './draft-paste-ready-scanner'
import type { DraftPasteReadySignal } from './agent-launch/catalog/tui-agent-config-types'
import {
GROK_STARTUP_PTY_TRACE,
type GrokStartupTraceChunk
} from './__fixtures__/grok-startup-pty-trace'
import { GROK_INLINE_STARTUP_PTY_TRACE } from './__fixtures__/grok-inline-startup-pty-trace'
const QUIET_WINDOW_MS = 1500
const HARD_TIMEOUT_MS = 8000
function chunkData(chunk: GrokStartupTraceChunk): string {
return chunk.data ?? 'x'.repeat(chunk.bytes ?? 0)
}
/** Replay caller timer semantics: re-arm quiet requests, cancel on earlier chunks, and let hard timeout outrank late markers. Null means timeout; main drops that draft. Mirrors agent-draft-readiness.ts/orca-runtime.ts. */
function replayReadyAtMs(
signal: DraftPasteReadySignal,
trace: GrokStartupTraceChunk[]
): number | null {
const scanner = createDraftPasteReadyScanner(signal)
let quietDeadline: number | null = null
for (const [index, chunk] of trace.entries()) {
const settledAt =
quietDeadline !== null ? Math.min(quietDeadline, HARD_TIMEOUT_MS) : HARD_TIMEOUT_MS
if (chunk.t >= settledAt) {
return quietDeadline !== null && quietDeadline <= HARD_TIMEOUT_MS ? quietDeadline : null
}
const scanned = scanner.observe(chunkData(chunk))
if (scanned.ready) {
return chunk.t
}
quietDeadline = scanned.armQuietTimer ? chunk.t + QUIET_WINDOW_MS : quietDeadline
if (index === trace.length - 1 && quietDeadline !== null && quietDeadline < HARD_TIMEOUT_MS) {
return quietDeadline
}
}
return null
}
describe('grok startup trace replay (alternate-screen mode)', () => {
it('reports readiness on the frame that paints the composer box', () => {
const composerFrame = GROK_STARTUP_PTY_TRACE.find((chunk) => chunk.data?.includes('❯'))
expect(composerFrame).toBeDefined()
expect(replayReadyAtMs('grok-composer-prompt', GROK_STARTUP_PTY_TRACE)).toBe(composerFrame?.t)
})
})
describe('grok startup trace replay (inline mode, no alternate screen)', () => {
it('arms a quiet window before the inline trace reaches the modeled timeout', () => {
// Inline grok emits no 1049h; retain a separate quiet anchor or main would drop the issue-URL draft.
const readyAt = replayReadyAtMs('grok-composer-prompt', GROK_INLINE_STARTUP_PTY_TRACE)
expect(readyAt).not.toBeNull()
expect(readyAt).toBeLessThan(HARD_TIMEOUT_MS)
})
})
@@ -6,27 +6,15 @@ describe('DeepSeek Build native one-shot identity exclusion', () => {
it.each([
'dsb agent -p task',
'dsb agent -- --print task',
'deepseek-build agent -- --prompt-file task.txt',
'deepseek-build agent --single task',
'dsb agent --print task',
'dsb agent --prompt-json "[]"',
'dsb agent --prompt-file /tmp/task.txt',
'deepseek-build-agent -p task',
'deepseek-build-agent.exe --print task',
'deepseek-build-agent --single=task',
'deepseek-build-agent -ptask',
'deepseek-build-agent -cp task',
'deepseek-build-agent -cptask',
'deepseek-build-agent -p-',
'deepseek-build-agent -cp--print',
'dsb agent -p-',
'dsb agent -cp--print',
'dsb agent -cp task',
'dsb run task',
'deepseek-build-agent --resume saved-session --print task',
'deepseek-build-agent --resume --prompt-file task.txt',
'dsb --cwd folder agent --model deepseek-v4-flash --prompt-file task.txt',
'node --import ./preload.mjs /x/node_modules/@innocarpe/deepseek-build/npm/bin/dsb.js agent --print task',
'"C:\\Program Files\\nodejs\\node.exe" --require preload.js "C:\\x\\node_modules\\@innocarpe\\deepseek-build\\npm\\bin\\deepseek-build.js" agent --prompt-json=[]'
])('does not claim interactive ownership for %s', (line) => {
expect(recognizeAgentProcessFromCommandLine(line)).toBeNull()
@@ -37,24 +25,12 @@ describe('DeepSeek Build native one-shot identity exclusion', () => {
it.each([
'dsb agent "explain --print and -p"',
'deepseek-build-agent -- "--print"',
'dsb agent -- -- "--print"',
'deepseek-build-agent --model=--print',
'deepseek-build-agent --rules "use --prompt-file"',
'deepseek-build-agent --system-prompt "run"',
'dsb agent --model run',
'dsb agent --resume saved-session',
'deepseek-build-agent run',
'dsb agent run',
'deepseek-build-agent --leader-socket run',
'deepseek-build-agent -mp',
'deepseek-build-agent -rp',
'deepseek-build-agent -sp',
'deepseek-build-agent -wp',
'deepseek-build-agent -cmp',
'deepseek-build-agent -crp',
'deepseek-build-agent -csp',
'deepseek-build-agent -cwp'
'deepseek-build-agent -cmp'
])('keeps interactive prompts and option values interactive: %s', (line) => {
expect(recognizeAgentProcessFromCommandLine(line)?.agent).toBe('dsb')
})
-53
View File
@@ -1,53 +0,0 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { runProcess } from '@orca/process-host'
import { recognizeAgentProcessFromCommandLine } from './agent-status/process/agent-process-recognition'
const binary = process.env.ORCA_REAL_DSH_CLI
// No model call: published profile configuration and help establish the launcher contract.
describe.skipIf(!binary)('published DSH 0.2 CLI', () => {
it('keeps positional and explicit headless profiles outside interactive recognition', async () => {
if (!binary) {
throw new Error('Set ORCA_REAL_DSH_CLI to the official dsh executable')
}
const root = await mkdtemp(join(tmpdir(), 'orca-dsh-cli-'))
const env = { ...process.env, DSH_HOME: root, DEEPSEEK_API_KEY: '' }
try {
const version = await runProcess({ program: binary, args: ['--version'], cwd: root, env })
expect(version.code).toBe(0)
expect(version.stdout.trim()).toMatch(/^0\.2\./)
for (const profile of ['headless', 'sdk', 'sdk-minimal', 'acp']) {
for (const args of [[profile], ['--profile', profile]]) {
const result = await runProcess({
program: binary,
args: [...args, '--dump-default-config'],
cwd: root,
env,
timeoutMs: 30_000
})
expect(result.code).toBe(0)
expect(result.stdout).toContain('@deepseek-ai/dsh-')
const command = `"${binary}" ${args.join(' ')}`
expect(recognizeAgentProcessFromCommandLine(command)).toBeNull()
expect(
recognizeAgentProcessFromCommandLine(command, { includeHeadlessOneShot: true })?.agent
).toBe('dsh')
}
}
const help = await runProcess({
program: binary,
args: ['headless', '--help'],
cwd: root,
env,
timeoutMs: 30_000
})
expect(help.code).toBe(0)
expect(help.stdout).toContain('Answer one task and exit')
} finally {
await rm(root, { recursive: true, force: true })
}
}, 120_000)
})