diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index 507f3de2451a..84f1272cd028 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -1160,6 +1160,7 @@ "src/main/automations/external-manager-scoped.test.ts": 256, "src/main/automations/external-manager.test.ts": 207, "src/main/automations/headless-automation-agent-launch.test.ts": 1100, + "tests/e2e/headless-automation-agent-launch.unit.test.ts": 1100, "src/main/automations/headless-dispatch-durability.test.ts": 401, "src/main/automations/headless-run-terminal-retention.test.ts": 115, "src/main/automations/headless-workspace-create.test.ts": 34, diff --git a/config/scripts/orcad-entry-build.test.mjs b/config/scripts/orcad-entry-build.test.mjs index a72189fa61a7..9396dcbc17ec 100644 --- a/config/scripts/orcad-entry-build.test.mjs +++ b/config/scripts/orcad-entry-build.test.mjs @@ -14,15 +14,25 @@ import { runProcessSync } from '@orca/process-host' const directory = mkdtempSync(join(tmpdir(), 'orca-structured-provider-build-')) const bundle = join(directory, 'orcad-server.js') +let serverMetafile beforeAll(async () => { - await buildOrcadEntry(bundle) + serverMetafile = (await buildOrcadEntry(bundle)).metafile }, 60_000) afterAll(() => { rmSync(directory, { recursive: true, force: true }) }) +it('ships no runtime Electron imports in the actual server graph', () => { + const electronImporters = Object.entries(serverMetafile.inputs) + .filter(([, input]) => + input.imports.some(({ path }) => path === 'electron' || path.startsWith('electron/')) + ) + .map(([path]) => path) + expect(electronImporters).toEqual([]) +}) + it('loads the structured Claude SDK through the packaged server under plain Node', () => { const loaded = runProcessSync({ program: process.execPath, diff --git a/config/tsconfig.tc.web.json b/config/tsconfig.tc.web.json index 3dd1ef616a8a..7ad94dda9ec8 100644 --- a/config/tsconfig.tc.web.json +++ b/config/tsconfig.tc.web.json @@ -26,6 +26,7 @@ "../src/shared/**/*", "../src/packages/process-host/src/__fixtures__/**/*", "../src/main/gitlab/mappers.ts", + "../src/main/persistence/profile-state-cutover-fixture.ts", "../src/main/runtime/sidebar-inputs/sidebar-clock.ts", "../src/main/runtime/sidebar-inputs/sidebar-retention-owner.ts", "../src/main/runtime/sidebar-inputs/producer-revision.ts", diff --git a/src/main/automations/automation-agent-run-result.ts b/src/main/automations/automation-agent-run-result.ts new file mode 100644 index 000000000000..e2042d8e0565 --- /dev/null +++ b/src/main/automations/automation-agent-run-result.ts @@ -0,0 +1,93 @@ +import type { AgentLaunchResult } from '../../shared/agent-launch-intent' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import type { AutomationRun } from '../../shared/automations-types' +import type { AutomationChatAgentLaunch } from './automation-chat-agent-launch' +import { tuiAgentDisplayName } from '../../shared/tui-agent-display-names' +import { parsePaneKey } from '../../shared/stable-pane-id' +import { readAutomationRunReceipt } from './automation-run-receipt' +import { AutomationRunLaunchError } from './headless-dispatch' + +export function publishedLaunchTarget( + runtime: Pick, + result: Pick +): AutomationChatAgentLaunch { + let paneKey = result.outcome.kind === 'terminal' ? (result.outcome.paneKey ?? null) : null + let ptyId: string | null = null + if (result.outcome.kind === 'terminal') { + try { + paneKey ??= runtime.getTerminalPaneKey(result.outcome.handle) + } catch { + /* Keep publication identity. */ + } + try { + ptyId = runtime.getTerminalPtyIdForHandle(result.outcome.handle) + } catch { + /* Process evidence is optional for opening. */ + } + } + return { + workspaceId: result.worktreeId, + workspaceDisplayName: null, + sessionKind: result.outcome.kind === 'structured' ? 'chat' : 'terminal', + chatSessionId: result.outcome.kind === 'structured' ? result.outcome.sessionId : null, + terminalHandle: result.outcome.kind === 'terminal' ? result.outcome.handle : null, + terminalSessionId: parsePaneKey(paneKey ?? '')?.tabId ?? null, + terminalPaneKey: paneKey, + terminalPtyId: ptyId + } +} + +export async function enrichAutomationRunTarget( + runtime: OrcaRuntimeService, + target: AutomationChatAgentLaunch +): Promise { + try { + const shown = await runtime.showManagedWorktree(`id:${target.workspaceId}`) + target.workspaceDisplayName = shown.displayName ?? null + } catch { + // Publication already owns the target; optional display metadata cannot erase it. + } + if (target.terminalHandle && !target.terminalSessionId) { + try { + target.terminalSessionId = (await runtime.showTerminal(target.terminalHandle)).tabId ?? null + } catch { + // Keep the published pane and process identity when its presentation is unavailable. + } + } + return target +} + +/** A lost reply is not proof of no effect; recovery reads the ordinary operation receipt. */ +export async function automationRunAcceptedTarget( + runtime: OrcaRuntimeService, + run: Pick, + target: AutomationChatAgentLaunch | undefined, + error: unknown, + agent: string +): Promise { + const receipt = await runtime + .openAgentSessionRecordStore() + .then((store) => readAutomationRunReceipt(store, run)) + .catch(() => null) + if (receipt?.accepted) { + return receipt.kind === 'terminal' + ? publishedLaunchTarget(runtime, receipt.launch) + : { + workspaceId: receipt.workspaceId, + workspaceDisplayName: null, + sessionKind: 'chat', + chatSessionId: receipt.sessionId, + terminalHandle: null, + terminalSessionId: null, + terminalPaneKey: null, + terminalPtyId: null + } + } + if (target) { + throw new AutomationRunLaunchError( + `${tuiAgentDisplayName(agent)} could not confirm this run's prompt. Open the run before trying again.`, + target + ) + } + throw error +} diff --git a/src/main/automations/automation-chat-agent-launch.ts b/src/main/automations/automation-chat-agent-launch.ts new file mode 100644 index 000000000000..90d97e7fa2b7 --- /dev/null +++ b/src/main/automations/automation-chat-agent-launch.ts @@ -0,0 +1,116 @@ +import type { Automation, AutomationRun } from '../../shared/automations-types' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import { launchAgentOnHost } from '../runtime/rpc/methods/agent-launch' +import { reuseAutomationChat } from './automation-chat-session-reuse' +import { buildHeadlessAutomationWorkspaceName } from './headless-workspace-create' +import type { AutomationRunTargetResult } from './run-target-resolution' +import { + AutomationRunLaunchError, + type HeadlessAutomationDispatchLaunch +} from './headless-dispatch' +import { + publishedLaunchTarget, + enrichAutomationRunTarget, + automationRunAcceptedTarget +} from './automation-agent-run-result' +import { automationRunOperationId, AUTOMATION_AGENT_CALLER } from './automation-run-operation' +import { createAutomationDispatchToken } from './dispatch-tokens' +import { tuiAgentDisplayName } from '../../shared/tui-agent-display-names' + +export type AutomationChatAgentLaunch = HeadlessAutomationDispatchLaunch & { + terminalHandle: string | null +} + +export type AutomationChatLaunchRequest = { + automation: Automation + run: Pick + target: Extract + runs: readonly AutomationRun[] +} + +export async function launchAutomationChatAgent( + runtime: OrcaRuntimeService, + request: AutomationChatLaunchRequest +): Promise { + try { + return await enrichAutomationRunTarget(runtime, await launchChat(runtime, request)) + } catch (error) { + if (error instanceof AutomationRunLaunchError) { + throw error + } + console.error('[automations] chat launch failed:', error) + throw new Error( + `${tuiAgentDisplayName(request.automation.agentId) ?? 'The agent'} could not confirm this run's prompt. Open its workspace before running again.` + ) + } +} + +async function launchChat( + runtime: OrcaRuntimeService, + request: AutomationChatLaunchRequest +): Promise { + const { automation, run, target } = request + let published: AutomationChatAgentLaunch | undefined + if (automation.reuseSession && automation.workspaceId) { + const reused = await reuseAutomationChat(runtime, request) + if (reused) { + return reused + } + } + const operationId = automationRunOperationId(run, 'fresh-launch') + try { + const result = await launchAgentOnHost( + { + agent: automation.agentId, + operationId, + surface: 'chat', + presentation: 'background', + prompt: { text: automation.prompt, delivery: 'submit' }, + target: + automation.workspaceMode === 'existing' + ? { kind: 'existing', worktree: `id:${automation.workspaceId}` } + : { + kind: 'create-worktree', + create: { + repo: `id:${target.repo.id}`, + name: buildHeadlessAutomationWorkspaceName(run.title, run.scheduledFor), + ...(automation.baseBranch ? { baseBranch: automation.baseBranch } : {}), + setupDecision: automation.setupDecision ?? 'skip', + activate: false, + automationProvenanceRequest: { + automationId: automation.id, + automationRunId: run.id, + dispatchToken: createAutomationDispatchToken(automation.id, run.id), + createRequestId: operationId + } + } + } + }, + { runtime, caller: AUTOMATION_AGENT_CALLER }, + { + onSurfacePublished: (surface) => { + published = publishedLaunchTarget(runtime, surface) + } + } + ) + if (result.prompt?.outcome !== 'journaled' && result.prompt?.outcome !== 'handed-to-terminal') { + throw new AutomationRunLaunchError( + `${tuiAgentDisplayName(automation.agentId)} started, but Orca could not confirm this run's prompt. Open the run before trying again.`, + published ?? publishedLaunchTarget(runtime, result) + ) + } + return publishedLaunchTarget(runtime, result) + } catch (error) { + if ( + error instanceof Error && + ('code' in error + ? error.code === 'agent_session_operation_expired' + : error.message.includes('agent_session_operation_expired')) + ) { + throw new AutomationRunLaunchError( + `${tuiAgentDisplayName(automation.agentId)} could not start because this run waited too long. Run the automation again.` + ) + } + return automationRunAcceptedTarget(runtime, run, published, error, automation.agentId) + } +} diff --git a/src/main/automations/automation-chat-run-measurement-test-harness.ts b/src/main/automations/automation-chat-run-measurement-test-harness.ts new file mode 100644 index 000000000000..32c27c51886d --- /dev/null +++ b/src/main/automations/automation-chat-run-measurement-test-harness.ts @@ -0,0 +1,236 @@ +import { vi, type Mock, type MockInstance } from 'vitest' +import type { AgentJournalSnapshot } from '../../shared/agent-session-journal-types' +import type { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store' +import type { StructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-host' + +export type AutomationChatRunMeasurement = { + measure: () => number[] + full: MockInstance + observerReads: MockInstance + registration: MockInstance + releases: Mock<() => void>[] + keys: [ + MockInstance, + MockInstance, + MockInstance, + MockInstance + ] + timers: MockInstance<(callback: (_: void) => void, delay?: number) => NodeJS.Timeout> + cleared: MockInstance<(timeout: NodeJS.Timeout | string | number | undefined) => void> + details: () => { + callbacks: number + committedRows: number + deltaReads: number + deltaRows: number + copied: number + iteratorYields: number + projections: number + projectedRows: number + scannedRows: number + } +} + +export function measureAutomationChatRun( + journal: AgentSessionJournal, + host: StructuredAgentSessionHost +): AutomationChatRunMeasurement { + let itemReads = 0, + submissionReads = 0, + itemFinds = 0, + rootVisits = 0, + submissionFinds = 0, + submissionVisits = 0, + itemIterations = 0 + const snapshots = new WeakMap() + function wrapSnapshot(original: AgentJournalSnapshot): AgentJournalSnapshot { + const prior = snapshots.get(original) + if (prior) { + return prior + } + function rows(values: T[], items: boolean): T[] { + return new Proxy(values, { + get(target, key, receiver) { + if (typeof key === 'string' && /^(0|[1-9][0-9]*)$/.test(key)) { + if (items) { + itemReads++ + } else { + submissionReads++ + } + } + if (key === 'find') { + return (predicate: (value: T, index: number, values: T[]) => unknown) => { + if (items) { + itemFinds++ + } else { + submissionFinds++ + } + return Array.prototype.find.call(receiver, (value: T, index: number, array: T[]) => { + if (items) { + rootVisits++ + } else { + submissionVisits++ + } + return predicate(value, index, array) + }) + } + } + if (items && key === Symbol.iterator) { + return function* () { + for (let i = 0; i < target.length; i++) { + itemIterations++ + yield receiver[i] + } + } + } + // oxlint-disable-next-line anti-slop/no-reflect-get -- Proxy get trap: only Reflect.get forwards a raw string|symbol key with the proxy receiver. + return Reflect.get(target, key, receiver) + } + }) + } + const wrapped = { + ...original, + items: rows(original.items, true), + submissions: rows(original.submissions, false) + } + snapshots.set(original, wrapped) + return wrapped + } + let projections = 0, + projectedRows = 0, + scannedRows = 0 + const materialized = new WeakSet() + const realPublicRead = journal.publicRead.bind(journal) + const publicReads = vi.spyOn(journal, 'publicRead').mockImplementation(() => { + const view = realPublicRead() + return { + get normalizationKey() { + return view.normalizationKey + }, + get snapshot() { + const result = view.snapshot + if (!materialized.has(view)) { + materialized.add(view) + projections++ + projectedRows += result.items.length + result.submissions.length + } + return wrapSnapshot(result) + } + } + }) + const visitItems = journal.visitItems.bind(journal) + const visits = vi.spyOn(journal, 'visitItems').mockImplementation((visit) => + visitItems((...args) => { + scannedRows++ + visit(...args) + }) + ) + let deltaRows = 0 + const readSince = journal.readSince.bind(journal) + const deltas = vi.spyOn(journal, 'readSince').mockImplementation((...args) => { + const value = readSince(...args) + if (value.ok) { + deltaRows += value.rows.length + } + return value + }) + const timers = vi.spyOn(globalThis, 'setTimeout'), + cleared = vi.spyOn(globalThis, 'clearTimeout') + const realSnapshot = journal.snapshot.bind(journal) + const full = vi.spyOn(journal, 'snapshot').mockImplementation((...args) => { + const value = realSnapshot(...args) + return value + }) + const releases: Mock<() => void>[] = [] + let callbacks = 0, + committedRows = 0, + copied = 0, + iteratorYields = 0 + const submissions = journal.submissions.bind(journal) + const submissionCopies = vi.spyOn(journal, 'submissions').mockImplementation(() => { + const rows = submissions() + copied += rows.length + return rows + }) + // Count actual folded history iterators, without replacing their algorithms. + const folded = journal['state'] + const values = folded.items.values.bind(folded.items) + vi.spyOn(folded.items, 'values').mockImplementation(function* () { + for (const item of values()) { + iteratorYields++ + yield item + } + return undefined + }) + const fullApis = [ + 'pendingSubmissions', + 'runningTurn', + 'newestTurn', + 'threadGoalSource', + 'contextUsage', + 'visitItemsWithLinkage' + ] as const + const calls = fullApis.map((name) => vi.spyOn(journal, name)) + const keys: AutomationChatRunMeasurement['keys'] = [ + vi.spyOn(journal, 'item'), + vi.spyOn(journal, 'submission'), + vi.spyOn(journal.queuedMessages, 'get'), + vi.spyOn(journal, 'canonicalItemId') + ] + const observerReads = vi.spyOn(host, 'journalSnapshot') + const realObserve = host.observeConversationPublications.bind(host) + const registration = vi + .spyOn(host, 'observeConversationPublications') + .mockImplementation((id, observer) => { + const release = realObserve(id, { + ...observer, + next: (hint) => { + callbacks++ + committedRows += hint.rows?.length ?? 0 + observer.next(hint) + } + }) + const wrapped = vi.fn(release) + releases.push(wrapped) + return wrapped + }) + const measure = () => [ + copied, + iteratorYields, + projections, + projectedRows, + scannedRows, + full.mock.calls.length, + ...calls.map((spy) => spy.mock.calls.length), + publicReads.mock.calls.length, + submissionCopies.mock.calls.length, + visits.mock.calls.length, + itemReads, + submissionReads, + itemFinds, + rootVisits, + submissionFinds, + submissionVisits, + itemIterations + ] + return { + measure, + full, + observerReads, + registration, + releases, + keys, + timers, + cleared, + details: () => ({ + callbacks, + committedRows, + deltaReads: deltas.mock.calls.length, + deltaRows, + copied, + iteratorYields, + projections, + projectedRows, + scannedRows + }) + } +} diff --git a/src/main/automations/automation-chat-run-observation.ts b/src/main/automations/automation-chat-run-observation.ts new file mode 100644 index 000000000000..09e0f70c722d --- /dev/null +++ b/src/main/automations/automation-chat-run-observation.ts @@ -0,0 +1,116 @@ +import type { AgentJournalSnapshot } from '../../shared/agent-session-journal-types' +import type { AgentSessionSendResult } from '../../shared/agent-session-wire' +import { agentJournalSubmissionKey } from '../../shared/agent-session-journal-item-key' +import { + readAgentJournalTurn, + readAgentJournalTurnOutcome +} from '../../shared/agent-session-turn-record' +import { createHeadlessAutomationOutputSnapshotBuffer } from './headless-dispatch' +import type { AutomationRunCompletionObservation } from './run-completion-watcher' + +export function resolveChatAutomationRun( + snapshot: AgentJournalSnapshot, + messageId: string, + agent: string, + queued: AgentSessionSendResult | null = null +) { + const submission = + queued && 'submission' in queued + ? queued.submission + : snapshot.submissions.find((entry) => entry.clientMessageId === messageId) + const turnItem = submission ? submissionTurn(snapshot, submission) : undefined + return { + submission, + turnItem, + observation: observationForResolvedRun(snapshot, submission, turnItem, agent, queued) + } +} + +export function chatAutomationRunObservation( + snapshot: AgentJournalSnapshot, + messageId: string, + agent: string, + queued: AgentSessionSendResult | null = null +): AutomationRunCompletionObservation | null { + return resolveChatAutomationRun(snapshot, messageId, agent, queued).observation +} + +function observationForResolvedRun( + snapshot: AgentJournalSnapshot, + submission: AgentJournalSnapshot['submissions'][number] | undefined, + turnItem: AgentJournalSnapshot['items'][number] | undefined, + agent: string, + queued: AgentSessionSendResult | null = null +): AutomationRunCompletionObservation | null { + if (queued && 'queued' in queued) { + return queued.queued.state === 'withdrawn' || queued.queued.state === 'returned' + ? { + status: 'dispatch_failed', + error: `${agent} did not receive this queued prompt. Open the chat before running again.` + } + : null + } + if (!submission) { + return null + } + const turn = turnItem ? readAgentJournalTurn(turnItem.body) : null + if (!turn || !turnItem) { + return submission.dispatchState === 'rejected' || submission.dispatchState === 'unknown' + ? { + status: 'dispatch_failed', + error: `${agent} could not confirm this run's prompt. Open the chat before running it again.` + } + : null + } + if (turn.state === 'running') { + return null + } + const buffer = createHeadlessAutomationOutputSnapshotBuffer() + for (const item of snapshot.items) { + if ( + item.agentId || + item.turnScope?.kind !== 'turn' || + item.turnScope.turnItemId !== turnItem.itemId || + item.body.kind !== 'message' || + item.body.role !== 'assistant' + ) { + continue + } + for (const block of item.body.blocks) { + if (block.type === 'text') { + buffer.append(`${block.text}\n`) + } + } + } + const outcome = readAgentJournalTurnOutcome(turn) + return { + status: outcome === 'success' ? 'completed' : 'dispatch_failed', + outputSnapshot: buffer.snapshot(), + error: + outcome === 'success' + ? null + : outcome === 'cancellation' || turn.state === 'interrupted' + ? `${agent} was Interrupted. Open the chat or run the automation again.` + : `${agent} did not complete this run. Open the chat and try again.` + } +} + +function submissionTurn( + snapshot: AgentJournalSnapshot, + submission: AgentJournalSnapshot['submissions'][number] +) { + const keys = new Set([ + agentJournalSubmissionKey(submission.clientMessageId), + ...(submission.providerItemId ? [submission.providerItemId] : []) + ]) + return snapshot.items.find((item) => { + const turn = readAgentJournalTurn(item.body) + return ( + turn && + !item.agentId && + (keys.has(turn.userItemId ?? '') || + (submission.answeredInTurn?.via === 'start' && + submission.answeredInTurn.turnItemId === item.itemId)) + ) + }) +} diff --git a/src/main/automations/automation-chat-session-reuse.ts b/src/main/automations/automation-chat-session-reuse.ts new file mode 100644 index 000000000000..6f13d8534304 --- /dev/null +++ b/src/main/automations/automation-chat-session-reuse.ts @@ -0,0 +1,114 @@ +import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import type { + AutomationChatLaunchRequest, + AutomationChatAgentLaunch +} from './automation-chat-agent-launch' +import { automationRunRecency } from '../../shared/automation-session-reuse' +import { getStructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-registry' +import { AUTOMATION_AGENT_CALLER, automationRunOperationId } from './automation-run-operation' +import { rpcCallerOperationKey } from '../runtime/rpc/rpc-caller-identity' +import { + structuredAgentSessionMessageSendMutation, + structuredAgentSessionSendBody +} from '../../shared/structured-agent-session-send-mutation' +import { automationRunAcceptedTarget } from './automation-agent-run-result' + +export async function reuseAutomationChat( + runtime: OrcaRuntimeService, + { automation, run, runs }: AutomationChatLaunchRequest +): Promise { + let preparationError: { error: unknown } | undefined + const store = await runtime.openAgentSessionRecordStore().catch((error: unknown) => { + preparationError = { error } + return null + }) + try { + await runtime.ensureStructuredAgentSessionHost() + } catch (error) { + preparationError = { error } + } + const host = getStructuredAgentSessionHost() + const seen = new Set() + for (const previous of runs + .filter((entry) => entry.automationId === automation.id && entry.id !== run.id) + .toSorted((a, b) => automationRunRecency(b) - automationRunRecency(a))) { + const id = previous.chatSessionId + if (previous.sessionKind !== 'chat' || !id || seen.has(id)) { + continue + } + seen.add(id) + const target: AutomationChatAgentLaunch = { + // The caller only attempts Chat reuse for a stable workspace. + workspaceId: automation.workspaceId!, + workspaceDisplayName: null, + sessionKind: 'chat', + chatSessionId: id, + terminalHandle: null, + terminalSessionId: null, + terminalPaneKey: null, + terminalPtyId: null + } + try { + if (!store) { + throw preparationError?.error + } + const selected = store.selectWritableRecord(id) + if (selected.kind === 'missing' && !store.readOnly) { + continue + } + if (selected.kind !== 'writable' || store.isSessionUnreadable(id)) { + throw new Error('Chat record is unavailable') + } + const current = store.getConversation(id) + if (!current) { + throw new Error('Chat record is unavailable') + } + if ( + current.provider !== automation.agentId || + current.location.workspaceId !== automation.workspaceId + ) { + continue + } + target.workspaceId = current.location.workspaceId + if (preparationError || !host) { + throw preparationError?.error ?? new Error('Chat host is unavailable') + } + const operationId = automationRunOperationId(run, 'reuse-send') + const callerKey = rpcCallerOperationKey(AUTOMATION_AGENT_CALLER) + const sent = await host.send( + { callerKey }, + structuredAgentSessionMessageSendMutation({ + sessionId: id, + clientOperationId: operationId, + expectedRuntimeFence: current.currentFence, + delivery: 'queue-if-active', + body: structuredAgentSessionSendBody(automation.prompt, []) + }) + ) + if (sent.ok) { + return target + } + if ( + sent.refusal.code === 'agent_session_ownership_unknown' && + sent.refusal.details?.reason === 'sessionNotAttached' && + !store.readOnly && + store.selectWritableRecord(id).kind === 'missing' && + !store.isSessionUnreadable(id) && + !store.getOperationRow(callerKey, operationId) && + store.readCommandReceipt({ kind: 'global' }, operationId).verdict === 'absent' + ) { + return null + } + return automationRunAcceptedTarget( + runtime, + run, + target, + new Error('send refused'), + automation.agentId + ) + } catch (error) { + return automationRunAcceptedTarget(runtime, run, target, error, automation.agentId) + } + } + return null +} diff --git a/src/main/automations/automation-dispatch-request.ts b/src/main/automations/automation-dispatch-request.ts index 3a317c5f016a..bab94fe9c545 100644 --- a/src/main/automations/automation-dispatch-request.ts +++ b/src/main/automations/automation-dispatch-request.ts @@ -1,6 +1,11 @@ +import { failedPrecheckResult, runAutomationPrecheck } from './precheck-runner' import type { WebContents } from 'electron' import { isDeepStrictEqual } from 'node:util' -import type { Automation, AutomationRun } from '../../shared/automations-types' +import type { + Automation, + AutomationRun, + AutomationPrecheckResult +} from '../../shared/automations-types' import { getRepoExecutionHostId } from '../../shared/execution-host' import type { Store } from '../persistence' import type { AutomationRunWriter } from './automation-run-writer' @@ -37,6 +42,7 @@ type DispatchContext = Pick< isActive(): boolean getRenderer(): AutomationRendererChannel | null headlessDispatcher: HeadlessAutomationDispatcher | null + chatDispatcher?: HeadlessAutomationDispatcher | null resolveTarget(automation: Automation): AutomationRunTargetResult } @@ -116,7 +122,10 @@ export async function requestAutomationDispatch( let target = resolveCurrentTarget() const refusal = describeScheduledRefusal({ target, - canDispatch: Boolean(ctx.getRenderer() || ctx.headlessDispatcher) + canDispatch: + automation.surface === 'chat' + ? Boolean(ctx.chatDispatcher) + : Boolean(ctx.getRenderer() || ctx.headlessDispatcher) }) if (refusal || !target.ok) { return refuse(refusal ?? automationRunFailure('noDispatchHost')) @@ -144,7 +153,7 @@ export async function requestAutomationDispatch( if (lateRefusal || !target.ok) { return refuse(lateRefusal ?? automationRunFailure('noDispatchHost')) } - const renderer = ctx.getRenderer() + const renderer = automation.surface === 'chat' ? null : ctx.getRenderer() if (renderer) { return sendRendererDispatch( renderer, @@ -157,7 +166,7 @@ export async function requestAutomationDispatch( run ) } - const dispatcher = ctx.headlessDispatcher + const dispatcher = automation.surface === 'chat' ? ctx.chatDispatcher : ctx.headlessDispatcher if (!dispatcher) { return refuse(automationRunFailure('noDispatchHost')) } @@ -186,3 +195,33 @@ export async function requestAutomationDispatch( } }) } + +export async function runAutomationRequestPrecheck( + store: Store, + automationId: string, + runId: string, + resolveTarget: (automation: Automation) => AutomationRunTargetResult +): Promise { + const automation = store.listAutomations().find((entry) => entry.id === automationId) + if (!automation) { + throw new Error('Automation not found.') + } + const run = store.listAutomationRuns(automationId).find((entry) => entry.id === runId) + if (!run) { + throw new Error('Automation run not found.') + } + if (run.trigger !== 'scheduled' || !automation.precheck) { + return null + } + const target = resolveTarget(automation) + if (!target.ok) { + return failedPrecheckResult(automation.precheck, Date.now(), target.error) + } + return await runAutomationPrecheck({ + precheck: automation.precheck, + target: + automation.executionTargetType === 'ssh' + ? { type: 'ssh', cwd: target.cwd, connectionId: automation.executionTargetId } + : { type: 'local', cwd: target.cwd } + }) +} diff --git a/src/main/automations/automation-run-operation.ts b/src/main/automations/automation-run-operation.ts new file mode 100644 index 000000000000..4d73a7d9e960 --- /dev/null +++ b/src/main/automations/automation-run-operation.ts @@ -0,0 +1,15 @@ +import { canonicalAgentSessionDigest } from '../../shared/agent-session-mutation-envelope' +import type { AutomationRun } from '../../shared/automations-types' + +export const AUTOMATION_AGENT_CALLER = { kind: 'local-cli' } as const + +export function automationRunOperationId( + run: Pick, + purpose: 'fresh-launch' | 'reuse-send' +): string { + const entropy = canonicalAgentSessionDigest({ + domain: `automation:${purpose}`, + runId: run.id + }).slice(0, 32) + return `${run.createdAt}-${entropy}` +} diff --git a/src/main/automations/automation-run-receipt.ts b/src/main/automations/automation-run-receipt.ts new file mode 100644 index 000000000000..7f5a5c9963b5 --- /dev/null +++ b/src/main/automations/automation-run-receipt.ts @@ -0,0 +1,74 @@ +import type { AutomationRun } from '../../shared/automations-types' +import { isAgentLaunchResult, type AgentLaunchResult } from '../../shared/agent-launch-intent' +import type { AgentSessionRecordStore } from '../runtime/agent-session-record-store' +import { rpcCallerOperationKey } from '../runtime/rpc/rpc-caller-identity' +import { AUTOMATION_AGENT_CALLER, automationRunOperationId } from './automation-run-operation' + +export type AutomationRunReceipt = + | { + kind: 'chat' + sessionId: string + workspaceId: string + messageId: string | null + accepted: boolean + } + | { + kind: 'terminal' + accepted: boolean + launch: AgentLaunchResult & { + outcome: Extract + } + } + +/** Publication and acceptance are separate receipts; neither recovery path sends again. */ +export function readAutomationRunReceipt( + store: Pick, + run: Pick +): AutomationRunReceipt | null { + const callerKey = rpcCallerOperationKey(AUTOMATION_AGENT_CALLER) + for (const purpose of ['fresh-launch'] as const) { + const row = store.getOperationRow(callerKey, automationRunOperationId(run, purpose)) + if (!row) { + continue + } + if (row.outcome.status !== 'succeeded' || !isAgentLaunchResult(row.outcome.launch)) { + return null + } + const launch = row.outcome.launch + if (launch.receipt.preferred !== 'structured') { + return null + } + if (launch.outcome.kind === 'structured') { + return { + kind: 'chat', + sessionId: launch.outcome.sessionId, + workspaceId: launch.worktreeId, + messageId: launch.prompt?.outcome === 'journaled' ? launch.prompt.messageId : null, + accepted: launch.prompt?.outcome === 'journaled' + } + } + if (launch.outcome.kind === 'terminal') { + return { + kind: 'terminal', + accepted: launch.prompt?.outcome === 'handed-to-terminal', + launch: { ...launch, outcome: launch.outcome } + } + } + return null + } + const messageId = automationRunOperationId(run, 'reuse-send') + const send = store.getOperationRow(callerKey, messageId) + if (send?.outcome.status !== 'succeeded') { + return null + } + const conversation = store.getConversation(send.outcome.sessionId) + return conversation + ? { + kind: 'chat', + sessionId: send.outcome.sessionId, + workspaceId: conversation.location.workspaceId, + messageId, + accepted: true + } + : null +} diff --git a/src/main/automations/headless-dispatch-durability.test.ts b/src/main/automations/headless-dispatch-durability.test.ts index 5bd10b8fe253..a863fd976b41 100644 --- a/src/main/automations/headless-dispatch-durability.test.ts +++ b/src/main/automations/headless-dispatch-durability.test.ts @@ -31,6 +31,8 @@ function fixture(launch: HeadlessAutomationDispatchLaunch) { } const terminal = { + sessionKind: 'terminal' as const, + chatSessionId: null, workspaceId: 'launched-workspace', terminalSessionId: 'launched-tab', terminalPaneKey: 'launched-pane', diff --git a/src/main/automations/headless-dispatch-runner.ts b/src/main/automations/headless-dispatch-runner.ts index e668a42cd44d..caf05dd3ec36 100644 --- a/src/main/automations/headless-dispatch-runner.ts +++ b/src/main/automations/headless-dispatch-runner.ts @@ -12,6 +12,7 @@ import type { HeadlessAutomationDispatcher, HeadlessAutomationDispatchLaunch } from './headless-dispatch' +import { AutomationRunLaunchError } from './headless-dispatch' import type { AutomationRunTargetResult } from './run-target-resolution' import type { AutomationRunWriter } from './automation-run-writer' import { @@ -77,10 +78,14 @@ export async function runHeadlessAutomationDispatch( runId: run.id, status: refusal ? 'skipped_unavailable' : 'dispatch_failed', workspaceId: automation.workspaceId, + ...(error instanceof AutomationRunLaunchError ? error.target : {}), + ...(automation.surface === 'chat' ? { dispatchedAt, precheckResult } : {}), ...(refusal ?? { error: describeDispatchError(error) }) }) } const launchRunTarget = { + sessionKind: launch.sessionKind ?? 'terminal', + chatSessionId: launch.chatSessionId ?? null, workspaceId: launch.workspaceId, workspaceDisplayName: launch.workspaceDisplayName ?? null, terminalSessionId: launch.terminalSessionId, diff --git a/src/main/automations/headless-dispatch.ts b/src/main/automations/headless-dispatch.ts index af1aa6851029..82707ce18d39 100644 --- a/src/main/automations/headless-dispatch.ts +++ b/src/main/automations/headless-dispatch.ts @@ -9,6 +9,8 @@ import type { AutomationRunFailureCodeFields } from '../../shared/automation-run const MAX_HEADLESS_OUTPUT_SNAPSHOT_CHARS = 256 * 1024 export type HeadlessAutomationDispatchLaunch = { + sessionKind?: 'terminal' | 'chat' + chatSessionId?: string | null workspaceId: string workspaceDisplayName?: string | null terminalSessionId: string | null @@ -29,6 +31,15 @@ export type HeadlessAutomationDispatcher = (request: { target: Extract }) => Promise +export class AutomationRunLaunchError extends Error { + constructor( + message: string, + readonly target?: HeadlessAutomationDispatchLaunch + ) { + super(message) + } +} + export function createHeadlessAutomationOutputSnapshotBuffer(): { append: (chunk: string) => void snapshot: () => AutomationRunOutputSnapshot | null diff --git a/src/main/automations/run-completion-watcher.test.ts b/src/main/automations/run-completion-watcher.test.ts index 66ea838eff1f..3a6c76357ec3 100644 --- a/src/main/automations/run-completion-watcher.test.ts +++ b/src/main/automations/run-completion-watcher.test.ts @@ -97,6 +97,7 @@ describe('authority-owned automation run completion', () => { const store = await createStore() const automation = createAutomation(store) const service = new AutomationService(store, { + allowRemoteHostScheduling: true, headlessDispatcher: async () => ({ ...LAUNCH_TARGET }), terminalObserver: createObserver(async () => ({ status: 'completed', error: null })) }) @@ -113,6 +114,7 @@ describe('authority-owned automation run completion', () => { const store = await createStore() const automation = createAutomation(store) const service = new AutomationService(store, { + allowRemoteHostScheduling: true, headlessDispatcher: async () => ({ ...LAUNCH_TARGET }), terminalObserver: createObserver( async () => ({ status: 'completed' }), @@ -130,6 +132,7 @@ describe('authority-owned automation run completion', () => { const automation = createAutomation(store) const logged = vi.spyOn(console, 'error').mockImplementation(() => {}) const service = new AutomationService(store, { + allowRemoteHostScheduling: true, headlessDispatcher: async () => ({ ...LAUNCH_TARGET }), terminalObserver: createObserver(async () => { throw new Error('terminal_handle_stale') @@ -230,6 +233,7 @@ describe('authority-owned automation run completion', () => { const automation = createAutomation(store) let resolveObservation: ((value: AutomationRunCompletionObservation) => void) | null = null const service = new AutomationService(store, { + allowRemoteHostScheduling: true, headlessDispatcher: async () => ({ ...LAUNCH_TARGET }), terminalObserver: createObserver( () => @@ -268,6 +272,7 @@ describe('authority-owned automation run completion', () => { const automation = createAutomation(store) const aborted: boolean[] = [] const service = new AutomationService(store, { + allowRemoteHostScheduling: true, headlessDispatcher: async () => ({ ...LAUNCH_TARGET }), terminalObserver: createObserver( (signal) => @@ -292,6 +297,7 @@ describe('authority-owned automation run completion', () => { const automation = createAutomation(store) const publish = vi.fn() const service = new AutomationService(store, { + allowRemoteHostScheduling: true, headlessDispatcher: async () => ({ ...LAUNCH_TARGET }), onAutomationsChanged: publish }) @@ -320,6 +326,7 @@ describe('automationsChanged publication', () => { const automation = createAutomation(store) const seen: { payload: AutomationsChangedPayload; status: string | undefined }[] = [] const service = new AutomationService(store, { + allowRemoteHostScheduling: true, headlessDispatcher: async () => ({ ...LAUNCH_TARGET }), onAutomationsChanged: (payload) => { seen.push({ diff --git a/src/main/automations/run-completion-watcher.ts b/src/main/automations/run-completion-watcher.ts index 8e4d45a929a0..4a733003eb53 100644 --- a/src/main/automations/run-completion-watcher.ts +++ b/src/main/automations/run-completion-watcher.ts @@ -175,6 +175,8 @@ export class AutomationRunCompletionWatcher { runId: run.id, status: observation.status, workspaceId: current.workspaceId, + sessionKind: current.sessionKind, + chatSessionId: current.chatSessionId, terminalSessionId: current.terminalSessionId, terminalPaneKey: current.terminalPaneKey, terminalPtyId: current.terminalPtyId, diff --git a/src/main/automations/runtime-automation-service.test.ts b/src/main/automations/runtime-automation-service.test.ts index c5ba99297b92..258683870ede 100644 --- a/src/main/automations/runtime-automation-service.test.ts +++ b/src/main/automations/runtime-automation-service.test.ts @@ -1,14 +1,26 @@ -import { describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type * as AgentLauncher from './automation-chat-agent-launch' import type { HeadlessAutomationDispatcher } from './headless-dispatch' import type { AutomationRunTerminalObserver } from './run-completion-watcher' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import type { Store } from '../persistence' +import { buildProfileStateCutoverFixture } from '../persistence/profile-state-cutover-fixture' +import { automationRunOperationId } from './automation-run-operation' -type CapturedServiceOptions = { +type Options = { headlessDispatcher?: HeadlessAutomationDispatcher + chatDispatcher?: HeadlessAutomationDispatcher terminalObserver?: AutomationRunTerminalObserver } - -const captured = vi.hoisted((): { options: CapturedServiceOptions } => ({ options: {} })) - +const captured = vi.hoisted(() => { + const options: Options = {} + return { + options, + launch: vi.fn(), + observeChat: vi.fn(), + markDispatchResult: vi.fn() + } +}) const { deliverTerminalAgentLaunchPrompt } = vi.hoisted(() => ({ deliverTerminalAgentLaunchPrompt: vi.fn(async () => true) })) @@ -20,17 +32,249 @@ vi.mock('./service', () => ({ AutomationService: class { start(): void {} stop(): void {} - constructor(_store: unknown, opts: CapturedServiceOptions) { + markDispatchResult = captured.markDispatchResult + constructor(_store: unknown, opts: Options) { captured.options = opts } } })) - +vi.mock('./automation-chat-agent-launch', async (original) => ({ + ...(await original()), + launchAutomationChatAgent: captured.launch +})) +vi.mock('./runtime-chat-run-observer', () => ({ observeAutomationChatRun: captured.observeChat })) import { createRuntimeAutomationService } from './runtime-automation-service' +const state = buildProfileStateCutoverFixture('/fixture') +const run = { + ...state.automationRuns[0], + createdAt: 1_700_000_000_000, + status: 'dispatching' as const, + chatSessionId: null +} +function fixture(headless: boolean, definitionSurface: 'chat' | 'terminal' = 'chat') { + const rows = new Map() + const records = { + getOperationRow: (_caller: string, id: string) => rows.get(id), + getConversation: () => ({ + sessionId: 'claude_chat', + provider: 'claude', + location: { workspaceId: 'wt-1' } + }) + } + const runtime = { + setAutomationService: vi.fn(), + notifyAutomationsChanged: vi.fn(), + openAgentSessionRecordStore: async () => records, + openedAgentSessionRecordStore: () => records, + getTerminalHandleForPaneKey: vi.fn((_pane: string): string | null => null), + getTerminalPtyIdForHandle: vi.fn((_handle: string): string | null => 'pty-1'), + getTerminalPaneKey: vi.fn( + () => '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d:3f2504e0-4f89-41d3-9a0c-0305e82c3301' + ), + waitForTerminal: vi.fn(async () => ({ state: 'done' })), + getAgentStatusRowsForPane: vi.fn(() => []) + } + createRuntimeAutomationService({ + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: construction and recovery use only these store boundaries. + store: { + listAutomationRuns: () => [], + listAutomations: () => [ + { id: run.automationId, agentId: 'claude', surface: definitionSurface } + ] + } as unknown as Store, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: launching and chat observation are mocked; the runtime implements the recovery boundaries. + runtime: runtime as unknown as OrcaRuntimeService, + headless + }) + return { runtime, rows } +} +beforeEach(() => { + vi.clearAllMocks() + captured.markDispatchResult.mockImplementation(async (result) => ({ ...run, ...result })) + captured.observeChat.mockResolvedValue({ status: 'completed' }) +}) +describe('host-owned automation execution', () => { + it.each([false, true])( + 'uses the same Chat dispatcher on desktop/headless=%s without supplying a desktop Terminal dispatcher', + async (headless) => { + fixture(headless) + captured.launch.mockResolvedValue({ + workspaceId: 'wt-1', + terminalSessionId: 'tab-1', + terminalPaneKey: + '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d:3f2504e0-4f89-41d3-9a0c-0305e82c3301', + terminalHandle: 'term-1' + }) + expect(Boolean(captured.options.headlessDispatcher)).toBe(headless) + const dispatcher = captured.options.chatDispatcher! + const result = await dispatcher({ + automation: { ...state.automations[0], surface: 'chat' }, + run, + target: { ok: true, cwd: '/fixture', repo: state.repos[0] } + }) + expect(result.completion).toBeUndefined() + expect(captured.launch).toHaveBeenCalledOnce() + expect( + captured.options.terminalObserver!.resolveRunTerminal({ + ...run, + status: 'dispatched', + terminalPaneKey: + '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d:3f2504e0-4f89-41d3-9a0c-0305e82c3301' + }) + ).toBe('term-1') + } + ) + it.each(['fresh-launch', 'reuse-send'] as const)( + 'recovers a %s accepted chat before the automation run identity was saved', + async (purpose) => { + const { rows } = fixture(false, purpose === 'fresh-launch' ? 'terminal' : 'chat') + rows.set(automationRunOperationId(run, purpose), { + outcome: { + status: 'succeeded', + sessionId: 'claude_chat', + ...(purpose === 'fresh-launch' + ? { + launch: { + worktreeId: 'wt-1', + outcome: { kind: 'structured', sessionId: 'claude_chat', handle: 'chat-tab' }, + receipt: { + mode: 'structured', + preferred: 'structured', + reason: 'requested', + detail: 'Chat' + }, + prompt: { delivery: 'submit', outcome: 'journaled', messageId: 'opening' } + } + } + : {}) + } + }) + const observer = captured.options.terminalObserver! + const handle = observer.resolveRunTerminal(run)! + expect( + await observer.observeCompletion(handle, { run, signal: new AbortController().signal }) + ).toEqual({ status: 'completed' }) + expect(captured.markDispatchResult).toHaveBeenCalledWith( + expect.objectContaining({ + sessionKind: 'chat', + chatSessionId: 'claude_chat', + terminalPaneKey: null, + terminalSessionId: null, + terminalPtyId: null + }) + ) + expect(captured.observeChat).toHaveBeenCalledOnce() + expect(captured.launch).not.toHaveBeenCalled() + } + ) + it('recovers an accepted Chat request that actually fell back to Terminal without relaunch', async () => { + const { rows, runtime } = fixture(false, 'terminal') + rows.set(automationRunOperationId(run, 'fresh-launch'), { + outcome: { + status: 'succeeded', + launch: { + worktreeId: 'wt-1', + outcome: { + kind: 'terminal', + handle: 'term-fallback', + paneKey: 'tab:11111111-1111-4111-8111-111111111111' + }, + receipt: { + mode: 'terminal', + preferred: 'structured', + reason: 'unsupported', + detail: 'Fallback' + }, + prompt: { delivery: 'submit', outcome: 'handed-to-terminal' } + } + } + }) + runtime.waitForTerminal.mockRejectedValueOnce(new Error('ordinary-terminal-observer')) + const observer = captured.options.terminalObserver! + await expect( + observer.observeCompletion(observer.resolveRunTerminal(run)!, { + run, + signal: new AbortController().signal + }) + ).rejects.toThrow('ordinary-terminal-observer') + expect(captured.markDispatchResult).toHaveBeenCalledWith( + expect.objectContaining({ + status: 'dispatched', + sessionKind: 'terminal', + terminalPtyId: 'pty-1' + }) + ) + expect(runtime.waitForTerminal).toHaveBeenCalledWith('term-fallback', expect.anything()) + expect(captured.observeChat).not.toHaveBeenCalled() + expect(captured.launch).not.toHaveBeenCalled() + }) + it.each(['chat', 'terminal'] as const)( + 'recovers a published failed %s receipt without accepting or sending it', + async (kind) => { + const { rows, runtime } = fixture(false) + rows.set(automationRunOperationId(run, 'fresh-launch'), { + outcome: { + status: 'succeeded', + launch: { + worktreeId: 'actually-published', + outcome: + kind === 'chat' + ? { kind: 'structured', sessionId: 'claude_published', handle: 'chat-tab' } + : { + kind: 'terminal', + handle: 'term-published', + paneKey: 'tab:11111111-1111-4111-8111-111111111111' + }, + receipt: { + mode: kind === 'chat' ? 'structured' : 'terminal', + preferred: 'structured', + reason: 'requested', + detail: 'Published' + }, + prompt: { delivery: 'submit', outcome: 'unconfirmed' } + } + } + }) + const observer = captured.options.terminalObserver! + expect( + await observer.observeCompletion(observer.resolveRunTerminal(run)!, { + run, + signal: new AbortController().signal + }) + ).toMatchObject({ status: 'dispatch_failed' }) + expect(captured.markDispatchResult).toHaveBeenCalledWith( + expect.objectContaining({ + workspaceId: 'actually-published', + status: 'dispatch_failed', + sessionKind: kind, + ...(kind === 'chat' + ? { chatSessionId: 'claude_published', terminalPaneKey: null } + : { + terminalSessionId: 'tab', + terminalPaneKey: 'tab:11111111-1111-4111-8111-111111111111' + }) + }) + ) + expect(runtime.waitForTerminal).not.toHaveBeenCalled() + expect(captured.observeChat).not.toHaveBeenCalled() + expect(captured.launch).not.toHaveBeenCalled() + } + ) + it('refuses an ambiguous crash without resending or marking success', async () => { + const { rows } = fixture(false) + rows.set(automationRunOperationId(run, 'fresh-launch'), { outcome: { status: 'unknown' } }) + const observer = captured.options.terminalObserver! + expect( + await observer.observeCompletion(observer.resolveRunTerminal(run)!, { + run, + signal: new AbortController().signal + }) + ).toMatchObject({ status: 'dispatch_failed', error: expect.stringContaining('Claude') }) + expect(captured.launch).not.toHaveBeenCalled() + }) +}) -function capturedOption( - key: K -): NonNullable { +function capturedOption(key: K): NonNullable { const value = captured.options[key] if (value === undefined) { throw new Error(`the service was constructed without ${key}`) diff --git a/src/main/automations/runtime-automation-service.ts b/src/main/automations/runtime-automation-service.ts index 84b52c88659c..49978be09dd6 100644 --- a/src/main/automations/runtime-automation-service.ts +++ b/src/main/automations/runtime-automation-service.ts @@ -1,3 +1,8 @@ +import { observeAutomationChatRun } from './runtime-chat-run-observer' +import { readAutomationRunReceipt } from './automation-run-receipt' +import { publishedLaunchTarget } from './automation-agent-run-result' +import { launchAutomationChatAgent } from './automation-chat-agent-launch' +import { tuiAgentDisplayName } from '../../shared/tui-agent-display-names' import type { ClaudeUsageStore } from '../claude-usage/store' import type { CodexUsageStore } from '../codex-usage/store' import type { Store } from '../persistence' @@ -41,11 +46,94 @@ export function createRuntimeAutomationService(input: { codexUsage, terminalObserver: { ...observer, - resolveRunTerminal: (run) => - (run.terminalPaneKey ? launchedHandles.get(run.terminalPaneKey) : undefined) ?? - observer.resolveRunTerminal(run), + resolveRunTerminal: (run) => { + if (run.sessionKind === 'chat') { + return `automation:${run.id}` + } + if (run.status === 'dispatching') { + const records = runtime.openedAgentSessionRecordStore() + if ( + (records && readAutomationRunReceipt(records, run)) || + store.listAutomations().find((entry) => entry.id === run.automationId)?.surface === + 'chat' + ) { + return `automation:${run.id}` + } + if (!records) { + void runtime.openAgentSessionRecordStore().catch((error: unknown) => { + console.warn('[automations] could not read accepted Chat operation:', error) + }) + } + } + return ( + (run.terminalPaneKey ? launchedHandles.get(run.terminalPaneKey) : undefined) ?? + observer.resolveRunTerminal(run) + ) + }, observeCompletion: async (handle, options) => { - const observation = await observer.observeCompletion(handle, options) + let run = options.run + if (run && handle.startsWith('automation:')) { + if (!run.chatSessionId) { + const records = await runtime.openAgentSessionRecordStore() + const receipt = readAutomationRunReceipt(records, run) + const agent = + tuiAgentDisplayName( + store.listAutomations().find((entry) => entry.id === run?.automationId)?.agentId ?? + 'Agent' + ) ?? 'Agent' + if (!receipt) { + return { + status: 'dispatch_failed', + error: `${agent} could not confirm this run after Orca restarted. Open its workspace before running again.` + } + } + const target = + receipt.kind === 'terminal' + ? publishedLaunchTarget(runtime, receipt.launch) + : { + workspaceId: receipt.workspaceId, + sessionKind: 'chat' as const, + chatSessionId: receipt.sessionId, + terminalPaneKey: null, + terminalSessionId: null, + terminalPtyId: null + } + run = await service.markDispatchResult({ + ...target, + runId: run.id, + status: receipt.accepted ? 'dispatched' : 'dispatch_failed', + error: receipt.accepted + ? null + : `${agent} could not confirm this run's prompt. Open the run before trying again.` + }) + if (!receipt.accepted) { + return { status: 'dispatch_failed', error: run.error } + } + if (receipt.kind === 'terminal') { + handle = receipt.launch.outcome.handle + } + } + if (run.sessionKind === 'chat') { + try { + return await observeAutomationChatRun(runtime, run, options.signal) + } catch (error) { + if (options.signal.aborted) { + throw error + } + console.error('[automations] chat run observation failed:', error) + const agent = + tuiAgentDisplayName( + store.listAutomations().find((entry) => entry.id === run?.automationId) + ?.agentId ?? 'Agent' + ) ?? 'Agent' + return { + status: 'dispatch_failed', + error: `${agent} stopped reporting this run's result. Open the chat before running again.` + } + } + } + } + const observation = await observer.observeCompletion(handle, { ...options, run }) if (options.run && observation.error === AGENT_HOOKS_REVIEW_BLOCKED_ERROR) { const markDispatchResult = service.markDispatchResult.bind(service) void closeEarlierHookReviewRunTerminals( @@ -60,6 +148,19 @@ export function createRuntimeAutomationService(input: { }, onAutomationsChanged: (payload) => runtime.notifyAutomationsChanged(payload), allowRemoteHostScheduling: input.headless, + chatDispatcher: async (request) => { + const { terminalHandle, ...launch } = await launchAutomationChatAgent(runtime, { + ...request, + runs: store.listAutomationRuns(request.automation.id) + }) + if (launch.terminalPaneKey && terminalHandle) { + launchedHandles.set(launch.terminalPaneKey, terminalHandle) + if (launchedHandles.size > MAX_REMEMBERED_LAUNCHES) { + launchedHandles.delete(launchedHandles.keys().next().value ?? '') + } + } + return launch + }, headlessDispatcher: input.headless ? async (request) => { const { terminalHandle, ...launch } = await launchHeadlessAutomationAgent(runtime, { diff --git a/src/main/automations/runtime-chat-run-observer.test.ts b/src/main/automations/runtime-chat-run-observer.test.ts new file mode 100644 index 000000000000..cb04c2922db6 --- /dev/null +++ b/src/main/automations/runtime-chat-run-observer.test.ts @@ -0,0 +1,707 @@ +import { measureAutomationChatRun } from './automation-chat-run-measurement-test-harness' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { + AgentJournalSnapshot, + AgentJournalRenderItem, + AgentJournalSubmission +} from '../../shared/agent-session-journal-types' +import { + agentJournalSubmissionKey, + agentJournalItemKey +} from '../../shared/agent-session-journal-item-key' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import { buildProfileStateCutoverFixture } from '../persistence/profile-state-cutover-fixture' +import { chatAutomationRunObservation, observeAutomationChatRun } from './runtime-chat-run-observer' +import type { JournalPublication } from '../native-chat/agent-session-wire/structured-agent-session-conversations' +import type { StructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-host' +import { + createQueuedMessageTestRig, + eventually +} from '../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { + HOST_TEST_SESSION, + HOST_TEST_THREAD, + hostTestMessage +} from '../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types' +import { automationRunOperationId } from './automation-run-operation' + +const mocks = vi.hoisted(() => { + const hostState: { actualHost: StructuredAgentSessionHost | null } = { actualHost: null } + return { + ...hostState, + host: { + journalSnapshot: vi.fn(), + observeConversationPublications: vi.fn(), + queuedSendAnswer: vi.fn(async () => null) + } + } +}) +vi.mock('../native-chat/agent-session-wire/structured-agent-session-registry', () => ({ + getStructuredAgentSessionHost: () => mocks.actualHost ?? mocks.host +})) +const submission: AgentJournalSubmission = { + clientMessageId: 'prompt', + fence: 1, + payloadFingerprint: 'hash', + dispatchState: 'accepted', + providerItemId: 'provider-user', + reason: null, + submittedAt: 1, + resolvedAt: 2 +} +function turn( + itemId: string, + userItemId: string, + state: 'running' | 'completed' | 'interrupted' = 'completed' +): AgentJournalRenderItem { + return { + itemId, + revision: 1, + sequence: 1, + observedAt: 1, + body: { + kind: 'turn', + turnId: itemId, + userItemId, + state, + ...(state === 'completed' ? { outcome: 'success' as const } : {}) + } + } +} +function answer(itemId: string, turnItemId: string, text: string): AgentJournalRenderItem { + return { + itemId, + revision: 1, + sequence: 2, + observedAt: 2, + turnScope: { kind: 'turn', turnItemId }, + body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text }] } + } +} +function snapshot(items: AgentJournalRenderItem[] = []): AgentJournalSnapshot { + return { + sessionId: 'claude_chat', + cursor: { epoch: 'epoch', sequence: 2 }, + items, + submissions: [submission] + } +} +beforeEach(() => { + vi.clearAllMocks() + mocks.actualHost = null +}) +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() +}) +describe('exact automation chat turn', () => { + it('waits for its own prompt even when a later human turn completed', () => { + expect( + chatAutomationRunObservation( + snapshot([turn('own', 'provider-user', 'running'), turn('human', 'other')]), + 'prompt', + 'Claude' + ) + ).toBeNull() + const missingRoot = snapshot([turn('human', 'other')]) + const roots = vi.spyOn(missingRoot.items, 'find') + expect(chatAutomationRunObservation(missingRoot, 'prompt', 'Claude')).toBeNull() + expect(roots).toHaveBeenCalledOnce() + missingRoot.submissions = [] + roots.mockClear() + expect(chatAutomationRunObservation(missingRoot, 'prompt', 'Claude')).toBeNull() + expect(roots).not.toHaveBeenCalled() + }) + it('matches the Orca opener alias and snapshots only the accepted root turn', () => { + const view = snapshot([ + turn('own', agentJournalSubmissionKey('prompt')), + answer('a', 'own', 'Automation output'), + answer('b', 'human', 'Private later output'), + { ...answer('c', 'own', 'Child output'), agentId: 'child' } + ]) + let outputRows = 0 + const items = view.items[Symbol.iterator].bind(view.items) + vi.spyOn(view.items, Symbol.iterator).mockImplementation(function* () { + for (const item of items()) { + outputRows++ + yield item + } + return undefined + }) + const result = chatAutomationRunObservation(view, 'prompt', 'Codex') + expect(outputRows).toBe(4) + expect(result).toMatchObject({ + status: 'completed', + error: null, + outputSnapshot: { content: 'Automation output' } + }) + }) + it('accepts explicit start proof and never claims a steered or unlinked turn', () => { + const view = snapshot([turn('own', 'different')]) + view.submissions = [{ ...submission, answeredInTurn: { turnItemId: 'own', via: 'steer' } }] + expect(chatAutomationRunObservation(view, 'prompt', 'Codex')).toBeNull() + view.submissions = [{ ...submission, answeredInTurn: { turnItemId: 'own', via: 'start' } }] + expect(chatAutomationRunObservation(view, 'prompt', 'Codex')?.status).toBe('completed') + }) + it('reports Stop as Interrupted and unknown or refused prompts as failures', () => { + expect( + chatAutomationRunObservation( + snapshot([turn('own', 'provider-user', 'interrupted')]), + 'prompt', + 'Claude' + ) + ).toMatchObject({ status: 'dispatch_failed', error: expect.stringContaining('Interrupted') }) + const view = snapshot() + view.submissions = [{ ...submission, dispatchState: 'unknown' }] + expect(chatAutomationRunObservation(view, 'prompt', 'Claude')).toMatchObject({ + status: 'dispatch_failed', + error: expect.stringContaining('Claude') + }) + }) + it('does not infer success from completed without an outcome and bounds output', () => { + const own = turn('own', 'provider-user') + own.body = { kind: 'turn', turnId: 'own', userItemId: 'provider-user', state: 'completed' } + const result = chatAutomationRunObservation( + snapshot([own, answer('a', 'own', 'x'.repeat(300_000))]), + 'prompt', + 'Claude' + ) + expect(result?.status).toBe('dispatch_failed') + expect(result?.outputSnapshot?.content.length).toBeLessThanOrEqual(256 * 1024) + expect(result?.outputSnapshot?.truncated).toBe(true) + }) +}) + +describe('restart observation and disposal', () => { + function fixture() { + const run = { + ...buildProfileStateCutoverFixture('/fixture').automationRuns[0], + createdAt: Date.now(), + dispatchedAt: Date.now(), + sessionKind: 'chat' as const, + chatSessionId: 'claude_chat' + } + const messageId = automationRunOperationId(run, 'reuse-send') + const records = { + getOperationRow: vi.fn((_caller: string, id: string) => + id === messageId + ? { outcome: { status: 'succeeded', sessionId: 'claude_chat' } } + : undefined + ), + getConversation: () => ({ + sessionId: 'claude_chat', + provider: 'claude', + location: { workspaceId: 'wt-1' } + }) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: observation reaches only these two runtime boundaries. + const runtime = { + ensureStructuredAgentSessionHost: vi.fn(), + openAgentSessionRecordStore: async () => records + } as unknown as OrcaRuntimeService + const view = snapshot([turn('own', agentJournalSubmissionKey(messageId), 'running')]) + view.submissions = [{ ...submission, clientMessageId: messageId }] + return { run, records, runtime, view } + } + it('registers synchronously before read and abort wins over a late read', async () => { + const { run, runtime, view } = fixture() + const release = vi.fn() + const read = Promise.withResolvers() + mocks.host.observeConversationPublications.mockImplementation((_id, observer) => { + expect(mocks.host.journalSnapshot).not.toHaveBeenCalled() + observer.next({ kind: 'reset', source: {}, journal: null }) + return release + }) + mocks.host.journalSnapshot.mockReturnValue(read.promise) + const controller = new AbortController() + const pending = observeAutomationChatRun(runtime, run, controller.signal) + const rejected = expect(pending).rejects.toThrow('request_aborted') + await vi.waitFor(() => expect(mocks.host.journalSnapshot).toHaveBeenCalledOnce()) + controller.abort() + await rejected + read.resolve(view) + await Promise.resolve() + expect(release).toHaveBeenCalledOnce() + expect(mocks.host.queuedSendAnswer).not.toHaveBeenCalled() + }) + it('fences replacement and row-free changes across both awaits without losing exact completion', async () => { + const { run, runtime, view } = fixture() + const release = vi.fn() + const source = {} + let notify: (hint: JournalPublication) => void = () => {} + mocks.host.observeConversationPublications.mockImplementation((_id, observer) => { + notify = observer.next + notify({ kind: 'reset', source, journal: null }) + return release + }) + const delayed = Promise.withResolvers() + const opening = Promise.withResolvers() + mocks.host.journalSnapshot.mockReturnValueOnce(opening.promise).mockResolvedValue(view) + mocks.host.queuedSendAnswer.mockReturnValueOnce(delayed.promise) + const pending = observeAutomationChatRun(runtime, run, new AbortController().signal) + await vi.waitFor(() => expect(mocks.host.journalSnapshot).toHaveBeenCalledOnce()) + notify({ kind: 'reset', source: {}, journal: null }) + opening.resolve({ + ...view, + items: [turn('old-completed', view.submissions[0].providerItemId!)] + }) + await vi.waitFor(() => expect(mocks.host.queuedSendAnswer).toHaveBeenCalledOnce()) + notify({ kind: 'operational', source, journal: null }) + view.items[0] = turn('own', view.submissions[0].providerItemId!) + delayed.resolve(null) + expect(await pending).toMatchObject({ status: 'completed' }) + expect(mocks.host.journalSnapshot).toHaveBeenCalledTimes(3) + expect(release).toHaveBeenCalledOnce() + }) + it('ends read errors, listener errors, host-end and the six-hour deadline exactly once', async () => { + vi.useFakeTimers() + const { run, runtime, view } = fixture() + for (const mode of ['read', 'listener', 'end', 'deadline'] as const) { + const release = vi.fn() + let observer: + | { next: (hint: JournalPublication) => void; error: (error: unknown) => void } + | undefined + mocks.host.observeConversationPublications.mockImplementation((_id, next) => { + observer = next + next.next({ kind: 'reset', source: {}, journal: null }) + return release + }) + mocks.host.journalSnapshot.mockImplementation(async () => { + if (mode === 'read') { + throw new Error('unreadable') + } + return view + }) + const pending = observeAutomationChatRun(runtime, run, new AbortController().signal) + const result = pending.then( + (value) => value, + (error) => error + ) + await vi.advanceTimersByTimeAsync(0) + if (mode === 'listener') { + observer!.error(new Error('consumer')) + } + if (mode === 'end') { + observer!.next({ kind: 'end', source: null, journal: null }) + } + if (mode === 'deadline') { + await vi.advanceTimersByTimeAsync(6 * 60 * 60 * 1000) + } + expect(await result).toMatchObject( + mode === 'deadline' + ? { status: 'dispatch_failed' } + : { + message: + mode === 'read' + ? 'unreadable' + : mode === 'listener' + ? 'consumer' + : 'Chat session host stopped' + } + ) + observer!.next({ kind: 'reset', source: {}, journal: null }) + expect(release).toHaveBeenCalledOnce() + expect(vi.getTimerCount()).toBe(0) + } + }) + it('fails promptly when no exact accepted receipt survives', async () => { + const { run, runtime, records } = fixture() + records.getOperationRow.mockReturnValue(undefined) + expect( + await observeAutomationChatRun(runtime, run, new AbortController().signal) + ).toMatchObject({ status: 'dispatch_failed', error: expect.stringContaining('confirm') }) + expect(mocks.host.observeConversationPublications).not.toHaveBeenCalled() + }) +}) + +// The provider is scripted; queue ownership, journal, catch-up and publication are real. +describe('real host queue publication and operation bounds', () => { + it.each([100, 1000])( + 'observes Q→S at %i prior turns without token-triggered history scans', + async (history) => { + const totals: number[][] = [] + for (const mode of ['baseline', 'internal', 'display'] as const) { + const rig = await createQueuedMessageTestRig({ restartable: true }) + mocks.actualHost = rig.host + const controller = new AbortController() + try { + const working = await rig.workingSend() + let sink = rig.providerEvents() + const journal = rig.host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)!.journal + for (let n = 0; n < history; n++) { + await journal.appendSubmission({ + clientMessageId: `old-send-${n}`, + payloadFingerprint: 'a'.repeat(64), + fence: 1, + body: hostTestMessage(`old prompt ${n}`) + }) + await journal.resolveDispatch({ + clientMessageId: `old-send-${n}`, + state: 'accepted', + providerIdentity: null, + fence: 1 + }) + sink.appendItem( + { provider: 'codex', threadId: HOST_TEST_THREAD, turnId: `old-${n}`, ordinal: 0 }, + { kind: 'turn', turnId: `old-${n}`, state: 'completed', outcome: 'success' }, + { turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + if (n % 100 === 99) { + await sink.written?.() + } + } + await sink.written?.() + const run = { + ...buildProfileStateCutoverFixture('/fixture').automationRuns[0], + createdAt: Date.now(), + dispatchedAt: Date.now(), + sessionKind: 'chat' as const, + chatSessionId: HOST_TEST_SESSION + } + const q = automationRunOperationId(run, 'reuse-send') + const body = hostTestMessage('automation behind human backlog') + const fields = { body, delivery: 'queue-if-active' as const } + expect( + await rig.host.send( + { callerKey: 'client-1' }, + { + ...fields, + envelope: rig.envelope(fields, 'agentSession.send', q) + } + ) + ).toMatchObject({ ok: true, value: { queued: { messageId: q, state: 'waiting' } } }) + const metrics = measureAutomationChatRun(journal, rig.host) + const { measure, full, observerReads, registration, releases, keys, timers, cleared } = + metrics + const tokenBurst = async () => { + for (let n = 0; n < 25; n++) { + sink.appendItem( + { provider: 'codex', threadId: HOST_TEST_THREAD, turnId: 'unrelated', ordinal: 1 }, + { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: `token-${n}` }] + }, + { turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + sink.publish() + await sink.written?.() + await rig.host.flushStreamedEvents(HOST_TEST_SESSION) + } + } + const difference = (before: number[]) => + measure().map((value, index) => value - before[index]) + const displayRelease = + mode === 'display' + ? await rig.host.subscribe({ + id: 'ordinary-display', + sessionId: HOST_TEST_SESSION, + emit: () => {} + }) + : () => {} + const beforeBaseline = measure() + await tokenBurst() + const baselineWork = difference(beforeBaseline) + const runtimeFacade = { + ensureStructuredAgentSessionHost: async () => {}, + openAgentSessionRecordStore: async () => ({ + getOperationRow: (_caller: string, id: string) => + id === q + ? { outcome: { status: 'succeeded', sessionId: HOST_TEST_SESSION } } + : undefined, + getConversation: () => ({ + provider: 'codex', + location: { workspaceId: 'workspace-1' } + }) + }) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: initialization/receipt reads are scripted; the actual host/journal/queue/observer and N/10N measurements execute. + const runtime = runtimeFacade as unknown as OrcaRuntimeService + let pending = + mode === 'internal' ? observeAutomationChatRun(runtime, run, controller.signal) : null + void pending?.catch(() => {}) + if (pending) { + await eventually(() => expect(registration).toHaveBeenCalledOnce()) + } + await rig.host.flushStreamedEvents(HOST_TEST_SESSION) + await eventually(() => expect(full.mock.calls.length).toBeGreaterThan(0)) + const beforeTokens = measure() + const readsBeforeTokens = observerReads.mock.calls.length + const keysBeforeTokens = keys.map((spy) => spy.mock.calls.length) + await tokenBurst() + expect(observerReads.mock.calls.length).toBe(readsBeforeTokens) + const observerWork = difference(beforeTokens) + expect(observerWork).toEqual(baselineWork) + const keyedAdded = keys.map((spy, i) => spy.mock.calls.length - keysBeforeTokens[i]) + expect(keyedAdded.reduce((a, b) => a + b, 0)).toBeLessThanOrEqual(25 * 12) + const unchangedReads = observerReads.mock.calls.length + await journal.resolveDispatch({ + clientMessageId: 'old-send-0', + state: 'accepted', + providerIdentity: null, + fence: 1 + }) + await rig.host.flushStreamedEvents(HOST_TEST_SESSION) + expect(observerReads).toHaveBeenCalledTimes(unchangedReads) + if (pending) { + controller.abort() + await expect(pending).rejects.toThrow('request_aborted') + expect(releases[0]).toHaveBeenCalledOnce() + pending = observeAutomationChatRun(runtime, run, new AbortController().signal) + await eventually(() => expect(registration).toHaveBeenCalledTimes(2)) + } + await rig.settleAccepted(working, 'human') + sink.appendItem( + { provider: 'codex', threadId: HOST_TEST_THREAD, turnId: 'turn-human', ordinal: 1 }, + { kind: 'turn', turnId: 'turn-human', state: 'completed', outcome: 'success' }, + { turnScope: AGENT_JOURNAL_THREAD_SCOPE, lifecycle: true } + ) + sink.publish({ lifecycle: true }) + expect(await sink.written?.()).toEqual({ ok: true }) + await rig.host.flushStreamedEvents(HOST_TEST_SESSION) + const handoff = () => + journal.submissions().findLast((entry) => entry.queuedMessageId === q) + await eventually(() => expect(handoff()).toBeDefined()) + const sent = handoff()!.clientMessageId + expect(sent).not.toBe(q) + await eventually(() => expect(journal.submission(sent)?.handedOverAt).toBeDefined()) + await rig.settleAccepted(sent, 'automation') + await rig.host.flushStreamedEvents(HOST_TEST_SESSION) + const beforeRestatement = observerReads.mock.calls.length + await journal.resolveDispatch({ + clientMessageId: sent, + state: 'accepted', + providerIdentity: null, + fence: 1 + }) + await rig.host.flushStreamedEvents(HOST_TEST_SESSION) + expect(observerReads).toHaveBeenCalledTimes(beforeRestatement) + const beforeWork = observerReads.mock.calls.length + rig.host['clientDelivery'].publishRestored(HOST_TEST_SESSION) + rig.host.publishWorkChanged(HOST_TEST_SESSION) + if (pending) { + await eventually(() => + expect(observerReads.mock.calls.length).toBeGreaterThan(beforeWork) + ) + } + const accepted = journal.submission(sent) + sink = rig.providerEvents() + const ownId = { + provider: 'codex' as const, + threadId: HOST_TEST_THREAD, + turnId: 'turn-automation', + ordinal: 1 + } + sink.appendItem( + ownId, + { + kind: 'turn', + turnId: 'turn-automation', + userItemId: accepted!.providerItemId!, + state: 'completed', + outcome: 'success' + }, + { turnScope: AGENT_JOURNAL_THREAD_SCOPE, lifecycle: true } + ) + sink.appendItem( + { ...ownId, ordinal: 2 }, + { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: 'Exact automation output' }] + }, + { turnScope: { kind: 'turn', turnItemId: agentJournalItemKey(ownId) } } + ) + sink.publish({ lifecycle: true }) + expect(await sink.written?.()).toEqual({ ok: true }) + await rig.host.flushStreamedEvents(HOST_TEST_SESSION) + expect( + pending + ? await pending + : chatAutomationRunObservation( + await rig.host.journalSnapshot(HOST_TEST_SESSION), + q, + 'Codex', + await rig.host.queuedSendAnswer(HOST_TEST_SESSION, q) + ) + ).toMatchObject({ + status: 'completed', + outputSnapshot: { content: 'Exact automation output' } + }) + expect(rig.dispatch).toHaveBeenCalledTimes(2) + expect(releases).toHaveLength(mode === 'internal' ? 2 : 0) + for (const release of releases) { + expect(release).toHaveBeenCalledOnce() + } + for (const [index, args] of timers.mock.calls.entries()) { + if (Number(args[1]) > 5 * 60 * 60 * 1000) { + expect(cleared).toHaveBeenCalledWith(timers.mock.results[index].value) + } + } + displayRelease() + expect(registration).toHaveBeenCalledTimes(mode === 'internal' ? 2 : 0) + expect(observerReads.mock.calls.length).toBeLessThanOrEqual(12) + const { copied, iteratorYields, projectedRows, scannedRows } = metrics.details() + expect(copied + iteratorYields + projectedRows + scannedRows).toBeLessThan( + (history + 30) * 4000 + ) + const sessions = rig.host.collaboratorsForTests().sessions + expect(sessions['observers'].size).toBe(0) + expect(sessions['attachments'].size).toBe(1) + totals.push(measure()) + process.stdout.write( + `${JSON.stringify({ history, mode, sourceAttachments: sessions['attachments'].size, logicalObservers: sessions['observers'].size, baselineWork, observerWork, keyedAdded, totals: measure(), ...metrics.details(), reconciliations: observerReads.mock.calls.length, registrations: registration.mock.calls.length, releases: releases.filter((r) => r.mock.calls.length === 1).length })}\n` + ) + } finally { + controller.abort() + mocks.actualHost = null + await rig.dispose() + vi.restoreAllMocks() + } + } + const added = totals[1].map((value, i) => value - totals[0][i]) + expect(added.slice(0, 15).filter((_, i) => i !== 5 && i !== 12)).toEqual( + added + .slice(0, 15) + .filter((_, i) => i !== 5 && i !== 12) + .map(() => 0) + ) + expect(added[5]).toBe(6) + expect(added[12]).toBe(6) + expect(totals[0].slice(17, 21)).toEqual([1, 2 * history + 5, 0, 0]) + expect(totals[1].slice(17, 21)).toEqual([5, 10 * history + 20, 2, 2 * history + 2]) + expect(added.slice(15)).toEqual([ + 8 * history + 15, + 2 * history + 2, + 4, + 8 * history + 15, + 2, + 2 * history + 2, + 0 + ]) + process.stdout.write( + `${JSON.stringify({ history, fullWorkloadBaseline: totals[0], fullWorkloadInternal: totals[1], added, displayControl: totals[2] })}\n` + ) + } + ) + it.each(['withdraw', 'return', 'missing', 'end'] as const)( + 'settles a queue-only %s without resending', + async (outcome) => { + const rig = await createQueuedMessageTestRig({ + idleSweep: { idleMs: 0, intervalMs: 3600000 } + }) + mocks.actualHost = rig.host + try { + const working = await rig.workingSend() + const run = { + ...buildProfileStateCutoverFixture('/fixture').automationRuns[0], + createdAt: Date.now(), + dispatchedAt: Date.now(), + chatSessionId: HOST_TEST_SESSION + } + const q = automationRunOperationId(run, 'reuse-send') + const fields = { body: hostTestMessage('queued'), delivery: 'queue-if-active' as const } + await rig.host.send( + { callerKey: 'client-1' }, + { ...fields, envelope: rig.envelope(fields, 'agentSession.send', q) } + ) + const runtime = { + ensureStructuredAgentSessionHost: async () => {}, + openAgentSessionRecordStore: async () => ({ + getOperationRow: (_caller: string, id: string) => + id === automationRunOperationId(run, 'reuse-send') + ? { outcome: { status: 'succeeded', sessionId: HOST_TEST_SESSION } } + : undefined, + getConversation: () => ({ provider: 'codex', location: { workspaceId: 'workspace-1' } }) + }) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: initialization/receipt reads are scripted; the actual host/journal/queue/observer and eviction/reopen lifecycle execute. + const typedRuntime = runtime as unknown as OrcaRuntimeService + const live = observeAutomationChatRun(typedRuntime, run, new AbortController().signal) + const liveResult = live.then( + (value) => value, + (error) => error + ) + const reads = vi.spyOn(rig.host, 'journalSnapshot') + await eventually(() => expect(reads).toHaveBeenCalled()) + + expect( + chatAutomationRunObservation( + await rig.host.journalSnapshot(HOST_TEST_SESSION), + q, + 'Codex', + await rig.host.queuedSendAnswer(HOST_TEST_SESSION, q) + ) + ).toBeNull() + await rig.stop() + await rig.settleAccepted(working, 'stopped') + const starts = rig.starts.mock.calls.length, + sends = rig.dispatch.mock.calls.length + const { sessions, lifetime, serialize } = rig.host.collaboratorsForTests() + const old = sessions.get(HOST_TEST_SESSION)!.journal + await lifetime.idleSweep.tick() + expect(rig.closeSession).toHaveBeenCalledOnce() + expect(sessions.get(HOST_TEST_SESSION)?.journal).toBe(old) + await serialize(HOST_TEST_SESSION, async () => { + sessions.delete(HOST_TEST_SESSION) + await old.close() + }) + await eventually(() => expect(sessions.get(HOST_TEST_SESSION)?.journal).not.toBe(old)) + await eventually(async () => + expect(await rig.host.queuedSendAnswer(HOST_TEST_SESSION, q)).toMatchObject({ + queued: { state: 'waiting' } + }) + ) + const cached = sessions.get(HOST_TEST_SESSION)!.journal + await serialize(HOST_TEST_SESSION, async () => { + sessions.clear() + await cached.close() + }) + await eventually(() => expect(sessions.has(HOST_TEST_SESSION)).toBe(true)) + expect(rig.starts).toHaveBeenCalledTimes(starts) + expect(rig.dispatch).toHaveBeenCalledTimes(sends) + expect( + chatAutomationRunObservation( + await rig.host.journalSnapshot(HOST_TEST_SESSION), + q, + 'Codex', + await rig.host.queuedSendAnswer(HOST_TEST_SESSION, q) + ) + ).toBeNull() + if (outcome === 'missing' || outcome === 'end') { + if (outcome === 'missing') { + await rig.store['transact']((draft) => draft.records.delete(HOST_TEST_SESSION)) + sessions.delete(HOST_TEST_SESSION) + } else { + rig.host.stopDelivery() + } + expect(await liveResult).toBeInstanceOf(Error) + expect(sessions['observers'].size).toBe(0) + return + } + if (outcome === 'withdraw') { + await rig.deleteQueued(q) + } else { + await rig.stop() + await rig.sendNow(q) + const handoff = await rig.handoffId(q) + await rig.settleRejected(handoff, 'provider refused') + } + expect( + chatAutomationRunObservation( + await rig.host.journalSnapshot(HOST_TEST_SESSION), + q, + 'Codex', + await rig.host.queuedSendAnswer(HOST_TEST_SESSION, q) + ) + ).toMatchObject({ status: 'dispatch_failed' }) + expect(await liveResult).toMatchObject({ status: 'dispatch_failed' }) + expect(run.chatSessionId).toBe(HOST_TEST_SESSION) + } finally { + mocks.actualHost = null + await rig.dispose() + } + } + ) +}) diff --git a/src/main/automations/runtime-chat-run-observer.ts b/src/main/automations/runtime-chat-run-observer.ts new file mode 100644 index 000000000000..72f9c87490e7 --- /dev/null +++ b/src/main/automations/runtime-chat-run-observer.ts @@ -0,0 +1,217 @@ +import { resolveChatAutomationRun } from './automation-chat-run-observation' +export { chatAutomationRunObservation } from './automation-chat-run-observation' +import type { JournalPublication } from '../native-chat/agent-session-wire/structured-agent-session-conversations' +import type { AutomationRun } from '../../shared/automations-types' +import { agentJournalSubmissionKey } from '../../shared/agent-session-journal-item-key' +import { + readAgentJournalTurn, + readAgentJournalTurnOutcome +} from '../../shared/agent-session-turn-record' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import { getStructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-registry' +import { readAutomationRunReceipt } from './automation-run-receipt' +import type { AutomationRunCompletionObservation } from './run-completion-watcher' +import { tuiAgentDisplayName } from '../../shared/tui-agent-display-names' + +export async function observeAutomationChatRun( + runtime: OrcaRuntimeService, + run: AutomationRun, + signal: AbortSignal +): Promise { + await runtime.ensureStructuredAgentSessionHost() + const host = getStructuredAgentSessionHost() + if (!host || !run.chatSessionId) { + throw new Error('Chat session unavailable') + } + const store = await runtime.openAgentSessionRecordStore() + const receipt = readAutomationRunReceipt(store, run) + const agent = + tuiAgentDisplayName(store.getConversation(run.chatSessionId)?.provider ?? 'Agent') ?? 'Agent' + if ( + receipt?.kind !== 'chat' || + receipt.sessionId !== run.chatSessionId || + !receipt.messageId || + !receipt.accepted + ) { + return { + status: 'dispatch_failed', + error: `${agent} could not confirm this run's prompt. Open the chat before running again.` + } + } + const messageId = receipt.messageId + const sessionId = run.chatSessionId + return new Promise((resolve, reject) => { + let release: (() => void) | undefined + let settled = false + let reading = false + let dirty = false + let fingerprint = '' + let source: JournalPublication['source'] = null + let currentJournal: JournalPublication['journal'] = null + let cursor: JournalPublication['cursor'] + let revision = 0 + let submissionId = messageId + let providerItemId: string | null = null + let turnItemId: string | null = null + const finish = (result?: AutomationRunCompletionObservation, error?: unknown): void => { + if (settled) { + return + } + settled = true + source = null + currentJournal = null + cursor = undefined + clearTimeout(deadline) + signal.removeEventListener('abort', abort) + release?.() + if (error) { + reject(error) + } else { + resolve(result!) + } + } + const abort = (): void => finish(undefined, new Error('request_aborted')) + const deadline = setTimeout( + () => + finish({ + status: 'dispatch_failed', + error: `${agent} did not report a result within 6 hours. Open the chat before running again.` + }), + Math.max(1, (run.dispatchedAt ?? run.createdAt) + 6 * 60 * 60 * 1000 - Date.now()) + ) + const interest = (): string => { + const journal = currentJournal + const card = journal?.queuedMessages.get(messageId) + const entry = journal?.submission(card?.consumedAs ?? submissionId) + const root = turnItemId ? journal?.item(journal.canonicalItemId(turnItemId)) : null + const turn = root ? readAgentJournalTurn(root.body) : null + return JSON.stringify([ + card?.state, + card?.consumedAs, + entry?.clientMessageId, + entry?.dispatchState, + entry?.providerItemId, + entry?.answeredInTurn, + root && turn + ? [root.itemId, turn.userItemId, turn.state, readAgentJournalTurnOutcome(turn)] + : null + ]) + } + const read = async (): Promise => { + if (settled) { + return + } + if (reading) { + return + } + reading = true + try { + do { + dirty = false + const version = revision + const readingSource = source + const current = () => !settled && version === revision && readingSource === source + const snapshot = await host.journalSnapshot(sessionId) + if (!current()) { + continue + } + const queued = await host.queuedSendAnswer(sessionId, messageId) + if (!current()) { + continue + } + const { submission, turnItem, observation } = resolveChatAutomationRun( + snapshot, + messageId, + agent, + queued + ) + if (submission) { + submissionId = submission.clientMessageId + providerItemId = submission.providerItemId + turnItemId = turnItem?.itemId ?? null + } + fingerprint = interest() + if (observation) { + finish(observation) + return + } + } while (dirty && !settled) + } catch (error) { + if (!dirty) { + finish(undefined, error) + } + } finally { + reading = false + if (dirty && !settled) { + queueMicrotask(() => void read()) + } + } + } + signal.addEventListener('abort', abort, { once: true }) + if (signal.aborted) { + abort() + return + } + release = host.observeConversationPublications(sessionId, { + next: (hint) => { + if (settled) { + return + } + if (hint.kind === 'end') { + finish(undefined, new Error('Chat session host stopped')) + return + } + currentJournal = hint.journal + const semantic = interest() + const rows = hint.rows + const currentCursor = cursor + const contiguous = + currentCursor && + hint.cursor?.epoch === currentCursor.epoch && + rows?.every( + (row, i) => + row.epoch === currentCursor.epoch && row.seq === currentCursor.sequence + i + 1 + ) && + hint.cursor.sequence === currentCursor.sequence + rows.length + const linked = rows?.some((row) => { + if (row.kind === 'submission') { + return row.queuedMessageId === messageId && row.clientMessageId !== submissionId + } + const mutations = row.kind === 'lifecycle-batch' ? row.mutations : [row] + return mutations.some((item) => { + if (item.kind !== 'item') { + return false + } + const turn = readAgentJournalTurn(item.body) + return ( + (item.body.kind === 'message' && item.body.role === 'user') || + (turn && + !turnItemId && + !item.agentId && + (turn.userItemId === providerItemId || + turn.userItemId === agentJournalSubmissionKey(submissionId))) + ) + }) + }) + const changed = + source !== hint.source || + hint.kind !== 'commit' || + !contiguous || + semantic !== fingerprint || + linked + source = hint.source + cursor = hint.cursor + fingerprint = semantic + if (changed) { + revision++ + dirty = true + queueMicrotask(() => void read()) + } + }, + error: (error) => finish(undefined, error) + }) + if (settled) { + release() + } + }) +} diff --git a/src/main/automations/service-lifecycle.test.ts b/src/main/automations/service-lifecycle.test.ts new file mode 100644 index 000000000000..ee6434c26111 --- /dev/null +++ b/src/main/automations/service-lifecycle.test.ts @@ -0,0 +1,169 @@ +import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { createStore, closeTestStores, testState } from '../persistence/persistence-test-harness' +import { buildProfileStateCutoverFixture } from '../persistence/profile-state-cutover-fixture' +import { AutomationRunLaunchError } from './headless-dispatch' +import { AutomationService } from './service' +import type { Repo } from '../../shared/repo-types' + +vi.mock('electron', () => ({ + app: { getPath: () => testState.dir }, + safeStorage: { + isEncryptionAvailable: () => true, + encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'), + decryptString: (ciphertext: Buffer) => ciphertext.toString('utf-8').slice('encrypted:'.length) + } +})) + +it.each(['chat', 'terminal'] as const)( + 'durably saves an unsuccessful published %s target without a resend', + async (kind) => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-34332-failed-target-')) + const store = await createStore() + try { + store.addRepo({ + ...buildProfileStateCutoverFixture('/repo').repos[0], + id: 'r1', + path: '/repo' + }) + const automation = store.createAutomation({ + name: 'Failed delivery', + prompt: 'check', + agentId: 'claude', + launchSetupPatch: { surface: 'chat' }, + projectId: 'r1', + workspaceMode: 'existing', + workspaceId: 'r1::/repo', + timezone: 'UTC', + rrule: 'FREQ=DAILY', + dtstart: 1 + }) + const published = { + workspaceId: 'actually-created', + sessionKind: kind, + chatSessionId: kind === 'chat' ? 'claude_actual' : null, + terminalSessionId: kind === 'terminal' ? 'actual-tab' : null, + terminalPaneKey: + kind === 'terminal' ? 'actual-tab:11111111-1111-4111-8111-111111111111' : null, + terminalPtyId: kind === 'terminal' ? 'actual-pty' : null + } + const dispatch = vi.fn(async () => { + throw new AutomationRunLaunchError( + 'Claude could not confirm delivery. Open the run.', + published + ) + }) + const service = new AutomationService(store, { chatDispatcher: dispatch }) + service.setWebContents({ isDestroyed: () => false, send: vi.fn() }) + service.setRendererReady() + const failed = await service.runNow(automation.id) + expect(failed).toMatchObject({ ...published, status: 'dispatch_failed' }) + expect(store.listAutomationRuns()[0]).toMatchObject({ + ...published, + status: 'dispatch_failed' + }) + expect(dispatch).toHaveBeenCalledOnce() + service.stop() + } finally { + await closeTestStores() + rmSync(testState.dir, { recursive: true, force: true }) + } + } +) + +const makeRepo = (overrides: Partial = {}): Repo => ({ + id: 'r1', + path: '/repo', + displayName: 'test', + badgeColor: '#fff', + addedAt: 1, + ...overrides +}) + +describe('AutomationService', () => { + beforeEach(() => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-automations-test-')) + vi.useFakeTimers() + }) + + afterEach(async () => { + await closeTestStores() + vi.useRealTimers() + rmSync(testState.dir, { recursive: true, force: true }) + }) + + it.each([undefined, 'terminal', 'chat'] as const)( + 'routes saved surface=%s independently of the Chat callback and renderer readiness', + async (surface) => { + const store = await createStore() + store.addRepo(makeRepo()) + const automation = store.createAutomation({ + name: 'Surface routing', + prompt: 'Check the repo', + agentId: 'claude', + projectId: 'r1', + workspaceMode: 'existing', + workspaceId: 'r1::/repo', + timezone: 'UTC', + rrule: 'FREQ=DAILY', + dtstart: Date.now() + 86_400_000, + ...(surface ? { launchSetupPatch: { surface } } : {}) + }) + const launch = { workspaceId: 'wt1', terminalSessionId: null } + const chat = vi.fn(async () => ({ + ...launch, + sessionKind: 'chat' as const, + chatSessionId: 'claude_chat' + })) + const terminal = vi.fn(async () => launch) + const send = vi.fn() + const desktop = new AutomationService(store, { chatDispatcher: chat }) + desktop.setWebContents({ isDestroyed: () => false, send }) + desktop.start() + expect((await desktop.runNow(automation.id)).status).toBe('skipped_unavailable') + expect(chat).not.toHaveBeenCalled() + desktop.setRendererReady() + vi.setSystemTime(Date.now() + 1) + const dispatched = await desktop.runNow(automation.id) + expect(dispatched.error).toBeNull() + if (surface === 'chat') { + expect(dispatched).toMatchObject({ status: 'dispatched', chatSessionId: 'claude_chat' }) + expect(chat).toHaveBeenCalledOnce() + expect(send).not.toHaveBeenCalled() + } else { + expect(dispatched.status).toBe('dispatching') + expect(send).toHaveBeenCalledWith( + 'automations:dispatchRequested', + expect.objectContaining({ + automation: expect.objectContaining({ + id: automation.id, + prompt: automation.prompt, + workspaceMode: automation.workspaceMode, + workspaceId: automation.workspaceId, + ...(surface ? { surface } : {}) + }), + run: expect.objectContaining({ id: dispatched.id }) + }) + ) + expect(chat).not.toHaveBeenCalled() + } + desktop.stop() + chat.mockClear() + vi.setSystemTime(Date.now() + 1) + const headless = new AutomationService(store, { + allowRemoteHostScheduling: true, + headlessDispatcher: terminal, + chatDispatcher: chat + }) + try { + expect((await headless.runNow(automation.id)).status).toBe('dispatched') + expect(chat).toHaveBeenCalledTimes(surface === 'chat' ? 1 : 0) + expect(terminal).toHaveBeenCalledTimes(surface === 'chat' ? 0 : 1) + } finally { + headless.stop() + } + } + ) +}) diff --git a/src/main/automations/service.ts b/src/main/automations/service.ts index 212e42dc232e..94ca3b5de75b 100644 --- a/src/main/automations/service.ts +++ b/src/main/automations/service.ts @@ -1,6 +1,7 @@ import { AutomationDispatchCancelledError, requestAutomationDispatch, + runAutomationRequestPrecheck, type AutomationRendererChannel } from './automation-dispatch-request' export type { AutomationRendererChannel } from './automation-dispatch-request' @@ -14,7 +15,6 @@ import { } from '../../shared/automations-types' import type { ClaudeUsageStore } from '../claude-usage/store' import type { CodexUsageStore } from '../codex-usage/store' -import { failedPrecheckResult, runAutomationPrecheck } from './precheck-runner' import { captureLegacyRunTarget, resolveAutomationRunTarget, @@ -57,6 +57,7 @@ export class AutomationService { private readonly codexUsage: CodexUsageStore | null private readonly allowRemoteHostScheduling: boolean private readonly headlessDispatcher: HeadlessAutomationDispatcher | null + private readonly chatDispatcher: HeadlessAutomationDispatcher | null private readonly automationLanes = new Map>() /** Close unused completed terminals on headless hosts; return the count. */ releaseFinishedRunTerminals: (() => Promise) | null = null @@ -74,6 +75,7 @@ export class AutomationService { codexUsage?: CodexUsageStore allowRemoteHostScheduling?: boolean headlessDispatcher?: HeadlessAutomationDispatcher + chatDispatcher?: HeadlessAutomationDispatcher terminalObserver?: AutomationRunTerminalObserver onAutomationsChanged?: PublishAutomationsChanged } = {} @@ -84,6 +86,7 @@ export class AutomationService { this.codexUsage = opts.codexUsage ?? null this.allowRemoteHostScheduling = opts.allowRemoteHostScheduling ?? false this.headlessDispatcher = opts.headlessDispatcher ?? null + this.chatDispatcher = opts.chatDispatcher ?? null this.publish = opts.onAutomationsChanged ?? null this.runs = createAutomationRunWriter(store, this.publish) this.completionWatcher = opts.terminalObserver @@ -166,28 +169,9 @@ export class AutomationService { } async runPrecheck(automationId: string, runId: string): Promise { - const automation = this.store.listAutomations().find((entry) => entry.id === automationId) - if (!automation) { - throw new Error('Automation not found.') - } - const run = this.store.listAutomationRuns(automationId).find((entry) => entry.id === runId) - if (!run) { - throw new Error('Automation run not found.') - } - if (run.trigger !== 'scheduled' || !automation.precheck) { - return null - } - const target = this.resolveTarget(automation) - if (!target.ok) { - return failedPrecheckResult(automation.precheck, Date.now(), target.error) - } - return await runAutomationPrecheck({ - precheck: automation.precheck, - target: - automation.executionTargetType === 'ssh' - ? { type: 'ssh', cwd: target.cwd, connectionId: automation.executionTargetId } - : { type: 'local', cwd: target.cwd } - }) + return runAutomationRequestPrecheck(this.store, automationId, runId, (automation) => + this.resolveTarget(automation) + ) } async markDispatchResult(result: AutomationDispatchResult): Promise { @@ -314,6 +298,10 @@ export class AutomationService { isActive: () => !this.stopped && generation === this.dispatchGeneration, getRenderer: () => (this.canDispatchToRenderer() ? this.webContents : null), headlessDispatcher: this.headlessDispatcher, + chatDispatcher: + this.allowRemoteHostScheduling || this.canDispatchToRenderer() + ? this.chatDispatcher + : null, resolveTarget: (current) => this.resolveTarget(current), runPrecheck: () => this.runPrecheck(automation.id, run.id), markDispatchResult: (result) => this.markDispatchResult(result), diff --git a/src/main/native-chat/agent-session-journal/journal-stop-marks.ts b/src/main/native-chat/agent-session-journal/journal-stop-marks.ts index 1f9836a5a9d6..1de9e825267b 100644 --- a/src/main/native-chat/agent-session-journal/journal-stop-marks.ts +++ b/src/main/native-chat/agent-session-journal/journal-stop-marks.ts @@ -15,8 +15,14 @@ export class JournalStopMarks { constructor(private readonly deps: { state: () => JournalReducerState }) {} /** One nonthrowing listener, replaced on each call; settle edges do not trigger commits. */ - observeSettleEdges(listener: () => void): void { - this.onSettleEdge = listener + observeSettleEdges(listener: () => void): () => void { + const registered = () => listener() + this.onSettleEdge = registered + return () => { + if (this.onSettleEdge === registered) { + this.onSettleEdge = null + } + } } latest(): JournalLatestStop | null { diff --git a/src/main/native-chat/agent-session-journal/journal-store.ts b/src/main/native-chat/agent-session-journal/journal-store.ts index f3efaa62d345..53432c789e29 100644 --- a/src/main/native-chat/agent-session-journal/journal-store.ts +++ b/src/main/native-chat/agent-session-journal/journal-store.ts @@ -24,7 +24,7 @@ import { } from '../../../shared/structured-agent-session-live-turn' import { readJournalSince } from './journal-cursor' import type { JournalHostDatabase } from './journal-host-database' -import { journalRowsAfterReader, type JournalLoad } from './journal-open' +import { journalRowsAfterReader } from './journal-open' import { markJournalPendingSubmissionsUnknown, rejectJournalPendingSubmissions, @@ -45,21 +45,16 @@ import type { JournalReadSince, JournalTombstoneInput } from './journal-store-contracts' -import type { JournalQueuedMessages } from './journal-queued-messages' import { journalQueueResumeRowBuilder, journalQueueReopenRowBuilder, journalStopEventRowBuilder } from './journal-stop-and-resume-rows' import type { AgentJournalEpochReason, JournalStopEvent, JournalRow } from './journal-row-schema' -import type { JournalOperationReceipt, JournalRowWriter } from './journal-row-writer' -import type { JournalSubmissionWriter } from './journal-submission-writer' -import type { JournalEpochController } from './journal-epoch-controller' +import type { JournalOperationReceipt } from './journal-row-writer' import { JournalWriteQueue } from './journal-write-queue' import { journalItemExecutionFence, journalItemProvenance } from './journal-item-provenance' import { createJournalStoreCollaborators } from './journal-store-collaborators' -import type { JournalItemAppender } from './journal-item-appender' -import type { JournalStepWriter } from './journal-step-writer' import { journalThreadGoalSource, type JournalThreadGoalSource } from './journal-thread-goal-source' export { AgentSessionJournalError } from './journal-write-guards' @@ -79,15 +74,15 @@ export class AgentSessionJournal { private reopenUnmarked: AgentJournalCursor | null = null private onCommitted: ((rows?: readonly JournalRow[]) => void) | null = null private readonly queue: JournalWriteQueue - private readonly rowWriter: JournalRowWriter - private readonly epochController: JournalEpochController - private readonly itemAppender: JournalItemAppender + private readonly rowWriter: JournalCollaborators['rowWriter'] + private readonly epochController: JournalCollaborators['epochController'] + private readonly itemAppender: JournalCollaborators['itemAppender'] private readonly lifecycleBatchAppender: JournalCollaborators['lifecycleBatchAppender'] - private readonly submissionWriter: JournalSubmissionWriter - private readonly stepWriter: JournalStepWriter + private readonly submissionWriter: JournalCollaborators['submissionWriter'] + private readonly stepWriter: JournalCollaborators['stepWriter'] private readonly restore: () => Promise /** Queued cards never count as owed work. */ - readonly queuedMessages: JournalQueuedMessages + readonly queuedMessages: JournalCollaborators['queuedMessages'] readonly stopMarks: JournalCollaborators['stopMarks'] readonly stops: JournalCollaborators['stops'] readonly context: JournalCollaborators['context'] @@ -109,7 +104,7 @@ export class AgentSessionJournal { readOnly: () => this.database.readOnly, cursor: this.cursor, adopt: (loaded) => { - this.adoptLoadedJournal(loaded) + this.state = loaded.state this.onCommitted?.() }, commit: (rows, savedAt) => { @@ -171,8 +166,14 @@ export class AgentSessionJournal { } /** One nonthrowing listener; undefined rows mean adopted history, an empty array means metadata. */ - observeCommits(listener: (rows?: readonly JournalRow[]) => void): void { - this.onCommitted = listener + observeCommits(listener: (rows?: readonly JournalRow[]) => void): () => void { + const registered: typeof listener = (...args) => listener(...args) + this.onCommitted = registered + return () => { + if (this.onCommitted === registered) { + this.onCommitted = null + } + } } cursor = (): AgentJournalCursor => ({ @@ -264,15 +265,15 @@ export class AgentSessionJournal { } /** Assign revisions here so callers cannot publish reducer-stale upserts. */ - appendItem(...args: Parameters) { + appendItem(...args: Parameters) { return this.itemAppender.append(...args) } - appendClaimingAttachments: JournalItemAppender['appendClaimingAttachments'] = (...args) => + appendClaimingAttachments: typeof this.itemAppender.appendClaimingAttachments = (...args) => this.itemAppender.appendClaimingAttachments(...args) /** Resolve on the write lane; null appends nothing. */ - appendResolvedItem: JournalItemAppender['appendResolved'] = (resolve, options) => + appendResolvedItem: typeof this.itemAppender.appendResolved = (resolve, options) => this.itemAppender.appendResolved(resolve, options) appendTombstone( @@ -332,17 +333,17 @@ export class AgentSessionJournal { appendPlannedLifecycleBatch = (input: JournalPlannedLifecycleBatchInput) => this.lifecycleBatchAppender.appendPlanned(input) - appendSteps: JournalStepWriter['append'] = (steps) => this.stepWriter.append(steps) + appendSteps: typeof this.stepWriter.append = (steps) => this.stepWriter.append(steps) - appendSubmission(...args: Parameters) { + appendSubmission(...args: Parameters) { return this.submissionWriter.append(...args) } - resolveDispatch(...args: Parameters) { + resolveDispatch(...args: Parameters) { return this.submissionWriter.resolveDispatch(...args) } - acceptLate: JournalSubmissionWriter['acceptLate'] = (i) => this.submissionWriter.acceptLate(i) + acceptLate: typeof this.submissionWriter.acceptLate = (i) => this.submissionWriter.acceptLate(i) /** Retire unanswered sends after their execution owner ended, without assuming delivery. */ async markPendingSubmissionsUnknown(fence: number, reason?: string): Promise { @@ -369,12 +370,8 @@ export class AgentSessionJournal { } replaceEpochItems( - ...args: Parameters + ...args: Parameters ): Promise { return this.epochController.replace(...args) } - - private adoptLoadedJournal(loaded: JournalLoad): void { - this.state = loaded.state - } } diff --git a/src/main/native-chat/agent-session-wire/agent-session-subscriber-catch-up.ts b/src/main/native-chat/agent-session-wire/agent-session-subscriber-catch-up.ts index 00c27060413e..59c77a12f0b8 100644 --- a/src/main/native-chat/agent-session-wire/agent-session-subscriber-catch-up.ts +++ b/src/main/native-chat/agent-session-wire/agent-session-subscriber-catch-up.ts @@ -193,7 +193,10 @@ export function deliverToSubscriber( ) subscriber.cursor = page.window.nextCursor if (!page.hasNewer || !port.isActive(subscriber)) { - refreshPublishedWork(delivery, subscriber, journal, work, shared) + // The contiguous page already carries current fields and changed submissions. + if (work && work.workViewKey() !== subscriber.workView) { + refreshPublishedWork(delivery, subscriber, journal, work, shared) + } return } } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts new file mode 100644 index 000000000000..44ffbe9b9268 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts @@ -0,0 +1,55 @@ +import type { AgentJournalRenderItem } from '../../../shared/agent-session-journal-types' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import type { + JournalItemRow, + JournalTombstoneRow, + JournalLifecycleMutation +} from '../agent-session-journal/journal-row-schema' + +export type PromptProjection = { + epoch: string + sequence: number + fence: number | null + items: AgentJournalRenderItem[] + dependencies: Set +} + +export function reusePromptProjection( + journal: Partial>, + prior: PromptProjection | undefined, + cursor: Pick, + liveFence: number | null +): AgentJournalRenderItem[] | undefined { + if ( + prior?.epoch === cursor.epoch && + prior.sequence === cursor.sequence && + prior.fence === liveFence + ) { + return prior.items + } + if (prior?.epoch === cursor.epoch && prior.fence === liveFence && journal.readSince) { + const delta = journal.readSince(prior, 200) + const touches = ( + change: JournalItemRow | JournalTombstoneRow | JournalLifecycleMutation + ): boolean => + prior.dependencies.has(change.itemId) || + (change.kind === 'item' && + (change.body.kind === 'approval' || change.body.kind === 'question')) + if ( + delta.ok && + delta.cursor.sequence === cursor.sequence && + delta.rows.at(-1)?.seq === cursor.sequence && + delta.rows.every( + (row, index) => + row.seq === prior.sequence + index + 1 && + (row.kind === 'lifecycle-batch' + ? !row.mutations.some(touches) + : (row.kind === 'item' || row.kind === 'tombstone') && !touches(row)) + ) + ) { + prior.sequence = cursor.sequence + return prior.items + } + } + return undefined +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts index 4d1c19c8885a..aba64e1346e9 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts @@ -67,7 +67,11 @@ async function liveReader() { batches: events.slice(opened).filter((event) => event.type === 'batch').length } } - return { received } + const hydration = events.findLast((event) => event.type === 'snapshot' || event.type === 'reset') + return { + received, + hydratedCursor: hydration?.page.liveCursor ?? hydration?.page.window.nextCursor + } } async function send(text: string): Promise { @@ -218,7 +222,42 @@ describe('an open chat receives each row once', () => { if (!journal) { throw new Error('the attached chat has no journal') } - const readSince = vi.spyOn(journal, 'readSince') + const hydratedCursor = journal.cursor() + expect(pane.hydratedCursor).toEqual(hydratedCursor) + const reads: { + epoch: string + sequence: number + limit: number | undefined + ok: boolean + returnedCursor: { epoch: string; sequence: number } | null + rowCount: number + rows: { epoch: string; sequence: number; kind: string; itemId: string | null }[] + }[] = [] + const realReadSince = journal.readSince.bind(journal) + const readSince = vi.spyOn(journal, 'readSince').mockImplementation((cursor, limit) => { + const epoch = cursor.epoch + const sequence = cursor.sequence + const result = realReadSince(cursor, limit) + reads.push({ + epoch, + sequence, + limit, + ok: result.ok, + returnedCursor: result.ok + ? { epoch: result.cursor.epoch, sequence: result.cursor.sequence } + : null, + rowCount: result.ok ? result.rows.length : 0, + rows: result.ok + ? result.rows.map((row) => ({ + epoch: row.epoch, + sequence: row.seq, + kind: row.kind, + itemId: 'itemId' in row ? row.itemId : null + })) + : [] + }) + return result + }) sink.appendItem( { provider: 'orca', clientMessageId: 'streamed' }, @@ -229,8 +268,41 @@ describe('an open chat receives each row once', () => { await host.flushStreamedEvents(SESSION) expect(pane.received().statuses).toEqual(['streamed row']) - // Caught-up publication must not reread streamed rows. - expect(readSince).toHaveBeenCalledOnce() + expect(pane.received().batches).toBe(1) + const committedCursor = { epoch: hydratedCursor.epoch, sequence: hydratedCursor.sequence + 1 } + expect(journal.cursor()).toEqual(committedCursor) + const readResult = { + epoch: hydratedCursor.epoch, + sequence: hydratedCursor.sequence, + ok: true, + returnedCursor: committedCursor, + rowCount: 1, + rows: [ + { + epoch: committedCursor.epoch, + sequence: committedCursor.sequence, + kind: 'item', + itemId: 'orca:streamed' + } + ] + } + // Call-time provenance: readForward owns lookahead; reusePromptProjection owns the delta. + const paneHistoryRead = { ...readResult, limit: 201 } + const promptDeltaRead = { ...readResult, limit: 200 } + expect(reads.filter(({ limit }) => limit === paneHistoryRead.limit)).toEqual([paneHistoryRead]) + expect(reads.filter(({ limit }) => limit === promptDeltaRead.limit)).toEqual([promptDeltaRead]) + expect(reads).toHaveLength(2) + expect(readSince).toHaveBeenCalledTimes(2) + expect(reads.reduce((count, read) => count + read.rowCount, 0)).toBe(2) + + const delivered = pane.received() + const settledReads = [...reads] + sink.publish() + await host.flushStreamedEvents(SESSION) + + expect(reads).toEqual(settledReads) + expect(readSince).toHaveBeenCalledTimes(2) + expect(pane.received()).toEqual(delivered) }) it('when a writer publishes the row it appended', async () => { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-background-task-channel.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-background-task-channel.ts index 7c960a983cf5..b57da53780bb 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-background-task-channel.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-background-task-channel.ts @@ -1,3 +1,5 @@ +import { structuredAgentSessionOwnerStatus } from './structured-agent-session-owner-status' +import { queuedSendAnswer } from './structured-agent-session-queued-send-answer' import type { AgentSessionCurrentRequestsRead } from '../../../shared/agent-session-current-requests-wire' import { readCurrentRequestsPiece } from './agent-session-current-requests' import type { @@ -36,6 +38,15 @@ export class StructuredAgentSessionBackgroundTaskChannel { private readonly childWorkIncomplete: (sessionId: string) => boolean = () => false ) {} + handoffStatus = (sessionId: string) => structuredAgentSessionOwnerStatus(this.deps, sessionId) + + /** Full reduction: absence from a bounded page cannot prove a revised/tombstoned item is absent. */ + journalSnapshot = async (sessionId: string) => + (await this.conversation(sessionId)).journal.snapshot() + + queuedSendAnswer = async (sessionId: string, messageId: string) => + queuedSendAnswer((await this.conversation(sessionId)).journal, messageId) + async history( request: AgentSessionHistoryRequest, scope?: AgentSessionHistoryScope, diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-client-delivery.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-client-delivery.ts index 27f3d5e0146e..382275028b7c 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-client-delivery.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-client-delivery.ts @@ -1,6 +1,6 @@ +import type { StructuredAgentSessionConversations } from './structured-agent-session-conversations' import { StructuredAgentSessionSavedStatus } from './structured-agent-session-saved-status' -import { StructuredAgentSessionRequestFailures } from './structured-agent-session-request-failures' -import { structuredAgentSessionFailureWordsContext } from './structured-agent-session-send-preparation' +import { createStructuredAgentSessionHostRequestFailures } from './structured-agent-session-host-request-failures' import { AT_REST_COMMANDS_READ_BUDGET_MS } from './at-rest-command-catalog' import type { AgentSessionStatusSummary } from '../../../shared/agent-session-wire' import { AgentSessionRefusalError } from '../../../shared/agent-session-wire-refusals' @@ -56,18 +56,13 @@ export class StructuredAgentSessionClientDelivery { onChildWorkChanged: (sessionId: string) => void, // Current clients interpret an absent opening roster as no tasks. readBackgroundTasks: NonNullable, - starting?: (sessionId: string) => boolean + starting?: (sessionId: string) => boolean, + private readonly publications?: Pick< + StructuredAgentSessionConversations, + 'publish' | 'endPublications' + > ) { - this.requestFailures = new StructuredAgentSessionRequestFailures({ - sessions, - onFailure: (failure) => deps().onRequestFailure?.(failure), - capturePendingOutput: (input) => deps().adapter.capturePendingOutput?.(input), - wordsContext: (sessionId) => - structuredAgentSessionFailureWordsContext( - deps().store.getRecord(sessionId), - sessions.get(sessionId)?.journal - ) - }) + this.requestFailures = createStructuredAgentSessionHostRequestFailures(sessions, deps) this.savedStatus = new StructuredAgentSessionSavedStatus(deps) this.statusFeed = createStructuredAgentSessionHostStatusFeed({ onPublished: this.savedStatus.observe, @@ -199,6 +194,7 @@ export class StructuredAgentSessionClientDelivery { this.statusFeed.childWorkIncomplete(sessionId) publishStatusAndSettlement = (sessionId: string): void => { + this.publications?.publish(sessionId, 'operational') this.statusFeed.publish(sessionId) const journal = this.sessions.get(sessionId)?.journal if (journal) { @@ -225,6 +221,7 @@ export class StructuredAgentSessionClientDelivery { // Invalidate cached work before every reader re-derives. session.operationalRevision = (session.operationalRevision ?? 0) + 1 const { journal } = session + this.publications?.publish(sessionId, 'operational') if (options.restate) { const fence = structuredAgentSessionConversationFence(this.deps().store, sessionId) this.subscribers.snapshot(sessionId, journal, fence) @@ -240,6 +237,7 @@ export class StructuredAgentSessionClientDelivery { } publishRestored = (sessionId: string): void => { + this.publications?.publish(sessionId, 'reset') this.statusFeed.publish(sessionId, undefined, { replay: true }) this.turnCompletionFeed.observe(sessionId, undefined, { historical: true }) } @@ -270,6 +268,7 @@ export class StructuredAgentSessionClientDelivery { /** Closing handles retains session-list rows; agent-status retains them only while tabs need them. */ closeSession(sessionId: string, options: { listed: boolean }): void { + this.publications?.publish(sessionId, 'detach') this.requestFailures.forget(sessionId) this.sendSettlement.closeSession(sessionId) if (options.listed) { @@ -282,6 +281,7 @@ export class StructuredAgentSessionClientDelivery { } async closeAll(): Promise { + this.publications?.endPublications() await this.drainStatusWrites() this.requestFailures.clear() this.stopAtRestCommandUpdates() diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.test.ts index fcc31395c0f0..8f53bd583caf 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.test.ts @@ -6,7 +6,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { AgentSessionJournalIdentity } from '../../../shared/agent-session-journal-types' import type { AgentSessionJournal } from '../agent-session-journal/journal-store' import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' -import { StructuredAgentSessionConversations } from './structured-agent-session-conversations' +import { + StructuredAgentSessionConversations, + type JournalPublication +} from './structured-agent-session-conversations' import type { StructuredAgentSessionHostSession } from './structured-agent-session-host-types' import { hostTestAttachParams } from './structured-agent-session-host-test-data' import { recordingStructuredAgentSessionLogger } from './structured-agent-session-logger-test-support' @@ -33,7 +36,11 @@ afterEach(async () => { async function openJournal(name: string): Promise { root ??= await mkdtemp(join(tmpdir(), 'orca-conversations-')) - return journals.open({ identity: IDENTITY, stateDirectory: join(root, name) }) + return journals.open({ + identity: IDENTITY, + mintEpoch: () => 'conversations-test-epoch', + stateDirectory: join(root, name) + }) } function session(journal: AgentSessionJournal) { @@ -162,3 +169,174 @@ describe('a conversation delivers what its journal commits', () => { }) }) }) + +describe('internal publication lifetime, independently of presentation', () => { + it('retires source slots on replacement/clear, isolates bad readers, and fences old disposers', async () => { + const conversations = new StructuredAgentSessionConversations({ + deliver: vi.fn(), + logger: recordingStructuredAgentSessionLogger().logger, + now: () => 0 + }) + const old = await openJournal('old'), + current = await openJournal('current') + const next = vi.fn(), + error = vi.fn(), + bad = vi.fn() + const release = conversations.observeConversationPublications('session-1', { next, error }) + conversations.set('session-1', session(old)) + const oldSource = next.mock.lastCall![0].source + conversations.set('session-1', session(old)) + expect(next).toHaveBeenCalledTimes(2) + conversations.set('session-1', session(current)) + expect(next.mock.lastCall![0].source).not.toBe(oldSource) + expect(current.cursor()).toEqual(old.cursor()) + const fail = conversations.observeConversationPublications('session-1', { + next: (hint) => { + if (hint.kind === 'commit') { + throw new Error('consumer') + } + }, + error: bad + }) + await appendStatus(current, 'durable despite consumer failure') + expect(bad).toHaveBeenCalledOnce() + expect(next.mock.lastCall![0]).toMatchObject({ kind: 'commit', journal: current }) + const count = next.mock.calls.length + await appendStatus(old, 'detached') + expect(next).toHaveBeenCalledTimes(count) + const map: Map = conversations + map.clear() + expect(next.mock.lastCall![0]).toMatchObject({ kind: 'detach', source: null, journal: null }) + await appendStatus(current, 'after clear') + expect(next).toHaveBeenCalledTimes(count + 1) + release() + release() + fail() + const successor = { next: vi.fn(), error: vi.fn() } + const releaseB = conversations.observeConversationPublications('session-1', successor) + release() + conversations.publish('session-1', 'operational') + expect(successor.next.mock.lastCall![0].kind).toBe('operational') + const releaseC = conversations.observeConversationPublications('session-1', successor) + releaseB() + releaseB() + conversations.set('session-1', session(current)) + await appendStatus(current, 'independent acquisition survives') + expect(successor.next.mock.lastCall![0].kind).toBe('commit') + let reentrantRelease = () => {} + const reentrant = vi.fn() + const initialFailure = conversations.observeConversationPublications('session-1', { + next: () => { + throw new Error('initial reader') + }, + error: () => { + reentrantRelease = conversations.observeConversationPublications('session-1', { + next: reentrant, + error: vi.fn() + }) + } + }) + initialFailure() + conversations.publish('session-1', 'operational') + expect(reentrant.mock.lastCall![0].kind).toBe('operational') + conversations.endPublications() + expect(successor.next.mock.lastCall![0].kind).toBe('end') + expect(reentrant.mock.lastCall![0].kind).toBe('end') + releaseC() + reentrantRelease() + expect(conversations['observers'].size).toBe(0) + const listener = vi.fn() + const before = old.observeCommits(listener) + const after = old.observeCommits(listener) + before() + before() + await appendStatus(old, 'new listener survives old disposal') + expect(listener).toHaveBeenCalledOnce() + after() + after() + const settle = vi.fn(), + prior = old.stopMarks.observeSettleEdges(settle) + const dispose = old.stopMarks.observeSettleEdges(settle) + prior() + old.stopMarks.settled({ settling: true }, 'turn') + expect(settle).toHaveBeenCalledOnce() + dispose() + expect(error).not.toHaveBeenCalled() + }) + + it('forwards actual host commits, Stop/work/restore/drop/clear/end without starting or sending to read', async () => { + const { createQueuedMessageTestRig } = + await import('./structured-agent-session-queued-message-rig.test-fixture') + const { HOST_TEST_SESSION: id } = await import('./structured-agent-session-host-test-data') + const rig = await createQueuedMessageTestRig({ restartable: true }) + const events: JournalPublication[] = [] + const started = rig.starts.mock.calls.length, + dispatched = rig.dispatch.mock.calls.length + const release = rig.host.observeConversationPublications(id, { + next: (hint) => events.push(hint), + error: (error) => { + throw error + } + }) + try { + const { sessions } = rig.host.collaboratorsForTests() + const first = sessions.get(id)!.journal + await appendStatus(first, 'zero display readers') + expect(events.findLast((event) => event.kind === 'commit')).toMatchObject({ + kind: 'commit', + journal: first, + cursor: first.cursor(), + rows: [expect.objectContaining({ kind: 'item' })] + }) + const cursor = first.cursor() + rig.host.publishWorkChanged(id) + const delivery = rig.host['clientDelivery'] + delivery.publishGenerationEnded(id, { restate: true }) + delivery.publishStatusAndSettlement(id) + delivery.publishRestored(id) + expect(events.slice(-4).map((e) => e.kind)).toEqual([ + 'operational', + 'operational', + 'operational', + 'reset' + ]) + expect(events.at(-1)).toMatchObject({ kind: 'reset', cursor }) + await rig.stop() + expect(events.filter((event) => event.kind === 'operational').length).toBeGreaterThan(1) + await rig.host.close(id, 'evict') + expect(events.some((event) => event.kind === 'detach' && event.source === null)).toBe(true) + const reopened = await rig.host.journalSnapshot(id) + expect(reopened.items).toContainEqual( + expect.objectContaining({ body: { kind: 'status', text: 'zero display readers' } }) + ) + const second = sessions.get(id)!.journal + expect(second).not.toBe(first) + const oldEvents = events.length + // Old journal is closed and its slots are detached. + first.stopMarks.settled({ settling: true }, 'old') + expect(events).toHaveLength(oldEvents) + await second.replaceEpochItems('handle_forked', 1, []) + expect(events.at(-1)?.kind).toBe('reset') + const plain: Map = sessions + plain.clear() + expect(events.at(-1)).toMatchObject({ kind: 'detach', journal: null }) + await rig.host.journalSnapshot(id) + expect(rig.starts).toHaveBeenCalledTimes(started) + expect(rig.dispatch).toHaveBeenCalledTimes(dispatched) + rig.host.stopDelivery() + expect(events.at(-1)?.kind).toBe('end') + const late = vi.fn() + const lateRelease = rig.host.observeConversationPublications(id, { + next: late, + error: vi.fn() + }) + expect(late).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ kind: 'end' })) + lateRelease() + release() + release() + } finally { + release() + await rig.dispose() + } + }) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts index f4e04b943bdf..7238f2bf166a 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts @@ -1,14 +1,33 @@ +import type { AgentJournalCursor } from '../../../shared/agent-session-journal-types' import type { JournalRow } from '../agent-session-journal/journal-row-schema' import type { AgentSessionJournal } from '../agent-session-journal/journal-store' import type { StructuredAgentSessionHostSession } from './structured-agent-session-host-types' import type { StructuredAgentSessionLogger } from './structured-agent-session-logger' +export type JournalPublication = { + kind: 'commit' | 'reset' | 'operational' | 'detach' | 'end' + source: object | null + journal: AgentSessionJournal | null + cursor?: AgentJournalCursor + rows?: readonly JournalRow[] +} +type PublicationObserver = { + next: (hint: JournalPublication) => void + error: (error: unknown) => void +} + /** Bind commit delivery at adoption so writers cannot forget publication. Deliver in a microtask * to isolate durable writes from reader failures; ignore replaced/dropped handles. Activity clocks are memory-only. */ export class StructuredAgentSessionConversations extends Map< string, StructuredAgentSessionHostSession > { + private readonly observers = new Map>() + private readonly attachments = new Map< + string, + { journal: AgentSessionJournal; release: () => void } + >() + private ended = false private readonly activity = new Map() constructor( @@ -33,11 +52,27 @@ export class StructuredAgentSessionConversations extends Map< override set(sessionId: string, session: StructuredAgentSessionHostSession): this { const { journal } = session + if (this.get(sessionId)?.journal === journal) { + this.touch(sessionId) + this.delivery.observe?.(sessionId, journal) + this.delivery.onOpened?.(sessionId) + return super.set(sessionId, session) + } + this.attachments.get(sessionId)?.release() let queued = false - journal.observeCommits((rows) => { - if (this.get(sessionId)?.journal !== journal) { + const source = { + journal, + release: () => { + releaseCommit() + releaseSettle() + } + } + const current = () => this.attachments.get(sessionId) === source + const releaseCommit = journal.observeCommits((rows) => { + if (!current()) { return } + this.publish(sessionId, rows === undefined ? 'reset' : 'commit', rows) try { this.delivery.observe?.(sessionId, journal, rows) } catch (error) { @@ -53,7 +88,7 @@ export class StructuredAgentSessionConversations extends Map< queued = true queueMicrotask(() => { queued = false - if (this.get(sessionId)?.journal !== journal) { + if (!current()) { return } try { @@ -67,9 +102,13 @@ export class StructuredAgentSessionConversations extends Map< } }) }) - journal.stopMarks.observeSettleEdges(() => { + const releaseSettle = journal.stopMarks.observeSettleEdges(() => { + if (!current()) { + return + } + this.publish(sessionId, 'operational') queueMicrotask(() => { - if (this.get(sessionId)?.journal !== journal) { + if (!current()) { return } try { @@ -83,17 +122,112 @@ export class StructuredAgentSessionConversations extends Map< } }) }) + this.attachments.set(sessionId, source) this.activity.set(sessionId, this.delivery.now()) const adopted = super.set(sessionId, session) + this.publish(sessionId, 'reset') this.delivery.observe?.(sessionId, journal) this.delivery.onOpened?.(sessionId) return adopted } + observeConversationPublications(sessionId: string, observer: PublicationObserver): () => void { + if (this.ended) { + this.deliverHint(observer, { kind: 'end', source: null, journal: null }, () => {}) + return () => {} + } + let listeners = this.observers.get(sessionId) + if (!listeners) { + listeners = new Set() + this.observers.set(sessionId, listeners) + } + const registration = { observer } + listeners.add(registration) + const release = () => this.removeObserver(sessionId, registration) + this.deliverHint(observer, this.hint(sessionId, 'reset'), release) + return release + } + + private hint( + sessionId: string, + kind: JournalPublication['kind'], + rows?: readonly JournalRow[] + ): JournalPublication { + const source = kind === 'detach' || kind === 'end' ? undefined : this.attachments.get(sessionId) + return { + kind, + source: source ?? null, + journal: source?.journal ?? null, + cursor: source?.journal.cursor(), + rows + } + } + + publish(sessionId: string, kind: JournalPublication['kind'], rows?: readonly JournalRow[]): void { + const observers = this.observers.get(sessionId) + if (!observers?.size) { + return + } + const hint = this.hint(sessionId, kind, rows) + for (const registration of observers) { + this.deliverHint(registration.observer, hint, () => + this.removeObserver(sessionId, registration) + ) + } + } + + private removeObserver(sessionId: string, registration: { observer: PublicationObserver }): void { + const listeners = this.observers.get(sessionId) + listeners?.delete(registration) + if (listeners?.size === 0) { + this.observers.delete(sessionId) + } + } + + private deliverHint( + observer: PublicationObserver, + hint: JournalPublication, + release: () => void + ): void { + try { + observer.next(hint) + } catch (error) { + release() + try { + observer.error(error) + } catch { + // A consumer cannot fail another consumer or the durable writer. + } + } + } + + endPublications(): void { + if (this.ended) { + return + } + this.ended = true + for (const id of this.observers.keys()) { + this.publish(id, 'end') + } + this.observers.clear() + } + override delete(sessionId: string): boolean { + this.attachments.get(sessionId)?.release() + this.attachments.delete(sessionId) this.delivery.forget?.(sessionId) this.activity.delete(sessionId) - return super.delete(sessionId) + const removed = super.delete(sessionId) + if (removed) { + this.publish(sessionId, 'detach') + } + return removed + } + + override clear(): void { + for (const id of this.keys()) { + this.delete(id) + } } touch(sessionId: string): void { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts index afda0e231154..607776d1a619 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts @@ -276,3 +276,29 @@ describe('a live owner', () => { expect(view.listed()?.status).not.toBe('idle') }) }) + +it('reuses token deltas but refreshes pending prompt dependencies', async () => { + rig = await createQueuedMessageTestRig() + await rig.workingSend() + await leaveUnfinishedWork(rig, { prompt: true }) + const journal = currentJournal(rig) + const before = currentWork(rig).actionablePrompts() + expect(before.map((item) => item.itemId)).toContain(APPROVAL_ID) + const visits = vi.spyOn(journal, 'visitItems') + const token = { provider: 'codex' as const, threadId: 'tokens', turnId: 'tokens', ordinal: 1 } + const body = { kind: 'message' as const, role: 'assistant' as const, blocks: [] } + await journal.appendItem(token, body, { fence: 1, turnScope: { kind: 'thread' } }) + expect(currentWork(rig).actionablePrompts()).toBe(before) + expect(visits).not.toHaveBeenCalled() + await journal.appendTombstone(APPROVAL, { fence: 1 }) + expect(currentWork(rig).actionablePromptIds()).toEqual([]) + expect(visits).toHaveBeenCalledOnce() + await leaveUnfinishedWork(rig, { prompt: true }) + expect(currentWork(rig).actionablePromptIds()).toContain(APPROVAL_ID) + visits.mockClear() + for (let n = 0; n < 201; n++) { + await journal.appendItem(token, body, { fence: 1, turnScope: { kind: 'thread' } }) + } + expect(currentWork(rig).actionablePromptIds()).toContain(APPROVAL_ID) + expect(visits).toHaveBeenCalledOnce() +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.ts index f750f6bbf4dd..f01019164dc7 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.ts @@ -1,3 +1,9 @@ +import { + reusePromptProjection, + type PromptProjection +} from './structured-agent-session-actionable-prompts' +import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { compareAgentJournalItems } from '../../../shared/agent-session-journal-position' import type { AgentSessionConversationView } from '../../../shared/agent-session-conversation-view' import { isHistoricalProviderTimelineItem } from '../agent-session-timeline/provider-timeline-history' import { currentRequestsProjection } from './agent-session-current-requests' @@ -10,7 +16,6 @@ import { type AgentJournalSubmission, type AgentJournalTurnScope } from '../../../shared/agent-session-journal-types' -import { compareAgentJournalItems } from '../../../shared/agent-session-journal-position' import { isQueuedAgentJournalSubmission } from '../../../shared/agent-session-queued-submission' import type { AgentSessionRecord } from '../../../shared/agent-session-record' import type { AgentSessionLatestTurn } from '../../../shared/agent-session-wire' @@ -27,7 +32,8 @@ import { export type StructuredAgentSessionCurrentWorkJournal = Pick< AgentSessionJournal, 'runningTurn' | 'itemFence' | 'visitItems' | 'submissions' | 'wroteBeforeOpen' | 'item' | 'cursor' -> +> & + Partial> export type StructuredAgentSessionWorkEvidence = { record: Pick | null @@ -110,12 +116,6 @@ function structuredAgentSessionHandsOver( ) } -type PromptProjection = { - epoch: string - sequence: number - fence: number | null - items: AgentJournalRenderItem[] -} const promptProjections = new WeakMap() /** Re-read lease evidence per decision; immutable prompts share cursor/fence caches. */ @@ -232,22 +232,27 @@ export class StructuredAgentSessionCurrentWork { actionablePrompts(): AgentJournalRenderItem[] { const cursor = this.journal.cursor() const prior = promptProjections.get(this.journal) - if ( - prior?.epoch === cursor.epoch && - prior.sequence === cursor.sequence && - prior.fence === this.liveFence - ) { - return prior.items + const reusable = reusePromptProjection(this.journal, prior, cursor, this.liveFence) + if (reusable) { + return reusable } + const dependencies = new Set() const items: AgentJournalRenderItem[] = [] this.journal.visitItems((itemId, _sequence, body) => { if ( (body.kind === 'approval' || body.kind === 'question') && - body.resolution.state === 'pending' && - this.isCurrentItem(itemId) + body.resolution.state === 'pending' ) { const item = this.journal.item(itemId) - if (item) { + dependencies.add(itemId) + if (item?.turnScope?.kind === 'turn') { + dependencies.add(item.turnScope.turnItemId) + const turn = readAgentJournalTurn(this.journal.item(item.turnScope.turnItemId)?.body) + if (turn?.userItemId) { + dependencies.add(turn.userItemId) + } + } + if (item && this.isCurrentItem(itemId)) { items.push(item) } } @@ -258,7 +263,12 @@ export class StructuredAgentSessionCurrentWork { items.every((item, index) => item === prior.items[index]) ? prior.items : items - promptProjections.set(this.journal, { ...cursor, fence: this.liveFence, items: stable }) + promptProjections.set(this.journal, { + ...cursor, + fence: this.liveFence, + items: stable, + dependencies + }) return stable } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-host-request-failures.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host-request-failures.ts new file mode 100644 index 000000000000..074703b24c47 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-host-request-failures.ts @@ -0,0 +1,22 @@ +import { StructuredAgentSessionRequestFailures } from './structured-agent-session-request-failures' +import { structuredAgentSessionFailureWordsContext } from './structured-agent-session-send-preparation' +import type { + StructuredAgentSessionHostDeps, + StructuredAgentSessionHostSession +} from './structured-agent-session-host-types' + +export function createStructuredAgentSessionHostRequestFailures( + sessions: Map, + deps: () => StructuredAgentSessionHostDeps +): StructuredAgentSessionRequestFailures { + return new StructuredAgentSessionRequestFailures({ + sessions, + onFailure: (failure) => deps().onRequestFailure?.(failure), + capturePendingOutput: (input) => deps().adapter.capturePendingOutput?.(input), + wordsContext: (sessionId) => + structuredAgentSessionFailureWordsContext( + deps().store.getRecord(sessionId), + sessions.get(sessionId)?.journal + ) + }) +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts index ce8916f826f7..200ec06f3aa1 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts @@ -10,7 +10,6 @@ import * as leases from './structured-agent-session-restart-reconcile' import { StructuredAgentSessionTaskQueue } from './structured-agent-session-task-queue' import * as providerSupport from './structured-agent-session-provider-support' import * as reveal from './structured-agent-session-reveal' -import { structuredAgentSessionOwnerStatus } from './structured-agent-session-owner-status' import { StructuredAgentSessionHostRuntimeState } from './structured-agent-session-host-runtime-state' import { structuredAgentSessionEntryDelegates } from './structured-agent-session-create' import type { StructuredAgentSessionLifetimeContext } from './structured-agent-session-host-lifetime' @@ -25,13 +24,13 @@ import type * as HostTypes from './structured-agent-session-host-types' import { StructuredAgentSessionEventRecovery } from './structured-agent-session-event-recovery' import { StructuredAgentSessionBackgroundTaskChannel as BackgroundTasks } from './structured-agent-session-background-task-channel' import { StructuredAgentSessionClientDelivery } from './structured-agent-session-client-delivery' -import { StructuredAgentSessionConversations } from './structured-agent-session-conversations' +import { createStructuredAgentSessionPublicationWiring } from './structured-agent-session-publication-wiring' import * as resume from './structured-agent-session-restart-resume-host' import { structuredAgentSessionRestartResumeSurfaces } from './structured-agent-session-restart-resume-wiring' import * as conversation from './structured-agent-session-host-delivery' import { wireStructuredAgentSessionQueuedMessages as wireQueuedMessages } from './structured-agent-session-queued-wiring' import * as sessionLogger from './structured-agent-session-logger' -import { sleepStructuredAgentSessionWorkspace } from './structured-agent-session-workspace-sleep' +import { createStructuredAgentSessionWorkspaceSleeper } from './structured-agent-session-workspace-sleep' export type { StructuredAgentSessionHostDeps } from './structured-agent-session-host-types' export class StructuredAgentSessionHost { @@ -39,16 +38,11 @@ export class StructuredAgentSessionHost { () => this.mutationContext(), this ) - private readonly sessions = new StructuredAgentSessionConversations({ - observe: (id, journal, rows) => this.clientDelivery.requestFailures.observe(id, journal, rows), - forget: (id) => this.clientDelivery.requestFailures.forget(id), - deliver: (sessionId, journal) => { - this.subscribers.publish(sessionId, journal) - this.conversationDelivery.afterCommit(sessionId, journal) - }, - deliverSettleEdge: (id, journal) => this.conversationDelivery.afterSettleEdge(id, journal), - logger: sessionLogger.deferredStructuredAgentSessionLogger(() => this.deps.logger), - onOpened: (sessionId) => this.queued.onOpened(sessionId), + private readonly sessions = createStructuredAgentSessionPublicationWiring({ + client: () => this.clientDelivery, + delivery: () => this.conversationDelivery, + opened: (id) => this.queued.onOpened(id), + logger: () => this.deps.logger, now: () => this.now() }) private readonly queued = wireQueuedMessages(this.sessions, () => this.mutationContext()) @@ -61,7 +55,8 @@ export class StructuredAgentSessionHost { (sessionId) => this.restartResume.onAgentStarted(sessionId), (sessionId) => this.backgroundTasks.publish(sessionId), (sessionId) => this.backgroundTasks.read(sessionId), - (sessionId) => this.runtimeState?.startFlights.projectsStarting(sessionId) ?? false + (sessionId) => this.runtimeState?.startFlights.projectsStarting(sessionId) ?? false, + this.sessions ) private readonly subscribers = this.clientDelivery.subscribers private readonly tasks = new StructuredAgentSessionTaskQueue() @@ -194,22 +189,15 @@ export class StructuredAgentSessionHost { this.lifetime.close(sessionId, cause) /** Stop hidden children too, using one bounded host snapshot. */ - sleepWorkspace = (workspaceId: string, markAsleep?: boolean) => - sleepStructuredAgentSessionWorkspace( - { - deps: this.deps, - tasks: this.tasks, - lifetime: this.lifetime, - sessions: this.sessions, - // Starts registered after Stop are newer work. - deliveryRunning: (id) => - this.conversationDelivery.loop.isRunning(id) || this.runtimeState.startFlights.has(id), - childWorkIncomplete: this.clientDelivery.childWorkIncomplete, - publishRecordNotes: this.clientDelivery.publishRecordNotes - }, - workspaceId, - markAsleep - ) + sleepWorkspace = createStructuredAgentSessionWorkspaceSleeper(() => ({ + deps: this.deps, + tasks: this.tasks, + lifetime: this.lifetime, + sessions: this.sessions, + conversationDelivery: this.conversationDelivery, + runtimeState: this.runtimeState, + clientDelivery: this.clientDelivery + })) supportsCreate = (location: AgentSessionExecutionLocation, agent: string): boolean => providerSupport.adapterSupportsCreate(this.deps.adapter, location, agent) @@ -253,7 +241,10 @@ export class StructuredAgentSessionHost { flushStreamedEvents = (id: string): Promise => this.runtimeState.flushEventSink(id) /** Quit stops delivery and queued-card handover. */ - stopDelivery = () => [this.conversationDelivery, this.queued.drain].forEach((d) => d.dispose()) + stopDelivery = () => { + this.sessions.endPublications() + ;[this.conversationDelivery, this.queued.drain].forEach((d) => d.dispose()) + } async flushAllStreamedEvents(options?: { trigger?: 'quit' | 'update' }): Promise { this.stopDelivery() @@ -310,15 +301,18 @@ export class StructuredAgentSessionHost { this.clientDelivery.readCommandsSettled(sessionId, commandsOnRequest) /** Read the store; idle-released chats have no session-map entry. */ - handoffStatus = (sessionId: string) => structuredAgentSessionOwnerStatus(this.deps, sessionId) + handoffStatus = (sessionId: string) => this.backgroundTasks.handoffStatus(sessionId) history: BackgroundTasks['history'] = (...args) => this.backgroundTasks.history(...args) readonly continuationContext: ReturnType - /** Full reduction: absence from a bounded page cannot prove a revised/tombstoned item is absent. */ - journalSnapshot = async (sessionId: string) => - (await this.lifetime.conversation(sessionId)).journal.snapshot() + observeConversationPublications: typeof this.sessions.observeConversationPublications = ( + ...args + ) => this.sessions.observeConversationPublications(...args) + journalSnapshot = (sessionId: string) => this.backgroundTasks.journalSnapshot(sessionId) + queuedSendAnswer = (sessionId: string, messageId: string) => + this.backgroundTasks.queuedSendAnswer(sessionId, messageId) currentWork = this.clientDelivery.readCurrentWork readCurrentRequests: BackgroundTasks['currentRequests'] = (...args) => diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-publication-wiring.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-publication-wiring.ts new file mode 100644 index 000000000000..65870b10fbb8 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-publication-wiring.ts @@ -0,0 +1,29 @@ +import { StructuredAgentSessionConversations } from './structured-agent-session-conversations' +import type { StructuredAgentSessionClientDelivery } from './structured-agent-session-client-delivery' +import type { StructuredAgentSessionConversationDelivery } from './structured-agent-session-host-delivery' +import { + deferredStructuredAgentSessionLogger, + type StructuredAgentSessionLogger +} from './structured-agent-session-logger' + +/** Resolve collaborators only when called: host fields are wired before constructor initialization. */ +export function createStructuredAgentSessionPublicationWiring(input: { + client: () => StructuredAgentSessionClientDelivery + delivery: () => StructuredAgentSessionConversationDelivery + opened: (id: string) => void + logger: () => StructuredAgentSessionLogger + now: () => number +}): StructuredAgentSessionConversations { + return new StructuredAgentSessionConversations({ + observe: (id, journal, rows) => input.client().requestFailures.observe(id, journal, rows), + forget: (id) => input.client().requestFailures.forget(id), + deliver: (id, journal) => { + input.client().subscribers.publish(id, journal) + input.delivery().afterCommit(id, journal) + }, + deliverSettleEdge: (id, journal) => input.delivery().afterSettleEdge(id, journal), + logger: deferredStructuredAgentSessionLogger(input.logger), + onOpened: input.opened, + now: input.now + }) +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts index 0e1c74f7f3fd..c53833a37231 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts @@ -109,7 +109,7 @@ describe('AgentSessionSubscribers', () => { expect(current.items).toHaveLength(size) expect(current.items.at(-1)?.body).toEqual(body(text)) expect(journal.publicRead().snapshot).toBe(current) - expect(events.filter((event) => event.type === 'batch')).toHaveLength(2 * readers) + expect(events.filter((event) => event.type === 'batch')).toHaveLength(readers) expect( events .flatMap((event) => (event.type === 'batch' ? event.batch.items : [])) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-workspace-sleep.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-workspace-sleep.ts index 2f761530d8cc..b967ae3340e1 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-workspace-sleep.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-workspace-sleep.ts @@ -9,6 +9,10 @@ import type { StructuredAgentSessionConversationLifetime } from './structured-ag import type { StructuredAgentSessionConversations } from './structured-agent-session-conversations' import type { StructuredAgentSessionTaskQueue } from './structured-agent-session-task-queue' +import type { StructuredAgentSessionClientDelivery } from './structured-agent-session-client-delivery' +import type { StructuredAgentSessionConversationDelivery } from './structured-agent-session-host-delivery' +import type { StructuredAgentSessionHostRuntimeState } from './structured-agent-session-host-runtime-state' + type WorkspaceSleepHost = { deps: Pick tasks: StructuredAgentSessionTaskQueue @@ -19,6 +23,36 @@ type WorkspaceSleepHost = { publishRecordNotes: (sessionId: string) => void } +export function createStructuredAgentSessionWorkspaceSleeper( + readHost: () => Pick & { + clientDelivery: Pick< + StructuredAgentSessionClientDelivery, + 'childWorkIncomplete' | 'publishRecordNotes' + > + conversationDelivery: Pick + runtimeState: Pick + } +) { + return (workspaceId: string, markAsleep?: boolean) => { + const host = readHost() + return sleepStructuredAgentSessionWorkspace( + { + deps: host.deps, + tasks: host.tasks, + lifetime: host.lifetime, + sessions: host.sessions, + // Starts registered after Stop are newer work. + deliveryRunning: (id) => + host.conversationDelivery.loop.isRunning(id) || host.runtimeState.startFlights.has(id), + childWorkIncomplete: host.clientDelivery.childWorkIncomplete, + publishRecordNotes: host.clientDelivery.publishRecordNotes + }, + workspaceId, + markAsleep + ) + } +} + type WorkspaceSleepVerdict = { stopped: true } | { stopped: false; fence: number } | null /** Return only this call’s current proven stops; markAsleep marks exactly those receipts. */ diff --git a/src/main/persistence/applying-settings/persistence-automation-extra-agent-args.test.ts b/src/main/persistence/applying-settings/persistence-automation-extra-agent-args.test.ts index 084f2a548be9..d8a497c76227 100644 --- a/src/main/persistence/applying-settings/persistence-automation-extra-agent-args.test.ts +++ b/src/main/persistence/applying-settings/persistence-automation-extra-agent-args.test.ts @@ -126,4 +126,60 @@ describe('automation extra agent args persistence', () => { store.updateAutomation(id, { extraAgentArgs: '', reuseSession: true }).reuseSession ).toBe(true) }) + it('atomically saves Chat with retained Terminal extras and keeps legacy records Terminal after reload', async () => { + const store = await createStore() + store.addRepo(makeRepo()) + const legacy = store.createAutomation(BASE) + const chat = store.createAutomation({ + ...BASE, + reuseSession: true, + launchSetupPatch: { + surface: 'chat', + arguments: { kind: 'legacy-extras', value: '--model opus' } + } + }) + expect(chat).toMatchObject({ + surface: 'chat', + extraAgentArgs: '--model opus', + launchSetup: { surface: 'chat', extraAgentArgs: '--model opus' } + }) + expect(() => + store.updateAutomation(chat.id, { launchSetupPatch: { surface: 'terminal' } }) + ).toThrow('fresh session') + expect(store.listAutomations().find((row) => row.id === chat.id)?.surface).toBe('chat') + expect(() => + store.updateAutomation(chat.id, { + extraAgentArgs: '', + launchSetupPatch: { surface: 'terminal' } + }) + ).toThrow('one launch setup') + store.updateAutomation(chat.id, { + reuseSession: false, + launchSetupPatch: { surface: 'terminal', arguments: { kind: 'legacy-extras', value: '' } } + }) + expect(store.listAutomations().find((row) => row.id === chat.id)).toMatchObject({ + surface: 'terminal' + }) + store.flush() + await closeTestStores() + const reloaded = await createStore() + expect(reloaded.listAutomations().find((row) => row.id === legacy.id)?.surface).toBeUndefined() + expect( + reloaded.listAutomations().find((row) => row.id === chat.id)?.extraAgentArgs + ).toBeUndefined() + }) + it('records the old-desktop reconstructed move limitation and preserves surface with the new patch', async () => { + const store = await createStore() + store.addRepo(makeRepo()) + const source = store.createAutomation({ ...BASE, launchSetupPatch: { surface: 'chat' } }) + const oldClientCopy = store.createAutomation({ ...BASE, creationKey: 'old-move' }) + const currentCopy = store.createAutomation({ + ...BASE, + creationKey: 'new-move', + launchSetupPatch: { surface: source.surface } + }) + store.deleteAutomation(source.id) + expect(oldClientCopy.surface).toBeUndefined() + expect(currentCopy.surface).toBe('chat') + }) }) diff --git a/src/main/persistence/scheduling-automations/automation-definition-operations.ts b/src/main/persistence/scheduling-automations/automation-definition-operations.ts index fc318d5e0469..455627881c2a 100644 --- a/src/main/persistence/scheduling-automations/automation-definition-operations.ts +++ b/src/main/persistence/scheduling-automations/automation-definition-operations.ts @@ -1,3 +1,7 @@ +import { + applyAutomationLaunchSetupPatch, + automationWithLaunchSetup +} from '../../../shared/automation-launch-setup' import { randomUUID } from 'node:crypto' import { invalidateLocalWorktreeMetadataPruneInputs } from '../../local-worktree-metadata-prune-gate' import type { @@ -49,7 +53,7 @@ export type AutomationDefinitionOperations = { export function listAutomations(state: PersistedState): Automation[] { return (state.automations ?? []) - .map((automation) => normalizeAutomationSessionReuse(automation)) + .map((automation) => automationWithLaunchSetup(normalizeAutomationSessionReuse(automation))) .sort((left, right) => left.name.localeCompare(right.name)) } @@ -63,7 +67,7 @@ export function createAutomation( (automation) => automation.creationKey === input.creationKey ) if (existing) { - return existing + return automationWithLaunchSetup(existing) } } const repo = operations.state.repos.find((entry) => entry.id === input.projectId) @@ -86,7 +90,8 @@ export function createAutomation( } const schedulerOwner = getAutomationSchedulerOwner(repo) const contexts = getAutomationContextsForRepo(repo, operations.state.projectHostSetups ?? []) - const extraAgentArgs = storedExtraAgentArgs(input.extraAgentArgs) + const setup = applyAutomationLaunchSetupPatch(input) + const extraAgentArgs = storedExtraAgentArgs(setup.extraAgentArgs) const automation: Automation = { id: randomUUID(), ...(input.creationKey ? { creationKey: input.creationKey } : {}), @@ -94,6 +99,7 @@ export function createAutomation( prompt: input.prompt, precheck: normalizeAutomationPrecheck(input.precheck), agentId: input.agentId, + ...(setup.surface ? { surface: setup.surface } : {}), ...(extraAgentArgs !== undefined ? { extraAgentArgs } : {}), // Prefer authority-local contexts; client-assigned runtime IDs cannot identify this store's host. runContext: contexts.runContext ?? input.runContext ?? null, @@ -123,7 +129,7 @@ export function createAutomation( operations.state.automations = [...(operations.state.automations ?? []), automation] operations.recordCreated() operations.flush() - return automation + return automationWithLaunchSetup(automation) } export function updateAutomation( @@ -152,9 +158,12 @@ export function updateAutomation( assertAutomationDestination(options.destination, projectionContext) } // Ignore undefined values preserved by structuredClone; explicit clears use null. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: filtering removes only undefined entries from the validated patch and retains every remaining field's type. const definedUpdates = Object.fromEntries( - Object.entries(updates).filter(([, value]) => value !== undefined) - ) as AutomationUpdateInput + Object.entries(applyAutomationLaunchSetupPatch(updates)).filter( + ([, value]) => value !== undefined + ) + ) as Omit & Pick const repoId = updates.projectId ?? current.projectId const repo = operations.state.repos.find((entry) => entry.id === repoId) const selectorMoveRequested = @@ -255,7 +264,7 @@ export function updateAutomation( entry.id === id ? updated : entry ) operations.flush() - return updated + return automationWithLaunchSetup(updated) } /** Stamp legacy targets once without retargeting user- or migration-owned contexts. */ diff --git a/src/main/persistence/scheduling-automations/automation-run-operations.ts b/src/main/persistence/scheduling-automations/automation-run-operations.ts index af94b921456b..c4d286ac1607 100644 --- a/src/main/persistence/scheduling-automations/automation-run-operations.ts +++ b/src/main/persistence/scheduling-automations/automation-run-operations.ts @@ -198,6 +198,10 @@ export function updateAutomationRun( const updated: AutomationRun = { ...current, status: result.status, + sessionKind: result.sessionKind ?? current.sessionKind, + chatSessionId: Object.hasOwn(result, 'chatSessionId') + ? (result.chatSessionId ?? null) + : current.chatSessionId, workspaceId, workspaceDisplayName: workspaceDisplayName ?? diff --git a/src/main/runtime/rpc/methods/agent-launch-replay.ts b/src/main/runtime/rpc/methods/agent-launch-replay.ts index ad576489731b..9a3f59d232f5 100644 --- a/src/main/runtime/rpc/methods/agent-launch-replay.ts +++ b/src/main/runtime/rpc/methods/agent-launch-replay.ts @@ -13,6 +13,7 @@ import type { AgentSessionOperationRefusalCode } from '../../../../shared/agent-session-operation-ledger' import { resolveAgentSessionReplayOutcome } from '../../../native-chat/agent-session-wire/structured-agent-session-replay-outcome' +import type { TerminalSpawnDispatch } from '../../../agent-launch/agent-launch-not-started' import type { RpcContext } from '../core' import { rpcCallerOperationKey } from '../rpc-caller-identity' import { agentLaunchFailureMessage } from './agent-launch-failure-code' @@ -29,6 +30,15 @@ export function agentLaunchOperationCallerKey(context: Pick void +} + export type AgentLaunchAdmission = /** This caller owns the operation. It alone runs the effect, and it must settle the row. */ | { diff --git a/src/main/runtime/rpc/methods/agent-launch-target-authorization.ts b/src/main/runtime/rpc/methods/agent-launch-target-authorization.ts index 9deb1915e399..6e5dcf323664 100644 --- a/src/main/runtime/rpc/methods/agent-launch-target-authorization.ts +++ b/src/main/runtime/rpc/methods/agent-launch-target-authorization.ts @@ -1,3 +1,4 @@ +import { AGENT_LAUNCH_RUNTIME_CAPABILITY } from '../../../../shared/agent-launch-runtime-capability' /** Authorize workspace creation against its own method allowlist; mobile access to agent.launch must not bypass create restrictions. */ import { AgentLaunchTargetForbiddenError } from '../../../../shared/agent-launch-target-forbidden' @@ -22,3 +23,13 @@ export function assertAgentLaunchTargetAuthorized( throw new AgentLaunchTargetForbiddenError() } } + +/** agent.launch.v2 declares support for both outcomes. CLI/runtime-socket and SSH bridges have no clientKind/capabilities; the desktop renderer is a runtime client and must advertise support. */ +export function supportsAgentLaunch( + context: Pick +): boolean { + return ( + context.clientKind === undefined || + context.clientCapabilities?.includes(AGENT_LAUNCH_RUNTIME_CAPABILITY) === true + ) +} diff --git a/src/main/runtime/rpc/methods/agent-launch.ts b/src/main/runtime/rpc/methods/agent-launch.ts index adda5fbdcb13..ecc26fd36f08 100644 --- a/src/main/runtime/rpc/methods/agent-launch.ts +++ b/src/main/runtime/rpc/methods/agent-launch.ts @@ -2,7 +2,6 @@ * Keep worktree.create's PTY/handle contract for older clients. * operationId adds durable at-most-once execution and recorded replay; unknown outcomes refuse, while stranded-surface recovery remains separate. */ -import { AGENT_LAUNCH_RUNTIME_CAPABILITY } from '../../../../shared/agent-launch-runtime-capability' import { agentLaunchFeatureRequirement } from '../agent-launch-feature-requirement' import { AgentLaunchTabClosedError } from '../../../../shared/agent-launch-tab-closed' import { computeAgentLaunchFingerprint } from '../../../../shared/agent-launch-operation' @@ -13,13 +12,14 @@ import { WORKTREE_CREATE_COLLISION_CODE } from '../../../../shared/new-workspace/worktree-create-collision' import { executeAgentLaunch } from '../../../agent-launch/agent-launch-executor' -import { - trackTerminalSpawnDispatch, - type TerminalSpawnDispatch -} from '../../../agent-launch/agent-launch-not-started' +import { trackTerminalSpawnDispatch } from '../../../agent-launch/agent-launch-not-started' import type { OrcaRuntimeService } from '../../orca-runtime' import { defineMethod, type RpcContext } from '../core' -import { admitAgentLaunchOperation, agentLaunchOperationCallerKey } from './agent-launch-replay' +import { + admitAgentLaunchOperation, + agentLaunchOperationCallerKey, + type ReplaySafeLaunch +} from './agent-launch-replay' import { AgentLaunchExecutionError, agentLaunchRefusalError, @@ -44,7 +44,10 @@ import { selectAgentLaunchTabForCaller } from './agent-launch-caller-selection' import { agentLaunchWorkspaceFactory } from './agent-launch-worktree-creation' -import { assertAgentLaunchTargetAuthorized } from './agent-launch-target-authorization' +import { + assertAgentLaunchTargetAuthorized, + supportsAgentLaunch +} from './agent-launch-target-authorization' import { resolveUnlaunchedIntent } from './agent-launch-intent-resolution' import { publishEarlyTab, @@ -52,28 +55,15 @@ import { type AgentLaunchView } from './agent-launch-tab-publication' -/** agent.launch.v2 declares support for both outcomes. CLI/runtime-socket and SSH bridges have no clientKind/capabilities; the desktop renderer is a runtime client and must advertise support. */ -export function supportsAgentLaunch( - context: Pick -): boolean { - return ( - context.clientKind === undefined || - context.clientCapabilities?.includes(AGENT_LAUNCH_RUNTIME_CAPABILITY) === true - ) -} +export { supportsAgentLaunch } from './agent-launch-target-authorization' -/** What a launch admitted under an operation id carries into its execution. */ -type ReplaySafeLaunch = { - attachOperationId: string - callerKey: string - terminalSpawn: TerminalSpawnDispatch - /** Queue provisional surface/prompt recording without awaiting it; ordered ledger transactions keep final settlement after it. */ - recordSurface: (provisional: AgentLaunchResult) => void +type HostLaunchContext = RpcContext & { + agentLaunchPolicy?: { onSurfacePublished?: (surface: AgentLaunchResult) => void } } async function runAgentLaunch( { intent, decidedMode }: Awaited>, - context: RpcContext, + context: HostLaunchContext, view: AgentLaunchView, replaySafe?: ReplaySafeLaunch ): Promise { @@ -93,6 +83,11 @@ async function runAgentLaunch( workspaces: agentLaunchWorkspaceFactory(context, intent.agent), // The tab is shown as it is published, not after a prompt that can take a minute to land. onSurfacePublished: (surface) => { + try { + context.agentLaunchPolicy?.onSurfacePublished?.(surface) + } catch (error) { + console.warn('[agent-launch] publication bookkeeping failed', error) + } view.early?.surfacePublished(surface) replaySafe?.recordSurface(withPlacement(surface, view)) if (callerNavigationId !== null && view.presentation !== 'background') { @@ -107,7 +102,7 @@ async function runAgentLaunch( * Named operations bypass it: durable admission alone decides execution, including existing-workspace launches. */ function runLegacyAgentLaunch( params: AgentLaunchParams, - context: RpcContext + context: HostLaunchContext ): Promise { // No early tab, as before: only a replay-safe launch shows its tab before its agent exists. const execute = async () => @@ -153,7 +148,7 @@ function activeAgentLaunchesFor(runtime: OrcaRuntimeService): Map { // The tab is the host's first act: admission has a cold cost the user should not watch. @@ -189,7 +184,7 @@ async function executeReplaySafeAgentLaunch( async function executeAdmittedAgentLaunch( params: AgentLaunchParams & { operationId: string }, - context: RpcContext, + context: HostLaunchContext, admission: Extract< Awaited>, { decision: 'execute' } @@ -239,7 +234,7 @@ async function executeAdmittedAgentLaunch( function runReplaySafeAgentLaunch( params: AgentLaunchParams & { operationId: string }, - context: RpcContext + context: HostLaunchContext ): Promise { const callerKey = agentLaunchOperationCallerKey(context) const key = agentSessionOperationKey(callerKey, params.operationId) @@ -301,29 +296,31 @@ export const AGENT_LAUNCH_METHODS = [ requires: agentLaunchFeatureRequirement, permission: 'workspace', params: AgentLaunch, - handler: async (params, context): Promise => { - if (!supportsAgentLaunch(context)) { - throw new Error('agent_launch_unsupported') - } - assertAgentLaunchTargetAuthorized(params.target, context) - if (!params.operationId) { - return runLegacyAgentLaunch(params, context) - } - return runReplaySafeAgentLaunch( - { - ...params, - operationId: params.operationId - }, - context - ).catch((error: unknown) => { - // Preserve the original error contract for callers of the optional-identity method. - if (error instanceof AgentLaunchExecutionError) { - throw error.cause instanceof AgentLaunchTabClosedError - ? agentLaunchTabClosedAnswer(context) - : error.cause - } - throw error - }) - } + handler: (params, context) => launchAgentOnHost(params, context) }) ] + +/** In-process schedules and RPC callers share admission, factories and prompt settlement. */ +export async function launchAgentOnHost( + { operationId, ...params }: AgentLaunchParams, + context: RpcContext, + policy?: HostLaunchContext['agentLaunchPolicy'] +): Promise { + const host = { ...context, agentLaunchPolicy: policy } + if (!supportsAgentLaunch(host)) { + throw new Error('agent_launch_unsupported') + } + assertAgentLaunchTargetAuthorized(params.target, host) + if (!operationId) { + return runLegacyAgentLaunch(params, host) + } + return runReplaySafeAgentLaunch({ ...params, operationId }, host).catch((error: unknown) => { + // Preserve the original error contract for callers of the optional-identity method. + if (error instanceof AgentLaunchExecutionError) { + throw error.cause instanceof AgentLaunchTabClosedError + ? agentLaunchTabClosedAnswer(host) + : error.cause + } + throw error + }) +} diff --git a/src/main/runtime/runtime-automation-controller.ts b/src/main/runtime/runtime-automation-controller.ts index 2c6b95dfb95f..23e5a8ecab7e 100644 --- a/src/main/runtime/runtime-automation-controller.ts +++ b/src/main/runtime/runtime-automation-controller.ts @@ -34,10 +34,8 @@ export type RuntimeAutomationCreateInput = Omit< export type RuntimeAutomationUpdateInput = Omit< AutomationUpdateInput, 'projectId' | 'workspaceId' -> & { - repo?: string - workspace?: string -} +> & + Pick type RuntimeAutomationTargetResolvers = { showRepo: (selector: string) => Promise @@ -127,6 +125,7 @@ export class RuntimeAutomationController { precheck: input.precheck, agentId: input.agentId, extraAgentArgs: input.extraAgentArgs, + launchSetupPatch: input.launchSetupPatch, runContext: input.runContext, sourceContext: input.sourceContext, projectId: target.projectId, @@ -241,6 +240,7 @@ export class RuntimeAutomationController { 'precheck', 'agentId', 'extraAgentArgs', + 'launchSetupPatch', 'runContext', 'sourceContext', 'baseBranch', diff --git a/src/renderer/src/components/automations/AutomationEditorDialog.tsx b/src/renderer/src/components/automations/AutomationEditorDialog.tsx index eab20122fb32..1e8257342195 100644 --- a/src/renderer/src/components/automations/AutomationEditorDialog.tsx +++ b/src/renderer/src/components/automations/AutomationEditorDialog.tsx @@ -1,4 +1,12 @@ import React from 'react' +import { useAppStore } from '@/store' +import { selectAgentLaunchRouteView } from '@/lib/agent-launch-route-input' +import { useChatProgramFacts } from '@/lib/host-chat-program-acquisition' +import { + automationChatSupport, + automationDraftSurface, + automationLaunchWorkspace +} from './automation-launch-surface' import { Dialog, DialogContent } from '@/components/ui/dialog' import { getAgentCatalog } from '@/lib/agent-catalog' import { filterEnabledTuiAgents } from '../../../../shared/tui-agent-selection' @@ -38,6 +46,7 @@ export type AutomationDraft = { name: string prompt: string agentId: TuiAgent + surface?: 'chat' | 'terminal' /** Saved as-is; empty means none. */ extraAgentArgs: string projectId: string @@ -120,6 +129,11 @@ export function AutomationEditorDialog({ const dialogContentRef = React.useRef(null) const isCreateMode = !isEditing const destination = isCreateMode ? createDestination : editDestination + const launchWorkspace = automationLaunchWorkspace(draft, destination?.resolution) + useChatProgramFacts(launchWorkspace, open) + const routeState = useAppStore(selectAgentLaunchRouteView) + const chatSupported = automationChatSupport(routeState, draft, launchWorkspace) + const surface = automationDraftSurface(draft, settings, chatSupported) const visibleAgents = React.useMemo(() => { const enabledIds = new Set( filterEnabledTuiAgents( @@ -178,6 +192,8 @@ export function AutomationEditorDialog({ /> 0} onOpenChange={onOpenChange} onSave={onSave} diff --git a/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.test.tsx b/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.test.tsx index f244e186a2c7..0f59e56df4bf 100644 --- a/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.test.tsx +++ b/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.test.tsx @@ -41,6 +41,8 @@ const DRAFT: AutomationDraft = { function renderSidebar(onDraftChange: (updater: (d: AutomationDraft) => AutomationDraft) => void) { return render( - + + {surface === 'terminal' ? ( + + ) : null} {destination ? (
diff --git a/src/renderer/src/components/automations/AutomationRunDetailsPage.test.tsx b/src/renderer/src/components/automations/AutomationRunDetailsPage.test.tsx index 50b40f8473dc..8e84ac530e51 100644 --- a/src/renderer/src/components/automations/AutomationRunDetailsPage.test.tsx +++ b/src/renderer/src/components/automations/AutomationRunDetailsPage.test.tsx @@ -1,10 +1,12 @@ // @vitest-environment happy-dom import '@testing-library/jest-dom/vitest' -import { cleanup, render, screen } from '@testing-library/react' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import type { AutomationRun } from '../../../../shared/automations-types' import { AutomationRunDetailsPage } from './AutomationRunDetailsPage' +import { i18n, loadRendererUiLanguage } from '@/i18n/i18n' +import { getAutomationRunViewState } from './automation-run-view-state' import type { AutomationRunViewState } from './automation-run-view-state' // These fixtures exercise markdown without rendering diagrams. @@ -75,6 +77,50 @@ describe('AutomationRunDetailsPage', () => { expect(screen.getByRole('button', { name: 'View run' })).toBeEnabled() }) + it('renders the real Chat action from normally loaded Spanish resources', async () => { + const previous = i18n.language + const hadSpanish = i18n.hasResourceBundle('es', 'translation') + try { + await loadRendererUiLanguage('es') + await i18n.changeLanguage('es') + const chat = { ...run, sessionKind: 'chat' as const, chatSessionId: 'pi_saved_chat' } + const viewState = getAutomationRunViewState({ + run: chat, + workspaceExists: true, + terminalTargetExists: false + }) + expect(viewState).toEqual({ + availability: 'chat', + actionLabel: 'Ver ejecución', + statusLabel: 'La ejecución está abierta', + canOpen: true + }) + const open = vi.fn() + render( + {}} + onOpenWorkspace={open} + onBack={() => {}} + /> + ) + fireEvent.click(screen.getByRole('button', { name: 'Ver ejecución' })) + expect(open).toHaveBeenCalledOnce() + expect(chat.chatSessionId).toBe('pi_saved_chat') + } finally { + await i18n.changeLanguage(previous) + if (!hadSpanish) { + i18n.removeResourceBundle('es', 'translation') + } + } + }) + it('hides the open action when the supplied view state disallows it', () => { renderPage({ availability: 'metadata', diff --git a/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx new file mode 100644 index 000000000000..88f1d1162d04 --- /dev/null +++ b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx @@ -0,0 +1,335 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { + AutomationEditorDialog, + AUTOMATION_EDITOR_SEGMENTED_GROUP_CLASS, + AUTOMATION_EDITOR_SEGMENTED_ITEM_CLASS, + type AutomationDraft +} from './AutomationEditorDialog' +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' +import { makeStoreState } from './automations-page-fixtures' +import type { AgentLaunchRouteStore } from '@/lib/agent-launch-route-input' +import { getDefaultSettings } from '../../../../shared/constants' +import type { RuntimeStatus } from '../../../../shared/runtime-types' +import { setLocalRuntimeCapabilitiesForTests } from '@/runtime/local-runtime-capabilities' +import { + AUTOMATION_SURFACE_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY, + STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY +} from '../../../../shared/protocol-version' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import { AutomationSurfaceField } from './AutomationSurfaceField' +import { automationChatSupport, automationDraftSurface } from './automation-launch-surface' +import { buildAutomationEditDraft } from './automation-edit-draft' +import { buildProfileStateCutoverFixture } from '../../../../main/persistence/profile-state-cutover-fixture' + +const registryRpc = vi.hoisted(() => vi.fn()) +vi.mock('@/runtime/runtime-rpc-client', () => ({ callRuntimeRpc: registryRpc })) +vi.mock('@/store', () => ({ + useAppStore: (selector: (state: typeof routeState) => unknown) => selector(routeState) +})) +vi.mock('@/lib/host-chat-program-acquisition', () => ({ useChatProgramFacts: () => undefined })) +vi.mock('./AutomationEditorPromptEditor', () => ({ getAutomationPromptEditorRoot: () => null })) +vi.mock('./AutomationEditorPromptSection', () => ({ AutomationEditorPromptSection: () => null })) +vi.mock('./AutomationEditorSettingsSidebar', () => ({ + AutomationEditorSettingsSidebar: ({ + draft, + settings, + chatSupported, + onDraftChange + }: { + draft: AutomationDraft + settings: GlobalSettings | null + chatSupported: boolean | null + onDraftChange: (updater: (draft: AutomationDraft) => AutomationDraft) => void + }) => ( + + ) +})) +vi.mock('./AutomationEditorDialogHeader', () => ({ AutomationEditorDialogHeader: () => null })) + +import { + loadHostStructuredAgents, + resetHostStructuredAgentsForTests +} from '@/runtime/host-structured-agents' + +function makeRouteState(): AgentLaunchRouteStore { + return { + ...makeStoreState().state, + projects: [], + projectGroups: [], + folderWorkspaces: [], + activeRepoId: null, + activeWorktreeId: null, + settings: getDefaultSettings('/tmp'), + runtimeStatusByEnvironmentId: new Map() + } +} + +let routeState = makeRouteState() +beforeEach(() => { + routeState = makeRouteState() + resetHostStructuredAgentsForTests() + registryRpc.mockReset() +}) +afterEach(() => { + setLocalRuntimeCapabilitiesForTests(null) +}) + +// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this pure control reads only the default switch and selected agent/surface. +const settings = { experimentalNativeChat: true } as GlobalSettings +// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: unrelated editor fields are never read by this control. +const draft = { agentId: 'claude', extraAgentArgs: '--model opus' } as AutomationDraft +afterEach(cleanup) +it('places the current default on the right, highlights it, and preserves arguments through toggles', () => { + const change = vi.fn() + const previous = render( + + + Terminal + + + Chat + + + ) + const previousClasses = Array.from( + previous.container.querySelectorAll( + '[data-slot="toggle-group"], [data-slot="toggle-group-item"]' + ), + (element) => element.className + ) + expect(screen.getByRole('radiogroup').hasAttribute('data-variant')).toBe(false) + expect(screen.getByRole('radio', { name: 'Chat' }).getAttribute('data-state')).toBe('on') + previous.unmount() + const current = render( + + ) + expect( + Array.from( + current.container.querySelectorAll( + '[data-slot="toggle-group"], [data-slot="toggle-group-item"]' + ), + (element) => element.className + ) + ).toEqual(previousClasses) + const radios = screen.getAllByRole('radio') + expect(radios.map((radio) => radio.textContent)).toEqual(['Terminal', 'Chat']) + expect(radios[1].getAttribute('aria-checked')).toBe('true') + fireEvent.click(radios[0]) + expect(change.mock.calls[0][0](draft)).toMatchObject({ + surface: 'terminal', + extraAgentArgs: '--model opus' + }) +}) +it('keeps legacy automations Terminal when the current default is Chat', () => { + const legacy = buildAutomationEditDraft( + buildProfileStateCutoverFixture('/fixture').automations[0] + ) + expect(legacy.surface).toBe('terminal') + expect(automationDraftSurface(legacy, settings, true)).toBe('terminal') +}) +it('reserves disabled controls until host support is known and hides Chat on unsupported hosts', () => { + const props = { draft, settings, onDraftChange: vi.fn() } + const view = render() + expect(screen.getAllByRole('radio').every((radio) => radio.hasAttribute('disabled'))).toBe(true) + expect(screen.getAllByRole('radio').map((radio) => radio.getAttribute('aria-checked'))).toEqual([ + 'false', + 'true' + ]) + view.rerender() + expect(screen.getAllByRole('radio').map((radio) => radio.getAttribute('aria-checked'))).toEqual([ + 'false', + 'true' + ]) + expect(screen.getAllByRole('radio').some((radio) => radio.hasAttribute('disabled'))).toBe(false) + view.rerender() + expect(screen.queryByRole('radio')).toBeNull() +}) +it('rederives unknown native preference for the current agent while explicit and legacy Terminal win', () => { + const perAgent = { ...settings, nativeChatProviders: { claude: false } } + expect(automationDraftSurface(draft, perAgent, null)).toBe('terminal') + expect(automationDraftSurface({ ...draft, agentId: 'codex' }, perAgent, null)).toBe('chat') + const change = vi.fn() + const view = render( + + ) + expect(screen.getAllByRole('radio').map((radio) => radio.textContent)).toEqual([ + 'Chat', + 'Terminal' + ]) + expect(screen.getAllByRole('radio')[1].getAttribute('aria-checked')).toBe('true') + view.rerender( + + ) + expect(screen.getAllByRole('radio').map((radio) => radio.textContent)).toEqual([ + 'Terminal', + 'Chat' + ]) + expect(screen.getAllByRole('radio')[1].getAttribute('aria-checked')).toBe('true') + for (const supported of [null, true, false]) { + expect(automationDraftSurface({ ...draft, surface: 'terminal' }, settings, supported)).toBe( + 'terminal' + ) + } + expect(automationDraftSurface({ ...draft, surface: 'chat' }, settings, false)).toBe('chat') +}) + +it('the real field and footer withhold native Chat until current registration publishes', async () => { + const fixtures = makeStoreState() + const { surface: _legacy, ...newDraft } = buildAutomationEditDraft( + buildProfileStateCutoverFixture('/fixture').automations[0] + ) + const onSave = vi.fn() + const props = { + open: true, + isEditing: false, + isSaving: false, + canSave: true, + repos: fixtures.state.repos, + projectHostSetups: fixtures.state.projectHostSetups, + automationYamlHooksByRepoKey: {}, + getAutomationHooksCacheKey: (id: string) => id, + repoMap: fixtures.repoMap, + worktrees: [...fixtures.worktreeMap.values()], + settings, + draft: { ...newDraft, agentId: 'pi' as const }, + onProjectChange: vi.fn(), + onOpenChange: vi.fn(), + onDraftChange: vi.fn(), + onSetupDecisionTouched: vi.fn(), + onApplyTemplate: vi.fn(), + onSave + } + setLocalRuntimeCapabilitiesForTests(registeredCapabilities) + const view = render() + const button = screen.getByRole('button', { name: 'Create' }) + expect(button.hasAttribute('disabled')).toBe(true) + fireEvent.click(button) + expect(onSave).not.toHaveBeenCalled() + expect(screen.getAllByRole('radio').map((radio) => radio.getAttribute('aria-checked'))).toEqual([ + 'false', + 'true' + ]) + expect(screen.getAllByRole('radio').every((radio) => radio.hasAttribute('disabled'))).toBe(true) + registryRpc.mockResolvedValue({ agents: [{ agent: 'pi', capabilities: {} }] }) + await loadHostStructuredAgents('local', registeredCapabilities, null) + view.rerender() + expect(button.hasAttribute('disabled')).toBe(false) + fireEvent.click(button) + expect(onSave).toHaveBeenCalledOnce() + setLocalRuntimeCapabilitiesForTests(null) + view.rerender( + + ) + expect(button.hasAttribute('disabled')).toBe(false) + view.rerender() + expect(button.hasAttribute('disabled')).toBe(true) + setLocalRuntimeCapabilitiesForTests([]) + view.rerender() + expect(button.hasAttribute('disabled')).toBe(true) +}) + +const registeredCapabilities = [ + AUTOMATION_SURFACE_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY, + STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY +] + +it('observes only established current-runtime facts and retains independent definitive blockers', async () => { + const pi = { ...draft, agentId: 'pi' as const } + const local = { kind: 'git-worktree' as const } + const support = () => automationChatSupport(routeState, pi, local) + setLocalRuntimeCapabilitiesForTests(registeredCapabilities) + expect(support()).toBeNull() + expect(automationChatSupport(routeState, draft, local)).toBe(true) + for (const response of [new Error('offline'), {}]) { + registryRpc.mockImplementation(async () => { + if (response instanceof Error) { + throw response + } + return response + }) + await loadHostStructuredAgents('local', registeredCapabilities, null) + expect(support()).toBeNull() + } + registryRpc.mockResolvedValue({ agents: [] }) + await loadHostStructuredAgents('local', registeredCapabilities, null) + expect(support()).toBe(false) + resetHostStructuredAgentsForTests() + setLocalRuntimeCapabilitiesForTests( + registeredCapabilities.filter( + (c) => c !== STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY + ) + ) + expect(support()).toBe(false) + setLocalRuntimeCapabilitiesForTests( + registeredCapabilities.filter((c) => c !== STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY) + ) + expect(support()).toBe(false) + setLocalRuntimeCapabilitiesForTests(null) + expect(support()).toBeNull() + expect(automationChatSupport(routeState, pi, { ...local, executionHostId: 'ssh:remote' })).toBe( + false + ) + const paired = { ...local, executionHostId: 'runtime:paired' } + const pairedStatus: RuntimeStatus = { + runtimeId: 'A', + rendererGraphEpoch: 0, + graphStatus: 'ready', + authoritativeWindowId: null, + liveTabCount: 0, + liveLeafCount: 0, + capabilities: registeredCapabilities + } + routeState.runtimeStatusByEnvironmentId = new Map([ + ['paired', { checkedAt: 0, status: pairedStatus }] + ]) + registryRpc.mockResolvedValue({ agents: [{ agent: 'pi', capabilities: {} }] }) + await loadHostStructuredAgents('runtime:paired', registeredCapabilities, 'A') + expect(automationChatSupport(routeState, pi, paired)).toBe(true) + routeState.runtimeStatusByEnvironmentId = new Map([ + ['paired', { checkedAt: 0, status: { ...pairedStatus, runtimeId: 'B' } }] + ]) + expect(automationChatSupport(routeState, pi, paired)).toBeNull() + routeState.runtimeStatusByEnvironmentId = new Map([ + [ + 'paired', + { + checkedAt: 0, + status: { + ...pairedStatus, + runtimeId: 'B', + capabilities: registeredCapabilities.filter( + (c) => c !== STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY + ) + } + } + ] + ]) + expect(automationChatSupport(routeState, pi, paired)).toBe(false) +}) diff --git a/src/renderer/src/components/automations/AutomationSurfaceField.tsx b/src/renderer/src/components/automations/AutomationSurfaceField.tsx new file mode 100644 index 000000000000..ccad8bff5e3f --- /dev/null +++ b/src/renderer/src/components/automations/AutomationSurfaceField.tsx @@ -0,0 +1,63 @@ +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' +import { translate } from '@/i18n/i18n' +import { isNativeChatDefaultFor } from '../../../../shared/structured-native-chat-launch-route' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import { Field, AUTOMATION_EDITOR_SECTION_LABEL_CLASS } from './automation-page-parts' +import { automationDraftSurface } from './automation-launch-surface' +import type { AutomationDraft } from './AutomationEditorDialog' + +export function AutomationSurfaceField({ + draft, + settings, + supported, + onDraftChange +}: { + draft: AutomationDraft + settings: GlobalSettings | null + supported: boolean | null + onDraftChange: (updater: (current: AutomationDraft) => AutomationDraft) => void +}): React.JSX.Element | null { + if (supported === false && draft.surface !== 'chat') { + return
+ } + const defaultSurface = isNativeChatDefaultFor(settings, draft.agentId) ? 'chat' : 'terminal' + const surfaces = + defaultSurface === 'chat' ? (['terminal', 'chat'] as const) : (['chat', 'terminal'] as const) + return ( + + { + if (surface === 'chat' || surface === 'terminal') { + onDraftChange((current) => ({ ...current, surface })) + } + }} + > + {surfaces.map((surface) => ( + + {surface === 'chat' + ? translate('components.automations.chat', 'Chat') + : translate('components.automations.terminal', 'Terminal')} + + ))} + + + ) +} diff --git a/src/renderer/src/components/automations/AutomationsPage.create-destination.test.tsx b/src/renderer/src/components/automations/AutomationsPage.create-destination.test.tsx index 9bb05e7efc10..9b6b72005525 100644 --- a/src/renderer/src/components/automations/AutomationsPage.create-destination.test.tsx +++ b/src/renderer/src/components/automations/AutomationsPage.create-destination.test.tsx @@ -2,11 +2,6 @@ /** Choose, display and revalidate the storage destination explicitly; workspace execution cannot infer authority, and stale destinations must preserve the refused form. */ -import { act } from 'react' -import { describe, expect, it, vi } from 'vitest' -import type { Automation } from '../../../../shared/automations-types' -import { hostStableKey } from '../../../../shared/automation-owner-key' -import { unscopedAutomationListRows, type AutomationListRow } from './automation-list-row-identity' import { addRuntimeProject, api, @@ -21,158 +16,300 @@ import { scopedList, settleHostQueries } from './automations-page-test-harness' -import { listedRow } from './automations-page-listed-items' +import { + CHAT_CAPABILITIES, + createRpcCalls, + draftRecord, + holdRuntimeSave, + learnRuntimeAgents, + observeRuntimeIncarnation, + openCreateDialogFor, + runtimeCreateReturns, + save +} from './automations-page-actions-test-harness' +import { act } from 'react' +import { getDefaultSettings } from '../../../../shared/constants' +import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' +import type { HookCheckResult } from '@/runtime/runtime-hooks-client' +import { describe, expect, it, vi } from 'vitest' +import { + addSshHost, + addSshProject, + capableChatDestination, + DESKTOP_SELF_KEY, + observeRuntimeChat, + RUNTIME_SELF_KEY, + SSH_HOST_KEY, + SSH_REPO_ID +} from './automations-page-destination-fixtures' import { makeAutomation, REPO_ID, WORKSPACE_ID } from './automations-page-fixtures' -import type { Repo } from '../../../../shared/repo-types' installAutomationsPageHarness() -const SSH_TARGET_ID = 'ssh-target-1' -const SSH_REPO_ID = 'repo-ssh' -const SSH_HOST_KEY = hostStableKey({ - authority: { kind: 'desktop' }, - selector: { kind: 'ssh', targetId: SSH_TARGET_ID } -}) - -const DESKTOP_SELF_KEY = hostStableKey({ - authority: { kind: 'desktop' }, - selector: { kind: 'self' } -}) -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. */ -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. */ -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 - } - ] -} - -/** A runtime project with the same host-local id as the desktop project. */ -function addCollidingRuntimeProject(): void { - const repo: Repo = { - id: REPO_ID, - displayName: 'orca on m4-air', - path: '/repos/orca', - badgeColor: '#111111', - addedAt: 1, - worktreeBaseRef: 'main', - executionHostId: `runtime:${RUNTIME_ID}` - } - mocks.state.repos = [...(mocks.state.repos as Repo[]), repo] - mocks.state.projectHostSetups = [ - ...mocks.state.projectHostSetups, - { - id: 'setup-runtime-collision', - projectId: 'project-runtime-collision', - hostId: `runtime:${RUNTIME_ID}`, - repoId: REPO_ID, - path: '/repos/orca', - displayName: 'orca on m4-air', - setupState: 'ready', - setupMethod: 'legacy-repo', - createdAt: 1, - updatedAt: 1 - } - ] -} - -/** The runtime answers a create; without this the RPC double returns an empty result. */ -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 } +describe('AutomationsPage create destination', () => { + it.each(['default-off', 'explicit'] as const)( + 'creates %s Terminal on the selected runtime while Chat observation is unavailable', + async (selection) => { + api.automations.list.mockResolvedValue([]) + scopedList([]) + runtimeHost([], []) + runtimeCreateReturns(makeAutomation({ id: 'a-new', name: 'Sweep' })) + mocks.state.runtimeStatusByEnvironmentId = new Map() + addRuntimeProject() + if (selection === 'explicit') { + mocks.state.settings = { ...getDefaultSettings('/tmp'), experimentalNativeChat: true } } - return await previous?.(target, method, params, options) + mocks.state.automationHostFilter = RUNTIME_SELF_FILTER + + await renderPage() + await settleHostQueries() + await openCreateDialogFor(RUNTIME_REPO_ID, RUNTIME_WORKSPACE_ID) + if (selection === 'explicit') { + await act(async () => { + mocks.editorDialog?.onDraftChange((current) => ({ + ...draftRecord(current), + surface: 'terminal' + })) + }) + } + await save() + + // Send the runtime’s own repo ID to its authority; the desktop is always the client authority, not the selected host. + expect(api.automations.create).not.toHaveBeenCalled() + expect(createRpcCalls()).toHaveLength(1) + expect(createRpcCalls()[0]?.[0]).toEqual({ kind: 'environment', environmentId: RUNTIME_ID }) + expect(createRpcCalls()[0]?.[2]).not.toHaveProperty('launchSetupPatch') + expect(createRpcCalls()[0]?.[3]).toMatchObject({ expectedEnvironmentPairingRevision: 4 }) + expect(createRpcCalls()[0]?.[2]).toMatchObject({ + repo: `id:${RUNTIME_REPO_ID}`, + workspace: `id:${RUNTIME_WORKSPACE_ID}`, + destination: { selector: { kind: 'self' } } + }) } ) -} - -async function openCreateDialogFor(projectId: string, workspaceId: string): Promise { - await act(async () => { - mocks.listPanel?.openCreateDialog() - }) - await act(async () => { - mocks.editorDialog?.onDraftChange((current) => ({ - ...(current as Record), - name: 'Sweep', - prompt: 'Do the sweep', - projectId, - workspaceMode: 'existing', - workspaceId - })) - }) -} -async function save(): Promise { - await act(async () => { - mocks.editorDialog?.onSave() - }) -} + it.each([true, false])( + 'retains native intent through unknown support, then saves the known %s outcome', + async (supported) => { + api.automations.list.mockResolvedValue([]) + scopedList([]) + runtimeHost([], []) + addRuntimeProject() + mocks.state.settings = { ...getDefaultSettings('/tmp'), experimentalNativeChat: true } + mocks.state.automationHostFilter = RUNTIME_SELF_FILTER + runtimeCreateReturns(makeAutomation({ id: 'a-new' })) + observeRuntimeChat(null) + if (supported) { + observeRuntimeIncarnation('A') + } + const page = await renderPage() + await settleHostQueries() + await openCreateDialogFor(RUNTIME_REPO_ID, RUNTIME_WORKSPACE_ID) + await act(async () => { + mocks.editorDialog?.onDraftChange((current) => ({ + ...draftRecord(current), + agentId: supported ? 'pi' : 'claude', + extraAgentArgs: '--model opus', + reuseSession: false + })) + }) + await save() + expect(createRpcCalls()).toHaveLength(0) + expect(api.automations.create).not.toHaveBeenCalled() + expect(mocks.editorDialog?.open).toBe(true) + await act(async () => { + mocks.editorDialog?.onDraftChange((current) => ({ + ...draftRecord(current), + surface: 'chat' + })) + }) + await save() + expect(createRpcCalls()).toHaveLength(0) + await act(async () => { + mocks.editorDialog?.onDraftChange((current) => ({ + ...draftRecord(current), + surface: undefined + })) + }) -function createRpcCalls(): unknown[][] { - return mocks.callRuntimeRpc.mock.calls.filter((call) => call[1] === 'automation.create') -} + capableChatDestination() + if (supported) { + observeRuntimeIncarnation('A') + await learnRuntimeAgents('A', ['pi']) + } + if (!supported) { + observeRuntimeChat( + CHAT_CAPABILITIES.filter( + (capability) => capability !== STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY + ) + ) + } + await page.rerender() + await save() + expect(mocks.toastError.mock.calls).toEqual([]) + expect(mocks.editorDialog?.notice).toBeFalsy() + expect(createRpcCalls()).toHaveLength(1) + if (supported) { + expect(createRpcCalls()[0]?.[2]).toMatchObject({ + launchSetupPatch: { + surface: 'chat', + arguments: { kind: 'legacy-extras', value: '--model opus' } + } + }) + } else { + expect(createRpcCalls()[0]?.[2]).not.toHaveProperty('launchSetupPatch') + expect(createRpcCalls()[0]?.[2]).toMatchObject({ extraAgentArgs: '--model opus' }) + } + } + ) -describe('AutomationsPage create destination', () => { - it('creates on the selected runtime rather than under the desktop authority', async () => { + it('retains admitted native Chat when support becomes unknown during the actual hook await', async () => { api.automations.list.mockResolvedValue([]) scopedList([]) runtimeHost([], []) - runtimeCreateReturns(makeAutomation({ id: 'a-new', name: 'Sweep' })) addRuntimeProject() + capableChatDestination() + mocks.state.settings = { ...getDefaultSettings('/tmp'), experimentalNativeChat: true } mocks.state.automationHostFilter = RUNTIME_SELF_FILTER + runtimeCreateReturns(makeAutomation({ id: 'a-new', surface: 'chat' })) + const { checkRuntimeHooks } = await import('@/runtime/runtime-hooks-client') + const held = Promise.withResolvers() + vi.mocked(checkRuntimeHooks).mockReturnValue(held.promise) + try { + const page = await renderPage() + await settleHostQueries() + await openCreateDialogFor(RUNTIME_REPO_ID, RUNTIME_WORKSPACE_ID) + await act(async () => { + mocks.editorDialog?.onDraftChange((current) => ({ + ...draftRecord(current), + workspaceMode: 'new_per_run', + workspaceId: '', + extraAgentArgs: '--model opus' + })) + }) + await save() + expect(checkRuntimeHooks).toHaveBeenCalledWith(`runtime:${RUNTIME_ID}`, RUNTIME_REPO_ID, {}) + expect(createRpcCalls()).toHaveLength(0) + observeRuntimeChat(null) + await page.rerender() + await act(async () => { + held.resolve({ status: 'ok', hasHooks: false, hooks: null, mayNeedUpdate: false }) + }) + await settleHostQueries() + expect(createRpcCalls()).toHaveLength(1) + expect(createRpcCalls()[0]?.[2]).toMatchObject({ + launchSetupPatch: { + surface: 'chat', + arguments: { kind: 'legacy-extras', value: '--model opus' } + } + }) + } finally { + held.resolve({ status: 'ok', hasHooks: false, hooks: null, mayNeedUpdate: false }) + vi.mocked(checkRuntimeHooks).mockResolvedValue({ + status: 'ok', + hasHooks: false, + hooks: null, + mayNeedUpdate: false + }) + } + }) - await renderPage() - await settleHostQueries() - await openCreateDialogFor(RUNTIME_REPO_ID, RUNTIME_WORKSPACE_ID) - await save() + it.each([ + { + name: 'implicit Chat / unknown', + initial: ['pi'], + late: undefined, + surface: undefined, + expected: 'chat' + }, + { + name: 'implicit Chat / exclusion', + initial: ['pi'], + late: [], + surface: undefined, + expected: 'terminal' + }, + { + name: 'explicit Chat / exclusion', + initial: ['pi'], + late: [], + surface: 'chat' as const, + expected: 'chat' + }, + { + name: 'admitted Terminal / unknown', + initial: [], + late: undefined, + surface: undefined, + expected: 'terminal' + }, + { + name: 'admitted Terminal / positive', + initial: [], + late: ['pi'], + surface: undefined, + expected: 'terminal' + } + ])( + 'preserves the admitted operation across the real await: $name', + async ({ initial, late, surface, expected }) => { + const held = await holdRuntimeSave(surface ? { surface } : {}, initial) + if (surface) { + expect(mocks.editorDialog?.draft).toHaveProperty('surface', surface) + } else { + expect(mocks.editorDialog?.draft).not.toHaveProperty('surface') + } + observeRuntimeIncarnation('B') + if (late) { + await learnRuntimeAgents('B', late) + } + await held.page.rerender() + await held.release() + expect(createRpcCalls()).toHaveLength(1) + expect(createRpcCalls()[0]?.[0]).toEqual({ kind: 'environment', environmentId: RUNTIME_ID }) + expect(createRpcCalls()[0]?.[3]).toMatchObject({ expectedEnvironmentPairingRevision: 4 }) + if (expected === 'chat') { + expect(createRpcCalls()[0]?.[2]).toMatchObject({ launchSetupPatch: { surface: 'chat' } }) + } else { + expect(createRpcCalls()[0]?.[2]).not.toHaveProperty('launchSetupPatch') + } + if (surface) { + expect(mocks.editorDialog?.draft).toHaveProperty('surface', surface) + } else { + expect(mocks.editorDialog?.draft).not.toHaveProperty('surface') + } + expect(mocks.toastSuccess).toHaveBeenCalledOnce() + } + ) - // Send the runtime’s own repo ID to its authority; the desktop is always the client authority, not the selected host. - expect(api.automations.create).not.toHaveBeenCalled() + it('retains atomic Chat arguments through a failed current-runtime read and reaches real lower refusal', async () => { + const held = await holdRuntimeSave({ extraAgentArgs: '--model opus' }) + observeRuntimeIncarnation('B') + const previous = mocks.callRuntimeRpc.getMockImplementation() + mocks.callRuntimeRpc.mockImplementation(async (target, method, params, options) => { + if (method === 'agentSession.agents') { + throw new Error('offline') + } + if (method === 'automation.create') { + throw new Error('host refuses create') + } + return await previous?.(target, method, params, options) + }) + const { loadHostStructuredAgents } = await import('@/runtime/host-structured-agents') + const { REGISTERED_CHAT_CAPABILITIES } = await import('./automations-page-actions-test-harness') + await loadHostStructuredAgents(`runtime:${RUNTIME_ID}`, REGISTERED_CHAT_CAPABILITIES, 'B') + await held.page.rerender() + await held.release() expect(createRpcCalls()).toHaveLength(1) - expect(createRpcCalls()[0]?.[0]).toEqual({ kind: 'environment', environmentId: RUNTIME_ID }) - expect(createRpcCalls()[0]?.[3]).toMatchObject({ expectedEnvironmentPairingRevision: 4 }) expect(createRpcCalls()[0]?.[2]).toMatchObject({ - repo: `id:${RUNTIME_REPO_ID}`, - workspace: `id:${RUNTIME_WORKSPACE_ID}`, - destination: { selector: { kind: 'self' } } + launchSetupPatch: { + surface: 'chat', + arguments: { kind: 'legacy-extras', value: '--model opus' } + } }) + expect(mocks.toastSuccess).not.toHaveBeenCalled() + expect(mocks.editorDialog?.open).toBe(true) + expect(mocks.editorDialog?.notice?.message).toBeTruthy() }) it('refuses a desktop project for a runtime destination instead of sending its id', async () => { @@ -198,6 +335,9 @@ describe('AutomationsPage create destination', () => { api.automations.list.mockResolvedValue([]) scopedList([]) addRuntimeProject() + mocks.state.runtimeStatusByEnvironmentId = new Map([ + [RUNTIME_ID, { status: { capabilities: [] } }] + ]) await renderPage() await settleHostQueries() @@ -352,299 +492,6 @@ describe('AutomationsPage create destination', () => { }) }) -describe('AutomationsPage edit fencing', () => { - async function editAndSave(row: AutomationListRow): Promise { - await act(async () => { - void mocks.listPanel?.openEditDialog(row) - }) - await act(async () => { - mocks.editorDialog?.onDraftChange((current) => ({ - ...(current as Record), - name: 'Renamed' - })) - }) - await save() - } - - function updatePreconditions(): unknown[] { - return api.automations.update.mock.calls.map( - ([payload]) => (payload as { expectedOwner?: unknown }).expectedOwner - ) - } - - it('fences the save even when the record cannot be re-read', async () => { - const automation = makeAutomation({ id: 'a-1' }) - api.automations.list.mockResolvedValue([]) - scopedList([automation]) - - await renderPage() - await settleHostQueries() - // The row is gone from its host by the time the form is saved. - scopedList([]) - await editAndSave(listedRow(automation.id)) - - expect(api.automations.update).toHaveBeenCalled() - expect(updatePreconditions()).not.toContain(undefined) - }) - - it('refuses the save when nothing names the record’s host', async () => { - const automation = makeAutomation({ id: 'a-1' }) - // No host answered, so no owner was captured; the legacy-addressable record is also gone. - api.automations.listScoped.mockRejectedValue(new Error('offline')) - api.automations.list.mockResolvedValue([]) - - await renderPage() - await settleHostQueries() - // Only the pre-catalog projection could have supplied the clicked key before any host answered. - await editAndSave(unscopedAutomationListRows([automation])[0]!) - - expect(api.automations.update).not.toHaveBeenCalled() - expect(mocks.editorDialog?.notice?.message).toBeTruthy() - }) -}) - -describe('AutomationsPage edit dialog projects', () => { - it('offers the edited row’s own host projects, not the create destination’s', async () => { - const automation = makeAutomation({ - id: 'a-runtime', - projectId: RUNTIME_REPO_ID, - workspaceId: RUNTIME_WORKSPACE_ID - }) - // The ambient desktop list never held this row; only its captured owner can locate it. - api.automations.list.mockResolvedValue([]) - scopedList([]) - runtimeHost([automation], []) - addRuntimeProject() - - await renderPage() - await settleHostQueries() - await act(async () => { - void mocks.listPanel?.openEditDialog(listedRow(automation.id)) - }) - - expect(mocks.editorDialog?.isEditing).toBe(true) - expect(mocks.editorDialog?.repos?.map((repo) => repo.id)).toEqual([RUNTIME_REPO_ID]) - }) -}) - -describe('AutomationsPage edit destination', () => { - it('names the edited row’s own host, and offers every host it could move to', async () => { - const automation = makeAutomation({ id: 'a-1' }) - api.automations.list.mockResolvedValue([]) - scopedList([automation]) - addSshHost() - addSshProject() - runtimeHost([], []) - - await renderPage() - await settleHostQueries() - await act(async () => { - void mocks.listPanel?.openEditDialog(listedRow(automation.id)) - }) - - const resolution = mocks.editorDialog?.editDestination?.resolution - expect(resolution?.status === 'ready' && resolution.entry.stableKey).toBe(DESKTOP_SELF_KEY) - // Cross-authority moves create at the destination then delete at the source; keep both legal destinations offered. - expect(mocks.editorDialog?.editDestination?.entries.map((entry) => entry.stableKey)).toContain( - RUNTIME_SELF_KEY - ) - expect(mocks.editorDialog?.editDestination?.moveWarning).toBeFalsy() - }) - - it('moves the record across authorities by creating there and deleting here', async () => { - const automation = makeAutomation({ id: 'a-1' }) - api.automations.list.mockResolvedValue([]) - scopedList([automation]) - runtimeHost([], []) - addRuntimeProject() - runtimeCreateReturns(makeAutomation({ id: 'a-moved', projectId: RUNTIME_REPO_ID })) - - await renderPage() - await settleHostQueries() - await act(async () => { - void mocks.listPanel?.openEditDialog(listedRow(automation.id)) - }) - await act(async () => { - mocks.editorDialog?.editDestination?.onSelect(RUNTIME_SELF_KEY) - }) - - expect(mocks.editorDialog?.editDestination?.moveWarning).toBeTruthy() - - await act(async () => { - mocks.editorDialog?.onDraftChange((current) => ({ - ...(current as Record), - projectId: RUNTIME_REPO_ID, - workspaceMode: 'existing', - workspaceId: RUNTIME_WORKSPACE_ID - })) - }) - await save() - - expect(api.automations.update).not.toHaveBeenCalled() - expect(createRpcCalls()).toHaveLength(1) - expect(createRpcCalls()[0]?.[2]).toMatchObject({ - repo: `id:${RUNTIME_REPO_ID}`, - dtstart: automation.dtstart - }) - expect(api.automations.delete).toHaveBeenCalledWith(expect.objectContaining({ id: 'a-1' })) - }) - - it('moves when the destination project has the same host-local id', async () => { - const automation = makeAutomation({ id: 'a-1' }) - api.automations.list.mockResolvedValue([]) - scopedList([automation]) - runtimeHost([], []) - addCollidingRuntimeProject() - runtimeCreateReturns(makeAutomation({ id: 'a-moved', projectId: REPO_ID })) - - await renderPage() - await settleHostQueries() - await act(async () => { - void mocks.listPanel?.openEditDialog(listedRow(automation.id)) - }) - await act(async () => { - mocks.editorDialog?.editDestination?.onSelect(RUNTIME_SELF_KEY) - }) - await save() - - expect(createRpcCalls()).toHaveLength(1) - expect(createRpcCalls()[0]?.[2]).toMatchObject({ repo: `id:${REPO_ID}` }) - expect(api.automations.delete).toHaveBeenCalled() - }) - - it('reuses the move creation key on retry even when the schedule changed', async () => { - const automation = makeAutomation({ id: 'a-1' }) - api.automations.list.mockResolvedValue([]) - scopedList([automation]) - runtimeHost([], []) - addRuntimeProject() - // Transport may fail after create commits; retries need the identical creationKey to avoid duplicates. - let failCreate = true - const previous = mocks.callRuntimeRpc.getMockImplementation() - mocks.callRuntimeRpc.mockImplementation( - async (target: unknown, method: string, params: unknown, options: unknown) => { - if (method === 'automation.create') { - if (failCreate) { - failCreate = false - throw new Error('socket hang up') - } - return { automation: makeAutomation({ id: 'a-moved', projectId: RUNTIME_REPO_ID }) } - } - return await previous?.(target, method, params, options) - } - ) - - await renderPage() - await settleHostQueries() - await act(async () => { - void mocks.listPanel?.openEditDialog(listedRow(automation.id)) - }) - await act(async () => { - mocks.editorDialog?.editDestination?.onSelect(RUNTIME_SELF_KEY) - }) - await act(async () => { - mocks.editorDialog?.onDraftChange((current) => ({ - ...(current as Record), - projectId: RUNTIME_REPO_ID, - workspaceMode: 'existing', - workspaceId: RUNTIME_WORKSPACE_ID, - // Changed schedules mint dtstart per attempt; this volatile field must not re-key a move. - preset: 'custom', - customSchedule: 'FREQ=DAILY;BYHOUR=10;BYMINUTE=0' - })) - }) - - const realNow = Date.now.bind(Date) - let clockSkew = 0 - const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => realNow() + clockSkew) - try { - await save() - clockSkew = 5000 - await save() - } finally { - nowSpy.mockRestore() - } - - const creationKeys = createRpcCalls().map( - (call) => (call[2] as { creationKey?: string }).creationKey - ) - expect(creationKeys).toHaveLength(2) - expect(creationKeys[0]).toBeTruthy() - expect(creationKeys[1]).toBe(creationKeys[0]) - expect(api.automations.delete).toHaveBeenCalledWith(expect.objectContaining({ id: 'a-1' })) - }) - - it('reports a kept original as two live copies, never as a completed move', async () => { - const automation = makeAutomation({ id: 'a-1' }) - api.automations.list.mockResolvedValue([]) - scopedList([automation]) - runtimeHost([], []) - addRuntimeProject() - runtimeCreateReturns(makeAutomation({ id: 'a-moved', projectId: RUNTIME_REPO_ID })) - api.automations.delete.mockRejectedValue(new Error('gone away')) - - await renderPage() - await settleHostQueries() - await act(async () => { - void mocks.listPanel?.openEditDialog(listedRow(automation.id)) - }) - await act(async () => { - mocks.editorDialog?.editDestination?.onSelect(RUNTIME_SELF_KEY) - }) - await act(async () => { - mocks.editorDialog?.onDraftChange((current) => ({ - ...(current as Record), - projectId: RUNTIME_REPO_ID, - workspaceMode: 'existing', - workspaceId: RUNTIME_WORKSPACE_ID - })) - }) - await save() - - expect(createRpcCalls()).toHaveLength(1) - expect(api.automations.delete).toHaveBeenCalled() - expect(mocks.toastError).toHaveBeenCalledWith(expect.stringContaining('could not be deleted')) - expect(mocks.toastSuccess).not.toHaveBeenCalled() - }) - - it('moves the record to the host the user picks, clearing the stranded project', async () => { - const automation = makeAutomation({ id: 'a-1' }) - api.automations.list.mockResolvedValue([]) - scopedList([automation]) - addSshHost() - addSshProject() - - await renderPage() - await settleHostQueries() - await act(async () => { - void mocks.listPanel?.openEditDialog(listedRow(automation.id)) - }) - await act(async () => { - mocks.editorDialog?.editDestination?.onSelect(SSH_HOST_KEY) - }) - - // Keeping the local project selected only defers the same refusal to submit. - expect(mocks.editorDialog?.repos?.map((repo) => repo.id)).toEqual([SSH_REPO_ID]) - expect(mocks.editorDialog?.draft?.projectId).toBe('') - - await act(async () => { - mocks.editorDialog?.onDraftChange((current) => ({ - ...(current as Record), - projectId: SSH_REPO_ID, - workspaceMode: 'new_per_run', - workspaceId: '' - })) - }) - await save() - - expect(api.automations.update).toHaveBeenCalledWith( - expect.objectContaining({ - destination: { selector: { kind: 'ssh', targetId: SSH_TARGET_ID, targetGeneration: 1 } } - }) - ) - }) -}) - describe('AutomationsPage create admission', () => { it('keeps the create button available while every offered host is ineligible', async () => { // Keep Create available to open the dialog that explains repairs, even before any host is eligible. diff --git a/src/renderer/src/components/automations/AutomationsPage.edit-destination.test.tsx b/src/renderer/src/components/automations/AutomationsPage.edit-destination.test.tsx new file mode 100644 index 000000000000..ac7bbdd60ea3 --- /dev/null +++ b/src/renderer/src/components/automations/AutomationsPage.edit-destination.test.tsx @@ -0,0 +1,543 @@ +// @vitest-environment happy-dom + +import { + addRuntimeProject, + api, + installAutomationsPageHarness, + mocks, + renderPage, + runtimeHost, + RUNTIME_ID, + RUNTIME_REPO_ID, + RUNTIME_WORKSPACE_ID, + scopedList, + settleHostQueries +} from './automations-page-test-harness' +import { + CHAT_CAPABILITIES, + createRpcCalls, + draftRecord, + runtimeCreateReturns, + save +} from './automations-page-actions-test-harness' +import { act } from 'react' +import { describe, expect, it, vi } from 'vitest' +import { getDefaultSettings } from '../../../../shared/constants' +import { AUTOMATION_SURFACE_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' +import type { Repo } from '../../../../shared/repo-types' +import { unscopedAutomationListRows, type AutomationListRow } from './automation-list-row-identity' +import { + addSshHost, + addSshProject, + capableChatDestination, + DESKTOP_SELF_KEY, + RUNTIME_SELF_KEY, + SSH_HOST_KEY, + SSH_REPO_ID, + SSH_TARGET_ID +} from './automations-page-destination-fixtures' +import { selfScopedList } from './automations-page-runtime-fixtures' +import { listedRow } from './automations-page-listed-items' +import { makeAutomation, REPO_ID } from './automations-page-fixtures' + +installAutomationsPageHarness() + +/** A runtime project with the same host-local id as the desktop project. */ +function addCollidingRuntimeProject(): void { + const repo: Repo = { + id: REPO_ID, + displayName: 'orca on m4-air', + path: '/repos/orca', + badgeColor: '#111111', + addedAt: 1, + worktreeBaseRef: 'main', + executionHostId: `runtime:${RUNTIME_ID}` + } + mocks.state.repos = [...(mocks.state.repos as Repo[]), repo] + mocks.state.projectHostSetups = [ + ...mocks.state.projectHostSetups, + { + id: 'setup-runtime-collision', + projectId: 'project-runtime-collision', + hostId: `runtime:${RUNTIME_ID}`, + repoId: REPO_ID, + path: '/repos/orca', + displayName: 'orca on m4-air', + setupState: 'ready', + setupMethod: 'legacy-repo', + createdAt: 1, + updatedAt: 1 + } + ] +} + +describe('AutomationsPage edit fencing', () => { + async function editAndSave(row: AutomationListRow): Promise { + await act(async () => { + void mocks.listPanel?.openEditDialog(row) + }) + await act(async () => { + mocks.editorDialog?.onDraftChange((current) => ({ + ...(current as Record), + name: 'Renamed' + })) + }) + await save() + } + + function updatePreconditions(): unknown[] { + return api.automations.update.mock.calls.map( + ([payload]) => (payload as { expectedOwner?: unknown }).expectedOwner + ) + } + + it('fences the save even when the record cannot be re-read', async () => { + const automation = makeAutomation({ id: 'a-1' }) + mocks.state.settings = { ...getDefaultSettings('/tmp'), experimentalNativeChat: true } + const { setLocalRuntimeCapabilitiesForTests } = + await import('@/runtime/local-runtime-capabilities') + setLocalRuntimeCapabilitiesForTests(null) + api.automations.list.mockResolvedValue([]) + scopedList([automation]) + + await renderPage() + await settleHostQueries() + // The row is gone from its host by the time the form is saved. + scopedList([]) + await editAndSave(listedRow(automation.id)) + + expect(api.automations.update).toHaveBeenCalled() + expect(updatePreconditions()).not.toContain(undefined) + expect(api.automations.update.mock.calls[0]?.[0]).toMatchObject({ + updates: { name: 'Renamed' } + }) + expect(api.automations.update.mock.calls[0]?.[0]?.updates).not.toHaveProperty( + 'launchSetupPatch' + ) + }) + + it('keeps saved Chat explicit through the real edit reread and atomically clears arguments', async () => { + const automation = makeAutomation({ surface: 'chat', extraAgentArgs: '--model opus' }) + api.automations.list.mockResolvedValue([]) + scopedList([automation]) + const { setLocalRuntimeCapabilitiesForTests } = + await import('@/runtime/local-runtime-capabilities') + setLocalRuntimeCapabilitiesForTests(CHAT_CAPABILITIES) + const page = await renderPage() + await settleHostQueries() + await act(async () => { + void mocks.listPanel?.openEditDialog(listedRow(automation.id)) + }) + await act(async () => { + mocks.editorDialog?.onDraftChange((current) => ({ + ...draftRecord(current), + extraAgentArgs: '' + })) + }) + const held = Promise.withResolvers>() + api.automations.listScoped.mockClear().mockReturnValueOnce(held.promise) + try { + await save() + expect(api.automations.listScoped).toHaveBeenCalled() + expect(api.automations.update).not.toHaveBeenCalled() + setLocalRuntimeCapabilitiesForTests(null) + await page.rerender() + await act(async () => { + held.resolve(selfScopedList([automation])) + }) + await settleHostQueries() + expect(api.automations.update).toHaveBeenCalledOnce() + expect(api.automations.update.mock.calls[0]?.[0]).toMatchObject({ + id: automation.id, + expectedOwner: { selector: { kind: 'self' } }, + updates: { + launchSetupPatch: { surface: 'chat', arguments: { kind: 'legacy-extras', value: '' } } + } + }) + expect(api.automations.update.mock.calls[0]?.[0]?.updates).not.toHaveProperty( + 'extraAgentArgs' + ) + expect(mocks.toastSuccess).toHaveBeenCalledOnce() + } finally { + held.resolve(selfScopedList([automation])) + } + }) + + it('refuses the save when nothing names the record’s host', async () => { + const automation = makeAutomation({ id: 'a-1' }) + // No host answered, so no owner was captured; the legacy-addressable record is also gone. + api.automations.listScoped.mockRejectedValue(new Error('offline')) + api.automations.list.mockResolvedValue([]) + + await renderPage() + await settleHostQueries() + // Only the pre-catalog projection could have supplied the clicked key before any host answered. + await editAndSave(unscopedAutomationListRows([automation])[0]!) + + expect(api.automations.update).not.toHaveBeenCalled() + expect(mocks.editorDialog?.notice?.message).toBeTruthy() + }) +}) + +describe('AutomationsPage edit dialog projects', () => { + it('offers the edited row’s own host projects, not the create destination’s', async () => { + const automation = makeAutomation({ + id: 'a-runtime', + projectId: RUNTIME_REPO_ID, + workspaceId: RUNTIME_WORKSPACE_ID + }) + // The ambient desktop list never held this row; only its captured owner can locate it. + api.automations.list.mockResolvedValue([]) + scopedList([]) + runtimeHost([automation], []) + addRuntimeProject() + + await renderPage() + await settleHostQueries() + await act(async () => { + void mocks.listPanel?.openEditDialog(listedRow(automation.id)) + }) + + expect(mocks.editorDialog?.isEditing).toBe(true) + expect(mocks.editorDialog?.repos?.map((repo) => repo.id)).toEqual([RUNTIME_REPO_ID]) + }) +}) + +describe('AutomationsPage edit destination', () => { + it('names the edited row’s own host, and offers every host it could move to', async () => { + const automation = makeAutomation({ id: 'a-1' }) + api.automations.list.mockResolvedValue([]) + scopedList([automation]) + addSshHost() + addSshProject() + runtimeHost([], []) + + await renderPage() + await settleHostQueries() + await act(async () => { + void mocks.listPanel?.openEditDialog(listedRow(automation.id)) + }) + + const resolution = mocks.editorDialog?.editDestination?.resolution + expect(resolution?.status === 'ready' && resolution.entry.stableKey).toBe(DESKTOP_SELF_KEY) + // Cross-authority moves create at the destination then delete at the source; keep both legal destinations offered. + expect(mocks.editorDialog?.editDestination?.entries.map((entry) => entry.stableKey)).toContain( + RUNTIME_SELF_KEY + ) + expect(mocks.editorDialog?.editDestination?.moveWarning).toBeFalsy() + }) + + it.each(['legacy', 'chat'] as const)( + 'moves the saved %s record across authorities by creating there and deleting here', + async (surface) => { + const automation = makeAutomation({ + id: 'a-1', + ...(surface === 'chat' ? { surface, extraAgentArgs: '--model opus' } : {}) + }) + api.automations.list.mockResolvedValue([]) + scopedList([automation]) + runtimeHost([], []) + addRuntimeProject() + if (surface === 'chat') { + capableChatDestination() + } + const removed = Promise.withResolvers() + api.automations.delete.mockReturnValueOnce(removed.promise) + runtimeCreateReturns( + makeAutomation({ + id: 'a-moved', + projectId: RUNTIME_REPO_ID, + ...(surface === 'chat' ? { surface, extraAgentArgs: '--model opus' } : {}) + }) + ) + + await renderPage() + await settleHostQueries() + await act(async () => { + void mocks.listPanel?.openEditDialog(listedRow(automation.id)) + }) + await act(async () => { + mocks.editorDialog?.editDestination?.onSelect(RUNTIME_SELF_KEY) + }) + + expect(mocks.editorDialog?.editDestination?.moveWarning).toBeTruthy() + + await act(async () => { + mocks.editorDialog?.onDraftChange((current) => ({ + ...(current as Record), + projectId: RUNTIME_REPO_ID, + workspaceMode: 'existing', + workspaceId: RUNTIME_WORKSPACE_ID + })) + }) + await save() + + expect(api.automations.update).not.toHaveBeenCalled() + expect(createRpcCalls()).toHaveLength(1) + expect(createRpcCalls()[0]?.[2]).toMatchObject({ + repo: `id:${RUNTIME_REPO_ID}`, + dtstart: automation.dtstart + }) + if (surface === 'chat') { + expect(createRpcCalls()[0]?.[2]).toMatchObject({ + launchSetupPatch: { + surface: 'chat', + arguments: { kind: 'legacy-extras', value: '--model opus' } + } + }) + } + expect(api.automations.delete).toHaveBeenCalledWith(expect.objectContaining({ id: 'a-1' })) + const createIndex = mocks.callRuntimeRpc.mock.calls.findIndex( + (call) => call[1] === 'automation.create' + ) + expect(mocks.callRuntimeRpc.mock.invocationCallOrder[createIndex]).toBeLessThan( + api.automations.delete.mock.invocationCallOrder[0] + ) + expect(mocks.toastSuccess).not.toHaveBeenCalled() + await act(async () => { + removed.resolve() + }) + await settleHostQueries() + expect(mocks.toastSuccess).toHaveBeenCalledWith(expect.stringContaining('moved')) + } + ) + + it.each(['old', 'unknown', 'refused'] as const)( + 'preserves the saved Chat source when destination creation is %s', + async (outcome) => { + const automation = makeAutomation({ + id: 'a-1', + surface: 'chat', + extraAgentArgs: '--model opus' + }) + api.automations.list.mockResolvedValue([]) + scopedList([automation]) + runtimeHost([], []) + addRuntimeProject() + capableChatDestination() + runtimeCreateReturns(makeAutomation({ id: 'a-moved', surface: 'chat' })) + await renderPage() + await settleHostQueries() + await act(async () => { + void mocks.listPanel?.openEditDialog(listedRow(automation.id)) + }) + await act(async () => { + mocks.editorDialog?.editDestination?.onSelect(RUNTIME_SELF_KEY) + }) + await act(async () => { + mocks.editorDialog?.onDraftChange((current) => ({ + ...draftRecord(current), + projectId: RUNTIME_REPO_ID, + workspaceMode: 'existing', + workspaceId: RUNTIME_WORKSPACE_ID + })) + }) + const { resetAutomationCapabilityProbes } = await import('./automation-scoped-list-client') + resetAutomationCapabilityProbes() + mocks.getRuntimeEnvironmentStatus.mockClear() + if (outcome === 'old') { + mocks.getRuntimeEnvironmentStatus.mockResolvedValue({ + capabilities: CHAT_CAPABILITIES.filter( + (capability) => capability !== AUTOMATION_SURFACE_RUNTIME_CAPABILITY + ) + }) + } else if (outcome === 'unknown') { + mocks.getRuntimeEnvironmentStatus.mockRejectedValue(new Error('capabilities unavailable')) + } else { + const previous = mocks.callRuntimeRpc.getMockImplementation() + mocks.callRuntimeRpc.mockImplementation(async (...args) => { + if (args[1] === 'automation.create') { + throw new Error('destination refused create') + } + return await previous?.(...args) + }) + } + await save() + expect(mocks.getRuntimeEnvironmentStatus).toHaveBeenCalled() + expect(createRpcCalls()).toHaveLength(outcome === 'refused' ? 1 : 0) + if (outcome === 'old') { + expect(mocks.editorDialog?.notice?.message).toContain('run automations in Chat') + } + if (outcome === 'refused') { + expect(createRpcCalls()[0]?.[2]).toMatchObject({ launchSetupPatch: { surface: 'chat' } }) + } + expect(api.automations.delete).not.toHaveBeenCalled() + expect(mocks.toastSuccess).not.toHaveBeenCalled() + expect(mocks.editorDialog?.open).toBe(true) + expect(mocks.editorDialog?.notice?.message).toBeTruthy() + } + ) + + it('moves when the destination project has the same host-local id', async () => { + const automation = makeAutomation({ id: 'a-1' }) + api.automations.list.mockResolvedValue([]) + scopedList([automation]) + runtimeHost([], []) + addCollidingRuntimeProject() + runtimeCreateReturns(makeAutomation({ id: 'a-moved', projectId: REPO_ID })) + + await renderPage() + await settleHostQueries() + await act(async () => { + void mocks.listPanel?.openEditDialog(listedRow(automation.id)) + }) + await act(async () => { + mocks.editorDialog?.editDestination?.onSelect(RUNTIME_SELF_KEY) + }) + await save() + + expect(createRpcCalls()).toHaveLength(1) + expect(createRpcCalls()[0]?.[2]).toMatchObject({ repo: `id:${REPO_ID}` }) + expect(api.automations.delete).toHaveBeenCalled() + }) + + it('reuses the move creation key on retry even when the schedule changed', async () => { + const automation = makeAutomation({ id: 'a-1' }) + api.automations.list.mockResolvedValue([]) + scopedList([automation]) + runtimeHost([], []) + addRuntimeProject() + // Transport may fail after create commits; retries need the identical creationKey to avoid duplicates. + let failCreate = true + const previous = mocks.callRuntimeRpc.getMockImplementation() + mocks.callRuntimeRpc.mockImplementation( + async (target: unknown, method: string, params: unknown, options: unknown) => { + if (method === 'automation.create') { + if (failCreate) { + failCreate = false + throw new Error('socket hang up') + } + return { automation: makeAutomation({ id: 'a-moved', projectId: RUNTIME_REPO_ID }) } + } + return await previous?.(target, method, params, options) + } + ) + + await renderPage() + await settleHostQueries() + await act(async () => { + void mocks.listPanel?.openEditDialog(listedRow(automation.id)) + }) + await act(async () => { + mocks.editorDialog?.editDestination?.onSelect(RUNTIME_SELF_KEY) + }) + await act(async () => { + mocks.editorDialog?.onDraftChange((current) => ({ + ...(current as Record), + projectId: RUNTIME_REPO_ID, + workspaceMode: 'existing', + workspaceId: RUNTIME_WORKSPACE_ID, + // Changed schedules mint dtstart per attempt; this volatile field must not re-key a move. + preset: 'custom', + customSchedule: 'FREQ=DAILY;BYHOUR=10;BYMINUTE=0' + })) + }) + + const realNow = Date.now.bind(Date) + let clockSkew = 0 + const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => realNow() + clockSkew) + try { + await save() + clockSkew = 5000 + await save() + } finally { + nowSpy.mockRestore() + } + + const creationKeys = createRpcCalls().map( + (call) => (call[2] as { creationKey?: string }).creationKey + ) + expect(creationKeys).toHaveLength(2) + expect(creationKeys[0]).toBeTruthy() + expect(creationKeys[1]).toBe(creationKeys[0]) + expect(api.automations.delete).toHaveBeenCalledWith(expect.objectContaining({ id: 'a-1' })) + }) + + it('reports a kept saved-Chat original as two live copies, never as a completed move', async () => { + const automation = makeAutomation({ + id: 'a-1', + surface: 'chat', + extraAgentArgs: '--model opus' + }) + api.automations.list.mockResolvedValue([]) + scopedList([automation]) + runtimeHost([], []) + addRuntimeProject() + capableChatDestination() + runtimeCreateReturns( + makeAutomation({ + id: 'a-moved', + projectId: RUNTIME_REPO_ID, + surface: 'chat', + extraAgentArgs: '--model opus' + }) + ) + api.automations.delete.mockRejectedValue(new Error('gone away')) + + await renderPage() + await settleHostQueries() + await act(async () => { + void mocks.listPanel?.openEditDialog(listedRow(automation.id)) + }) + await act(async () => { + mocks.editorDialog?.editDestination?.onSelect(RUNTIME_SELF_KEY) + }) + await act(async () => { + mocks.editorDialog?.onDraftChange((current) => ({ + ...(current as Record), + projectId: RUNTIME_REPO_ID, + workspaceMode: 'existing', + workspaceId: RUNTIME_WORKSPACE_ID + })) + }) + await save() + + expect(createRpcCalls()).toHaveLength(1) + expect(createRpcCalls()[0]?.[2]).toMatchObject({ + launchSetupPatch: { + surface: 'chat', + arguments: { kind: 'legacy-extras', value: '--model opus' } + } + }) + expect(api.automations.delete).toHaveBeenCalled() + expect(mocks.toastError).toHaveBeenCalledWith(expect.stringContaining('could not be deleted')) + expect(mocks.toastSuccess).not.toHaveBeenCalled() + }) + + it('moves the record to the host the user picks, clearing the stranded project', async () => { + const automation = makeAutomation({ id: 'a-1' }) + api.automations.list.mockResolvedValue([]) + scopedList([automation]) + addSshHost() + addSshProject() + + await renderPage() + await settleHostQueries() + await act(async () => { + void mocks.listPanel?.openEditDialog(listedRow(automation.id)) + }) + await act(async () => { + mocks.editorDialog?.editDestination?.onSelect(SSH_HOST_KEY) + }) + + // Keeping the local project selected only defers the same refusal to submit. + expect(mocks.editorDialog?.repos?.map((repo) => repo.id)).toEqual([SSH_REPO_ID]) + expect(mocks.editorDialog?.draft?.projectId).toBe('') + + await act(async () => { + mocks.editorDialog?.onDraftChange((current) => ({ + ...(current as Record), + projectId: SSH_REPO_ID, + workspaceMode: 'new_per_run', + workspaceId: '' + })) + }) + await save() + + expect(api.automations.update).toHaveBeenCalledWith( + expect.objectContaining({ + destination: { selector: { kind: 'ssh', targetId: SSH_TARGET_ID, targetGeneration: 1 } } + }) + ) + }) +}) diff --git a/src/renderer/src/components/automations/automation-capability-probe.ts b/src/renderer/src/components/automations/automation-capability-probe.ts index 4628c4f306bd..e89bcdfdb2e5 100644 --- a/src/renderer/src/components/automations/automation-capability-probe.ts +++ b/src/renderer/src/components/automations/automation-capability-probe.ts @@ -1,3 +1,8 @@ +import type { + AutomationCreateInput, + AutomationUpdateInput +} from '../../../../shared/automations-types' +import { AUTOMATION_SURFACE_RUNTIME_CAPABILITY } from '../../../../shared/automation-runtime-capabilities' import { getRuntimeEnvironmentStatus } from '@/runtime/runtime-rpc-client' import type { AutomationAuthorityRef } from '../../../../shared/automation-owner-ref' import { @@ -190,3 +195,35 @@ export { AUTOMATION_LIST_HOST_SCOPE_UPDATE_REQUIRED_MESSAGE, AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY } + +/** Old hosts keep their terminal contract; an explicit chat must refuse before a move creates anything. */ +export async function prepareAutomationLaunchSetup< + T extends AutomationCreateInput | AutomationUpdateInput +>( + authority: AutomationAuthorityRef, + input: T +): Promise & Pick> { + const { launchSetupPatch, ...legacy } = input + if (launchSetupPatch === undefined) { + await assertExtraAgentArgsSupported(authority, input.extraAgentArgs) + return input + } + if (input.extraAgentArgs !== undefined) { + throw new Error('Save automation arguments through one launch setup change.') + } + if (authority.kind === 'desktop') { + return input + } + const status = await sharedCapabilityProbe(authority, capabilityProbeKey(authority)) + if (status.capabilities?.includes(AUTOMATION_SURFACE_RUNTIME_CAPABILITY)) { + return input + } + if (launchSetupPatch.surface === 'chat') { + throw new AutomationHostScopeUnsupportedError( + 'Update Orca on this host to run automations in Chat.' + ) + } + const extraAgentArgs = launchSetupPatch.arguments?.value + await assertExtraAgentArgsSupported(authority, extraAgentArgs) + return { ...legacy, ...(extraAgentArgs !== undefined ? { extraAgentArgs } : {}) } +} diff --git a/src/renderer/src/components/automations/automation-draft-model.ts b/src/renderer/src/components/automations/automation-draft-model.ts index bb89afab1272..65ab0cb013f8 100644 --- a/src/renderer/src/components/automations/automation-draft-model.ts +++ b/src/renderer/src/components/automations/automation-draft-model.ts @@ -44,9 +44,9 @@ export function getAgentLabel(agentId: string): string { /** The field's error, or null when the draft's extras can be saved. */ export function getDraftExtraAgentArgsError( - draft: Pick + draft: Pick ): string | null { - if (!hasExtraAgentArgs(draft.extraAgentArgs)) { + if (draft.surface === 'chat' || !hasExtraAgentArgs(draft.extraAgentArgs)) { return null } const parsed = parseExtraAgentArgs({ @@ -58,9 +58,10 @@ export function getDraftExtraAgentArgsError( /** Reuse can't carry extras; the field offers a switch instead of flipping it silently. */ export function draftExtraAgentArgsNeedFreshSession( - draft: Pick + draft: Pick ): boolean { return ( + draft.surface !== 'chat' && hasExtraAgentArgs(draft.extraAgentArgs) && draft.workspaceMode === 'existing' && draft.reuseSession diff --git a/src/renderer/src/components/automations/automation-edit-draft.ts b/src/renderer/src/components/automations/automation-edit-draft.ts index ab5f08aa2770..1aa82cbba4b6 100644 --- a/src/renderer/src/components/automations/automation-edit-draft.ts +++ b/src/renderer/src/components/automations/automation-edit-draft.ts @@ -16,6 +16,7 @@ export function buildAutomationEditDraft(automation: Automation): AutomationDraf name: automation.name, prompt: automation.prompt, agentId: automation.agentId, + surface: automation.launchSetup?.surface ?? automation.surface ?? 'terminal', extraAgentArgs: automation.extraAgentArgs ?? '', projectId: getAutomationRunRepoId(automation), workspaceMode: automation.workspaceMode, diff --git a/src/renderer/src/components/automations/automation-extra-agent-args-capability.test.ts b/src/renderer/src/components/automations/automation-extra-agent-args-capability.test.ts index a144ccd170d5..5260a5a2a21d 100644 --- a/src/renderer/src/components/automations/automation-extra-agent-args-capability.test.ts +++ b/src/renderer/src/components/automations/automation-extra-agent-args-capability.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { + AUTOMATION_SURFACE_RUNTIME_CAPABILITY, AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY, AUTOMATION_EXTRA_AGENT_ARGS_RUNTIME_CAPABILITY, AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY @@ -95,4 +96,56 @@ describe('extra agent args capability gate', () => { ) expect(callRuntimeRpc.mock.calls[0]?.[2]).toMatchObject({ extraAgentArgs: '--model opus' }) }) + it('preserves a surface-only patch on an intermediate host without claiming complete picker setup', async () => { + const { createAutomationForDestination } = await client() + getRuntimeEnvironmentStatus.mockResolvedValue({ + capabilities: [...CURRENT_HOST.capabilities, AUTOMATION_SURFACE_RUNTIME_CAPABILITY] + }) + callRuntimeRpc.mockResolvedValue({ automation: { id: 'a1' } }) + await createAutomationForDestination( + RUNTIME, + { + ...INPUT, + launchSetupPatch: { + surface: 'chat', + arguments: { kind: 'legacy-extras', value: '--model opus' } + } + }, + { selector: { kind: 'self' } } + ) + expect(callRuntimeRpc.mock.calls[0]?.[2]).toMatchObject({ + launchSetupPatch: { + surface: 'chat', + arguments: { kind: 'legacy-extras', value: '--model opus' } + } + }) + expect(callRuntimeRpc.mock.calls[0]?.[2]).not.toHaveProperty('extraAgentArgs') + }) + it('keeps old-host Terminal writes legacy-shaped and refuses Chat before a move can write', async () => { + const { createAutomationForDestination } = await client() + getRuntimeEnvironmentStatus.mockResolvedValue(CURRENT_HOST) + callRuntimeRpc.mockResolvedValue({ automation: { id: 'a1' } }) + await createAutomationForDestination( + RUNTIME, + { + ...INPUT, + launchSetupPatch: { + surface: 'terminal', + arguments: { kind: 'legacy-extras', value: '--model opus' } + } + }, + { selector: { kind: 'self' } } + ) + expect(callRuntimeRpc.mock.calls[0]?.[2]).toMatchObject({ extraAgentArgs: '--model opus' }) + expect(callRuntimeRpc.mock.calls[0]?.[2]).not.toHaveProperty('launchSetupPatch') + callRuntimeRpc.mockClear() + await expect( + createAutomationForDestination( + RUNTIME, + { ...INPUT, launchSetupPatch: { surface: 'chat' } }, + { selector: { kind: 'self' } } + ) + ).rejects.toThrow('Update Orca on this host') + expect(callRuntimeRpc).not.toHaveBeenCalled() + }) }) diff --git a/src/renderer/src/components/automations/automation-host-client.ts b/src/renderer/src/components/automations/automation-host-client.ts index f59f70fba3fb..060c418a870b 100644 --- a/src/renderer/src/components/automations/automation-host-client.ts +++ b/src/renderer/src/components/automations/automation-host-client.ts @@ -1,6 +1,6 @@ import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' import { getPairedWebClientEnvironmentId } from '@/lib/paired-web-client-host' -import { assertEnvironmentSupportsExtraAgentArgs } from './automation-capability-probe' +import { prepareAutomationLaunchSetup } from './automation-capability-probe' import type { Automation, AutomationCreateInput, @@ -145,13 +145,16 @@ export async function updateAutomationForTarget( sourceTarget?: AutomationHostTarget | null ): Promise { const target = getAutomationOwnerTarget(automation, sourceTarget) - if (target.kind === 'environment') { - await assertEnvironmentSupportsExtraAgentArgs(target.environmentId, updates.extraAgentArgs) - } + const prepared = await prepareAutomationLaunchSetup( + target.kind === 'environment' + ? { kind: 'runtime', environmentId: target.environmentId, pairingRevision: 0 } + : { kind: 'desktop' }, + updates + ) const result = await callRuntimeRpc<{ automation: Automation }>( target, 'automation.update', - { id: automation.id, updates: toRuntimeAutomationUpdateInput(updates) }, + { id: automation.id, updates: toRuntimeAutomationUpdateInput(prepared) }, { timeoutMs: 15_000 } ) return result.automation diff --git a/src/renderer/src/components/automations/automation-launch-surface.ts b/src/renderer/src/components/automations/automation-launch-surface.ts new file mode 100644 index 000000000000..8847248590f8 --- /dev/null +++ b/src/renderer/src/components/automations/automation-launch-surface.ts @@ -0,0 +1,108 @@ +import type { Automation, AutomationUpdateInput } from '../../../../shared/automations-types' +import { hasExtraAgentArgs } from '../../../../shared/automation-extra-agent-args' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import { + AUTOMATION_SURFACE_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY, + STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY +} from '../../../../shared/protocol-version' +import { isNativeChatDefaultFor } from '../../../../shared/structured-native-chat-launch-route' +import { + buildAgentLaunchRouteInput, + type AgentLaunchRouteStore, + type ProspectiveWorkspace +} from '@/lib/agent-launch-route-input' +import { structuredAgentLaunchSupport } from '@/lib/agent-launch-routing' +import type { AutomationDraft } from './AutomationEditorDialog' +import type { AutomationCreateDestinationResolution } from './automation-create-destination' + +export function automationLaunchWorkspace( + draft: AutomationDraft, + destination?: AutomationCreateDestinationResolution +): ProspectiveWorkspace { + const ready = destination?.status === 'ready' ? destination : null + return { + kind: 'git-worktree', + repoId: draft.projectId, + ...(draft.workspaceMode === 'existing' && draft.workspaceId + ? { worktreeId: draft.workspaceId } + : {}), + ...(ready + ? { + executionHostId: + ready.destination.selector.kind === 'ssh' + ? `ssh:${ready.destination.selector.targetId}` + : ready.authority.kind === 'runtime' + ? `runtime:${ready.authority.environmentId}` + : 'local' + } + : {}) + } +} + +export function automationChatSupport( + state: AgentLaunchRouteStore, + draft: AutomationDraft, + workspace: ProspectiveWorkspace +): boolean | null { + const input = buildAgentLaunchRouteInput(state, { agent: draft.agentId, workspace }) + if ( + input.hostCapabilities !== null && + !input.hostCapabilities.includes(AUTOMATION_SURFACE_RUNTIME_CAPABILITY) + ) { + return false + } + // Satisfy only unlearned facts to expose independent blockers, never to establish support. + const possible = structuredAgentLaunchSupport({ + ...input, + hostCapabilities: input.hostCapabilities ?? [ + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY, + STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY + ], + hostStructuredAgents: input.hostStructuredAgents ?? [input.agent] + }) + if (!possible.supported) { + return false + } + return input.hostCapabilities === null + ? null + : structuredAgentLaunchSupport(input).supported + ? true + : null +} + +export function automationDraftSurface( + draft: AutomationDraft, + settings: GlobalSettings | null, + chatSupported: boolean | null +): 'chat' | 'terminal' { + return ( + draft.surface ?? + (chatSupported !== false && isNativeChatDefaultFor(settings, draft.agentId) + ? 'chat' + : 'terminal') + ) +} + +export function automationDraftLaunchSetup( + draft: Pick, + surface: 'chat' | 'terminal', + currentAutomation: Automation | null +): Pick { + const argumentsChanged = + hasExtraAgentArgs(draft.extraAgentArgs) || currentAutomation?.extraAgentArgs + return surface === 'chat' || currentAutomation?.surface === 'chat' + ? { + launchSetupPatch: { + surface, + ...(argumentsChanged + ? { arguments: { kind: 'legacy-extras' as const, value: draft.extraAgentArgs } } + : {}) + } + } + : argumentsChanged + ? { extraAgentArgs: draft.extraAgentArgs } + : {} +} diff --git a/src/renderer/src/components/automations/automation-orca-save.ts b/src/renderer/src/components/automations/automation-orca-save.ts index bdb0cc938df1..a74f1513ea38 100644 --- a/src/renderer/src/components/automations/automation-orca-save.ts +++ b/src/renderer/src/components/automations/automation-orca-save.ts @@ -1,3 +1,8 @@ +import { + automationChatSupport, + automationDraftLaunchSetup, + automationLaunchWorkspace +} from './automation-launch-surface' import { toast } from 'sonner' import type { Automation, @@ -15,7 +20,6 @@ import { type AutomationDispatchResult } from './automation-row-action-dispatch' import { buildDraftPrecheck } from './automation-draft-model' -import { hasExtraAgentArgs } from '../../../../shared/automation-extra-agent-args' import { buildAutomationRunContextForRepo } from './automation-run-context' import { resolveAutomationSetupDecisionForSave } from './automation-setup-decision' import { @@ -29,7 +33,7 @@ import type { AutomationSaveContext } from './automation-save-context' /** Saves an Orca automation, including destination validation and host moves. */ export async function saveOrcaAutomation( context: AutomationSaveContext, - time: { hour: number; minute: number; now: number } + time: { hour: number; minute: number; now: number; surface: 'chat' | 'terminal' } ): Promise { const { store, local, setup, destination, destinationForm, pageRefresh } = context const { repos, projectHostSetups } = store @@ -152,15 +156,23 @@ export async function saveOrcaAutomation( currentAutomation = (reread.ok ? reread.value : null) ?? currentAutomation } + const surface = + time.surface === 'chat' && + draft.surface === undefined && + automationChatSupport( + useAppStore.getState(), + draft, + automationLaunchWorkspace(draft, setupResolution ?? undefined) + ) === false + ? 'terminal' + : time.surface + const launchSetup = automationDraftLaunchSetup(draft, surface, currentAutomation) const updates: AutomationUpdateInput = { name: draft.name, prompt: draft.prompt, precheck, agentId: draft.agentId, - // Sent only when it carries or clears extras, so other edits stay legacy-shaped. - ...(hasExtraAgentArgs(draft.extraAgentArgs) || currentAutomation?.extraAgentArgs - ? { extraAgentArgs: draft.extraAgentArgs } - : {}), + ...launchSetup, runContext, projectId: draft.projectId, workspaceMode: draft.workspaceMode, @@ -180,7 +192,7 @@ export async function saveOrcaAutomation( prompt: draft.prompt, precheck, agentId: draft.agentId, - ...(hasExtraAgentArgs(draft.extraAgentArgs) ? { extraAgentArgs: draft.extraAgentArgs } : {}), + ...launchSetup, runContext, projectId: draft.projectId, workspaceMode: draft.workspaceMode, diff --git a/src/renderer/src/components/automations/automation-run-view-state.test.ts b/src/renderer/src/components/automations/automation-run-view-state.test.ts index 294239d0bd13..18b2acb25f1d 100644 --- a/src/renderer/src/components/automations/automation-run-view-state.test.ts +++ b/src/renderer/src/components/automations/automation-run-view-state.test.ts @@ -270,3 +270,19 @@ describe('getAutomationRerunPendingRemainingMs', () => { ).toBe(0) }) }) + +it('opens a Chat by its recorded identity without pretending it has a terminal', () => { + expect( + getAutomationRunViewState({ + run: makeRun({ + sessionKind: 'chat', + chatSessionId: 'claude_chat', + terminalSessionId: null, + terminalPaneKey: null, + terminalPtyId: null + }), + workspaceExists: true, + terminalTargetExists: false + }) + ).toMatchObject({ availability: 'chat', canOpen: true, actionLabel: 'View run' }) +}) diff --git a/src/renderer/src/components/automations/automation-run-view-state.ts b/src/renderer/src/components/automations/automation-run-view-state.ts index 4d35e922c860..812906fe3bd7 100644 --- a/src/renderer/src/components/automations/automation-run-view-state.ts +++ b/src/renderer/src/components/automations/automation-run-view-state.ts @@ -1,7 +1,12 @@ import type { Automation, AutomationRun } from '../../../../shared/automations-types' import { translate } from '@/i18n/i18n' -export type AutomationRunViewAvailability = 'terminal' | 'workspace' | 'snapshot' | 'metadata' +export type AutomationRunViewAvailability = + | 'chat' + | 'terminal' + | 'workspace' + | 'snapshot' + | 'metadata' export type AutomationRunViewState = { availability: AutomationRunViewAvailability @@ -61,6 +66,14 @@ export function getAutomationRunViewState({ /** The workspace's paired server holds the terminal; only it can say whether it still lives. */ terminalOnPairedServer?: boolean }): AutomationRunViewState { + if (run.sessionKind === 'chat' && run.chatSessionId && run.workspaceId && workspaceExists) { + return { + availability: 'chat', + actionLabel: translate('auto.components.automations.runViewState.viewRun', 'View run'), + statusLabel: translate('auto.components.automations.runViewState.runOpen', 'Run is open'), + canOpen: true + } + } const hasTerminalIdentity = Boolean(run.terminalPaneKey && run.terminalPtyId) // Why the pane alone: a slept run drops its PTY id but keeps its pane, which the server resumes. const hasPaneIdentity = Boolean(run.terminalPaneKey) diff --git a/src/renderer/src/components/automations/automation-run-workspace-action.paired-server.test.ts b/src/renderer/src/components/automations/automation-run-workspace-action.paired-server.test.ts index b892a02d3468..e73a0e537409 100644 --- a/src/renderer/src/components/automations/automation-run-workspace-action.paired-server.test.ts +++ b/src/renderer/src/components/automations/automation-run-workspace-action.paired-server.test.ts @@ -1,13 +1,19 @@ /** Paired runs use server PTY IDs while local mirrors use terminal handles; comparing those IDs falsely made available run terminals appear missing (#21213). */ import { beforeEach, describe, expect, it, vi } from 'vitest' +import { makeTabGroup, makeUnifiedTab } from '@/store/slices/store-test-helpers' +import type { Tab } from '../../../../shared/tab-types' import type { AutomationRun } from '../../../../shared/automations-types' import { toRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id' import { toWebTerminalSurfaceTabId } from '../../../../shared/terminal-surface-id' const mocks = vi.hoisted(() => { const state: Record = {} + const chatTabs: Tab[] = [] return { state, + chatTabs, + activateTab: vi.fn(), + rpc: vi.fn(), toastError: vi.fn(), toastMessage: vi.fn(), activateAndRevealWorktree: vi.fn(() => true), @@ -16,6 +22,10 @@ const mocks = vi.hoisted(() => { } }) +vi.mock('@/runtime/runtime-rpc-client', () => ({ + callRuntimeRpc: mocks.rpc, + runtimeEnvironmentSupportsCapability: async () => true +})) vi.mock('sonner', () => ({ toast: { error: mocks.toastError, message: mocks.toastMessage } })) vi.mock('@/store', () => ({ useAppStore: { getState: () => mocks.state } })) vi.mock('@/lib/worktree-activation', () => ({ @@ -33,6 +43,7 @@ import type { AutomationsPageActionContext } from './automations-page-action-con const ENV = 'env-a' const WT = 'repo-a::/srv/app' +const GROUP = 'recorded-chat-group' const LEAF = '11111111-1111-4111-8111-111111111111' const HOST_TAB = 'host-tab-1' const MIRRORED_TAB = toWebTerminalSurfaceTabId(HOST_TAB) @@ -82,9 +93,23 @@ function storeState(mirrored: boolean): Record { } : {}, ptyIdsByTabId: mirrored ? { [MIRRORED_TAB]: [MIRRORED_PTY] } : {}, - unifiedTabsByWorktree: {}, - groupsByWorktree: {}, - activeGroupIdByWorktree: {}, + unifiedTabsByWorktree: { [WT]: mocks.chatTabs }, + activateTab: mocks.activateTab, + focusGroup: vi.fn(), + groupsByWorktree: { + [WT]: [ + { + ...makeTabGroup({ id: GROUP, worktreeId: WT }), + get tabOrder() { + return mocks.chatTabs.map((tab) => tab.id) + }, + get activeTabId() { + return mocks.chatTabs[0]?.id ?? null + } + } + ] + }, + activeGroupIdByWorktree: { [WT]: GROUP }, setTabLayout: vi.fn(), setActiveTab: vi.fn(), setActiveTabType: vi.fn() @@ -100,11 +125,27 @@ function openRun(target: AutomationRun = run): void { createAutomationRunWorkspaceAction(context)(target) } -describe('opening a paired-server automation run', () => { - beforeEach(() => { - vi.clearAllMocks() +beforeEach(() => { + vi.clearAllMocks() + mocks.chatTabs.length = 0 + mocks.rpc.mockImplementation(async (_target, method, params) => { + if (method === 'agentSession.reveal') { + mocks.chatTabs.push( + makeUnifiedTab({ + id: 'recorded-chat', + groupId: GROUP, + entityId: params.sessionId, + worktreeId: WT, + executionHostId: `runtime:${ENV}`, + contentType: 'agent-session' + }) + ) + } + return { ok: true } }) +}) +describe('opening a paired-server automation run', () => { it('opens the mirrored pane of the run', () => { mocks.state = storeState(true) @@ -152,3 +193,117 @@ describe('opening a paired-server automation run', () => { expect(mocks.toastMessage).not.toHaveBeenCalled() }) }) + +it('opens the recorded Chat on its owning paired server without creating a session or terminal', async () => { + Object.assign(mocks.state, storeState(false)) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Chat opening reads only the selected row and workspace resolvers supplied here. + const action = createAutomationRunWorkspaceAction({ + store: { repoForRow: () => ({ id: 'repo-a' }), worktreeForRow: () => worktree }, + list: { selectedRow: {} } + } as never) + action({ + ...run, + sessionKind: 'chat', + chatSessionId: 'codex_recorded_chat', + terminalSessionId: null, + terminalPaneKey: null, + terminalPtyId: null + }) + await vi.waitFor(() => + expect(mocks.activateTab).toHaveBeenCalledWith('recorded-chat', { worktreeId: WT }) + ) + expect(mocks.state.focusGroup).toHaveBeenCalledWith(WT, GROUP) + expect(mocks.rpc).toHaveBeenCalledWith( + { kind: 'environment', environmentId: ENV }, + 'agentSession.reveal', + { sessionId: 'codex_recorded_chat' }, + expect.any(Object) + ) +}) + +it('keeps Run Details output and opens the workspace when the recorded chat is gone', async () => { + mocks.activateTab.mockClear() + Object.assign(mocks.state, storeState(false)) + mocks.rpc.mockResolvedValue({ ok: false, refusal: { code: 'agent_session_identity_required' } }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Chat opening reads only the selected row and workspace resolvers supplied here. + const action = createAutomationRunWorkspaceAction({ + store: { repoForRow: () => ({ id: 'repo-a' }), worktreeForRow: () => worktree }, + list: { selectedRow: {} } + } as never) + action({ + ...run, + sessionKind: 'chat', + chatSessionId: 'claude_missing', + terminalSessionId: null, + terminalPaneKey: null, + terminalPtyId: null + }) + await vi.waitFor(() => + expect(mocks.toastMessage).toHaveBeenCalledWith(expect.stringContaining('saved output remains')) + ) + expect(mocks.activateTab).not.toHaveBeenCalled() +}) + +it.each(['terminal', 'chat'] as const)( + 'opens the actual published %s target even when delivery failed', + async (kind) => { + Object.assign(mocks.state, storeState(false)) + mocks.activateTab.mockClear() + mocks.activateWebRuntimeSessionTab.mockClear() + const failed = { + ...run, + status: 'dispatch_failed' as const, + error: 'Prompt delivery could not be confirmed.', + sessionKind: kind, + ...(kind === 'chat' + ? { + chatSessionId: 'claude_published', + terminalSessionId: null, + terminalPaneKey: null, + terminalPtyId: null + } + : {}) + } + openRun(failed) + await vi.waitFor(() => + expect( + kind === 'chat' ? mocks.activateTab : mocks.activateWebRuntimeSessionTab + ).toHaveBeenCalledOnce() + ) + expect(mocks.activateAndRevealWorktree).toHaveBeenCalledWith(WT) + } +) + +it('presents one automation fallback when duplicate exact activation clicks reject', async () => { + Object.assign(mocks.state, storeState(false)) + mocks.chatTabs.push( + makeUnifiedTab({ + id: 'recorded-chat', + groupId: GROUP, + entityId: 'claude_published', + worktreeId: WT, + executionHostId: `runtime:${ENV}`, + contentType: 'agent-session' + }) + ) + mocks.state.focusGroup = vi.fn(() => { + throw new Error('activation unavailable') + }) + const recorded = { + ...run, + sessionKind: 'chat' as const, + chatSessionId: 'claude_published', + terminalSessionId: null, + terminalPaneKey: null, + terminalPtyId: null + } + openRun(recorded) + openRun(recorded) + await vi.waitFor(() => + expect(mocks.toastMessage).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining('saved output remains') + ) + ) + expect(mocks.toastError).not.toHaveBeenCalled() + expect(mocks.activateWebRuntimeSessionTab).not.toHaveBeenCalled() +}) diff --git a/src/renderer/src/components/automations/automation-run-workspace-action.ts b/src/renderer/src/components/automations/automation-run-workspace-action.ts index 7e20d4fae546..1fbc162c6f46 100644 --- a/src/renderer/src/components/automations/automation-run-workspace-action.ts +++ b/src/renderer/src/components/automations/automation-run-workspace-action.ts @@ -1,3 +1,6 @@ +import { openExistingStructuredSession } from '@/lib/open-existing-structured-session' +import { ALL_TUI_AGENTS } from '../../../../shared/tui-agent-display-names' +import { isStructuredAgentSessionIdFor } from '../../../../shared/structured-agent-session-create' import type { AutomationRun } from '../../../../shared/automations-types' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' @@ -15,7 +18,7 @@ import { import { getAutomationRunViewState } from './automation-run-view-state' import type { AutomationsPageActionContext } from './automations-page-action-context' -/** Opens the original run terminal when its host-qualified workspace is alive. */ +/** Opens the recorded run session on its owning host. */ export function createAutomationRunWorkspaceAction({ store, list }: AutomationsPageActionContext) { const { repoForRow, worktreeForRow } = store const { selectedRow } = list @@ -50,6 +53,17 @@ export function createAutomationRunWorkspaceAction({ store, list }: AutomationsP toast.error(runViewState.statusLabel) return } + if (runViewState.availability === 'chat' && run.chatSessionId) { + const agent = ALL_TUI_AGENTS.find((entry) => + isStructuredAgentSessionIdFor(entry, run.chatSessionId!) + ) + if (!agent || !activateAndRevealWorktree(run.workspaceId)) { + toast.error(workspaceUnavailableMessage()) + return + } + void openRunChat(run.workspaceId, run.chatSessionId, ownerEnvironmentId) + return + } const paneRef = parsePaneKey(run.terminalPaneKey ?? '') if (runViewState.availability === 'terminal' && !terminalTarget) { if (!ownerEnvironmentId || !paneRef) { @@ -84,6 +98,38 @@ export function createAutomationRunWorkspaceAction({ store, list }: AutomationsP } } +async function openRunChat( + worktreeId: string, + sessionId: string, + environmentId: string | null +): Promise { + try { + await openExistingStructuredSession( + { workspaceId: worktreeId, sessionId }, + { + target: environmentId ? { kind: 'environment', environmentId } : { kind: 'local' }, + present: (outcome) => { + if (outcome !== 'activated') { + runChatUnavailable() + } + }, + onError: runChatUnavailable + } + ) + } catch { + // The initiating interaction owns error feedback, including when this click joins it. + } +} + +function runChatUnavailable(): void { + toast.message( + translate( + 'components.automations.runChatUnavailable', + 'Run chat is unavailable. Showing its workspace; any saved output remains in Run Details.' + ) + ) +} + function workspaceUnavailableMessage(): string { return translate( 'auto.components.automations.AutomationsPage.e1bf9b1512', diff --git a/src/renderer/src/components/automations/automation-save-action.ts b/src/renderer/src/components/automations/automation-save-action.ts index 0463f62ba64b..1d3438b99d84 100644 --- a/src/renderer/src/components/automations/automation-save-action.ts +++ b/src/renderer/src/components/automations/automation-save-action.ts @@ -1,3 +1,9 @@ +import { useAppStore } from '@/store' +import { + automationChatSupport, + automationDraftSurface, + automationLaunchWorkspace +} from './automation-launch-surface' import { toast } from 'sonner' import { isTuiAgentEnabled } from '../../../../shared/tui-agent-selection' import { isValidAutomationSchedule } from '../../../../shared/automation-schedule-parsing' @@ -68,12 +74,26 @@ export function createAutomationSaveAction(context: AutomationSaveContext) { ) return } - const extrasError = draftExtraAgentArgsNeedFreshSession(draft) + const resolution = + editingAutomationId !== null + ? destinationForm.editHostResolution + : destination.createDestination.control.resolution + const chatSupported = automationChatSupport( + useAppStore.getState(), + draft, + automationLaunchWorkspace(draft, resolution) + ) + const surface = automationDraftSurface(draft, settings, chatSupported) + if (surface === 'chat' && chatSupported !== true) { + return + } + const effectiveDraft = { ...draft, surface } + const extrasError = draftExtraAgentArgsNeedFreshSession(effectiveDraft) ? translate( 'auto.components.automations.extraAgentArgs.needsFreshSession', 'Extra arguments require a fresh session for every run.' ) - : getDraftExtraAgentArgsError(draft) + : getDraftExtraAgentArgsError(effectiveDraft) if (extrasError) { toast.error(extrasError) return @@ -99,7 +119,7 @@ export function createAutomationSaveAction(context: AutomationSaveContext) { return } } - await saveOrcaAutomation(context, { hour, minute, now }) + await saveOrcaAutomation(context, { hour, minute, now, surface }) } catch (error) { toast.error( error instanceof Error diff --git a/src/renderer/src/components/automations/automation-scoped-list-client.ts b/src/renderer/src/components/automations/automation-scoped-list-client.ts index 57bfeb414d1f..205ef6c68e7b 100644 --- a/src/renderer/src/components/automations/automation-scoped-list-client.ts +++ b/src/renderer/src/components/automations/automation-scoped-list-client.ts @@ -30,7 +30,7 @@ import { } from './automation-host-client' import { assertAuthorityCapability, - assertExtraAgentArgsSupported, + prepareAutomationLaunchSetup, assertOwnerFencingSupported, assertAutomationCreateIdempotencySupported, AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY, @@ -198,10 +198,10 @@ async function updateFenced( destination?: AutomationDestination ): Promise { await assertOwnerFencingSupported(authority) - await assertExtraAgentArgsSupported(authority, updates.extraAgentArgs) + const prepared = await prepareAutomationLaunchSetup(authority, updates) const result = await callAuthority<{ automation: Automation }>(authority, 'automation.update', { id, - updates: toRuntimeAutomationUpdateInput(updates), + updates: toRuntimeAutomationUpdateInput(prepared), expectedOwner, destination }) @@ -293,9 +293,9 @@ export async function createAutomationForDestination( } await assertOwnerFencingSupported(authority) // Why before create: a move is create-then-delete and must refuse before mutating anything. - await assertExtraAgentArgsSupported(authority, input.extraAgentArgs) + const prepared = await prepareAutomationLaunchSetup(authority, input) const result = await callAuthority<{ automation: Automation }>(authority, 'automation.create', { - ...toRuntimeAutomationCreateInput(input), + ...toRuntimeAutomationCreateInput(prepared), destination }) return result.automation diff --git a/src/renderer/src/components/automations/automations-page-actions-test-harness.ts b/src/renderer/src/components/automations/automations-page-actions-test-harness.ts new file mode 100644 index 000000000000..2f4a157f06f5 --- /dev/null +++ b/src/renderer/src/components/automations/automations-page-actions-test-harness.ts @@ -0,0 +1,157 @@ +import { + addRuntimeProject, + api, + mocks, + renderPage, + runtimeHost, + RUNTIME_ID, + RUNTIME_REPO_ID, + RUNTIME_SELF_FILTER, + RUNTIME_WORKSPACE_ID, + scopedList, + settleHostQueries +} from './automations-page-test-harness' +import { act } from 'react' +import { expect, vi } from 'vitest' +import { checkRuntimeHooks, type HookCheckResult } from '@/runtime/runtime-hooks-client' +import { loadHostStructuredAgents } from '@/runtime/host-structured-agents' +import { getDefaultSettings } from '../../../../shared/constants' +import type { Automation } from '../../../../shared/automations-types' +import type { AutomationDraft } from './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, + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY, + STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY +} from '../../../../shared/protocol-version' +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 { + 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 { + 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 { + 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 = {}, + initialAgents = ['pi'] +) { + api.automations.list.mockResolvedValue([]) + scopedList([]) + runtimeHost([], []) + addRuntimeProject() + mocks.state.settings = { ...getDefaultSettings('/tmp'), experimentalNativeChat: true } + mocks.state.automationHostFilter = RUNTIME_SELF_FILTER + observeRuntimeIncarnation('A') + await learnRuntimeAgents('A', initialAgents) + runtimeCreateReturns(makeAutomation({ id: 'a-new' })) + const held = Promise.withResolvers() + 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() + } + } +} diff --git a/src/renderer/src/components/automations/automations-page-destination-fixtures.ts b/src/renderer/src/components/automations/automations-page-destination-fixtures.ts new file mode 100644 index 000000000000..9cca5aa784ea --- /dev/null +++ b/src/renderer/src/components/automations/automations-page-destination-fixtures.ts @@ -0,0 +1,69 @@ +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/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 + } + ] +} diff --git a/src/renderer/src/components/automations/automations-page-test-harness.tsx b/src/renderer/src/components/automations/automations-page-test-harness.tsx index 66c7814828ad..777ebd9f49bb 100644 --- a/src/renderer/src/components/automations/automations-page-test-harness.tsx +++ b/src/renderer/src/components/automations/automations-page-test-harness.tsx @@ -1,3 +1,5 @@ +import { resetHostStructuredAgentsForTests } from '@/runtime/host-structured-agents' +import { setLocalRuntimeCapabilitiesForTests } from '@/runtime/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' @@ -73,6 +75,7 @@ export type DetailPaneProps = { export type EditorDialogProps = { open: boolean isEditing: boolean + isSaving: boolean createDestination?: AutomationCreateDestinationControl editDestination?: AutomationCreateDestinationControl notice?: { message: string; recovery: string | null } | null @@ -393,8 +396,10 @@ 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) @@ -430,5 +435,6 @@ export function installAutomationsPageHarness(): void { roots.splice(0).forEach((root) => root.unmount()) }) document.body.innerHTML = '' + setLocalRuntimeCapabilitiesForTests(null) }) } diff --git a/src/renderer/src/components/right-sidebar/ai-vault-original-pane-actions.test.ts b/src/renderer/src/components/right-sidebar/ai-vault-original-pane-actions.test.ts index f9e37dad537f..58ee5ea9df72 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-original-pane-actions.test.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-original-pane-actions.test.ts @@ -1,8 +1,11 @@ // @vitest-environment happy-dom -import { renderHook } from '@testing-library/react' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { AiVaultSession } from '../../../../shared/ai-vault-types' +import { cleanup, renderHook } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => ({ + structured: vi.fn(async () => true), + findStructured: vi.fn((): object | null => null), activateAndRevealWorkspace: vi.fn<(workspaceId: string) => unknown>(), toastError: vi.fn<(message: string) => void>(), folderWorkspaces: new Array<{ id: string; projectGroupId: string; executionHostId: string }>() @@ -13,10 +16,10 @@ vi.mock('@/lib/worktree-activation', () => ({ })) vi.mock('@/lib/activate-tab-and-focus-pane', () => ({ activateTabAndFocusPane: vi.fn() })) vi.mock('@/lib/activate-ai-vault-structured-session', () => ({ - activateAiVaultStructuredSession: vi.fn() + activateAiVaultStructuredSession: mocks.structured })) vi.mock('@/lib/agent-session/structured-agent-session-tab-activation', () => ({ - findStructuredAgentSessionTab: vi.fn(() => null) + findStructuredAgentSessionTab: mocks.findStructured })) vi.mock('sonner', () => ({ toast: { error: mocks.toastError } })) vi.mock('@/store', () => { @@ -44,12 +47,16 @@ function folder(executionHostId: string) { return { id: 'folder-1', projectGroupId: 'group-1', executionHostId } } -describe('jumpToWorktree', () => { - beforeEach(() => { - vi.clearAllMocks() - mocks.folderWorkspaces = [] - }) +beforeEach(() => { + vi.resetAllMocks() + mocks.folderWorkspaces = [] + mocks.findStructured.mockReturnValue(null) + mocks.structured.mockResolvedValue(true) +}) + +afterEach(() => cleanup()) +describe('jumpToWorktree', () => { it('activates folder workspaces through the workspace activator', () => { mocks.activateAndRevealWorkspace.mockReturnValue({ primaryTabId: null }) const { result } = renderHook(() => useAiVaultOriginalPaneActions()) @@ -83,3 +90,35 @@ describe('jumpToWorktree', () => { ) }) }) + +it('keeps the original-pane handled boolean used by the History dialog close callback', async () => { + const session: AiVaultSession = { + id: 'history-chat', + executionHostId: 'local', + agent: 'claude', + sessionId: 'provider-1', + title: 'Saved Chat', + cwd: '/repo', + branch: null, + model: null, + filePath: '/fixture/session.jsonl', + codexHome: null, + createdAt: null, + updatedAt: null, + modifiedAt: '', + messageCount: 0, + totalTokens: 0, + previewMessages: [], + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: '', + subagent: null, + structuredSession: { workspaceId: 'workspace', sessionId: 'claude_saved' } + } + mocks.findStructured.mockReturnValue({}) + mocks.structured.mockResolvedValue(true) + const { result } = renderHook(() => useAiVaultOriginalPaneActions()) + expect(await result.current.jumpToOriginalPane(session)).toBe(true) + expect(mocks.structured).toHaveBeenCalledWith(session) + expect(mocks.activateAndRevealWorkspace).not.toHaveBeenCalled() +}) diff --git a/src/renderer/src/components/right-sidebar/ai-vault-session-launch-actions.test.ts b/src/renderer/src/components/right-sidebar/ai-vault-session-launch-actions.test.ts index d79f9d3c06d9..a4d0bd2accee 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-session-launch-actions.test.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-session-launch-actions.test.ts @@ -1,7 +1,10 @@ +import { createElement } from 'react' +import AiVaultSessionDropLayer from '../tab-group/AiVaultSessionDropLayer' +import { writeAiVaultSessionDragData } from '@/lib/ai-vault-session-drag' import type * as ForkStartup from '@/lib/ai-vault-session-fork-startup' // @vitest-environment happy-dom -import { renderHook, waitFor } from '@testing-library/react' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { cleanup, render, fireEvent, renderHook, waitFor } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { AiVaultSession } from '../../../../shared/ai-vault-types' import type { WebRuntimeTerminalCreateOutcome } from '@/runtime/web-runtime-session-types' @@ -14,6 +17,7 @@ const mocks = vi.hoisted(() => ({ prepareAiVaultSessionForTerminalResume: vi.fn(), launchAiVaultSessionInNewTab: vi.fn(), activateAiVaultResumeWorkspace: vi.fn(), + rpc: vi.fn(), toastError: vi.fn(), toastSuccess: vi.fn() })) @@ -55,6 +59,10 @@ vi.mock('./ai-vault-session-resume-in-chat-launch', () => ({ resumeAiVaultSessionInNewChat: vi.fn() })) vi.mock('sonner', () => ({ toast: { error: mocks.toastError, success: mocks.toastSuccess } })) +vi.mock('@/runtime/runtime-rpc-client', () => ({ + callRuntimeRpc: mocks.rpc, + runtimeEnvironmentSupportsCapability: async () => true +})) vi.mock('@/store', () => ({ useAppStore: { getState: mocks.getState } })) @@ -99,18 +107,21 @@ function renderActions(agentCmdOverrides?: { opencode?: string }) { ).result.current } -describe('Switch to Terminal launch', () => { - beforeEach(() => { - vi.clearAllMocks() - mocks.getState.mockReturnValue({ activeWorktreeId: 'worktree-1', settings: {} }) - mocks.prepareAiVaultSessionForFork.mockImplementation(async (session) => ({ - session, - copied: false - })) - mocks.buildAiVaultForkStartupForWorktree.mockReturnValue(FORK_STARTUP) - mocks.launchAiVaultSessionInNewTab.mockReturnValue({ tabId: 'tab-1' }) - }) +beforeEach(() => { + vi.resetAllMocks() + mocks.getState.mockReturnValue({ activeWorktreeId: 'worktree-1', settings: {} }) + mocks.prepareAiVaultSessionForFork.mockImplementation(async (session) => ({ + session, + copied: false + })) + mocks.buildAiVaultForkStartupForWorktree.mockReturnValue(FORK_STARTUP) + mocks.launchAiVaultSessionInNewTab.mockReturnValue({ tabId: 'tab-1' }) + mocks.rpc.mockResolvedValue(undefined) +}) + +afterEach(() => cleanup()) +describe('Switch to Terminal launch', () => { // Either OpenCode chat may own a 2.x conversation, so the copy may open in either CLI. it.each([ ['command', 'opencode'], @@ -230,7 +241,6 @@ describe('Switch to Terminal launch', () => { }) it('refuses the stale OMP row before creating a second terminal writer', async () => { - vi.clearAllMocks() mocks.prepareAiVaultSessionForTerminalResume.mockRejectedValue( new Error( "Error invoking remote method 'aiVault:prepareSessionResume': Error: agent_session_conflict" @@ -246,3 +256,69 @@ it('refuses the stale OMP row before creating a second terminal writer', async ( ) expect(mocks.launchAiVaultSessionInNewTab).not.toHaveBeenCalled() }) + +it('intercepts an ordinary structured Resume and actual pane drop on handled refusal without terminal execution', async () => { + mocks.getState.mockReturnValue({ + activeWorktreeId: 'worktree-1', + settings: {}, + repos: [], + worktreesByRepo: {}, + folderWorkspaces: [], + projectGroups: [], + unifiedTabsByWorktree: {} + }) + mocks.rpc.mockImplementation(async (_target, method) => { + if (method === 'session.tabs.list') { + throw new Error('advisory inventory unavailable') + } + return { ok: false, refusal: { code: 'agent_session_identity_required' } } + }) + const actions = renderActions() + actions.handleResume(owned) + await waitFor(() => + expect(mocks.toastError).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining('no longer on this host') + ) + ) + const rect = vi + .spyOn(HTMLElement.prototype, 'getBoundingClientRect') + .mockReturnValue(new DOMRect(0, 0, 100, 100)) + try { + const view = render( + createElement( + 'div', + { 'data-tab-group-body-id': 'group', 'data-worktree-id': 'worktree-1' }, + createElement(AiVaultSessionDropLayer, { worktreeId: 'worktree-1', enabled: true }) + ) + ) + try { + const transfer = new DataTransfer() + writeAiVaultSessionDragData(transfer, { + agent: 'claude', + sessionId: owned.sessionId, + structuredSession: owned.structuredSession, + title: owned.title, + command: '' + }) + const layer = view.container.querySelector('[data-ai-vault-session-drop-layer]') + if (!layer) { + throw new Error('drop layer must mount') + } + const drop = new MouseEvent('drop', { + clientX: 50, + clientY: 50, + bubbles: true, + cancelable: true + }) + Object.defineProperty(drop, 'dataTransfer', { value: transfer }) + fireEvent(layer, drop) + await waitFor(() => expect(mocks.toastError).toHaveBeenCalledTimes(2)) + expect(mocks.launchAiVaultSessionInNewTab).not.toHaveBeenCalled() + expect(mocks.prepareAiVaultSessionForTerminalResume).not.toHaveBeenCalled() + } finally { + view.unmount() + } + } finally { + rect.mockRestore() + } +}) diff --git a/src/renderer/src/components/ui/toggle-group.tsx b/src/renderer/src/components/ui/toggle-group.tsx index bc45aed4c700..6de8be1c2914 100644 --- a/src/renderer/src/components/ui/toggle-group.tsx +++ b/src/renderer/src/components/ui/toggle-group.tsx @@ -7,8 +7,12 @@ import * as ToggleGroupPrimitive from 'radix-ui/toggle-group' import { cn } from '@/lib/utils' import { toggleVariants } from '@/components/ui/toggle' +type ToggleGroupVariantProps = Omit, 'variant'> & { + variant?: VariantProps['variant'] | 'segmented-card' +} + const ToggleGroupContext = React.createContext< - VariantProps & { + ToggleGroupVariantProps & { spacing?: number } >({ @@ -25,7 +29,7 @@ function ToggleGroup({ children, ...props }: React.ComponentProps & - VariantProps & { + ToggleGroupVariantProps & { spacing?: number }) { const contextValue = React.useMemo(() => ({ variant, size, spacing }), [variant, size, spacing]) @@ -39,6 +43,7 @@ function ToggleGroup({ style={{ '--gap': spacing } as React.CSSProperties} className={cn( 'group/toggle-group flex w-fit items-center gap-[--spacing(var(--gap))] rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs', + variant === 'segmented-card' && 'grid w-full grid-cols-2 rounded-md bg-muted p-0.5', className )} {...props} @@ -54,22 +59,25 @@ function ToggleGroupItem({ variant, size, ...props -}: React.ComponentProps & VariantProps) { +}: React.ComponentProps & ToggleGroupVariantProps) { const context = React.useContext(ToggleGroupContext) + const selectedVariant = context.variant || variant return ( { const tabs: Record = {} return { + navigate: vi.fn(), + moved: vi.fn(() => false), call: vi.fn(), supports: vi.fn(), apply: vi.fn(), @@ -17,6 +19,8 @@ const mocks = vi.hoisted(() => { } } }) +vi.mock('./worktree-activation', () => ({ activateAndRevealWorktree: mocks.navigate })) +vi.mock('./wsl-moved-chat-activation', () => ({ activateWslMovedWorkspace: mocks.moved })) vi.mock('@/store', () => ({ useAppStore: { getState: () => ({ @@ -37,6 +41,7 @@ vi.mock('@/runtime/local-structured-session-tabs-sync/snapshot-apply', async (or applyStructuredSessionTabSnapshots: mocks.apply })) +import { openExistingStructuredSession } from './open-existing-structured-session' import { activateAiVaultStructuredSession } from './activate-ai-vault-structured-session' import { STRUCTURED_AGENT_SESSION_REVEAL_RUNTIME_CAPABILITY } from '../../../shared/protocol-version' @@ -58,6 +63,8 @@ function tab(id: string, host: 'local' | 'runtime:remote-2'): Tab { } beforeEach(() => { vi.clearAllMocks() + mocks.state.activeWorktreeId = 'workspace' + mocks.moved.mockReturnValue(false) mocks.state.unifiedTabsByWorktree = { workspace: [tab('wrong-local', 'local')] } mocks.supports.mockResolvedValue(true) mocks.call.mockImplementation(async (_host, method: string) => { @@ -94,3 +101,103 @@ it('keeps the known host through the default refresh/reveal/activation path with expect(mocks.activateTab).toHaveBeenCalledOnce() expect(mocks.activateTab).toHaveBeenCalledWith('right-remote', { worktreeId: 'workspace' }) }) + +it('keeps implicit activation unfiltered while explicit automation refuses an equal-ID other owner', async () => { + const pointer = { structuredSession: { workspaceId: 'workspace', sessionId: 'sender' } } + expect(await activateAiVaultStructuredSession(pointer)).toBe(true) + expect(mocks.activateTab).toHaveBeenCalledWith('wrong-local', { worktreeId: 'workspace' }) + expect(mocks.supports).not.toHaveBeenCalled() +}) + +it('shares one result and the first presentation across History and neutral callers, then permits retry', async () => { + const pointer = { workspaceId: 'workspace', sessionId: 'coalesced' } + const release = Promise.withResolvers<'gone'>() + const parts = { + activate: vi.fn(() => false), + refresh: vi.fn(async () => undefined), + reveal: vi.fn(() => release.promise), + gone: vi.fn(), + unavailable: vi.fn(), + hostCannotOpen: vi.fn() + } + const present = vi.fn() + const history = activateAiVaultStructuredSession({ structuredSession: pointer }, parts, TARGET) + const joined = openExistingStructuredSession(pointer, { target: TARGET, deps: parts, present }) + release.resolve('gone') + expect(await history).toBe(true) + expect(await joined).toBe('gone') + expect(parts.reveal).toHaveBeenCalledOnce() + expect(parts.gone).toHaveBeenCalledOnce() + expect(present).not.toHaveBeenCalled() + const pending = Promise.withResolvers<'gone'>() + parts.reveal.mockImplementationOnce(() => pending.promise) + const neutral = openExistingStructuredSession(pointer, { target: TARGET, deps: parts, present }) + const historyJoin = activateAiVaultStructuredSession( + { structuredSession: pointer }, + parts, + TARGET + ) + pending.resolve('gone') + expect(await neutral).toBe('gone') + expect(await historyJoin).toBe(true) + expect(present).toHaveBeenCalledExactlyOnceWith('gone') + expect(parts.gone).toHaveBeenCalledOnce() +}) + +it('releases a rejected interaction without converting an unexpected dependency failure into handled success', async () => { + const pointer = { workspaceId: 'workspace', sessionId: 'rejected' } + const parts = { + activate: vi.fn(() => false), + refresh: vi.fn(async () => undefined), + reveal: vi.fn(async () => { + throw new Error('dependency failure') + }), + gone: vi.fn(), + unavailable: vi.fn(), + hostCannotOpen: vi.fn() + } + const onError = vi.fn() + const first = openExistingStructuredSession(pointer, { + target: TARGET, + deps: parts, + present: vi.fn(), + onError + }) + const joined = activateAiVaultStructuredSession({ structuredSession: pointer }, parts, TARGET) + await expect(first).rejects.toThrow('dependency failure') + await expect(joined).rejects.toThrow('dependency failure') + expect(onError).toHaveBeenCalledOnce() + expect(parts.unavailable).not.toHaveBeenCalled() + parts.activate.mockReturnValue(true) + expect( + await activateAiVaultStructuredSession({ structuredSession: pointer }, parts, TARGET) + ).toBe(true) +}) + +it('preserves History success-only navigation, the active-workspace shortcut and moved-workspace fallback', async () => { + const session = { structuredSession: { workspaceId: 'workspace', sessionId: 'nav' } } + const parts = { + activate: vi.fn(() => false), + refresh: vi.fn(async () => undefined), + reveal: vi.fn(async () => 'gone' as const), + gone: vi.fn(), + unavailable: vi.fn(), + hostCannotOpen: vi.fn() + } + mocks.state.activeWorktreeId = 'elsewhere' + expect(await activateAiVaultStructuredSession(session, parts, TARGET)).toBe(true) + expect(parts.gone).toHaveBeenCalledOnce() + expect(mocks.navigate).not.toHaveBeenCalled() + expect(mocks.moved).not.toHaveBeenCalled() + parts.activate.mockReturnValue(true) + await activateAiVaultStructuredSession(session, parts, TARGET) + expect(mocks.navigate).toHaveBeenCalledExactlyOnceWith('workspace') + mocks.navigate.mockClear() + mocks.moved.mockReturnValue(true) + await activateAiVaultStructuredSession(session, parts, TARGET) + expect(mocks.navigate).not.toHaveBeenCalled() + mocks.state.activeWorktreeId = 'workspace' + mocks.moved.mockClear() + await activateAiVaultStructuredSession(session, parts, TARGET) + expect(mocks.moved).not.toHaveBeenCalled() +}) diff --git a/src/renderer/src/lib/activate-ai-vault-structured-session-reveal.test.ts b/src/renderer/src/lib/activate-ai-vault-structured-session-reveal.test.ts index afc159231b8b..08ce33b1f686 100644 --- a/src/renderer/src/lib/activate-ai-vault-structured-session-reveal.test.ts +++ b/src/renderer/src/lib/activate-ai-vault-structured-session-reveal.test.ts @@ -18,7 +18,10 @@ vi.mock('./worktree-runtime-owner', () => ({ runtimeEnvironmentIdOrLocalUnlessTwin: mocks.environmentIdFor })) -import { revealStructuredSession } from './activate-ai-vault-structured-session' +import { + activateAiVaultStructuredSession, + revealStructuredSession +} from './activate-ai-vault-structured-session' import { STRUCTURED_AGENT_SESSION_REVEAL_RUNTIME_CAPABILITY } from '../../../shared/protocol-version' import { RUNTIME_COMPAT_BLOCK_CODE } from '@/runtime/runtime-protocol-compat' @@ -152,3 +155,33 @@ describe('revealStructuredSession', () => { await expect(revealStructuredSession(target)).resolves.toBe('unreachable') }) }) + +it('bounds a cached stalled probe, releases the shared click and permits a subsequent explicit retry', async () => { + vi.useFakeTimers() + const host = { kind: 'environment', environmentId: 'cached-stalled' } as const + const cached = new Promise(() => {}) + mocks.supports.mockReturnValue(cached) + const parts = { + activate: vi.fn(() => false), + refresh: vi.fn(async () => undefined), + reveal: revealStructuredSession, + unavailable: vi.fn(), + gone: vi.fn(), + hostCannotOpen: vi.fn() + } + const session = { + structuredSession: { workspaceId: target.worktreeId, sessionId: target.sessionId } + } + try { + const click = activateAiVaultStructuredSession(session, parts, host) + await vi.advanceTimersByTimeAsync(5_001) + expect(await click).toBe(true) + expect(parts.unavailable).toHaveBeenCalledOnce() + expect(mocks.call).not.toHaveBeenCalled() + mocks.supports.mockResolvedValue(false) + expect(await activateAiVaultStructuredSession(session, parts, host)).toBe(true) + expect(parts.hostCannotOpen).toHaveBeenCalledOnce() + } finally { + vi.useRealTimers() + } +}) diff --git a/src/renderer/src/lib/activate-ai-vault-structured-session.ts b/src/renderer/src/lib/activate-ai-vault-structured-session.ts index 8234a37fee2e..c7bfea14e002 100644 --- a/src/renderer/src/lib/activate-ai-vault-structured-session.ts +++ b/src/renderer/src/lib/activate-ai-vault-structured-session.ts @@ -3,35 +3,18 @@ import type { AiVaultSession } from '../../../shared/ai-vault-types' import { translate } from '@/i18n/i18n' import { activateAndRevealWorktree } from './worktree-activation' import { activateWslMovedWorkspace } from './wsl-moved-chat-activation' -import { activateStructuredAgentSessionById } from './agent-session/structured-agent-session-tab-activation' import { useAppStore } from '@/store' -import { runtimeEnvironmentIdOrLocalUnlessTwin } from './worktree-runtime-owner' -import { callRuntimeRpc, runtimeEnvironmentSupportsCapability } from '@/runtime/runtime-rpc-client' import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' -import { runtimeTargetForOwnerEnvironment } from '@/runtime/runtime-client-target' -import { toRuntimeWorktreeSelector } from '@/runtime/runtime-worktree-selector' -import { refreshLocalStructuredSessionWorktreeTabs } from '@/runtime/local-structured-session-tabs-sync/inventory-refresh' -import { STRUCTURED_AGENT_SESSION_REVEAL_RUNTIME_CAPABILITY } from '../../../shared/protocol-version' -import { isRuntimeCompatBlockError } from '@/runtime/runtime-protocol-compat' -import { executionHostIdForStructuredTarget } from '@/runtime/structured-agent-session-owner' +import { + openExistingStructuredSession, + type StructuredSessionOpenDeps +} from './open-existing-structured-session' +export { + revealStructuredSession, + type StructuredSessionRevealOutcome +} from './open-existing-structured-session' -const STRUCTURED_SESSION_RESTORE_TIMEOUT_MS = 5_000 - -/** Keep distinct remedies: retry unreachable hosts, stop on a confirmed missing record, or update incompatible hosts/adapters. Failure to answer never proves a chat is gone. */ -export type StructuredSessionRevealOutcome = - | 'revealed' - | 'gone' - | 'host-cannot-open' - | 'unreachable' - -type StructuredSessionActivationDeps = { - activate: typeof activateStructuredAgentSessionById - refresh: (worktreeId: string, target?: RuntimeClientTarget) => Promise - reveal: (target: { - worktreeId: string - sessionId: string - target?: RuntimeClientTarget - }) => Promise +type StructuredSessionActivationDeps = StructuredSessionOpenDeps & { unavailable: () => void gone: () => void hostCannotOpen: () => void @@ -69,196 +52,37 @@ export const structuredSessionOpenFeedback: Pick< } } -const defaultDeps: StructuredSessionActivationDeps = { - activate: activateStructuredAgentSessionById, - refresh: refreshStructuredSessionTabs, - reveal: revealStructuredSession, - ...structuredSessionOpenFeedback -} - /** Read only structuredSession so history clicks and drag payloads follow the same reveal path. */ export async function activateAiVaultStructuredSession( session: Pick, - deps: StructuredSessionActivationDeps = defaultDeps, + deps?: StructuredSessionActivationDeps, target?: RuntimeClientTarget ): Promise { const structured = session.structuredSession if (!structured) { return false } - // Coalesce clicks across refresh/probe/reveal timeouts to avoid duplicate sequences and toasts. - const hostKey = executionHostIdForStructuredTarget( - target ?? - runtimeTargetForOwnerEnvironment( - runtimeEnvironmentIdOrLocalUnlessTwin(useAppStore.getState(), structured.workspaceId) - ) - ) - const key = `${hostKey}\0${structured.workspaceId}\0${structured.sessionId}` - const inFlight = activationsInFlight.get(key) - if (inFlight) { - return inFlight - } - const activation = activateStructuredSession(structured, deps, target) - activationsInFlight.set(key, activation) - try { - return await activation - } finally { - activationsInFlight.delete(key) - } -} - -const activationsInFlight = new Map>() - -async function activateStructuredSession( - structured: NonNullable, - deps: StructuredSessionActivationDeps, - host?: RuntimeClientTarget -): Promise { - const target = { - worktreeId: structured.workspaceId, - sessionId: structured.sessionId, - ...(host ? { target: host } : {}) - } - if (!deps.activate(target)) { - // Refresh can avoid reveal, but failure must fall through: host republication is the actual repair. - const refreshed = await refreshedWithoutThrowing(deps, structured.workspaceId, host) - if (!refreshed || !deps.activate(target)) { - // Ask the host to republish a closed or unpublished tab from its persisted record. - const revealed = await deps.reveal(target) - if (revealed !== 'revealed') { - if (revealed === 'gone') { - deps.gone() - } else if (revealed === 'host-cannot-open') { - deps.hostCannotOpen() - } else { - deps.unavailable() + const feedback = deps ?? structuredSessionOpenFeedback + await openExistingStructuredSession(structured, { + target, + deps, + present: (outcome) => { + if (outcome === 'activated') { + // A moved project's chat opens under its retained entry; the catalog does not list it. + if ( + useAppStore.getState().activeWorktreeId !== structured.workspaceId && + !activateWslMovedWorkspace(structured.workspaceId) + ) { + activateAndRevealWorktree(structured.workspaceId) } - return true - } - await refreshedWithoutThrowing(deps, structured.workspaceId, host) - if (!deps.activate(target)) { - deps.unavailable() - return true + } else if (outcome === 'gone') { + feedback.gone() + } else if (outcome === 'host-cannot-open') { + feedback.hostCannotOpen() + } else { + feedback.unavailable() } } - } - // A moved project's chat opens under its retained entry; the catalog does not list it. - if ( - useAppStore.getState().activeWorktreeId !== structured.workspaceId && - !activateWslMovedWorkspace(structured.workspaceId) - ) { - activateAndRevealWorktree(structured.workspaceId) - } + }) return true } - -/** Refresh is advisory; failures return false so reveal can still proceed. */ -async function refreshedWithoutThrowing( - deps: StructuredSessionActivationDeps, - worktreeId: string, - target?: RuntimeClientTarget -): Promise { - try { - await (target ? deps.refresh(worktreeId, target) : deps.refresh(worktreeId)) - return true - } catch { - return false - } -} - -/** Only revealed promises a tab; preserve distinct retry/missing/update outcomes for the other replies. */ -export async function revealStructuredSession(target: { - worktreeId: string - sessionId: string - target?: RuntimeClientTarget -}): Promise { - const host = - target.target ?? - runtimeTargetForOwnerEnvironment( - runtimeEnvironmentIdOrLocalUnlessTwin(useAppStore.getState(), target.worktreeId) - ) - // Probe the answering paired host’s build; the local host shares this build and needs no probe. - if (host.kind === 'environment') { - let supported: boolean - try { - // Race even cached probe promises: an older unbounded probe must not hold the session’s in-flight guard forever. - supported = await withStructuredSessionRestoreTimeout( - runtimeEnvironmentSupportsCapability( - host.environmentId, - STRUCTURED_AGENT_SESSION_REVEAL_RUNTIME_CAPABILITY, - STRUCTURED_SESSION_RESTORE_TIMEOUT_MS - ) - ) - } catch (error) { - // Only a version block proves age; other probe failures say nothing about the chat (as in remote-agent-session-launch). - return isRuntimeCompatBlockError(error) ? 'host-cannot-open' : 'unreachable' - } - if (!supported) { - return 'host-cannot-open' - } - } - let result: AgentSessionRevealReply | undefined - try { - result = await withStructuredSessionRestoreTimeout( - callRuntimeRpc( - host, - 'agentSession.reveal', - { sessionId: target.sessionId }, - { - timeoutMs: STRUCTURED_SESSION_RESTORE_TIMEOUT_MS - } - ) - ) - } catch { - return 'unreachable' - } - if (result?.ok === true) { - return 'revealed' - } - // Distinguish a missing record from an existing record the host cannot open; only the first means gone. - return result?.refusal?.code === 'agent_session_identity_required' ? 'gone' : 'host-cannot-open' -} - -type AgentSessionRevealReply = { ok?: boolean; refusal?: { code?: string } } - -async function refreshStructuredSessionTabs( - worktreeId: string, - target?: RuntimeClientTarget -): Promise { - const state = useAppStore.getState() - const host = - target ?? - runtimeTargetForOwnerEnvironment(runtimeEnvironmentIdOrLocalUnlessTwin(state, worktreeId)) - if (host.kind === 'local') { - await withStructuredSessionRestoreTimeout(refreshLocalStructuredSessionWorktreeTabs(worktreeId)) - return - } - // Paired inventories arrive through their existing host-scoped subscription. - await withStructuredSessionRestoreTimeout( - callRuntimeRpc( - host, - 'session.tabs.list', - { worktree: toRuntimeWorktreeSelector(worktreeId) }, - { timeoutMs: STRUCTURED_SESSION_RESTORE_TIMEOUT_MS } - ) - ) -} - -async function withStructuredSessionRestoreTimeout(promise: Promise): Promise { - let timer: ReturnType | undefined - try { - return await Promise.race([ - promise, - new Promise((_resolve, reject) => { - timer = setTimeout( - () => reject(new Error('structured_session_restore_timeout')), - STRUCTURED_SESSION_RESTORE_TIMEOUT_MS - ) - }) - ]) - } finally { - if (timer) { - clearTimeout(timer) - } - } -} diff --git a/src/renderer/src/lib/open-existing-structured-session.ts b/src/renderer/src/lib/open-existing-structured-session.ts new file mode 100644 index 000000000000..71f70935b0e7 --- /dev/null +++ b/src/renderer/src/lib/open-existing-structured-session.ts @@ -0,0 +1,221 @@ +import { activateStructuredAgentSessionById } from './agent-session/structured-agent-session-tab-activation' +import { useAppStore } from '@/store' +import { runtimeEnvironmentIdOrLocalUnlessTwin } from './worktree-runtime-owner' +import { callRuntimeRpc, runtimeEnvironmentSupportsCapability } from '@/runtime/runtime-rpc-client' +import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' +import { runtimeTargetForOwnerEnvironment } from '@/runtime/runtime-client-target' +import { toRuntimeWorktreeSelector } from '@/runtime/runtime-worktree-selector' +import { refreshLocalStructuredSessionWorktreeTabs } from '@/runtime/local-structured-session-tabs-sync/inventory-refresh' +import { STRUCTURED_AGENT_SESSION_REVEAL_RUNTIME_CAPABILITY } from '../../../shared/protocol-version' +import { isRuntimeCompatBlockError } from '@/runtime/runtime-protocol-compat' +import { executionHostIdForStructuredTarget } from '@/runtime/structured-agent-session-owner' + +type StructuredSessionIdentity = { workspaceId: string; sessionId: string } + +const STRUCTURED_SESSION_RESTORE_TIMEOUT_MS = 5_000 + +/** Keep distinct remedies: retry unreachable hosts, stop on a confirmed missing record, or update incompatible hosts/adapters. Failure to answer never proves a chat is gone. */ +export type StructuredSessionRevealOutcome = + | 'revealed' + | 'gone' + | 'host-cannot-open' + | 'unreachable' + +export type StructuredSessionOpenDeps = { + activate: typeof activateStructuredAgentSessionById + refresh: (worktreeId: string, target?: RuntimeClientTarget) => Promise + reveal: (target: { + worktreeId: string + sessionId: string + target?: RuntimeClientTarget + }) => Promise +} + +export type StructuredSessionOpenOutcome = 'activated' | 'gone' | 'host-cannot-open' | 'unavailable' + +const defaultDeps: StructuredSessionOpenDeps = { + activate: activateStructuredAgentSessionById, + refresh: refreshStructuredSessionTabs, + reveal: revealStructuredSession +} + +const activationsInFlight = new Map>() + +/** Reopen the host record; the first caller owns presentation for the shared interaction. */ +export async function openExistingStructuredSession( + structured: StructuredSessionIdentity, + options: { + target?: RuntimeClientTarget + deps?: StructuredSessionOpenDeps + present: (outcome: StructuredSessionOpenOutcome) => void + onError?: () => void + } +): Promise { + const { target, deps = defaultDeps, present } = options + const hostKey = executionHostIdForStructuredTarget( + target ?? + runtimeTargetForOwnerEnvironment( + runtimeEnvironmentIdOrLocalUnlessTwin(useAppStore.getState(), structured.workspaceId) + ) + ) + const key = `${hostKey}\0${structured.workspaceId}\0${structured.sessionId}` + const inFlight = activationsInFlight.get(key) + if (inFlight) { + return inFlight + } + const activation = activateStructuredSession(structured, deps, target).then( + (outcome) => { + present(outcome) + return outcome + }, + (error: unknown) => { + options.onError?.() + throw error + } + ) + activationsInFlight.set(key, activation) + try { + return await activation + } finally { + activationsInFlight.delete(key) + } +} + +async function activateStructuredSession( + structured: StructuredSessionIdentity, + deps: StructuredSessionOpenDeps, + host?: RuntimeClientTarget +): Promise { + const target = { + worktreeId: structured.workspaceId, + sessionId: structured.sessionId, + ...(host ? { target: host } : {}) + } + if (!deps.activate(target)) { + // Refresh can avoid reveal, but failure must fall through: host republication is the actual repair. + const refreshed = await refreshedWithoutThrowing(deps, structured.workspaceId, host) + if (!refreshed || !deps.activate(target)) { + // Ask the host to republish a closed or unpublished tab from its persisted record. + const revealed = await deps.reveal(target) + if (revealed !== 'revealed') { + return revealed === 'unreachable' ? 'unavailable' : revealed + } + await refreshedWithoutThrowing(deps, structured.workspaceId, host) + if (!deps.activate(target)) { + return 'unavailable' + } + } + } + return 'activated' +} + +/** Refresh is advisory; failures return false so reveal can still proceed. */ +async function refreshedWithoutThrowing( + deps: StructuredSessionOpenDeps, + worktreeId: string, + target?: RuntimeClientTarget +): Promise { + try { + await (target ? deps.refresh(worktreeId, target) : deps.refresh(worktreeId)) + return true + } catch { + return false + } +} + +/** Only revealed promises a tab; preserve distinct retry/missing/update outcomes for the other replies. */ +export async function revealStructuredSession(target: { + worktreeId: string + sessionId: string + target?: RuntimeClientTarget +}): Promise { + const host = + target.target ?? + runtimeTargetForOwnerEnvironment( + runtimeEnvironmentIdOrLocalUnlessTwin(useAppStore.getState(), target.worktreeId) + ) + // Probe the answering paired host’s build; the local host shares this build and needs no probe. + if (host.kind === 'environment') { + let supported: boolean + try { + // Race even cached probe promises: an older unbounded probe must not hold the session’s in-flight guard forever. + supported = await withStructuredSessionRestoreTimeout( + runtimeEnvironmentSupportsCapability( + host.environmentId, + STRUCTURED_AGENT_SESSION_REVEAL_RUNTIME_CAPABILITY, + STRUCTURED_SESSION_RESTORE_TIMEOUT_MS + ) + ) + } catch (error) { + // Only a version block proves age; other probe failures say nothing about the chat (as in remote-agent-session-launch). + return isRuntimeCompatBlockError(error) ? 'host-cannot-open' : 'unreachable' + } + if (!supported) { + return 'host-cannot-open' + } + } + let result: AgentSessionRevealReply | undefined + try { + result = await withStructuredSessionRestoreTimeout( + callRuntimeRpc( + host, + 'agentSession.reveal', + { sessionId: target.sessionId }, + { + timeoutMs: STRUCTURED_SESSION_RESTORE_TIMEOUT_MS + } + ) + ) + } catch { + return 'unreachable' + } + if (result?.ok === true) { + return 'revealed' + } + // Distinguish a missing record from an existing record the host cannot open; only the first means gone. + return result?.refusal?.code === 'agent_session_identity_required' ? 'gone' : 'host-cannot-open' +} + +type AgentSessionRevealReply = { ok?: boolean; refusal?: { code?: string } } + +async function refreshStructuredSessionTabs( + worktreeId: string, + target?: RuntimeClientTarget +): Promise { + const state = useAppStore.getState() + const host = + target ?? + runtimeTargetForOwnerEnvironment(runtimeEnvironmentIdOrLocalUnlessTwin(state, worktreeId)) + if (host.kind === 'local') { + await withStructuredSessionRestoreTimeout(refreshLocalStructuredSessionWorktreeTabs(worktreeId)) + return + } + // Paired inventories arrive through their existing host-scoped subscription. + await withStructuredSessionRestoreTimeout( + callRuntimeRpc( + host, + 'session.tabs.list', + { worktree: toRuntimeWorktreeSelector(worktreeId) }, + { timeoutMs: STRUCTURED_SESSION_RESTORE_TIMEOUT_MS } + ) + ) +} + +async function withStructuredSessionRestoreTimeout(promise: Promise): Promise { + let timer: ReturnType | undefined + try { + return await Promise.race([ + promise, + new Promise((_resolve, reject) => { + timer = setTimeout( + () => reject(new Error('structured_session_restore_timeout')), + STRUCTURED_SESSION_RESTORE_TIMEOUT_MS + ) + }) + ]) + } finally { + if (timer) { + clearTimeout(timer) + } + } +} diff --git a/src/shared/automation-extra-agent-args-record.ts b/src/shared/automation-extra-agent-args-record.ts index e6ad1cc042b3..66f6a39f1302 100644 --- a/src/shared/automation-extra-agent-args-record.ts +++ b/src/shared/automation-extra-agent-args-record.ts @@ -18,9 +18,9 @@ export function storedExtraAgentArgs(value: unknown): string | undefined { /** Validates a whole record, so a patch that only enables Reuse still sees stored extras. */ export function assertAutomationExtraAgentArgs( - automation: Pick + automation: Pick ): void { - if (!hasExtraAgentArgs(automation.extraAgentArgs)) { + if (automation.surface === 'chat' || !hasExtraAgentArgs(automation.extraAgentArgs)) { return } if (automation.reuseSession) { diff --git a/src/shared/automation-launch-setup.ts b/src/shared/automation-launch-setup.ts new file mode 100644 index 000000000000..0555808409d9 --- /dev/null +++ b/src/shared/automation-launch-setup.ts @@ -0,0 +1,32 @@ +import type { Automation, AutomationLaunchSetupPatch } from './automations-types' +import { AutomationLaunchSetupPatch as PatchSchema } from './rpc-contract/automation-params' + +export function applyAutomationLaunchSetupPatch< + T extends { extraAgentArgs?: string; launchSetupPatch?: AutomationLaunchSetupPatch } +>(input: T): Omit & Pick { + const { launchSetupPatch, ...rest } = input + if (launchSetupPatch === undefined) { + return rest + } + if (input.extraAgentArgs !== undefined) { + throw new Error('Save automation arguments through one launch setup change.') + } + const patch = PatchSchema.parse(launchSetupPatch) + return { + ...rest, + ...(patch.surface ? { surface: patch.surface } : {}), + ...(patch.arguments ? { extraAgentArgs: patch.arguments.value } : {}) + } +} + +export function automationWithLaunchSetup(automation: Automation): Automation { + return { + ...automation, + launchSetup: { + ...(automation.surface ? { surface: automation.surface } : {}), + ...(automation.extraAgentArgs !== undefined + ? { extraAgentArgs: automation.extraAgentArgs } + : {}) + } + } +} diff --git a/src/shared/automation-runtime-capabilities.ts b/src/shared/automation-runtime-capabilities.ts index 4c4d3cf76a6d..a629452406ad 100644 --- a/src/shared/automation-runtime-capabilities.ts +++ b/src/shared/automation-runtime-capabilities.ts @@ -13,7 +13,11 @@ export const AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY = export const AUTOMATION_EXTRA_AGENT_ARGS_RUNTIME_CAPABILITY = 'automations.extra-agent-args.v1' as const +// Surface-only hosts retain this capability when the complete picker setup contract ships. +export const AUTOMATION_SURFACE_RUNTIME_CAPABILITY = 'automations.surface.v1' as const + export const AUTOMATION_RUNTIME_CAPABILITIES = [ + AUTOMATION_SURFACE_RUNTIME_CAPABILITY, AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY, AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY, AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY, diff --git a/src/shared/automations-types.ts b/src/shared/automations-types.ts index 439613048b06..e830aa482eb7 100644 --- a/src/shared/automations-types.ts +++ b/src/shared/automations-types.ts @@ -88,6 +88,11 @@ export type AutomationPrecheckResult = { completedAt: number } +export type AutomationLaunchSetupPatch = { + surface?: 'chat' | 'terminal' + arguments?: { kind: 'legacy-extras'; value: string } +} + export type Automation = { id: string /** Optional client request key used to make cross-authority creates retry-safe. */ @@ -96,6 +101,8 @@ export type Automation = { prompt: string precheck: AutomationPrecheck | null agentId: TuiAgent + surface?: 'chat' | 'terminal' + launchSetup?: { surface?: 'chat' | 'terminal'; extraAgentArgs?: string } /** Saved text appended to the host's default agent Arguments on each fresh run; absent means none. */ extraAgentArgs?: string /** Why: runContext carries the logical project + host setup identity for @@ -143,7 +150,7 @@ export type AutomationRun = { workspaceId: string | null /** Keep run history understandable after workspace deletion removes live metadata. */ workspaceDisplayName?: string | null - sessionKind: 'terminal' + sessionKind: 'terminal' | 'chat' chatSessionId: string | null terminalSessionId: string | null /** Retain the executed pane/PTY because terminal tabs may later point elsewhere. */ @@ -180,6 +187,7 @@ export type AutomationCreateInput = { prompt: string precheck?: AutomationPrecheck | null agentId: TuiAgent + launchSetupPatch?: AutomationLaunchSetupPatch /** Empty or whitespace means no extras. */ extraAgentArgs?: string runContext?: WorkspaceRunContext | null @@ -199,7 +207,7 @@ export type AutomationCreateInput = { missedRunGraceMinutes?: number } -export type AutomationUpdateInput = Partial< +export type AutomationUpdateInput = { launchSetupPatch?: AutomationLaunchSetupPatch } & Partial< Pick< Automation, | 'name' @@ -231,6 +239,8 @@ export type AutomationDispatchRequest = { export type AutomationDispatchResult = { runId: string + sessionKind?: 'terminal' | 'chat' + chatSessionId?: string | null status: AutomationRunStatus workspaceId?: string | null workspaceDisplayName?: string | null diff --git a/src/shared/orcad-migration/orcad-migration-dormant-automation-validation.ts b/src/shared/orcad-migration/orcad-migration-dormant-automation-validation.ts index 9ba53982bb12..9b689528ed0d 100644 --- a/src/shared/orcad-migration/orcad-migration-dormant-automation-validation.ts +++ b/src/shared/orcad-migration/orcad-migration-dormant-automation-validation.ts @@ -96,6 +96,9 @@ function isMigratedAutomation(value: unknown): value is Automation { if (!isTuiAgent(record.agentId)) { throw new Error('orcad_migration_dormant_automation_agent_invalid') } + if (record.surface !== undefined && record.surface !== 'chat' && record.surface !== 'terminal') { + throw new Error('orcad_migration_dormant_automation_surface_invalid') + } if (record.extraAgentArgs !== undefined && typeof record.extraAgentArgs !== 'string') { throw new Error('orcad_migration_dormant_automation_extra_agent_args_invalid') } @@ -173,7 +176,7 @@ function isMigratedAutomationRun(value: unknown): value is AutomationRun { record.workspaceDisplayName, 'orcad_migration_dormant_automation_run_workspace_name_invalid' ) - if (record.sessionKind !== 'terminal') { + if (record.sessionKind !== 'terminal' && record.sessionKind !== 'chat') { throw new Error('orcad_migration_dormant_automation_run_session_invalid') } for (const field of [ @@ -185,6 +188,17 @@ function isMigratedAutomationRun(value: unknown): value is AutomationRun { ] as const) { optionalNullableString(record[field], `orcad_migration_dormant_automation_run_${field}_invalid`) } + if ( + record.sessionKind === 'chat' && + [record.terminalSessionId, record.terminalPaneKey, record.terminalPtyId].some( + (value) => value != null + ) + ) { + throw new Error('orcad_migration_dormant_automation_run_session_invalid') + } + if (record.sessionKind === 'terminal' && record.chatSessionId != null) { + throw new Error('orcad_migration_dormant_automation_run_session_invalid') + } parseOutputSnapshot(record.outputSnapshot) parsePrecheckResult(record.precheckResult) parseUsage(record.usage) diff --git a/src/shared/orcad-migration/orcad-migration-manifest.test.ts b/src/shared/orcad-migration/orcad-migration-manifest.test.ts index 265cfae9bb73..c3c80aeb4981 100644 --- a/src/shared/orcad-migration/orcad-migration-manifest.test.ts +++ b/src/shared/orcad-migration/orcad-migration-manifest.test.ts @@ -350,6 +350,50 @@ describe('orcad migration manifest', () => { manifestSha256: 'a'.repeat(64) } + const chatCandidate = { + ...candidate, + payload: { + ...candidate.payload, + dormantState: { + ...candidate.payload.dormantState, + automations: [{ ...automation, surface: 'chat' }], + automationRuns: [ + { + ...run, + sessionKind: 'chat', + chatSessionId: 'claude_chat', + terminalSessionId: null, + terminalPaneKey: null, + terminalPtyId: null + } + ] + } + } + } + const importedChat = parseOrcadMigrationManifest(chatCandidate).payload.dormantState + expect(importedChat?.automations?.[0].surface).toBe('chat') + expect(importedChat?.automationRuns?.[0]).toMatchObject({ + sessionKind: 'chat', + chatSessionId: 'claude_chat', + outputSnapshot: { content: 'all green' } + }) + expect(() => + parseOrcadMigrationManifest({ + ...chatCandidate, + payload: { + ...chatCandidate.payload, + dormantState: { + ...chatCandidate.payload.dormantState, + automationRuns: [ + { + ...chatCandidate.payload.dormantState.automationRuns[0], + terminalPaneKey: 'fake:terminal' + } + ] + } + } + }) + ).toThrow('orcad_migration_dormant_automation_run_session_invalid') expect( parseOrcadMigrationManifest(candidate).payload.dormantState?.automationRuns?.[0] ?.outputSnapshot?.content diff --git a/src/shared/protocol-version.ts b/src/shared/protocol-version.ts index 1061d91aa6ec..9978cb0aa370 100644 --- a/src/shared/protocol-version.ts +++ b/src/shared/protocol-version.ts @@ -66,7 +66,8 @@ export { AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY, AUTOMATION_OWNER_FENCING_UPDATE_REQUIRED_MESSAGE, AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY, - AUTOMATION_EXTRA_AGENT_ARGS_RUNTIME_CAPABILITY + AUTOMATION_EXTRA_AGENT_ARGS_RUNTIME_CAPABILITY, + AUTOMATION_SURFACE_RUNTIME_CAPABILITY } from './automation-runtime-capabilities' export { STRUCTURED_AGENT_SESSION_HOLD_RUNTIME_CAPABILITY, diff --git a/src/shared/rpc-contract/automation-params-extra-agent-args.test.ts b/src/shared/rpc-contract/automation-params-extra-agent-args.test.ts index 3b1cedc38fb1..345ea00dda30 100644 --- a/src/shared/rpc-contract/automation-params-extra-agent-args.test.ts +++ b/src/shared/rpc-contract/automation-params-extra-agent-args.test.ts @@ -29,4 +29,22 @@ describe('extraAgentArgs RPC params', () => { ).toBe(false) } ) + it('accepts the surface-only setup contract and rejects empty or future patch members', () => { + expect( + AutomationCreate.parse({ + ...CREATE, + launchSetupPatch: { surface: 'chat', arguments: { kind: 'legacy-extras', value: '' } } + }).launchSetupPatch + ).toEqual({ surface: 'chat', arguments: { kind: 'legacy-extras', value: '' } }) + for (const launchSetupPatch of [ + {}, + { surface: 'other' }, + { model: 'opus' }, + { arguments: { kind: 'full', value: 'x' } } + ]) { + expect(AutomationUpdate.safeParse({ id: 'a', updates: { launchSetupPatch } }).success).toBe( + false + ) + } + }) }) diff --git a/src/shared/rpc-contract/automation-params.ts b/src/shared/rpc-contract/automation-params.ts index ef675b93ac71..da1f3051bfa2 100644 --- a/src/shared/rpc-contract/automation-params.ts +++ b/src/shared/rpc-contract/automation-params.ts @@ -184,6 +184,15 @@ export const AutomationRuns = z.object({ // Why strict: null or a non-string must fail rather than fall back to "omitted", which preserves. const ExtraAgentArgs = z.string({ message: 'Extra agent arguments must be text.' }).optional() +export const AutomationLaunchSetupPatch = z + .strictObject({ + surface: z.enum(['chat', 'terminal']).optional(), + arguments: z.strictObject({ kind: z.literal('legacy-extras'), value: z.string() }).optional() + }) + .refine((patch) => patch.surface !== undefined || patch.arguments !== undefined, { + message: 'Choose an automation launch change.' + }) + export const AutomationCreate = z.object({ creationKey: OptionalString, name: requiredString('Missing automation name'), @@ -191,6 +200,7 @@ export const AutomationCreate = z.object({ precheck: AutomationPrecheck, agentId: TuiAgent, extraAgentArgs: ExtraAgentArgs, + launchSetupPatch: AutomationLaunchSetupPatch.optional(), runContext: WorkspaceRunContext, sourceContext: TaskSourceContext, repo: OptionalString, @@ -213,6 +223,7 @@ export const AutomationUpdateFields = z.object({ precheck: AutomationPrecheck, agentId: TuiAgent.optional(), extraAgentArgs: ExtraAgentArgs, + launchSetupPatch: AutomationLaunchSetupPatch.optional(), runContext: WorkspaceRunContext, sourceContext: TaskSourceContext, repo: OptionalString, diff --git a/tests/e2e/automation-chat-reopen.unit.test.ts b/tests/e2e/automation-chat-reopen.unit.test.ts new file mode 100644 index 000000000000..c0731b0f93d2 --- /dev/null +++ b/tests/e2e/automation-chat-reopen.unit.test.ts @@ -0,0 +1,109 @@ +import '../../src/main/runtime/rpc/unused-default-rpc-methods.test-fixture' +import { afterEach, expect, it, vi } from 'vitest' +import type { createTestStore } from '../../src/renderer/src/store/slices/store-test-helpers' +import type { RuntimeClientTarget } from '../../src/shared/runtime-client-target' + +const bridge = vi.hoisted(() => { + const current: { + store: ReturnType | null + call: + | ((target: RuntimeClientTarget, method: string, params: unknown) => Promise) + | null + } = { store: null, call: null } + return { current, fallback: vi.fn(), workspace: vi.fn(() => true) } +}) +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => { + if (!bridge.current.store) { + throw new Error('renderer fixture not bound') + } + return bridge.current.store.getState() + } + } +})) +vi.mock('@/runtime/runtime-rpc-client', () => ({ + callRuntimeRpc: (target: RuntimeClientTarget, method: string, params: unknown) => { + if (!bridge.current.call) { + throw new Error('transport fixture not bound') + } + return bridge.current.call(target, method, params) + }, + runtimeEnvironmentSupportsCapability: async () => true +})) +vi.mock('@/lib/worktree-activation', () => ({ activateAndRevealWorktree: bridge.workspace })) +vi.mock('sonner', () => ({ toast: { error: bridge.fallback, message: bridge.fallback } })) +vi.mock('../../src/main/claude/claude-cli-flag-prewarm', () => ({ + prewarmClaudeCliFlags: async () => undefined +})) + +import { CHAT, SURVIVOR, createReopenRig } from './helpers/automation-chat-reopen-test-harness' +import { createTabsSliceMockApi } from '../../src/renderer/src/store/slices/tabs-slice-test-harness' +import { resetWebSessionTabsSyncTestState } from '../../src/renderer/src/runtime/web-session-tabs-sync-test-harness' +import { resetLocalStructuredSessionVersionForTests } from '../../src/renderer/src/runtime/local-structured-session-tabs-sync/inventory-generation-fence' + +createTabsSliceMockApi() +afterEach(() => { + resetWebSessionTabsSyncTestState() + resetLocalStructuredSessionVersionForTests() + bridge.current.store = null + bridge.current.call = null + vi.clearAllMocks() +}) + +it.each([false, true])( + 'Details republishes the same closed durable Chat through real owners, paired=%s', + async (paired) => { + const rig = await createReopenRig(paired, (store) => { + bridge.current.store = store + }) + bridge.current.call = rig.call + try { + await rig.close() + expect(rig.selected()?.entityId).toBe(SURVIVOR) + expect( + rig.store + .getState() + .unifiedTabsByWorktree[rig.workspace]?.some((tab) => tab.entityId === CHAT) + ).toBe(false) + if (paired) { + rig.decoy() + } + rig.action() + await vi.waitFor(() => + expect(rig.calls.some(({ method }) => method === 'agentSession.reveal')).toBe(true) + ) + await vi.waitFor(() => + expect(rig.selected()).toMatchObject({ + entityId: CHAT, + executionHostId: paired ? 'runtime:reopen-host' : 'local' + }) + ) + expect(rig.host.isSessionTabVisible(CHAT)).toBe(true) + await rig.inventory() + expect(rig.selected()?.entityId).toBe(CHAT) + expect(bridge.fallback).not.toHaveBeenCalled() + // A later real close wins; the next explicit click is a new, released interaction. + await rig.close() + await rig.inventory() + expect(rig.selected()?.entityId).toBe(SURVIVOR) + expect(rig.host.isSessionTabVisible(CHAT)).toBe(false) + rig.action() + await vi.waitFor(() => + expect(rig.calls.filter(({ method }) => method === 'agentSession.reveal')).toHaveLength(2) + ) + await vi.waitFor(() => + expect(rig.selected()).toMatchObject({ + entityId: CHAT, + executionHostId: paired ? 'runtime:reopen-host' : 'local' + }) + ) + await rig.inventory() + expect(rig.selected()?.entityId).toBe(CHAT) + expect(bridge.fallback).not.toHaveBeenCalled() + await rig.unchanged() + } finally { + rig.dispose() + } + } +) diff --git a/tests/e2e/automation-save-fallback.unit.test.ts b/tests/e2e/automation-save-fallback.unit.test.ts new file mode 100644 index 000000000000..7dfb8fae889c --- /dev/null +++ b/tests/e2e/automation-save-fallback.unit.test.ts @@ -0,0 +1,97 @@ +// @vitest-environment happy-dom + +import { + installAutomationsPageHarness, + mocks, + RUNTIME_REPO_ID +} from '../../src/renderer/src/components/automations/automations-page-test-harness' +import { + createRpcCalls, + holdRuntimeSave, + observeRuntimeIncarnation, + REGISTERED_CHAT_CAPABILITIES +} from '../../src/renderer/src/components/automations/automations-page-actions-test-harness' +import { + closeTestStores, + createStore, + makeRepo, + testState +} from '../../src/main/persistence/persistence-test-harness' +import { AutomationCreate } from '../../src/shared/rpc-contract/automation-params' +import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../src/shared/protocol-version' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' + +vi.mock('../../src/main/telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../src/main/telemetry/cohort-classifier', () => ({ + getCohortAtEmit: () => ({ nth_repo_added: 2 }) +})) +installAutomationsPageHarness() + +it('settles the actual implicit late-false save with real final-store refusal of invalid Terminal extras', async () => { + const root = mkdtempSync(join(tmpdir(), 'orca-34332-save-')) + testState.dir = root + const disk = createStore() + disk.addRepo(makeRepo({ id: RUNTIME_REPO_ID })) + const before = disk.listAutomations() + const create = vi.spyOn(disk, 'createAutomation') + const held = await holdRuntimeSave({ agentId: 'claude', extraAgentArgs: '--resume x' }) + try { + expect(mocks.editorDialog?.draft).not.toHaveProperty('surface') + observeRuntimeIncarnation( + 'B', + REGISTERED_CHAT_CAPABILITIES.filter((c) => c !== STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY) + ) + const previous = mocks.callRuntimeRpc.getMockImplementation() + mocks.callRuntimeRpc.mockImplementation(async (target, method, payload, options) => { + if (method !== 'automation.create') { + return await previous?.(target, method, payload, options) + } + const { + repo, + workspace: _workspace, + destination: _destination, + workspaceMode, + timezone, + ...input + } = AutomationCreate.parse(payload) + expect(repo).toBe(`id:${RUNTIME_REPO_ID}`) + if (workspaceMode !== 'new_per_run') { + throw new Error('Expected actual new_per_run workspace mode') + } + if (typeof timezone !== 'string' || timezone.trim().length === 0) { + throw new Error('Expected actual nonempty timezone') + } + return { + automation: disk.createAutomation({ + ...input, + workspaceMode, + timezone, + projectId: RUNTIME_REPO_ID + }) + } + }) + await held.page.rerender() + await held.release() + expect(createRpcCalls()).toHaveLength(1) + expect(createRpcCalls()[0]?.[2]).not.toHaveProperty('launchSetupPatch') + expect(create).toHaveBeenCalledOnce() + expect(create).toHaveBeenCalledWith(expect.objectContaining({ extraAgentArgs: '--resume x' })) + expect(create.mock.results[0]?.type).toBe('throw') + expect(disk.listAutomations()).toEqual(before) + expect(mocks.toastSuccess).not.toHaveBeenCalled() + expect(mocks.editorDialog?.notice?.message).toContain('--resume') + expect(mocks.editorDialog?.open).toBe(true) + expect(mocks.editorDialog?.isSaving).toBe(false) + disk.flush() + await closeTestStores() + const reloaded = createStore() + expect(reloaded.listAutomations()).toEqual(before) + } finally { + await held.release() + await closeTestStores() + rmSync(root, { recursive: true, force: true }) + } +}) diff --git a/tests/e2e/headless-automation-agent-launch.unit.test.ts b/tests/e2e/headless-automation-agent-launch.unit.test.ts new file mode 100644 index 000000000000..7a5485f05694 --- /dev/null +++ b/tests/e2e/headless-automation-agent-launch.unit.test.ts @@ -0,0 +1,581 @@ +import '../../src/main/runtime/rpc/unused-default-rpc-methods.test-fixture' +import type { createChatRendererBridge } from './helpers/automation-chat-renderer-test-harness' +import { exerciseBusyChatReuse } from './helpers/automation-chat-reuse-test-harness' +import { readAutomationRunReceipt } from '../../src/main/automations/automation-run-receipt' +import { + AUTOMATION_AGENT_CALLER, + automationRunOperationId +} from '../../src/main/automations/automation-run-operation' +import { rpcCallerOperationKey } from '../../src/main/runtime/rpc/rpc-caller-identity' +import { + HOST_TEST_NOW, + HOST_TEST_SESSION, + HOST_TEST_LOCATION +} from '../../src/main/native-chat/agent-session-wire/structured-agent-session-host-test-data' +import type { callStructuredAgentSession } from '@/runtime/structured-agent-session-client' +import type { StructuredAgentSessionHost } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-host' +import { createQueuedMessageTestRig } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' +import type { AgentLaunchResult } from '../../src/shared/agent-launch-intent' +import { buildProfileStateCutoverFixture } from '../../src/main/persistence/profile-state-cutover-fixture' +import { launchAutomationChatAgent } from '../../src/main/automations/automation-chat-agent-launch' + +const mocks = vi.hoisted(() => { + const hostState: { + actualHost: StructuredAgentSessionHost | null + renderer: Awaited> | null + } = { actualHost: null, renderer: null } + return { + ...hostState, + hostAvailable: true, + readChat: vi.fn().mockResolvedValue({}), + launch: vi.fn(), + host: { journalSnapshot: vi.fn(), currentWork: vi.fn(), send: vi.fn() } + } +}) +vi.mock('../../src/main/runtime/rpc/methods/agent-launch', () => ({ + launchAgentOnHost: mocks.launch +})) +vi.mock('../../src/main/native-chat/agent-session-wire/structured-agent-session-registry', () => ({ + getStructuredAgentSessionHost: () => mocks.actualHost ?? (mocks.hostAvailable ? mocks.host : null) +})) +vi.mock('@/runtime/structured-agent-session-client', () => ({ + callStructuredAgentSession: (...args: Parameters) => + mocks.readChat(...args) +})) +vi.mock('@/runtime/runtime-rpc-client', () => ({ + callRuntimeRpc: ( + target: Parameters['call']>[0], + method: string, + params: unknown + ) => { + if (!mocks.renderer) { + throw new Error('renderer not bound') + } + return mocks.renderer.call(target, method, params) + }, + runtimeEnvironmentSupportsCapability: async () => true +})) +vi.mock('@/lib/worktree-activation', () => ({ activateAndRevealWorktree: () => true })) +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => + mocks.renderer?.store.getState() ?? { + settings: {}, + repos: [], + worktreesByRepo: {}, + getTab: () => undefined, + terminalLayoutsByTabId: {}, + ptyIdsByTabId: {} + } + } +})) +vi.mock('sonner', () => ({ toast: { error: vi.fn(), message: vi.fn() } })) +const state = buildProfileStateCutoverFixture('/fixture') +const run = { ...state.automationRuns[0], id: 'run-1', createdAt: Date.now() } +const automation = { + ...state.automations[0], + id: run.automationId, + agentId: 'claude' as const, + workspaceMode: 'existing' as const, + workspaceId: 'wt-1', + prompt: 'Audit', + surface: 'chat' as const, + extraAgentArgs: undefined +} +const target = { ok: true as const, repo: state.repos[0], cwd: '/fixture' } +const terminal: AgentLaunchResult = { + worktreeId: 'wt-1', + outcome: { kind: 'terminal', handle: 'term-1', paneKey: 'tab-1:leaf-1' }, + receipt: { + mode: 'terminal', + preferred: 'structured', + reason: 'structured_unsupported_on_host', + detail: 'Fallback' + }, + prompt: { delivery: 'submit', outcome: 'handed-to-terminal' } +} +const chat: AgentLaunchResult = { + ...terminal, + outcome: { kind: 'structured', sessionId: 'claude_chat', handle: 'chat-tab' }, + prompt: { delivery: 'submit', outcome: 'journaled', messageId: 'first-message' } +} +function fixture() { + const conversation = (id: string) => ({ + sessionId: id, + provider: 'claude', + location: { workspaceId: 'wt-1' }, + currentFence: 2 + }) + const records = { + readOnly: false, + selectWritableRecord: vi.fn((_id: string): { kind: 'writable' | 'missing' | 'unreadable' } => ({ + kind: 'writable' + })), + isSessionUnreadable: vi.fn(() => false), + readCommandReceipt: vi.fn(() => ({ verdict: 'absent' })), + getOperationRow: vi.fn(), + getConversation: vi.fn<(id: string) => ReturnType | null>(conversation) + } + const runtime = { + requireStore: () => ({ + getSettings: () => ({ + experimentalNativeChat: true, + workspaceDir: '/fixture', + nestWorkspaces: false, + agentDefaultArgs: { claude: '--model sonnet --add-dir docs' } + }) + }), + showTerminalWorkspaceLaunchScope: vi.fn(async () => ({ + id: 'wt-1', + path: '/fixture', + connectionId: 'ssh-test' + })), + showManagedWorktree: vi.fn(async () => ({ displayName: 'Audit' })), + showTerminal: vi.fn(async () => ({ tabId: 'tab-1' })), + getTerminalPtyIdForHandle: vi.fn(() => 'pty-1'), + getTerminalPaneKey: vi.fn(() => 'tab-1:leaf-1'), + getTerminalHandleForPaneKey: vi.fn(() => 'term-prev'), + getAgentStatusRowsForPane: vi.fn(() => [{ state: 'done', agentType: 'claude', receivedAt: 1 }]), + ensureStructuredAgentSessionHost: vi.fn(), + openAgentSessionRecordStore: vi.fn(async () => records) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the runtime boundaries above are reached; the ordinary launch is mocked separately. + return { runtime: runtime as unknown as OrcaRuntimeService, records } +} +beforeEach(() => { + vi.clearAllMocks() + mocks.actualHost = null + mocks.hostAvailable = true + mocks.launch.mockResolvedValue(terminal) + mocks.host.currentWork.mockReturnValue({ working: () => false }) + mocks.host.send.mockResolvedValue({ ok: true }) +}) +describe('automations through agent.launch', () => { + it.each(['claude', 'codex'] as const)( + 'launches explicit Chat for %s through the common entry and keeps its actual fallback', + async (agentId) => { + const { runtime } = fixture() + const result = await launchAutomationChatAgent(runtime, { + automation: { ...automation, agentId }, + run, + target, + runs: [] + }) + expect(mocks.launch).toHaveBeenCalledWith( + expect.objectContaining({ + agent: agentId, + surface: 'chat', + operationId: automationRunOperationId(run, 'fresh-launch'), + prompt: { text: 'Audit', delivery: 'submit' }, + presentation: 'background', + target: { kind: 'existing', worktree: 'id:wt-1' } + }), + expect.objectContaining({ runtime }), + expect.objectContaining({ + onSurfacePublished: expect.any(Function) + }) + ) + expect(result).toMatchObject({ + workspaceDisplayName: 'Audit', + sessionKind: 'terminal', + chatSessionId: null, + terminalPtyId: 'pty-1' + }) + } + ) + it('does not apply stored Terminal extras to Chat', async () => { + const { runtime } = fixture() + mocks.launch.mockResolvedValue(chat) + await launchAutomationChatAgent(runtime, { + automation: { ...automation, extraAgentArgs: '--model opus' }, + run, + target, + runs: [] + }) + expect(mocks.launch.mock.calls[0][0].agentArgs).toBeUndefined() + }) + it('refuses an expired admission without minting another launch identity', async () => { + const { runtime } = fixture() + mocks.launch.mockRejectedValue(new Error('agent_session_operation_expired')) + await expect( + launchAutomationChatAgent(runtime, { automation, run, target, runs: [] }) + ).rejects.toThrow( + 'Claude could not start because this run waited too long. Run the automation again.' + ) + expect(mocks.launch).toHaveBeenCalledTimes(1) + }) + it('records the actual chat identity and delegates new workspace setup and provenance', async () => { + const { runtime } = fixture() + mocks.launch.mockResolvedValue(chat) + const result = await launchAutomationChatAgent(runtime, { + automation: { + ...automation, + surface: 'chat', + workspaceMode: 'new_per_run', + workspaceId: null, + setupDecision: 'run' + }, + run, + target, + runs: [] + }) + expect(mocks.launch).toHaveBeenCalledWith( + expect.objectContaining({ + surface: 'chat', + target: { + kind: 'create-worktree', + create: expect.objectContaining({ + setupDecision: 'run', + activate: false, + automationProvenanceRequest: expect.objectContaining({ + automationId: automation.id, + automationRunId: run.id + }) + }) + } + }), + expect.anything(), + expect.anything() + ) + expect(result).toMatchObject({ + sessionKind: 'chat', + chatSessionId: 'claude_chat', + terminalHandle: null, + terminalPaneKey: null, + terminalSessionId: null, + terminalPtyId: null + }) + }) + it('chooses the newest compatible Chat despite busy work and stale nonfinal history', async () => { + const { runtime, records } = fixture() + mocks.host.currentWork.mockReturnValue({ working: () => true }) + const previous = { + ...run, + id: 'newest', + createdAt: run.createdAt + 10, + status: 'dispatched' as const, + workspaceId: 'stale-workspace', + sessionKind: 'chat' as const, + chatSessionId: 'claude_prev' + } + const result = await launchAutomationChatAgent(runtime, { + automation: { ...automation, surface: 'chat', reuseSession: true }, + run, + target, + runs: [ + { ...previous, id: 'non-chat', createdAt: previous.createdAt + 1, sessionKind: 'terminal' }, + { + ...previous, + id: 'other-automation', + automationId: 'other', + createdAt: previous.createdAt + 2 + }, + { ...previous, id: run.id, createdAt: previous.createdAt + 3 }, + previous, + { ...previous, id: 'duplicate', createdAt: run.createdAt }, + { + ...previous, + id: 'older-idle', + chatSessionId: 'claude_idle', + createdAt: run.createdAt - 1, + status: 'completed' + } + ] + }) + expect(result).toMatchObject({ chatSessionId: 'claude_prev', workspaceId: 'wt-1' }) + expect(records.getConversation).toHaveBeenCalledExactlyOnceWith('claude_prev') + expect(mocks.host.send).toHaveBeenCalledExactlyOnceWith( + expect.anything(), + expect.objectContaining({ + delivery: 'queue-if-active', + envelope: expect.objectContaining({ + sessionId: 'claude_prev', + clientOperationId: automationRunOperationId(run, 'reuse-send'), + expectedRuntimeFence: 2 + }) + }) + ) + expect(mocks.host.currentWork).not.toHaveBeenCalled() + expect(mocks.host.journalSnapshot).not.toHaveBeenCalled() + expect(mocks.launch).not.toHaveBeenCalled() + }) + it('skips genuinely missing/incompatible records and never needs a current work projection', async () => { + const { runtime, records } = fixture() + mocks.host.currentWork.mockReturnValue(null) + records.selectWritableRecord.mockImplementation((id) => ({ + kind: id === 'missing' ? 'missing' : 'writable' + })) + records.getConversation.mockImplementation((id) => ({ + sessionId: id, + provider: 'claude', + location: { workspaceId: id === 'moved' ? 'elsewhere' : 'wt-1' }, + currentFence: 2 + })) + const runs = ['missing', 'moved', 'claude_prev'].map((id, n) => ({ + ...run, + id, + createdAt: run.createdAt - n - 1, + status: 'dispatch_failed' as const, + sessionKind: 'chat' as const, + chatSessionId: id + })) + const request = { + automation: { ...automation, surface: 'chat' as const, reuseSession: true }, + run, + target, + runs + } + expect((await launchAutomationChatAgent(runtime, request)).chatSessionId).toBe('claude_prev') + expect(mocks.launch).not.toHaveBeenCalled() + mocks.host.send.mockClear() + mocks.launch.mockResolvedValue(chat) + await launchAutomationChatAgent(runtime, { ...request, runs: runs.slice(0, 2) }) + expect(mocks.host.send).not.toHaveBeenCalled() + expect(mocks.launch).toHaveBeenCalledOnce() + expect(mocks.launch.mock.calls[0][0].operationId).toBe( + automationRunOperationId(run, 'fresh-launch') + ) + }) +}) + +it.each(['terminal', 'chat'] as const)( + 'preserves published %s identity for refused, uncertain and throwing settlement', + async (kind) => { + const { runtime, records } = fixture() + const paneKey = 'tab-1:11111111-1111-4111-8111-111111111111' + const published = + kind === 'chat' + ? chat + : { ...terminal, outcome: { kind: 'terminal' as const, handle: 'term-1', paneKey } } + for (const outcome of ['not-delivered', 'unconfirmed', 'throw', 'accepted-throw'] as const) { + mocks.launch.mockImplementationOnce(async (_params, _context, policy) => { + policy.onSurfacePublished(published) + if (outcome === 'accepted-throw') { + records.getOperationRow.mockImplementation((_caller, id) => + id === automationRunOperationId(run, 'fresh-launch') + ? { outcome: { status: 'succeeded', launch: published } } + : undefined + ) + throw new Error('accepted reply lost') + } + if (outcome === 'throw') { + throw new Error('settlement transport lost') + } + return { ...published, prompt: { delivery: 'submit', outcome } } + }) + const result = await launchAutomationChatAgent(runtime, { + automation: { + ...automation, + surface: 'chat' + }, + run, + target, + runs: [] + }).catch((error) => error) + expect(outcome === 'accepted-throw' ? { target: result } : result).toMatchObject({ + target: { + workspaceId: 'wt-1', + sessionKind: kind === 'chat' ? 'chat' : 'terminal', + ...(kind === 'chat' + ? { chatSessionId: 'claude_chat', terminalPaneKey: null, terminalSessionId: null } + : { + terminalPaneKey: paneKey, + terminalSessionId: 'tab-1', + terminalPtyId: 'pty-1' + }) + } + }) + } + expect(mocks.launch).toHaveBeenCalledTimes(4) + expect(mocks.host.send).not.toHaveBeenCalled() + } +) + +it.each(['normal', 'lost-reply', 'restart'] as const)( + 'keeps busy Chat Q→S through %s, exact persisted output and normal Details', + (mode) => + exerciseBusyChatReuse(mode, automation, target, { + setHost: (host) => { + mocks.actualHost = host + }, + bindRenderer: (renderer) => { + mocks.renderer = renderer + }, + launch: mocks.launch + }) +) + +it('retains a known identity when record/host preparation cannot prove availability', async () => { + for (const failure of [ + 'unreadable', + 'null-view', + 'read-failed', + 'read-only-missing', + 'host-absent', + 'host-failed' + ] as const) { + const { runtime, records } = fixture() + mocks.host.send.mockClear() + mocks.hostAvailable = failure !== 'host-absent' + if (failure === 'unreadable') { + records.selectWritableRecord.mockReturnValue({ kind: 'unreadable' }) + } + if (failure === 'null-view') { + records.getConversation.mockReturnValue(null) + } + if (failure === 'read-failed') { + records.getConversation.mockImplementation(() => { + throw new Error('unreadable disk') + }) + } + if (failure === 'read-only-missing') { + records.readOnly = true + records.selectWritableRecord.mockReturnValue({ kind: 'missing' }) + } + if (failure === 'host-failed') { + vi.spyOn(runtime, 'ensureStructuredAgentSessionHost').mockRejectedValueOnce( + new Error('host failed') + ) + } + await expect( + launchAutomationChatAgent(runtime, { + automation: { ...automation, surface: 'chat', reuseSession: true }, + run, + target, + runs: [{ ...run, id: 'old', sessionKind: 'chat', chatSessionId: 'claude_prev' }] + }) + ).rejects.toMatchObject({ target: { sessionKind: 'chat', chatSessionId: 'claude_prev' } }) + expect(mocks.host.send).not.toHaveBeenCalled() + expect(mocks.launch).not.toHaveBeenCalled() + } +}) + +it.each(['before-admission', 'accepted-reply', 'accepted-lost-reply'] as const)( + 'permits fresh only for authoritative deletion %s', + async (when) => { + vi.spyOn(Date, 'now').mockReturnValue(HOST_TEST_NOW) + const current = { ...run, createdAt: HOST_TEST_NOW } + const rig = await createQueuedMessageTestRig({ restartable: true }) + mocks.actualHost = rig.host + let removedRecord = rig.store.getRecord(HOST_TEST_SESSION)! + const removeRecord = () => + rig.store['transact']((draft) => { + removedRecord = draft.records.get(HOST_TEST_SESSION)! + draft.records.delete(HOST_TEST_SESSION) + }) + try { + const { runtime } = fixture() + vi.spyOn(runtime, 'openAgentSessionRecordStore').mockResolvedValue(rig.store) + const sent = rig.host.send.bind(rig.host) + const send = vi.spyOn(rig.host, 'send').mockImplementationOnce(async (...args) => { + if (when === 'before-admission') { + await removeRecord() + } + const reply = await sent(...args) + if (when === 'before-admission') { + expect(reply).toMatchObject({ + ok: false, + refusal: { + code: 'agent_session_ownership_unknown', + details: { reason: 'sessionNotAttached' } + } + }) + } else { + expect(reply.ok).toBe(true) + await removeRecord() + if (when === 'accepted-lost-reply') { + throw new Error('accepted reply lost after deletion') + } + } + return reply + }) + mocks.launch.mockResolvedValue(chat) + const attempt = launchAutomationChatAgent(runtime, { + automation: { + ...automation, + agentId: 'codex', + workspaceId: HOST_TEST_LOCATION.workspaceId, + surface: 'chat', + reuseSession: true + }, + run: current, + target, + runs: [{ ...run, id: 'old', sessionKind: 'chat', chatSessionId: HOST_TEST_SESSION }] + }) + if (when === 'accepted-lost-reply') { + await expect(attempt).rejects.toMatchObject({ + target: { chatSessionId: HOST_TEST_SESSION } + }) + } else { + expect((await attempt).chatSessionId).toBe( + when === 'before-admission' ? 'claude_chat' : HOST_TEST_SESSION + ) + } + const q = automationRunOperationId(current, 'reuse-send') + expect(rig.store.readCommandReceipt({ kind: 'global' }, q).verdict).toBe('absent') + expect(readAutomationRunReceipt(rig.store, current)).toBeNull() + expect( + rig.store.getOperationRow(rpcCallerOperationKey(AUTOMATION_AGENT_CALLER), q)?.outcome.status + ).toBe(when === 'before-admission' ? undefined : 'succeeded') + expect(send).toHaveBeenCalledOnce() + expect(mocks.launch).toHaveBeenCalledTimes(when === 'before-admission' ? 1 : 0) + if (when === 'before-admission') { + expect(mocks.launch.mock.calls[0][0].operationId).toBe( + automationRunOperationId(current, 'fresh-launch') + ) + } + } finally { + mocks.actualHost = null + // Restore the injected deletion only after assertions so ordinary host teardown can run. + await rig.store['transact']((draft) => { + draft.records.set(HOST_TEST_SESSION, removedRecord) + }) + await rig.dispose() + } + } +) + +it.each(['unknown', 'refused', 'conflict', 'failed-row'] as const)( + 'retains known reused Chat on %s acceptance without resending', + async (acceptance) => { + const { runtime, records } = fixture() + mocks.host.send.mockImplementationOnce(async () => { + if (acceptance === 'unknown') { + throw new Error('transport lost') + } + return { + ok: false, + refusal: { + code: + acceptance === 'conflict' ? 'agent_session_conflict' : 'agent_session_operation_unknown' + } + } + }) + records.getOperationRow.mockReturnValue( + acceptance === 'failed-row' ? { outcome: { status: 'failed' } } : undefined + ) + await expect( + launchAutomationChatAgent(runtime, { + automation: { ...automation, surface: 'chat', reuseSession: true }, + run, + target, + runs: [ + { + ...run, + id: 'old', + status: 'completed', + workspaceId: 'wt-1', + sessionKind: 'chat', + chatSessionId: 'claude_prev' + } + ] + }) + ).rejects.toMatchObject({ target: { sessionKind: 'chat', chatSessionId: 'claude_prev' } }) + expect(mocks.host.send).toHaveBeenCalledOnce() + expect(mocks.launch).not.toHaveBeenCalled() + } +) + +afterEach(() => vi.restoreAllMocks()) diff --git a/tests/e2e/helpers/automation-chat-renderer-test-harness.ts b/tests/e2e/helpers/automation-chat-renderer-test-harness.ts new file mode 100644 index 000000000000..fa563d7156df --- /dev/null +++ b/tests/e2e/helpers/automation-chat-renderer-test-harness.ts @@ -0,0 +1,169 @@ +import type { AutomationRun } from '../../../src/shared/automations-types' +import { createAutomationRunWorkspaceAction } from '../../../src/renderer/src/components/automations/automation-run-workspace-action' +import type { AutomationsPageActionContext } from '../../../src/renderer/src/components/automations/automations-page-action-context' +import { expect, vi } from 'vitest' +import type { RuntimeClientTarget } from '../../../src/shared/runtime-client-target' +import type { RuntimeMobileSessionTabsResult } from '../../../src/shared/runtime-types' +import { RuntimeRpcEnvelopeSchema } from '../../../src/shared/runtime-rpc-envelope' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../src/shared/electron-remote-runtime-client-capabilities' +import { decodeSessionTabsDeltaEvents } from '../../../src/main/ipc/runtime-environments/runtime-environment-session-tabs-delta-decoding' +import { RpcDispatcher } from '../../../src/main/runtime/rpc/dispatcher' +import { STRUCTURED_AGENT_SESSION_METHODS } from '../../../src/main/runtime/rpc/methods/structured-agent-session' +import { SESSION_TAB_METHODS } from '../../../src/main/runtime/rpc/methods/session-tabs' +import { OrcaRuntimeService } from '../../../src/main/runtime/orca-runtime' +import { createTestStore } from '../../../src/renderer/src/store/slices/store-test-helpers' +import type { SessionTabsStreamEvent } from '../../../src/renderer/src/runtime/web-session-tabs-sync/state' +import { applyStructuredSessionTabSnapshots } from '../../../src/renderer/src/runtime/local-structured-session-tabs-sync/snapshot-apply' +import { applyWebSessionTabsSnapshot } from '../../../src/renderer/src/runtime/web-session-tabs-sync/snapshot-api' +import { decideWebSessionTabsSnapshot } from '../../../src/renderer/src/runtime/web-session-tabs-sync/tracking-decisions' + +export class ChatOpenTestRuntime extends OrcaRuntimeService { + protected override async refreshMobileSessionPtyRecords() { + return new Set() + } +} + +/** Only transport and PTY census are bridged; record reveal, publication, mirror and selection stay real. */ +export async function createChatRendererBridge( + runtime: OrcaRuntimeService, + workspace: string, + target: RuntimeClientTarget, + store: ReturnType = createTestStore() +) { + const paired = target.kind === 'environment' + const dispatcher = new RpcDispatcher({ + runtime, + methods: [ + ...STRUCTURED_AGENT_SESSION_METHODS.filter((method) => + ['agentSession.close', 'agentSession.history', 'agentSession.reveal'].includes(method.name) + ), + ...SESSION_TAB_METHODS.filter((method) => + [ + 'session.tabs.list', + 'session.tabs.close', + 'session.tabs.activate', + 'session.tabs.subscribe' + ].includes(method.name) + ) + ] + }) + let request = 0 + const options = { + clientKind: 'runtime' as const, + clientCapabilities: [...ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES] + } + const calls: { target: RuntimeClientTarget; method: string; params: unknown }[] = [] + const call = async (recipient: RuntimeClientTarget, method: string, params: unknown) => { + expect(recipient).toEqual(target) + calls.push({ target: recipient, method, params }) + const reply = await dispatcher.dispatch( + { id: `reopen-${++request}`, authToken: 'fixture', method, params }, + options + ) + if (!reply.ok) { + console.info('D1 transport refusal', method, JSON.stringify(reply.error)) + } + if (!reply.ok) { + throw new Error(`${method}: ${JSON.stringify(reply.error)}`) + } + return reply.result + } + const apply = (snapshot: RuntimeMobileSessionTabsResult) => { + if (paired) { + if ( + decideWebSessionTabsSnapshot( + snapshot, + target.kind === 'environment' ? target.environmentId : '' + ).apply + ) { + store.setState((state) => + applyWebSessionTabsSnapshot( + state, + snapshot, + target.kind === 'environment' ? target.environmentId : '' + ) + ) + } + } else { + applyStructuredSessionTabSnapshots([snapshot]) + } + } + const inventory = async () => { + const snapshot = await runtime.listMobileSessionTabs(`id:${workspace}`) + apply(snapshot) + return snapshot + } + // Only the transport is bridged: paired mirrors receive the actual production subscription. + const subscription = new AbortController() + if (paired) { + const decode = decodeSessionTabsDeltaEvents('session.tabs.subscribe', (payload) => { + if (payload.type !== 'response' || !payload.response.ok) { + return + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the real subscription handler emitted this frame and the production decoder reconstructed its tab deltas. + const event = payload.response.result as SessionTabsStreamEvent + if (event.type === 'snapshot' || event.type === 'updated') { + apply(event) + } + }) + await dispatcher.dispatchStreaming( + { + id: 'reopen-stream', + authToken: 'fixture', + method: 'session.tabs.subscribe', + params: { worktree: `id:${workspace}` } + }, + (json) => { + const response = RuntimeRpcEnvelopeSchema.parse(JSON.parse(json)) + if ('ok' in response) { + decode({ type: 'response', response }) + } + }, + { ...options, signal: subscription.signal } + ) + } + const selected = () => { + const state = store.getState() + const group = state.groupsByWorktree[workspace]?.find( + (candidate) => candidate.id === state.activeGroupIdByWorktree[workspace] + ) + return state.unifiedTabsByWorktree[workspace]?.find((tab) => tab.id === group?.activeTabId) + } + return { store, calls, call, inventory, apply, selected, dispose: () => subscription.abort() } +} + +export async function exerciseRecordedChatOpen( + runtime: OrcaRuntimeService, + run: AutomationRun, + bind: (renderer: Awaited> | null) => void +) { + if (!run.workspaceId || !run.chatSessionId) { + throw new Error('a recorded Chat is required') + } + const renderer = await createChatRendererBridge(runtime, run.workspaceId, { kind: 'local' }) + renderer.store.setState({ activeWorktreeId: run.workspaceId }) + const pageContext = { + store: { + repoForRow: () => undefined, + worktreeForRow: () => ({ id: run.workspaceId, hostId: 'local' }) + }, + list: { selectedRow: { key: 'row' } } + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only row/workspace lookup is scripted; the real Details action, opener, RPC, host, publication and renderer store execute. + const context = pageContext as unknown as AutomationsPageActionContext + bind(renderer) + try { + createAutomationRunWorkspaceAction(context)(run) + await vi.waitFor(() => + expect(renderer.selected()).toMatchObject({ + entityId: run.chatSessionId, + executionHostId: 'local' + }) + ) + await renderer.inventory() + expect(renderer.selected()?.entityId).toBe(run.chatSessionId) + } finally { + renderer.dispose() + bind(null) + } +} diff --git a/tests/e2e/helpers/automation-chat-reopen-test-harness.ts b/tests/e2e/helpers/automation-chat-reopen-test-harness.ts new file mode 100644 index 000000000000..65ccb8daa81d --- /dev/null +++ b/tests/e2e/helpers/automation-chat-reopen-test-harness.ts @@ -0,0 +1,158 @@ +import { createChatRendererBridge } from './automation-chat-renderer-test-harness' +import { expect, vi } from 'vitest' +import type { RuntimeClientTarget } from '../../../src/shared/runtime-client-target' +import { + authorityProfile, + openAuthorityRuntime, + root +} from '../../../src/main/runtime/structured-agent-session-tab-authority.test-support' +import { editPersistedTestAgentSessionStore } from '../../../src/main/runtime/agent-session-record-store-test-harness' +import { + codexProviderHandle, + encodePersistedAgentSessionProviderHandle +} from '../../../src/shared/agent-session-provider-handle-encoding' +import { + createTestStore, + makeUnifiedTab +} from '../../../src/renderer/src/store/slices/store-test-helpers' +import { makeFolderWorkspace } from '../../../src/renderer/src/store/slices/worktrees-slice-test-fixtures' +import { createAutomationRunWorkspaceAction } from '../../../src/renderer/src/components/automations/automation-run-workspace-action' +import type { AutomationsPageActionContext } from '../../../src/renderer/src/components/automations/automations-page-action-context' +import { createAutomationRunWriter } from '../../../src/main/automations/automation-run-writer' +import { makeRepo } from '../../../src/main/persistence/persistence-test-harness' +import { structuredAgentSessionTabId } from '../../../src/shared/structured-agent-session-projection' +import { retireStructuredAgentSessionTab } from '../../../src/renderer/src/runtime/structured-agent-session-tab-retirement' + +export const CHAT = 'claude_saved_reopen', + SURVIVOR = 'codex_surviving_chat' + +export async function createReopenRig( + paired: boolean, + bind: (store: ReturnType) => void +) { + const profile = await authorityProfile([], { + records: [CHAT, SURVIVOR], + visible: [CHAT, SURVIVOR] + }) + await editPersistedTestAgentSessionStore(root, (state) => { + state.sessionTabs = [CHAT, SURVIVOR].map((sessionId) => ({ + sessionId, + tabId: `agent-session:${sessionId}` + })) + const other = state.records[SURVIVOR]! + other.provider = 'codex' + other.accountHome = { variable: 'CODEX_HOME', path: `${root}/fixture-codex` } + other.providerHandleChain[0]!.handle = encodePersistedAgentSessionProviderHandle( + codexProviderHandle('survivor-thread') + ) + }) + const rig = await openAuthorityRuntime(profile) + const store = createTestStore() + bind(store) + const target: RuntimeClientTarget = paired + ? { kind: 'environment', environmentId: 'reopen-host' } + : { kind: 'local' } + const hostId = paired ? 'runtime:reopen-host' : 'local' + store.setState({ + folderWorkspaces: [ + makeFolderWorkspace({ + id: rig.folderId, + projectGroupId: rig.groupId, + folderPath: root, + executionHostId: hostId + }) + ], + projectGroups: [], + activeWorktreeId: rig.workspace, + activeWorkspaceExecutionHostId: hostId + }) + const renderer = await createChatRendererBridge(rig.runtime, rig.workspace, target, store) + const { calls, inventory } = renderer + await rig.runtime.restoreStructuredAgentSessionTabs() + await rig.runtime.publishStructuredAgentSessionTab({ + workspaceId: rig.workspace, + sessionId: CHAT, + agent: 'claude', + activate: true + }) + await rig.runtime.publishStructuredAgentSessionTab({ + workspaceId: rig.workspace, + sessionId: SURVIVOR, + agent: 'codex', + activate: false + }) + await inventory() + const repo = makeRepo({ id: 'reopen-repo', path: root }) + rig.profile.addRepo(repo) + const automation = rig.profile.createAutomation({ + projectId: repo.id, + name: 'Saved reopen', + rrule: 'FREQ=DAILY', + dtstart: Date.now(), + prompt: 'Preserved prompt', + agentId: 'claude', + workspaceMode: 'new_per_run', + timezone: 'UTC', + enabled: false, + launchSetupPatch: { surface: 'chat' } + }) + const writer = createAutomationRunWriter(rig.profile, null) + const created = await writer.createRun(automation, Date.now(), 'manual') + const run = await writer.updateRun({ + runId: created.id, + status: 'completed', + sessionKind: 'chat', + chatSessionId: CHAT, + workspaceId: rig.workspace, + outputSnapshot: { + format: 'plain_text', + content: 'Exact saved output', + truncated: false, + capturedAt: Date.now() + } + }) + const beforeJournal = await rig.host.journalSnapshot(CHAT) + const beforeRecord = rig.store.getConversation(CHAT) + const send = vi.spyOn(rig.host, 'send'), + create = vi.spyOn(rig.host, 'create') + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only these row resolvers are read by the real Details action; all Chat/open/close/store owners execute. + const context = { + store: { repoForRow: () => undefined, worktreeForRow: () => ({ id: rig.workspace, hostId }) }, + list: { selectedRow: { key: 'saved' } } + } as unknown as AutomationsPageActionContext + const action = createAutomationRunWorkspaceAction(context) + const close = async () => { + store.getState().closeUnifiedTab(structuredAgentSessionTabId(CHAT)) + await retireStructuredAgentSessionTab({ target, worktreeId: rig.workspace, sessionId: CHAT }) + await inventory() + expect(rig.host.isSessionTabVisible(CHAT)).toBe(false) + } + const unchanged = async () => { + expect(rig.profile.listAutomationRuns(automation.id)).toEqual([run]) + expect(await rig.host.journalSnapshot(CHAT)).toEqual(beforeJournal) + expect(rig.store.getConversation(CHAT)).toEqual(beforeRecord) + expect(send).not.toHaveBeenCalled() + expect(create).not.toHaveBeenCalled() + expect(rig.acquire).not.toHaveBeenCalled() + expect(calls.every(({ method }) => !/create|send|launch/.test(method))).toBe(true) + } + const decoy = () => { + store.setState((state) => ({ + unifiedTabsByWorktree: { + ...state.unifiedTabsByWorktree, + [rig.workspace]: [ + makeUnifiedTab({ + id: 'wrong-owner', + entityId: CHAT, + worktreeId: rig.workspace, + contentType: 'agent-session', + executionHostId: 'local', + groupId: 'decoy' + }), + ...(state.unifiedTabsByWorktree[rig.workspace] ?? []) + ] + } + })) + } + return { ...rig, ...renderer, target, action: () => action(run), close, unchanged, decoy } +} diff --git a/tests/e2e/helpers/automation-chat-reuse-test-harness.ts b/tests/e2e/helpers/automation-chat-reuse-test-harness.ts new file mode 100644 index 000000000000..0450dc6ca3e9 --- /dev/null +++ b/tests/e2e/helpers/automation-chat-reuse-test-harness.ts @@ -0,0 +1,270 @@ +import { + ChatOpenTestRuntime, + exerciseRecordedChatOpen, + type createChatRendererBridge +} from './automation-chat-renderer-test-harness' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, vi, type Mock } from 'vitest' +import type { OrcaRuntimeService } from '../../../src/main/runtime/orca-runtime' +import type { StructuredAgentSessionHost } from '../../../src/main/native-chat/agent-session-wire/structured-agent-session-host' +import { createRuntimeAutomationService } from '../../../src/main/automations/runtime-automation-service' +import { createAutomationRunWriter } from '../../../src/main/automations/automation-run-writer' +import type { AutomationChatLaunchRequest } from '../../../src/main/automations/automation-chat-agent-launch' +import { automationRunOperationId } from '../../../src/main/automations/automation-run-operation' +import { agentJournalItemKey } from '../../../src/shared/agent-session-journal-item-key' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../src/shared/agent-session-journal-types' +import { + HOST_TEST_NOW, + HOST_TEST_THREAD, + HOST_TEST_LOCATION +} from '../../../src/main/native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { + createQueuedMessageTestRig, + eventually +} from '../../../src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { + createStore, + closeTestStores, + testState, + readPersistedStateJson +} from '../../../src/main/persistence/persistence-test-harness' + +export type ChatReuseMode = 'normal' | 'lost-reply' | 'restart' + +export async function exerciseBusyChatReuse( + mode: ChatReuseMode, + automation: AutomationChatLaunchRequest['automation'], + target: AutomationChatLaunchRequest['target'], + controls: { + setHost: (host: StructuredAgentSessionHost | null) => void + bindRenderer: (renderer: Awaited> | null) => void + launch: Mock + } +): Promise { + const sessionId = 'codex_automation_reuse' + vi.spyOn(Date, 'now').mockReturnValue(HOST_TEST_NOW) + const rig = await createQueuedMessageTestRig({ restartable: true, sessionId }) + controls.setHost(rig.host) + const root = mkdtempSync(join(tmpdir(), 'orca-34332-accepted-')) + testState.dir = root + const disk = createStore() + let service: ReturnType | undefined + const intervals = vi.spyOn(globalThis, 'setInterval') + const cleared = vi.spyOn(globalThis, 'clearInterval') + try { + const working = await rig.workingSend() + disk.addRepo(target.repo) + const saved = disk.createAutomation({ + ...automation, + agentId: 'codex', + workspaceId: HOST_TEST_LOCATION.workspaceId, + launchSetupPatch: { surface: 'chat' }, + reuseSession: true, + enabled: false, + projectId: target.repo.id + }) + expect(saved.surface).toBe('chat') + const writer = createAutomationRunWriter(disk, null) + const first = await writer.createRun(saved, Date.now() - 2, 'manual') + const firstResult = await writer.updateRun({ + runId: first.id, + status: 'completed', + sessionKind: 'chat', + chatSessionId: sessionId, + workspaceId: saved.workspaceId, + outputSnapshot: { + format: 'plain_text', + content: 'Prior automation output', + truncated: false, + capturedAt: Date.now() + } + }) + expect(firstResult.outputSnapshot).toEqual({ + format: 'plain_text', + content: 'Prior automation output', + truncated: false, + capturedAt: HOST_TEST_NOW + }) + const previous = await writer.createRun(saved, Date.now() - 1, 'manual') + await writer.updateRun({ + runId: previous.id, + status: 'dispatch_failed', + sessionKind: 'chat', + chatSessionId: sessionId, + workspaceId: saved.workspaceId + }) + const current = await writer.createRun(saved, Date.now(), 'manual') + const sent = rig.host.send.bind(rig.host) + const send = vi.spyOn(rig.host, 'send').mockImplementationOnce(async (...args) => { + const answer = await sent(...args) + expect(answer).toMatchObject({ ok: true, value: { queued: { state: 'waiting' } } }) + if (mode === 'lost-reply') { + throw new Error('accepted reply lost') + } + return answer + }) + const runtimeFacade = { + ensureStructuredAgentSessionHost: async () => {}, + openAgentSessionRecordStore: async () => rig.store, + openedAgentSessionRecordStore: () => rig.store, + setAutomationService: vi.fn(), + notifyAutomationsChanged: vi.fn(), + showManagedWorktree: async () => { + throw new Error('optional display unavailable') + } + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the runtime facade is scripted; the real host/store and service/send/receipt/queue/observer/writer execute. + const runtime = runtimeFacade as unknown as OrcaRuntimeService + service = createRuntimeAutomationService({ store: disk, runtime, headless: true }) + const dispatched = await service.runNow(saved.id) + expect(dispatched).toMatchObject({ + status: 'dispatched', + sessionKind: 'chat', + chatSessionId: sessionId + }) + const q = automationRunOperationId(current, 'reuse-send') + expect(await rig.drafts()).toEqual([{ messageId: q, state: 'waiting' }]) + expect(await rig.handoff(q)).toBeUndefined() + expect(send).toHaveBeenCalledOnce() + service.start() + await eventually(() => + expect(rig.host.collaboratorsForTests().sessions['observers'].size).toBe(1) + ) + if (mode === 'restart') { + service.stop() + expect(rig.host.collaboratorsForTests().sessions['observers'].size).toBe(0) + // The crash's durable row predates saving the accepted Chat identity; Q's receipt survives. + await writer.updateRun({ + runId: current.id, + status: 'dispatching', + sessionKind: 'terminal', + chatSessionId: null + }) + await rig.restartHostProcess() + controls.setHost(rig.host) + service = createRuntimeAutomationService({ store: disk, runtime, headless: true }) + service.start() + await eventually(() => + expect(disk.listAutomationRuns(saved.id).find((r) => r.id === current.id)).toMatchObject({ + status: 'dispatched', + chatSessionId: sessionId + }) + ) + expect(await rig.drafts()).toEqual([{ messageId: q, state: 'waiting' }]) + expect(await rig.handoff(q)).toBeUndefined() + expect(await rig.queuePause()).toBeNull() + expect(await rig.sendNow(q)).toMatchObject({ + ok: true, + value: { submission: expect.anything() } + }) + } else { + await rig.settleAccepted(working, 'human') + const sink = rig.providerEvents() + sink.appendItem( + { provider: 'codex', threadId: HOST_TEST_THREAD, turnId: 'turn-human', ordinal: 1 }, + { kind: 'turn', turnId: 'turn-human', state: 'completed', outcome: 'success' }, + { turnScope: AGENT_JOURNAL_THREAD_SCOPE, lifecycle: true } + ) + sink.publish({ lifecycle: true }) + expect(await sink.written?.()).toEqual({ ok: true }) + await rig.host.flushStreamedEvents(sessionId) + } + const readCurrent = () => disk.listAutomationRuns(saved.id).find((r) => r.id === current.id)! + expect(readCurrent().status).toBe('dispatched') + await eventually(async () => expect(await rig.handoff(q)).toBeDefined()) + const submission = await rig.handoffId(q) + expect(submission).not.toBe(q) + await eventually(async () => + expect((await rig.submission(submission))?.handedOverAt).toBeDefined() + ) + await rig.settleAccepted(submission, 'automation') + const accepted = await rig.submission(submission) + const sink = rig.providerEvents() + const ownId = { + provider: 'codex' as const, + threadId: HOST_TEST_THREAD, + turnId: 'turn-automation', + ordinal: 1 + } + sink.appendItem( + ownId, + { + kind: 'turn', + turnId: 'turn-automation', + userItemId: accepted!.providerItemId!, + state: 'completed', + outcome: 'success' + }, + { turnScope: AGENT_JOURNAL_THREAD_SCOPE, lifecycle: true } + ) + sink.appendItem( + { ...ownId, ordinal: 2 }, + { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: 'Exact automation output' }] + }, + { turnScope: { kind: 'turn', turnItemId: agentJournalItemKey(ownId) } } + ) + sink.appendItem( + { ...ownId, turnId: 'human-other', ordinal: 3 }, + { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: 'Unrelated human output' }] + }, + { turnScope: { kind: 'turn', turnItemId: 'human-root' } } + ) + sink.publish({ lifecycle: true }) + expect(await sink.written?.()).toEqual({ ok: true }) + await rig.host.flushStreamedEvents(sessionId) + await eventually(() => + expect(readCurrent()).toMatchObject({ + status: 'completed', + chatSessionId: sessionId, + outputSnapshot: { content: 'Exact automation output' } + }) + ) + expect(disk.listAutomationRuns(saved.id).find((r) => r.id === first.id)).toEqual(firstResult) + expect(disk.listAutomationRuns(saved.id)).toHaveLength(3) + const persisted = JSON.parse(readPersistedStateJson(join(root, 'orca-data.json'))) + expect( + persisted.automationRuns.find((row: { id: string }) => row.id === current.id) + ).toMatchObject({ + chatSessionId: sessionId, + status: 'completed', + outputSnapshot: { content: 'Exact automation output' } + }) + await eventually(() => expect(readCurrent().usage).not.toBeNull()) + const beforeOpen = { + journal: await rig.host.journalSnapshot(sessionId), + runs: disk.listAutomationRuns(saved.id), + record: rig.store.getConversation(sessionId) + } + const create = vi.spyOn(rig.host, 'create') + const openingRuntime = new ChatOpenTestRuntime(disk) + vi.spyOn(openingRuntime, 'ensureStructuredAgentSessionHost').mockResolvedValue() + vi.spyOn(openingRuntime, 'openAgentSessionRecordStore').mockResolvedValue(rig.store) + await exerciseRecordedChatOpen(openingRuntime, readCurrent(), controls.bindRenderer) + expect(rig.host.isSessionTabVisible(sessionId)).toBe(true) + expect(await rig.host.journalSnapshot(sessionId)).toEqual(beforeOpen.journal) + expect(disk.listAutomationRuns(saved.id)).toEqual(beforeOpen.runs) + expect(rig.store.getConversation(sessionId)).toEqual(beforeOpen.record) + expect(create).not.toHaveBeenCalled() + expect(send).toHaveBeenCalledOnce() + expect(controls.launch).not.toHaveBeenCalled() + service.stop() + expect(rig.host.collaboratorsForTests().sessions['observers'].size).toBe(0) + } finally { + service?.stop() + controls.setHost(null) + await rig.dispose() + await closeTestStores() + rmSync(root, { recursive: true, force: true }) + for (const interval of intervals.mock.results) { + expect(cleared.mock.calls.some(([timer]) => timer === interval.value)).toBe(true) + } + } +}