From 9a37baa45f73a3db92d5a262ec79fdf02767904c Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:25:32 -0700 Subject: [PATCH 01/23] Let automations run in Chat or Terminal through the shared agent launcher --- .../automation-chat-session-reuse.ts | 91 ++ .../automation-dispatch-host-fence.test.ts | 31 +- .../automation-dispatch-request.ts | 23 +- .../automations/automation-run-operation.ts | 15 + .../automations/automation-run-receipt.ts | 58 ++ .../automation-worker-durability.test.ts | 40 +- src/main/automations/dispatch-refusal.ts | 26 +- .../headless-automation-agent-launch.test.ts | 518 +++++----- .../headless-automation-agent-launch.ts | 387 ++++---- .../headless-dispatch-durability.test.ts | 2 + .../automations/headless-dispatch-runner.ts | 2 + src/main/automations/headless-dispatch.ts | 2 + .../headless-workspace-create.test.ts | 101 +- .../automations/headless-workspace-create.ts | 35 - .../run-completion-watcher.test.ts | 7 + .../automations/run-completion-watcher.ts | 2 + .../runtime-automation-service.test.ts | 256 +++-- .../automations/runtime-automation-service.ts | 97 +- .../runtime-chat-run-observer.test.ts | 203 ++++ .../automations/runtime-chat-run-observer.ts | 190 ++++ src/main/automations/service.test.ts | 81 +- src/main/automations/service.ts | 20 +- ...stence-automation-extra-agent-args.test.ts | 56 ++ ...stence-legacy-automation-twin-host.test.ts | 10 +- .../automation-definition-operations.ts | 23 +- .../automation-run-operations.ts | 4 + .../rpc/methods/agent-launch-surfaces.ts | 12 +- .../methods/agent-launch-worktree-creation.ts | 5 +- .../runtime/rpc/methods/agent-launch.test.ts | 45 +- src/main/runtime/rpc/methods/agent-launch.ts | 69 +- .../runtime/runtime-automation-controller.ts | 8 +- .../automations/AutomationEditorDialog.tsx | 18 +- .../AutomationEditorSettingsSidebar.test.tsx | 2 + .../AutomationEditorSettingsSidebar.tsx | 17 +- .../AutomationSurfaceField.test.tsx | 50 + .../automations/AutomationSurfaceField.tsx | 68 ++ .../automation-capability-probe.ts | 37 + .../automations/automation-draft-model.ts | 7 +- .../automations/automation-edit-draft.ts | 1 + ...mation-extra-agent-args-capability.test.ts | 53 ++ .../automations/automation-host-client.ts | 13 +- .../automations/automation-launch-surface.ts | 61 ++ .../automations/automation-orca-save.ts | 27 +- .../automation-run-view-state.test.ts | 16 + .../automations/automation-run-view-state.ts | 15 +- ...run-workspace-action.paired-server.test.ts | 61 ++ .../automation-run-workspace-action.ts | 46 +- .../automations/automation-save-action.ts | 24 +- .../automation-scoped-list-client.ts | 10 +- .../automations-page-test-harness.tsx | 3 + .../hooks/automation-dispatch-completion.ts | 276 ------ .../src/hooks/automation-dispatch-handler.ts | 241 ----- ...automation-dispatch-observer-test-probe.ts | 30 - ...omation-dispatch-unverifiable-loss.test.ts | 102 -- .../hooks/automation-dispatch-workspace.ts | 258 ----- .../hooks/useAutomationDispatchEvents.test.ts | 885 +----------------- .../src/hooks/useAutomationDispatchEvents.ts | 3 - src/renderer/src/i18n/locales/en.json | 6 +- src/renderer/src/i18n/locales/es.json | 6 +- src/renderer/src/i18n/locales/fr.json | 6 +- src/renderer/src/i18n/locales/ja.json | 6 +- src/renderer/src/i18n/locales/ko.json | 6 +- src/renderer/src/i18n/locales/pt.json | 6 +- src/renderer/src/i18n/locales/zh.json | 6 +- .../automation-extra-agent-args-record.ts | 4 +- src/shared/automation-launch-setup.ts | 32 + src/shared/automation-runtime-capabilities.ts | 4 + src/shared/automations-types.ts | 14 +- ...migration-dormant-automation-validation.ts | 16 +- .../orcad-migration-manifest.test.ts | 44 + src/shared/protocol-version.ts | 3 +- ...automation-params-extra-agent-args.test.ts | 18 + src/shared/rpc-contract/automation-params.ts | 11 + 73 files changed, 2324 insertions(+), 2607 deletions(-) create mode 100644 src/main/automations/automation-chat-session-reuse.ts create mode 100644 src/main/automations/automation-run-operation.ts create mode 100644 src/main/automations/automation-run-receipt.ts create mode 100644 src/main/automations/runtime-chat-run-observer.test.ts create mode 100644 src/main/automations/runtime-chat-run-observer.ts create mode 100644 src/renderer/src/components/automations/AutomationSurfaceField.test.tsx create mode 100644 src/renderer/src/components/automations/AutomationSurfaceField.tsx create mode 100644 src/renderer/src/components/automations/automation-launch-surface.ts delete mode 100644 src/renderer/src/hooks/automation-dispatch-completion.ts delete mode 100644 src/renderer/src/hooks/automation-dispatch-handler.ts delete mode 100644 src/renderer/src/hooks/automation-dispatch-observer-test-probe.ts delete mode 100644 src/renderer/src/hooks/automation-dispatch-unverifiable-loss.test.ts delete mode 100644 src/renderer/src/hooks/automation-dispatch-workspace.ts create mode 100644 src/shared/automation-launch-setup.ts 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..cfae6142495f --- /dev/null +++ b/src/main/automations/automation-chat-session-reuse.ts @@ -0,0 +1,91 @@ +import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import type { + AutomationAgentLaunchRequest, + HeadlessAutomationAgentLaunch +} from './headless-automation-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 { tuiAgentDisplayName } from '../../shared/tui-agent-display-names' + +export async function reuseAutomationChat( + runtime: OrcaRuntimeService, + { automation, run, runs }: AutomationAgentLaunchRequest +): Promise { + await runtime.ensureStructuredAgentSessionHost() + const host = getStructuredAgentSessionHost() + if (!host) { + return null + } + const store = await runtime.openAgentSessionRecordStore() + 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 (!id || seen.has(id)) { + continue + } + seen.add(id) + if ( + previous.sessionKind !== 'chat' || + previous.status !== 'completed' || + previous.workspaceId !== automation.workspaceId + ) { + continue + } + const record = store.getConversation(id) + if ( + !record || + record.provider !== automation.agentId || + record.location.workspaceId !== automation.workspaceId + ) { + continue + } + await host.journalSnapshot(id) + const current = store.getConversation(id) + const work = host.currentWork(id) + if (!current || !work || work.working()) { + continue + } + const sent = await host.send( + { callerKey: rpcCallerOperationKey(AUTOMATION_AGENT_CALLER) }, + structuredAgentSessionMessageSendMutation({ + sessionId: id, + clientOperationId: automationRunOperationId(run, 'reuse-send'), + expectedRuntimeFence: current.currentFence, + delivery: 'queue-if-active', + body: structuredAgentSessionSendBody(automation.prompt, []) + }) + ) + if (!sent.ok) { + const row = store.getOperationRow( + rpcCallerOperationKey(AUTOMATION_AGENT_CALLER), + automationRunOperationId(run, 'reuse-send') + ) + if (sent.refusal.code === 'agent_session_conflict' || row?.outcome.status === 'failed') { + return null + } + throw new Error( + `${tuiAgentDisplayName(automation.agentId)} could not accept this automation run. Open the chat and try again.` + ) + } + const shown = await runtime.showManagedWorktree(`id:${automation.workspaceId}`) + return { + workspaceId: automation.workspaceId!, + workspaceDisplayName: shown.displayName ?? null, + sessionKind: 'chat', + chatSessionId: id, + terminalHandle: null, + terminalSessionId: null, + terminalPaneKey: null, + terminalPtyId: null + } + } + return null +} diff --git a/src/main/automations/automation-dispatch-host-fence.test.ts b/src/main/automations/automation-dispatch-host-fence.test.ts index b31d31b48da4..1a540eaaadbc 100644 --- a/src/main/automations/automation-dispatch-host-fence.test.ts +++ b/src/main/automations/automation-dispatch-host-fence.test.ts @@ -129,8 +129,8 @@ function attachedService(store: Store): { service: AutomationService send: ReturnType } { - const send = vi.fn() - const service = new AutomationService(store, { tickMs: 60_000 }) + const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) + const service = new AutomationService(store, { headlessDispatcher: send, tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, send } as never) return { service, send } } @@ -197,8 +197,9 @@ describe('scheduled dispatch fenced on the host the record captured', () => { vi.setSystemTime(new Date('2026-05-13T08:00:00')) const store = await createStore() const automation = seedRemoteScheduledAutomation(store) - const send = vi.fn() + const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) const service = new AutomationService(store, { + headlessDispatcher: send, tickMs: 60_000, allowRemoteHostScheduling: true }) @@ -212,7 +213,9 @@ describe('scheduled dispatch fenced on the host the record captured', () => { await evaluateAt(store, service, automation.id, '2026-05-13T09:01:00') - expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.anything()) + expect(send).toHaveBeenCalledWith( + expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) + ) }) it('dispatches while the registration the record captured is still the live one', async () => { @@ -223,8 +226,12 @@ describe('scheduled dispatch fenced on the host the record captured', () => { await evaluateAt(store, service, automation.id, '2026-05-13T09:01:00') - expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.anything()) - expect(store.listAutomationRuns(automation.id)[0]?.status).toBe('dispatching') + expect(send).toHaveBeenCalledWith( + expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) + ) + await vi.waitFor(() => + expect(store.listAutomationRuns(automation.id)[0]?.status).toBe('dispatched') + ) }) it('dispatches a record that captured no generation at all', async () => { @@ -237,7 +244,9 @@ describe('scheduled dispatch fenced on the host the record captured', () => { expect(automation.executionTargetGeneration).toBeUndefined() await evaluateAt(store, service, automation.id, '2026-05-13T09:01:00') - expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.anything()) + expect(send).toHaveBeenCalledWith( + expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) + ) }) it('refuses a legacy record with no run context once its host was replaced', async () => { @@ -322,7 +331,9 @@ describe('scheduled dispatch fenced on the host the record captured', () => { store.updateSshTarget(TARGET_ID, { orcadFence: undefined }) await evaluateAt(store, service, automation.id, '2026-05-13T09:02:00') - expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.anything()) + expect(send).toHaveBeenCalledWith( + expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) + ) }) it('still runs an automation Move anyway left on this desktop', async () => { @@ -338,6 +349,8 @@ describe('scheduled dispatch fenced on the host the record captured', () => { await evaluateAt(store, service, automation.id, '2026-05-13T09:01:00') - expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.anything()) + expect(send).toHaveBeenCalledWith( + expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) + ) }) }) diff --git a/src/main/automations/automation-dispatch-request.ts b/src/main/automations/automation-dispatch-request.ts index dd01312f7047..817921433630 100644 --- a/src/main/automations/automation-dispatch-request.ts +++ b/src/main/automations/automation-dispatch-request.ts @@ -11,12 +11,7 @@ import { runHeadlessAutomationDispatch } from './headless-dispatch-runner' import type { AutomationRunTargetResult } from './run-target-resolution' -import { createAutomationDispatchToken } from './dispatch-tokens' -import { - NO_DISPATCH_HOST, - describeScheduledRefusal, - sendRendererDispatch -} from './dispatch-refusal' +import { NO_DISPATCH_HOST, describeScheduledRefusal } from './dispatch-refusal' import { isOrcadFencedAutomation, ORCAD_FENCED_AUTOMATION } from './orcad-fenced-automation' import { AutomationDispatchCancelledError } from './automation-dispatch-cancelled-error' @@ -31,7 +26,6 @@ type DispatchContext = Pick< store: Store runs: AutomationRunWriter isActive(): boolean - getRenderer(): AutomationRendererChannel | null headlessDispatcher: HeadlessAutomationDispatcher | null resolveTarget(automation: Automation): AutomationRunTargetResult } @@ -115,7 +109,7 @@ export async function requestAutomationDispatch( let target = resolveCurrentTarget() const refusal = describeScheduledRefusal({ target, - canDispatch: Boolean(ctx.getRenderer() || ctx.headlessDispatcher) + canDispatch: Boolean(ctx.headlessDispatcher) }) if (refusal || !target.ok) { return refuse(refusal ?? NO_DISPATCH_HOST) @@ -137,19 +131,6 @@ export async function requestAutomationDispatch( if (lateRefusal || !target.ok) { return refuse(lateRefusal ?? NO_DISPATCH_HOST) } - const renderer = ctx.getRenderer() - if (renderer) { - return sendRendererDispatch( - renderer, - { - automation, - run, - dispatchToken: createAutomationDispatchToken(automation.id, run.id) - }, - ctx.runs, - run - ) - } const dispatcher = ctx.headlessDispatcher if (!dispatcher) { return refuse(NO_DISPATCH_HOST) diff --git a/src/main/automations/automation-run-operation.ts b/src/main/automations/automation-run-operation.ts new file mode 100644 index 000000000000..cacf935aa850 --- /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' | 'reuse-terminal-launch' +): 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..270789ee9311 --- /dev/null +++ b/src/main/automations/automation-run-receipt.ts @@ -0,0 +1,58 @@ +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 } + | { + kind: 'terminal' + launch: AgentLaunchResult & { + outcome: Extract + } + } + +/** Recover only recorded acceptance; a restart never sends the prompt again. */ +export function readAutomationRunReceipt( + store: Pick, + run: Pick +): AutomationRunReceipt | null { + const callerKey = rpcCallerOperationKey(AUTOMATION_AGENT_CALLER) + for (const purpose of ['fresh-launch', 'reuse-terminal-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.outcome.kind === 'structured' && launch.prompt?.outcome === 'journaled') { + return { + kind: 'chat', + sessionId: launch.outcome.sessionId, + workspaceId: launch.worktreeId, + messageId: launch.prompt.messageId + } + } + if (launch.outcome.kind === 'terminal' && launch.prompt?.outcome === 'handed-to-terminal') { + return { kind: '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 + } + : null +} diff --git a/src/main/automations/automation-worker-durability.test.ts b/src/main/automations/automation-worker-durability.test.ts index 1bf497a71a4e..44bc2a3103a2 100644 --- a/src/main/automations/automation-worker-durability.test.ts +++ b/src/main/automations/automation-worker-durability.test.ts @@ -58,7 +58,10 @@ describe('automation background writer durability', () => { vi.spyOn(Date, 'now').mockReturnValue(1_800_000_000_000) const { store, automation } = await fixture() const dispatcher = vi.fn(async () => launch) - const service = new AutomationService(store, { headlessDispatcher: dispatcher }) + const service = new AutomationService(store, { + allowRemoteHostScheduling: true, + headlessDispatcher: dispatcher + }) try { const runs = await Promise.all([service.runNow(automation.id), service.runNow(automation.id)]) expect(new Set(runs.map((run) => run.id)).size).toBe(1) @@ -82,7 +85,10 @@ describe('automation background writer durability', () => { ) return launch }) - const service = new AutomationService(store, { headlessDispatcher: dispatcher }) + const service = new AutomationService(store, { + allowRemoteHostScheduling: true, + headlessDispatcher: dispatcher + }) try { const run = service.runNow(automation.id) await Promise.resolve() @@ -99,7 +105,10 @@ describe('automation background writer durability', () => { const { store, automation } = await fixture() vi.spyOn(store, 'flushPendingOrThrowAsync').mockRejectedValueOnce(new Error('disk full')) const dispatcher = vi.fn(async () => launch) - const service = new AutomationService(store, { headlessDispatcher: dispatcher }) + const service = new AutomationService(store, { + allowRemoteHostScheduling: true, + headlessDispatcher: dispatcher + }) try { await expect(service.runNow(automation.id)).rejects.toThrow('disk full') expect(dispatcher).not.toHaveBeenCalled() @@ -127,7 +136,10 @@ describe('automation background writer durability', () => { await store.flushPendingOrThrowAsync() clock.mockReturnValue(dueAt + lateness) const dispatcher = vi.fn(async () => launch) - const service = new AutomationService(store, { headlessDispatcher: dispatcher }) + const service = new AutomationService(store, { + allowRemoteHostScheduling: true, + headlessDispatcher: dispatcher + }) try { service.start() await vi.waitFor(() => { @@ -149,7 +161,10 @@ describe('automation background writer durability', () => { const { store, automation } = await fixture() const acknowledgement = blockAcknowledgement(store, index) const dispatcher = vi.fn(async () => launch) - const service = new AutomationService(store, { headlessDispatcher: dispatcher }) + const service = new AutomationService(store, { + allowRemoteHostScheduling: true, + headlessDispatcher: dispatcher + }) const pending = service.runNow(automation.id) const rejected = expect(pending).rejects.toThrow('stopped before') await acknowledgement.blocked @@ -163,7 +178,10 @@ describe('automation background writer durability', () => { const { store, automation, readState } = await fixture() const acknowledgement = blockAcknowledgement(store, 2) const dispatcher = vi.fn(async () => launch) - const service = new AutomationService(store, { headlessDispatcher: dispatcher }) + const service = new AutomationService(store, { + allowRemoteHostScheduling: true, + headlessDispatcher: dispatcher + }) try { const pending = service.runNow(automation.id) const rejected = expect(pending).rejects.toThrow('removed before') @@ -186,7 +204,10 @@ describe('automation background writer durability', () => { const { store, automation } = await fixture() const acknowledgement = blockAcknowledgement(store, index) const dispatcher = vi.fn(async () => launch) - const service = new AutomationService(store, { headlessDispatcher: dispatcher }) + const service = new AutomationService(store, { + allowRemoteHostScheduling: true, + headlessDispatcher: dispatcher + }) try { const pending = service.runNow(automation.id) await acknowledgement.blocked @@ -206,7 +227,10 @@ describe('automation background writer durability', () => { const { store, automation } = await fixture() const acknowledgement = blockAcknowledgement(store, index) const dispatcher = vi.fn(async () => launch) - const service = new AutomationService(store, { headlessDispatcher: dispatcher }) + const service = new AutomationService(store, { + allowRemoteHostScheduling: true, + headlessDispatcher: dispatcher + }) try { const pending = service.runNow(automation.id) await acknowledgement.blocked diff --git a/src/main/automations/dispatch-refusal.ts b/src/main/automations/dispatch-refusal.ts index cac3c1cebf1e..26a93fd17e04 100644 --- a/src/main/automations/dispatch-refusal.ts +++ b/src/main/automations/dispatch-refusal.ts @@ -1,11 +1,6 @@ // Skip coalescing requires a fixed, byte-identical sentence for each refusal reason. -import type { WebContents } from 'electron' import type { Store } from '../persistence' -import type { - Automation, - AutomationDispatchRequest, - AutomationRun -} from '../../shared/automations-types' +import type { Automation } from '../../shared/automations-types' import { resolveAutomationRunTarget, type AutomationRunTargetResult } from './run-target-resolution' import type { AutomationRunWriter } from './automation-run-writer' import { wslMoveRepoBackoff } from '../persistence/moving-wsl-projects/wsl-move-background-backoff' @@ -94,25 +89,6 @@ export async function recordUnevaluableAutomation(input: { } } -export async function sendRendererDispatch( - channel: Pick | null, - payload: AutomationDispatchRequest, - runs: AutomationRunWriter, - run: AutomationRun -): Promise { - try { - channel?.send('automations:dispatchRequested', payload) - return run - } catch (error) { - return runs.updateRun({ - runId: run.id, - status: 'dispatch_failed', - workspaceId: run.workspaceId, - error: error instanceof Error ? error.message : String(error) - }) - } -} - /** Allow tick jitter beyond downtime grace; elapsed time still catches system sleep. * Short outages inside the tolerance are accepted; long inline dispatches may still exceed it. */ export function missedBeyondGrace(input: { diff --git a/src/main/automations/headless-automation-agent-launch.test.ts b/src/main/automations/headless-automation-agent-launch.test.ts index 2776dfa0292a..c838012fb5cb 100644 --- a/src/main/automations/headless-automation-agent-launch.test.ts +++ b/src/main/automations/headless-automation-agent-launch.test.ts @@ -1,256 +1,314 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { AutomationRun } from '../../shared/automations-types' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import type { AgentLaunchResult } from '../../shared/agent-launch-intent' +import { buildProfileStateCutoverFixture } from '../persistence/profile-state-cutover-fixture' +import { automationRunOperationId } from './automation-run-operation' +import { tokenizeStartupCommand } from '../../shared/tui-agent-startup-shell' import { launchHeadlessAutomationAgent } from './headless-automation-agent-launch' -const { deliverTerminalAgentLaunchPrompt } = vi.hoisted(() => ({ - deliverTerminalAgentLaunchPrompt: vi.fn(async (_args: Record) => true) +const mocks = vi.hoisted(() => ({ + launch: vi.fn(), + host: { journalSnapshot: vi.fn(), currentWork: vi.fn(), send: vi.fn() } })) -vi.mock('../runtime/rpc/methods/agent-launch-terminal-prompt', () => ({ - deliverTerminalAgentLaunchPrompt +vi.mock('../runtime/rpc/methods/agent-launch', () => ({ launchAgentOnHost: mocks.launch })) +vi.mock('../native-chat/agent-session-wire/structured-agent-session-registry', () => ({ + getStructuredAgentSessionHost: () => mocks.host })) - -beforeEach(() => { - deliverTerminalAgentLaunchPrompt.mockClear() - deliverTerminalAgentLaunchPrompt.mockResolvedValue(true) -}) - -const CHAT_DEFAULT_ON = { experimentalNativeChat: true } - -function harness(options: { startupTerminal?: Record | null } = {}) { - const runtime = { - requireStore: () => ({ getSettings: () => CHAT_DEFAULT_ON }), - getStructuredAgentSessionCreateSupport: vi.fn(async () => ({ supported: true })), - createManagedWorktree: vi.fn(async (_args: Record) => ({ - worktree: { id: 'repo-1::/wt/auto', displayName: 'auto-nightly' }, - ...(options.startupTerminal === null - ? { warning: 'Startup terminal failed.' } - : { - startupTerminal: options.startupTerminal ?? { - handle: 'term_new', - tabId: 'tab-new', - paneKey: 'tab-new:leaf-1', - ptyId: 'pty-new' - } - }) - })), - launchAgentTerminal: vi.fn(async (_selector: string, _opts: Record) => ({ - handle: 'term_existing', - tabId: 'tab-1', - paneKey: 'tab-1:leaf-1', - ptyId: 'pty-1', - worktreeId: 'wt-1', - title: 'Nightly', - suppressStartupUpdatePrompt: true - })), - showManagedWorktree: vi.fn(async () => ({ displayName: 'repo' })), - getAgentStatusRowsForPane: vi.fn((_paneKey: string) => [ - { state: 'done', agentType: 'claude', receivedAt: 2 } - ]), - getTerminalHandleForPaneKey: vi.fn((paneKey: string) => - paneKey === 'tab-prev:leaf-1' ? 'term_prev' : null - ), - getTerminalPtyIdForHandle: vi.fn((_handle: string) => 'pty-prev'), - deliverStartupFollowup: vi.fn( - async (_handle: string, _followup: { agent: string; prompt: string }) => true - ) - } - return runtime +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', + extraAgentArgs: undefined } - -function automation(overrides: Record) { - return { - id: 'auto-1', - agentId: 'claude', - prompt: ' fix the flaky test ', - workspaceMode: 'existing', - workspaceId: 'wt-1', - ...overrides - } +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: 'terminal', reason: 'requested', detail: 'Terminal' }, + prompt: { delivery: 'submit', outcome: 'handed-to-terminal' } } - -const RUN = { id: 'run-1', title: 'Nightly', scheduledFor: Date.UTC(2026, 9, 9, 3) } -const TARGET = { ok: true, repo: { id: 'repo-1', path: '/repo', displayName: 'repo' } } - -function previousRun(overrides: Partial = {}): AutomationRun { - return { - id: 'run-0', - automationId: 'auto-1', - title: 'Nightly', - scheduledFor: 1, - status: 'completed', - trigger: 'scheduled', - workspaceId: 'wt-1', - workspaceDisplayName: 'repo', - sessionKind: 'terminal', - chatSessionId: null, - terminalSessionId: 'tab-prev', - terminalPaneKey: 'tab-prev:leaf-1', - terminalPtyId: 'pty-prev', - outputSnapshot: null, - precheckResult: null, - usage: null, - error: null, - startedAt: 1, - dispatchedAt: 1, - createdAt: 1, - ...overrides +const chat: AgentLaunchResult = { + ...terminal, + outcome: { kind: 'structured', sessionId: 'claude_chat', handle: 'chat-tab' }, + prompt: { delivery: 'submit', outcome: 'journaled', messageId: 'first-message' } +} +function fixture() { + const records = { + getOperationRow: vi.fn(), + getConversation: vi.fn(() => ({ + sessionId: 'claude_prev', + provider: 'claude', + location: { workspaceId: 'wt-1' }, + currentFence: 2 + })) + } + 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 } } - -function launch( - runtime: ReturnType, - overrides: Record, - runs: AutomationRun[] = [] -) { - return launchHeadlessAutomationAgent( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the launch reads only the members faked in harness(). - runtime as never, - { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only these automation fields are read. - automation: automation(overrides) as never, - run: RUN, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the repo is read. - target: TARGET as never, - runs +beforeEach(() => { + vi.clearAllMocks() + 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)( + 'pins legacy %s runs to Terminal and preserves unattended/background policy', + async (agentId) => { + const { runtime } = fixture() + const result = await launchHeadlessAutomationAgent(runtime, { + automation: { ...automation, surface: undefined, agentId }, + run, + target, + runs: [] + }) + expect(mocks.launch).toHaveBeenCalledWith( + expect.objectContaining({ + agent: agentId, + surface: 'terminal', + operationId: automationRunOperationId(run, 'fresh-launch'), + prompt: { text: 'Audit', delivery: 'submit' }, + presentation: 'background', + target: { kind: 'existing', worktree: 'id:wt-1' } + }), + expect.objectContaining({ runtime }), + { + terminalTitle: run.title, + suppressStartupUpdatePrompt: true, + unprovableHost: 'write-unless-shell' + } + ) + expect(result).toMatchObject({ + sessionKind: 'terminal', + chatSessionId: null, + terminalPtyId: 'pty-1' + }) } ) -} - -describe('headless automation agent launch', () => { - it('starts a post-start agent bare and delivers its prompt once, after the terminal is recorded', async () => { - const runtime = harness() - let finishDelivery: (delivered: boolean) => void = () => {} - runtime.deliverStartupFollowup.mockImplementation( - () => new Promise((resolve) => (finishDelivery = resolve)) - ) - - const launched = await launch(runtime, { agentId: 'aider' }) - - expect(launched.terminalPaneKey).toBe('tab-1:leaf-1') - expect(runtime.launchAgentTerminal).toHaveBeenCalledWith( - 'id:wt-1', - expect.objectContaining({ agent: 'aider', prompt: '' }) - ) - expect(runtime.deliverStartupFollowup).toHaveBeenCalledTimes(1) - expect(runtime.deliverStartupFollowup).toHaveBeenCalledWith('term_existing', { - agent: 'aider', - prompt: 'fix the flaky test' + it('merges Terminal extras over the live host defaults, and never applies them to Chat', async () => { + const { runtime } = fixture() + await launchHeadlessAutomationAgent(runtime, { + automation: { ...automation, extraAgentArgs: '--model opus' }, + run, + target, + runs: [] + }) + expect(tokenizeStartupCommand(mocks.launch.mock.calls[0][0].agentArgs, 'posix')).toMatchObject({ + ok: true, + tokens: ['--add-dir', 'docs', '--model', 'opus'] + }) + mocks.launch.mockResolvedValue(chat) + await launchHeadlessAutomationAgent(runtime, { + automation: { ...automation, surface: 'chat', extraAgentArgs: '--model opus' }, + run: { ...run, id: 'chat-run' }, + target, + runs: [] }) - finishDelivery(true) + expect(mocks.launch.mock.calls[1][0].agentArgs).toBeUndefined() }) - - it('fails the run with the create warning when no agent terminal started, without a second one', async () => { - const runtime = harness({ startupTerminal: null }) - - await expect( - launch(runtime, { workspaceMode: 'new_per_run', workspaceId: null }) - ).rejects.toThrow('Startup terminal failed.') - expect(runtime.launchAgentTerminal).not.toHaveBeenCalled() + it('retains the actual pane for a reused terminal whose launch result has only a handle', async () => { + const { runtime } = fixture() + mocks.launch.mockResolvedValue({ + ...terminal, + outcome: { kind: 'terminal', handle: 'term-prev' } + }) + const result = await launchHeadlessAutomationAgent(runtime, { + automation: { ...automation, reuseSession: true }, + run, + target, + runs: [ + { + ...run, + id: 'old', + status: 'completed', + workspaceId: 'wt-1', + sessionKind: 'terminal', + terminalPaneKey: 'old:leaf', + terminalPtyId: 'pty-1' + } + ] + }) + expect(result).toMatchObject({ terminalPaneKey: 'tab-1:leaf-1', terminalPtyId: 'pty-1' }) + expect(mocks.launch).toHaveBeenCalledTimes(1) }) - - it('logs a failure after the terminal was recorded instead of dropping it', async () => { - const runtime = harness() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - runtime.deliverStartupFollowup.mockRejectedValue(new Error('writer broke')) - - const launched = await launch(runtime, { agentId: 'aider' }) - await vi.waitFor(() => - expect(warn).toHaveBeenCalledWith( - expect.stringContaining('after its terminal was published'), - expect.objectContaining({ message: 'writer broke' }) - ) + 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( + launchHeadlessAutomationAgent(runtime, { automation, run, target, runs: [] }) + ).rejects.toThrow( + 'Claude could not start because this run waited too long. Run the automation again.' ) - - expect(launched.terminalHandle).toBe('term_existing') - warn.mockRestore() + expect(mocks.launch).toHaveBeenCalledTimes(1) }) - - it('refuses an existing-workspace run whose workspace is gone', async () => { - const runtime = harness() - - await expect(launch(runtime, { workspaceId: null })).rejects.toThrow( - 'The target workspace is no longer available.' + it('records the actual chat identity and delegates new workspace setup and provenance', async () => { + const { runtime } = fixture() + mocks.launch.mockResolvedValue(chat) + const result = await launchHeadlessAutomationAgent(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(runtime.launchAgentTerminal).not.toHaveBeenCalled() - }) - - it('sends a reuse-session prompt into the idle agent its previous run left', async () => { - const runtime = harness() - - const launched = await launch(runtime, { reuseSession: true }, [previousRun()]) - - expect(deliverTerminalAgentLaunchPrompt).toHaveBeenCalledWith({ - runtime, - handle: 'term_prev', - agent: 'claude', - freshLaunch: false, - text: 'fix the flaky test', - unprovableHost: 'write-unless-shell' + expect(result).toMatchObject({ + sessionKind: 'chat', + chatSessionId: 'claude_chat', + terminalHandle: null, + terminalPaneKey: null, + terminalSessionId: null, + terminalPtyId: null }) - expect(runtime.launchAgentTerminal).not.toHaveBeenCalled() - expect(launched).toEqual({ + }) + it('separates a proven no-effect terminal reuse refusal from the fresh launch identity', async () => { + const { runtime, records } = fixture() + records.getOperationRow.mockReturnValue({ outcome: { status: 'failed' } }) + mocks.launch + .mockRejectedValueOnce(new Error('no longer an agent')) + .mockResolvedValueOnce(terminal) + const previous = { + ...run, + id: 'old', workspaceId: 'wt-1', - workspaceDisplayName: 'repo', - terminalHandle: 'term_prev', - terminalSessionId: 'tab-prev', - terminalPaneKey: 'tab-prev:leaf-1', - terminalPtyId: 'pty-prev' + status: 'completed' as const, + sessionKind: 'terminal' as const, + terminalPaneKey: 'old:leaf', + terminalPtyId: 'pty-1' + } + await launchHeadlessAutomationAgent(runtime, { + automation: { ...automation, reuseSession: true }, + run, + target, + runs: [previous] }) + expect(mocks.launch.mock.calls.map(([input]) => input.operationId)).toEqual([ + automationRunOperationId(run, 'reuse-terminal-launch'), + automationRunOperationId(run, 'fresh-launch') + ]) }) - - it('launches fresh when the idle agent did not take the prompt', async () => { - const runtime = harness() - deliverTerminalAgentLaunchPrompt.mockResolvedValue(false) - - const launched = await launch(runtime, { reuseSession: true }, [previousRun()]) - - expect(deliverTerminalAgentLaunchPrompt).toHaveBeenCalledTimes(1) - expect(runtime.launchAgentTerminal).toHaveBeenCalledTimes(1) - expect(launched.terminalHandle).toBe('term_existing') + it('never falls back after an ambiguous reuse launch', async () => { + const { runtime, records } = fixture() + records.getOperationRow.mockReturnValue({ outcome: { status: 'unknown' } }) + mocks.launch.mockRejectedValue(new Error('lost reply')) + await expect( + launchHeadlessAutomationAgent(runtime, { + automation: { ...automation, reuseSession: true }, + run, + target, + runs: [ + { + ...run, + id: 'old', + workspaceId: 'wt-1', + status: 'completed', + terminalPaneKey: 'old:leaf', + terminalPtyId: 'pty-1' + } + ] + }) + ).rejects.toThrow('Open its workspace before running again.') + expect(mocks.launch).toHaveBeenCalledTimes(1) }) - - it.each([ - ['its pane now holds another PTY', { ptyId: 'pty-restarted' }], - ['its agent is working', { row: { state: 'working', agentType: 'claude', receivedAt: 2 } }], - ['another agent is in it', { row: { state: 'done', agentType: 'codex', receivedAt: 2 } }], - ['the previous run did not complete', { run: { status: 'dispatch_failed' as const } }], - ['reuse is off', { reuseSession: false }] - ])('launches fresh without sending when %s', async (_label, setup) => { - const runtime = harness() - if ('ptyId' in setup) { - runtime.getTerminalPtyIdForHandle.mockReturnValue(setup.ptyId) - } - if ('row' in setup) { - runtime.getAgentStatusRowsForPane.mockReturnValue([setup.row]) + it('reuses only a completed compatible idle chat and derives a separate send identity', async () => { + const { runtime } = fixture() + const previous = { + ...run, + id: 'old', + status: 'completed' as const, + workspaceId: 'wt-1', + sessionKind: 'chat' as const, + chatSessionId: 'claude_prev' } - - await launch(runtime, { reuseSession: 'reuseSession' in setup ? setup.reuseSession : true }, [ - previousRun('run' in setup ? setup.run : {}) - ]) - - expect(deliverTerminalAgentLaunchPrompt).not.toHaveBeenCalled() - expect(runtime.launchAgentTerminal).toHaveBeenCalledTimes(1) - }) - - it('launches fresh while the previous run is still working in the reused agent', async () => { - const runtime = harness() - const inFlight = previousRun({ id: 'run-scheduled', status: 'dispatched', dispatchedAt: 2 }) - - await launch(runtime, { reuseSession: true }, [previousRun(), inFlight]) - - expect(deliverTerminalAgentLaunchPrompt).not.toHaveBeenCalled() - expect(runtime.launchAgentTerminal).toHaveBeenCalledTimes(1) + const result = await launchHeadlessAutomationAgent(runtime, { + automation: { ...automation, surface: 'chat', reuseSession: true }, + run, + target, + runs: [previous] + }) + expect(mocks.launch).not.toHaveBeenCalled() + expect(mocks.host.send).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + envelope: expect.objectContaining({ + sessionId: 'claude_prev', + clientOperationId: automationRunOperationId(run, 'reuse-send'), + expectedRuntimeFence: 2 + }) + }) + ) + expect(result.chatSessionId).toBe('claude_prev') }) - - it("reads the pane's newest status row, not a stale done", async () => { - const runtime = harness() - runtime.getAgentStatusRowsForPane.mockReturnValue([ - { state: 'done', agentType: 'claude', receivedAt: 1 }, - { state: 'working', agentType: 'claude', receivedAt: 3 } - ]) - - await launch(runtime, { reuseSession: true }, [previousRun()]) - - expect(deliverTerminalAgentLaunchPrompt).not.toHaveBeenCalled() + it('does not reuse a chat whose newest run or current human turn is unfinished', async () => { + const { runtime } = fixture() + mocks.launch.mockResolvedValue(chat) + mocks.host.currentWork.mockReturnValue({ working: () => true }) + await launchHeadlessAutomationAgent(runtime, { + automation: { ...automation, surface: 'chat', reuseSession: true }, + run, + target, + runs: [ + { + ...run, + id: 'old', + status: 'completed', + workspaceId: 'wt-1', + sessionKind: 'chat', + chatSessionId: 'claude_prev' + } + ] + }) + expect(mocks.host.send).not.toHaveBeenCalled() + expect(mocks.launch).toHaveBeenCalledTimes(1) }) }) diff --git a/src/main/automations/headless-automation-agent-launch.ts b/src/main/automations/headless-automation-agent-launch.ts index ac006a38ff81..4fae9b5c7e53 100644 --- a/src/main/automations/headless-automation-agent-launch.ts +++ b/src/main/automations/headless-automation-agent-launch.ts @@ -1,190 +1,234 @@ -// Automations observe PTYs, so launch terminal agents regardless of the chat default. - -import type { - AgentLaunchPublishedSurface, - AgentLaunchSurfaceExecution -} from '../agent-launch/agent-launch-execution' -import { executeAgentLaunch } from '../agent-launch/agent-launch-executor' import type { Automation, AutomationRun } from '../../shared/automations-types' -import { findReusableAutomationRun } from '../../shared/automation-session-reuse' +import type { AgentLaunchResult } from '../../shared/agent-launch-intent' import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import { deliverTerminalAgentLaunchPrompt } from '../runtime/rpc/methods/agent-launch-terminal-prompt' -import type { HeadlessAutomationDispatchLaunch } from './headless-dispatch' -import { buildHeadlessAutomationWorktreeCreateArgs } from './headless-workspace-create' +import { launchAgentOnHost } from '../runtime/rpc/methods/agent-launch' +import { findReusableAutomationRun } from '../../shared/automation-session-reuse' +import { reuseAutomationChat } from './automation-chat-session-reuse' +import { buildHeadlessAutomationWorkspaceName } from './headless-workspace-create' import type { AutomationRunTargetResult } from './run-target-resolution' +import type { HeadlessAutomationDispatchLaunch } from './headless-dispatch' +import { automationRunOperationId, AUTOMATION_AGENT_CALLER } from './automation-run-operation' +import { createAutomationDispatchToken } from './dispatch-tokens' +import { mergeExtraAgentArgs, hasExtraAgentArgs } from '../../shared/automation-extra-agent-args' +import { resolveTuiAgentLaunchArgs } from '../../shared/tui-agent-launch-defaults' +import { agentLaunchQuotingShell } from '../../shared/agent-launch-runtime' +import { + resolveAgentLaunchRuntime, + newWorktreeLaunchScope +} from '../runtime/agent-launch-scope-runtime' +import { rpcCallerOperationKey } from '../runtime/rpc/rpc-caller-identity' +import { tuiAgentDisplayName } from '../../shared/tui-agent-display-names' -const TERMINAL_ONLY_MESSAGE = 'An automation starts a terminal agent only.' - -type LaunchedTerminal = { - handle: string - tabId?: string | null - paneKey?: string | null - ptyId?: string | null +export type HeadlessAutomationAgentLaunch = HeadlessAutomationDispatchLaunch & { + terminalHandle: string | null } -export type HeadlessAutomationAgentLaunch = Omit & { - terminalHandle: string +export type AutomationAgentLaunchRequest = { + automation: Automation + run: Pick + target: Extract + runs: readonly AutomationRun[] } export async function launchHeadlessAutomationAgent( runtime: OrcaRuntimeService, - request: { - automation: Automation - run: Pick - target: Extract - runs: readonly AutomationRun[] - } + request: AutomationAgentLaunchRequest ): Promise { - const { automation, run, target } = request - const agent = automation.agentId - const text = automation.prompt?.trim() - if (automation.reuseSession && automation.workspaceMode === 'existing' && text) { - const reused = await sendToReusableSession(runtime, { ...request, text }) - if (reused) { - return reused + try { + return await launchAutomationAgent(runtime, request) + } catch (error) { + if (error instanceof AutomationRunLaunchError) { + throw error } + console.error('[automations] agent 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.` + ) } - let workspace: { id: string; displayName: string | null } | undefined - let terminal: LaunchedTerminal | undefined - const execution: AgentLaunchSurfaceExecution = { - runtime, - intent: { - agent, - // The workspace factory supplies create arguments from the automation. - target: - automation.workspaceMode === 'new_per_run' - ? { kind: 'create-worktree', create: {} } - : { kind: 'existing', worktree: requireWorkspaceId(automation) }, - ...(text ? { prompt: { text, delivery: 'submit' as const } } : {}) - }, - terminalOnly: true, - workspaces: { - createWorktree: async ({ startupAgent, startupPrompt }) => { - if (startupAgent === undefined) { - throw new Error(TERMINAL_ONLY_MESSAGE) - } - const { startupPrompt: _prompt, ...create } = buildHeadlessAutomationWorktreeCreateArgs({ - automation, - run, - repo: target.repo - }) - const created = await runtime.createManagedWorktree({ - ...create, - startupAgent, - ...(startupPrompt ? { startupPrompt } : {}) - }) - workspace = { - id: created.worktree.id, - displayName: created.worktree.displayName ?? null - } - const startup = created.startupTerminal - if (!startup?.handle) { - throw new Error( - created.warning || 'Automation workspace was created, but no agent terminal started.' +} + +class AutomationRunLaunchError extends Error {} + +async function launchAutomationAgent( + runtime: OrcaRuntimeService, + request: AutomationAgentLaunchRequest +): Promise { + const { automation, run, target } = request + const surface = automation.surface ?? 'terminal' + const context = { runtime, caller: AUTOMATION_AGENT_CALLER } + const policy = { + terminalTitle: run.title, + suppressStartupUpdatePrompt: true, + unprovableHost: 'write-unless-shell' + } as const + if ( + automation.reuseSession && + automation.workspaceId && + (surface === 'chat' || !hasExtraAgentArgs(automation.extraAgentArgs)) + ) { + if (surface === 'chat') { + const reused = await reuseAutomationChat(runtime, request) + if (reused) { + return reused + } + } else { + const reused = findReusableAutomationRun({ + automationId: automation.id, + agentId: automation.agentId, + worktreeId: automation.workspaceId, + currentRunId: run.id, + runs: request.runs.filter((entry) => entry.sessionKind === 'terminal'), + agentStatusForPane: (paneKey) => + runtime + .getAgentStatusRowsForPane(paneKey) + .filter((row) => !row.providerSessionOnly) + .toSorted((a, b) => b.receivedAt - a.receivedAt)[0], + liveSession: (previous) => runOwnHandle(runtime, previous) + }) + if (reused) { + const operationId = automationRunOperationId(run, 'reuse-terminal-launch') + try { + const result = await launchAgentOnHost( + { + agent: automation.agentId, + operationId, + target: { kind: 'existing', worktree: `id:${automation.workspaceId}` }, + surface, + reuseTerminal: { handle: reused }, + prompt: { text: automation.prompt, delivery: 'submit' }, + presentation: 'background' + }, + context, + policy ) - } - terminal = { ...startup, handle: startup.handle } - return { - worktreeId: created.worktree.id, - startupTerminalHandle: startup.handle, - ...(startup.paneKey ? { startupTerminalPaneKey: startup.paneKey } : {}), - // Creation stages long prompts while keeping them on the launch command. - ...(startupPrompt ? { promptRodeLaunchCommand: true } : {}) + if (result.prompt?.outcome === 'handed-to-terminal') { + return launchOutcome(runtime, result) + } + if (result.prompt?.outcome !== 'not-delivered') { + throw new AutomationRunLaunchError( + `${tuiAgentDisplayName(automation.agentId)} could not confirm this run's prompt. Open the terminal before running again.` + ) + } + } catch (error) { + const records = await runtime.openAgentSessionRecordStore() + const row = records.getOperationRow( + rpcCallerOperationKey(AUTOMATION_AGENT_CALLER), + operationId + ) + // Only the launch owner's durable no-effect verdict permits a different launch. + if (row?.outcome.status !== 'failed') { + throw error + } } } - }, - surfaces: { - createStructuredSession: () => { - throw new Error(TERMINAL_ONLY_MESSAGE) - }, - createTerminalAgent: async ({ worktreeId, startupPrompt }) => { - const launched = await runtime.launchAgentTerminal(`id:${worktreeId}`, { - agent, - prompt: startupPrompt ?? '', - title: run.title, - suppressStartupUpdatePrompt: true, - ...(automation.extraAgentArgs ? { extraAgentArgs: automation.extraAgentArgs } : {}) - }) - terminal = launched - const shown = await runtime.showManagedWorktree(`id:${launched.worktreeId}`) - workspace = { id: launched.worktreeId, displayName: shown.displayName ?? null } - return { - handle: launched.handle, - ...(launched.paneKey ? { paneKey: launched.paneKey } : {}), - ...(startupPrompt ? { promptRodeLaunchCommand: true } : {}) - } - }, - deliverTerminalPrompt: ({ handle, prompt }) => - runtime.deliverStartupFollowup(handle, { agent, prompt: prompt.text }) } } - await launchUntilPublished(execution) - if (!workspace || !terminal) { - throw new Error('Automation agent launch did not report its terminal.') + const operationId = automationRunOperationId(run, 'fresh-launch') + const settings = runtime.requireStore().getSettings() + let merged: ReturnType | null = null + if (surface === 'terminal' && hasExtraAgentArgs(automation.extraAgentArgs)) { + const scope = + automation.workspaceMode === 'existing' && automation.workspaceId + ? await runtime.showTerminalWorkspaceLaunchScope(`id:${automation.workspaceId}`) + : newWorktreeLaunchScope(target.repo, settings) + merged = mergeExtraAgentArgs({ + agent: automation.agentId, + extraAgentArgs: automation.extraAgentArgs, + defaultArgs: resolveTuiAgentLaunchArgs(automation.agentId, settings), + shell: agentLaunchQuotingShell( + resolveAgentLaunchRuntime(runtime.requireStore(), scope, undefined, automation.agentId) + ) + }) + } + if (merged && !merged.ok) { + throw new AutomationRunLaunchError( + `${tuiAgentDisplayName(automation.agentId)} could not start. ${merged.error}` + ) } - return { - workspaceId: workspace.id, - workspaceDisplayName: workspace.displayName, - terminalHandle: terminal.handle, - terminalSessionId: terminal.tabId ?? null, - terminalPaneKey: terminal.paneKey ?? null, - terminalPtyId: terminal.ptyId ?? null + try { + const result = await launchAgentOnHost( + { + agent: automation.agentId, + operationId, + surface, + presentation: 'background', + prompt: { text: automation.prompt, delivery: 'submit' }, + ...(merged?.ok ? { agentArgs: merged.agentArgs } : {}), + 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 + } + } + } + }, + context, + policy + ) + 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.` + ) + } + return launchOutcome(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.` + ) + } + throw error } } -async function sendToReusableSession( +async function launchOutcome( runtime: OrcaRuntimeService, - request: { - automation: Automation - run: Pick - runs: readonly AutomationRun[] - text: string - } -): Promise { - const { automation, text } = request - const worktreeId = requireWorkspaceId(automation) - const session = findReusableAutomationRun({ - automationId: automation.id, - agentId: automation.agentId, - worktreeId, - currentRunId: request.run.id, - runs: request.runs, - agentStatusForPane: (paneKey) => - runtime - .getAgentStatusRowsForPane(paneKey) - .filter((row) => !row.providerSessionOnly) - .toSorted((left, right) => right.receivedAt - left.receivedAt)[0], - liveSession: (previous) => { - const handle = runOwnHandle(runtime, previous) - return handle ? { handle, previous } : null + result: AgentLaunchResult +): Promise { + const shown = await runtime.showManagedWorktree(`id:${result.worktreeId}`) + if (result.outcome.kind === 'structured') { + return { + workspaceId: result.worktreeId, + workspaceDisplayName: shown.displayName ?? null, + sessionKind: 'chat', + chatSessionId: result.outcome.sessionId, + terminalHandle: null, + terminalSessionId: null, + terminalPaneKey: null, + terminalPtyId: null } - }) - if ( - !session || - !(await deliverTerminalAgentLaunchPrompt({ - runtime, - handle: session.handle, - agent: automation.agentId, - freshLaunch: false, - text, - // Windows cannot prove which agent is foreground; refuse only a proven shell. - unprovableHost: 'write-unless-shell' - })) - ) { - return null } - const shown = await runtime.showManagedWorktree(`id:${worktreeId}`) + const terminal = await runtime.showTerminal(result.outcome.handle) return { - workspaceId: worktreeId, + workspaceId: result.worktreeId, workspaceDisplayName: shown.displayName ?? null, - terminalHandle: session.handle, - terminalSessionId: session.previous.terminalSessionId, - terminalPaneKey: session.previous.terminalPaneKey, - terminalPtyId: session.previous.terminalPtyId + sessionKind: 'terminal', + chatSessionId: null, + terminalHandle: result.outcome.handle, + terminalSessionId: terminal.tabId ?? null, + terminalPaneKey: result.outcome.paneKey ?? runtime.getTerminalPaneKey(result.outcome.handle), + terminalPtyId: runtime.getTerminalPtyIdForHandle(result.outcome.handle) } } -/** Reject reused pane handles whose PTY no longer belongs to this run. */ +/** A pane may have been reused by a later process. */ export function runOwnHandle( runtime: Pick, run: AutomationRun @@ -198,32 +242,3 @@ export function runOwnHandle( ? handle : null } - -/** Return on terminal publication; post-start prompt delivery may still be pending. */ -function launchUntilPublished( - execution: AgentLaunchSurfaceExecution -): Promise { - return new Promise((resolve, reject) => { - let published = false - executeAgentLaunch({ - ...execution, - onSurfacePublished: (surface) => { - published = true - resolve(surface) - } - }).catch((error: unknown) => { - if (!published) { - reject(error) - return - } - console.warn('[automations] the agent launch failed after its terminal was published', error) - }) - }) -} - -function requireWorkspaceId(automation: Automation): string { - if (!automation.workspaceId) { - throw new Error('The target workspace is no longer available.') - } - return automation.workspaceId -} diff --git a/src/main/automations/headless-dispatch-durability.test.ts b/src/main/automations/headless-dispatch-durability.test.ts index 9b8ae3bbe71e..fe22ef14ca02 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 fabf85f3241d..946850a4f0aa 100644 --- a/src/main/automations/headless-dispatch-runner.ts +++ b/src/main/automations/headless-dispatch-runner.ts @@ -63,6 +63,8 @@ export async function runHeadlessAutomationDispatch( }) } 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 359673bc573e..3ee046734eab 100644 --- a/src/main/automations/headless-dispatch.ts +++ b/src/main/automations/headless-dispatch.ts @@ -8,6 +8,8 @@ import type { AutomationRunTargetResult } from './run-target-resolution' 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 diff --git a/src/main/automations/headless-workspace-create.test.ts b/src/main/automations/headless-workspace-create.test.ts index 8c2ffb3efe1d..380bb82e92e3 100644 --- a/src/main/automations/headless-workspace-create.test.ts +++ b/src/main/automations/headless-workspace-create.test.ts @@ -1,92 +1,11 @@ -import path from 'node:path' -import { describe, expect, it } from 'vitest' -import type { Automation } from '../../shared/automations-types' -import type { Repo } from '../../shared/repo-types' -import { buildHeadlessAutomationWorktreeCreateArgs } from './headless-workspace-create' - -const repoPath = path.join('tmp', 'orca') - -const repo: Repo = { - id: 'repo-1', - path: repoPath, - displayName: 'orca', - badgeColor: '#000', - addedAt: 1, - kind: 'git', - executionHostId: 'ssh:ssh-target-1' -} - -const automation: Automation = { - id: 'automation-1', - name: 'Nightly review', - prompt: 'Review changes', - precheck: null, - agentId: 'codex', - runContext: { - kind: 'workspace-run', - projectId: 'project-1', - hostId: 'ssh:ssh-target-1', - projectHostSetupId: 'setup-1', - repoId: 'repo-1', - path: repoPath - }, - sourceContext: null, - projectId: 'legacy-repo-1', - executionTargetType: 'ssh', - executionTargetId: 'ssh-target-1', - schedulerOwner: 'remote_host_service', - workspaceMode: 'new_per_run', - workspaceId: null, - baseBranch: 'origin/main', - setupDecision: 'skip', - reuseSession: false, - timezone: 'UTC', - rrule: 'FREQ=DAILY', - dtstart: 1, - enabled: true, - nextRunAt: 2, - missedRunPolicy: 'run_once_within_grace', - missedRunGraceMinutes: 720, - createdAt: 1, - updatedAt: 1 -} - -describe('headless automation workspace create args', () => { - it('stamps automation provenance for serve-mode new-per-run workspaces', () => { - const args = buildHeadlessAutomationWorktreeCreateArgs({ - automation, - run: { - id: 'run-1', - title: 'Nightly review run', - scheduledFor: Date.UTC(2026, 0, 2, 3, 4, 5) - }, - repo, - createdAt: 123 - }) - - expect(args).toMatchObject({ - repoSelector: 'repo-1', - name: 'auto-nightly-review-run-20260102T0304', - baseBranch: 'origin/main', - setupDecision: 'skip', - activate: false, - createdWithAgent: 'codex', - startupAgent: 'codex', - startupPrompt: 'Review changes', - telemetrySource: 'unknown', - automationProvenance: { - kind: 'created-by-automation', - automationId: 'automation-1', - automationNameSnapshot: 'Nightly review', - automationRunId: 'run-1', - automationRunTitleSnapshot: 'Nightly review run', - createdAt: 123, - executionTargetType: 'ssh', - executionTargetId: 'ssh-target-1', - projectId: 'project-1', - repoId: 'repo-1', - hostId: 'ssh:ssh-target-1' - } - }) - }) +import { expect, it } from 'vitest' +import { buildHeadlessAutomationWorkspaceName } from './headless-workspace-create' + +it('bounds automation workspace names while retaining the scheduled timestamp', () => { + expect( + buildHeadlessAutomationWorkspaceName('Nightly review run', Date.UTC(2026, 0, 2, 3, 4, 5)) + ).toBe('auto-nightly-review-run-20260102T0304') + expect(buildHeadlessAutomationWorkspaceName('!', Date.UTC(2026, 0, 2))).toBe( + 'auto-run-20260102T0000' + ) }) diff --git a/src/main/automations/headless-workspace-create.ts b/src/main/automations/headless-workspace-create.ts index 239d67db26fd..bcd17173113b 100644 --- a/src/main/automations/headless-workspace-create.ts +++ b/src/main/automations/headless-workspace-create.ts @@ -1,11 +1,3 @@ -import type { Automation, AutomationRun } from '../../shared/automations-types' -import { buildAutomationWorkspaceProvenance } from '../../shared/automation-workspace-provenance' -import type { Repo } from '../../shared/repo-types' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' - -type HeadlessAutomationRunForWorkspace = Pick -type RuntimeCreateManagedWorktreeArgs = Parameters[0] - export function buildHeadlessAutomationWorkspaceName( runTitle: string, scheduledFor: number @@ -19,30 +11,3 @@ export function buildHeadlessAutomationWorkspaceName( const stamp = new Date(scheduledFor).toISOString().replace(/[-:]/g, '').slice(0, 13) return `auto-${slug || 'run'}-${stamp}` } - -export function buildHeadlessAutomationWorktreeCreateArgs({ - automation, - run, - repo, - createdAt = Date.now() -}: { - automation: Automation - run: HeadlessAutomationRunForWorkspace - repo: Repo - createdAt?: number -}): RuntimeCreateManagedWorktreeArgs { - return { - repoSelector: repo.id, - name: buildHeadlessAutomationWorkspaceName(run.title, run.scheduledFor), - baseBranch: automation.baseBranch ?? undefined, - setupDecision: automation.setupDecision ?? 'skip', - activate: false, - createdWithAgent: automation.agentId, - startupAgent: automation.agentId, - startupPrompt: automation.prompt, - startupSuppressUpdatePrompt: true, - ...(automation.extraAgentArgs ? { startupExtraAgentArgs: automation.extraAgentArgs } : {}), - telemetrySource: 'unknown', - automationProvenance: buildAutomationWorkspaceProvenance(automation, run, repo, createdAt) - } -} 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 8b66ad815f1f..c54f7f17be97 100644 --- a/src/main/automations/run-completion-watcher.ts +++ b/src/main/automations/run-completion-watcher.ts @@ -174,6 +174,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 cc249a5d25cf..2f1ab559fd61 100644 --- a/src/main/automations/runtime-automation-service.test.ts +++ b/src/main/automations/runtime-automation-service.test.ts @@ -1,94 +1,206 @@ -import { describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type * as AgentLauncher from './headless-automation-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 terminalObserver?: AutomationRunTerminalObserver } - -const captured = vi.hoisted((): { options: CapturedServiceOptions } => ({ options: {} })) - -const { deliverTerminalAgentLaunchPrompt } = vi.hoisted(() => ({ - deliverTerminalAgentLaunchPrompt: vi.fn(async () => true) -})) -vi.mock('../runtime/rpc/methods/agent-launch-terminal-prompt', () => ({ - deliverTerminalAgentLaunchPrompt -})) - +const captured = vi.hoisted(() => { + const options: Options = {} + return { + options, + launch: vi.fn(), + observeChat: vi.fn(), + markDispatchResult: vi.fn() + } +}) 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('./headless-automation-agent-launch', async (original) => ({ + ...(await original()), + launchHeadlessAutomationAgent: captured.launch +})) +vi.mock('./runtime-chat-run-observer', () => ({ observeAutomationChatRun: captured.observeChat })) import { createRuntimeAutomationService } from './runtime-automation-service' - -function capturedOption( - key: K -): NonNullable { - const value = captured.options[key] - if (value === undefined) { - throw new Error(`the service was constructed without ${key}`) +const state = buildProfileStateCutoverFixture('/fixture') +const run = { + ...state.automationRuns[0], + createdAt: Date.now(), + status: 'dispatching' as const, + chatSessionId: null +} +function fixture(headless: boolean) { + const rows = new Map() + const runtime = { + setAutomationService: vi.fn(), + notifyAutomationsChanged: vi.fn(), + openAgentSessionRecordStore: async () => ({ + getOperationRow: (_caller: string, id: string) => rows.get(id), + getConversation: () => ({ + sessionId: 'claude_chat', + provider: 'claude', + location: { workspaceId: 'wt-1' } + }) + }), + getTerminalHandleForPaneKey: vi.fn(() => null), + getTerminalPtyIdForHandle: vi.fn(() => 'pty-1'), + getTerminalPaneKey: vi.fn( + () => '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d:3f2504e0-4f89-41d3-9a0c-0305e82c3301' + ), + waitForTerminal: vi.fn(async () => ({ state: 'done' })), + getAgentStatusRowsForPane: vi.fn(() => []) } - return value + 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' }] + } 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 } } - -describe('headless automation dispatch', () => { - it('hands the launched run to its watcher instead of awaiting one tui-idle wait itself', async () => { - const runtime = { - setAutomationService: vi.fn(), - notifyAutomationsChanged: vi.fn(), - launchAgentTerminal: vi.fn(async () => ({ - handle: 'terminal-1', - tabId: 'tab-1', - paneKey: 'tab-1:pane-1', - ptyId: 'pty-1', - worktreeId: 'wt-1' - })), - showManagedWorktree: vi.fn(async () => ({ displayName: 'repo' })), - waitForTerminal: vi.fn(), - getTerminalHandleForPaneKey: vi.fn(() => null), - getAgentStatusRowsForPane: vi.fn(() => []) - } - createRuntimeAutomationService({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the mocked service never reads the store; the dispatcher reads only past runs. - store: { listAutomationRuns: () => [] } as never, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the dispatcher reads only the members faked above. - runtime: runtime as never, - headless: true - }) - const dispatcher = capturedOption('headlessDispatcher') - const launch = await dispatcher({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a reuse-workspace automation; only these fields are read. - automation: { - workspaceMode: 'existing', +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 dispatcher on desktop/headless=%s and immediately hands completion to the watcher', + async (headless) => { + fixture(headless) + captured.launch.mockResolvedValue({ workspaceId: 'wt-1', - agentId: 'goose' - } as never, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the title is read. - run: { title: 'Nightly' } as never, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: unused for an existing workspace. - target: {} as never - }) - - expect(launch.completion).toBeUndefined() - expect(launch.terminalPaneKey).toBe('tab-1:pane-1') - expect(runtime.launchAgentTerminal).toHaveBeenCalledWith('id:wt-1', { - agent: 'goose', - prompt: '', - title: 'Nightly', - suppressStartupUpdatePrompt: true + terminalSessionId: 'tab-1', + terminalPaneKey: + '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d:3f2504e0-4f89-41d3-9a0c-0305e82c3301', + terminalHandle: 'term-1' + }) + const dispatcher = captured.options.headlessDispatcher! + const result = await dispatcher({ + automation: state.automations[0], + 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) + 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 a terminal reuse receipt without a pane key and never launches again', async () => { + const { rows, runtime } = fixture(false) + rows.set(automationRunOperationId(run, 'reuse-terminal-launch'), { + outcome: { + status: 'succeeded', + launch: { + worktreeId: 'wt-1', + outcome: { kind: 'terminal', handle: 'term-reused' }, + receipt: { + mode: 'terminal', + preferred: 'terminal', + reason: 'requested', + detail: 'Terminal' + }, + prompt: { delivery: 'submit', outcome: 'handed-to-terminal' } + } + } }) - expect(runtime.waitForTerminal).not.toHaveBeenCalled() - const observer = capturedOption('terminalObserver') - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: resolution reads only the pane key. - expect(observer.resolveRunTerminal({ terminalPaneKey: 'tab-1:pane-1' } as never)).toBe( - 'terminal-1' + runtime.waitForTerminal.mockRejectedValueOnce(new Error('test-stop')) + const observer = captured.options.terminalObserver! + await expect( + observer.observeCompletion(observer.resolveRunTerminal(run)!, { + run, + signal: new AbortController().signal + }) + ).rejects.toThrow('test-stop') + expect(captured.markDispatchResult).toHaveBeenCalledWith( + expect.objectContaining({ + sessionKind: 'terminal', + terminalPaneKey: + '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d:3f2504e0-4f89-41d3-9a0c-0305e82c3301', + terminalSessionId: '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d', + terminalPtyId: 'pty-1' + }) ) + 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() }) }) diff --git a/src/main/automations/runtime-automation-service.ts b/src/main/automations/runtime-automation-service.ts index 99b4c5c8aa53..ece048ba7685 100644 --- a/src/main/automations/runtime-automation-service.ts +++ b/src/main/automations/runtime-automation-service.ts @@ -1,3 +1,7 @@ +import { observeAutomationChatRun } from './runtime-chat-run-observer' +import { readAutomationRunReceipt } from './automation-run-receipt' +import { tuiAgentDisplayName } from '../../shared/tui-agent-display-names' +import { parsePaneKey } from '../../shared/stable-pane-id' import type { ClaudeUsageStore } from '../claude-usage/store' import type { CodexUsageStore } from '../codex-usage/store' import type { Store } from '../persistence' @@ -42,10 +46,69 @@ export function createRuntimeAutomationService(input: { terminalObserver: { ...observer, resolveRunTerminal: (run) => - (run.terminalPaneKey ? launchedHandles.get(run.terminalPaneKey) : undefined) ?? - observer.resolveRunTerminal(run), + run.sessionKind === 'chat' || run.status === 'dispatching' + ? `automation:${run.id}` + : ((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 terminal = receipt.kind === 'terminal' ? receipt.launch.outcome : null + const terminalPaneKey = terminal + ? (terminal.paneKey ?? runtime.getTerminalPaneKey(terminal.handle)) + : null + run = await service.markDispatchResult({ + runId: run.id, + status: 'dispatched', + workspaceId: + receipt.kind === 'chat' ? receipt.workspaceId : receipt.launch.worktreeId, + sessionKind: receipt.kind, + chatSessionId: receipt.kind === 'chat' ? receipt.sessionId : null, + terminalSessionId: terminal + ? (parsePaneKey(terminalPaneKey ?? '')?.tabId ?? null) + : null, + terminalPaneKey, + terminalPtyId: terminal ? runtime.getTerminalPtyIdForHandle(terminal.handle) : null + }) + if (terminal) { + handle = terminal.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 ?? + '' + ) ?? 'The 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,22 +123,20 @@ export function createRuntimeAutomationService(input: { }, onAutomationsChanged: (payload) => runtime.notifyAutomationsChanged(payload), allowRemoteHostScheduling: input.headless, - headlessDispatcher: input.headless - ? async (request) => { - const { terminalHandle, ...launch } = await launchHeadlessAutomationAgent(runtime, { - ...request, - runs: store.listAutomationRuns(request.automation.id) - }) - if (launch.terminalPaneKey) { - launchedHandles.set(launch.terminalPaneKey, terminalHandle) - if (launchedHandles.size > MAX_REMEMBERED_LAUNCHES) { - launchedHandles.delete(launchedHandles.keys().next().value ?? '') - } - } - // Let the watcher retry wait timeouts until completion or its observation deadline. - return launch + headlessDispatcher: async (request) => { + const { terminalHandle, ...launch } = await launchHeadlessAutomationAgent(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 ?? '') } - : undefined + } + // Let the watcher retry wait timeouts until completion or its observation deadline. + return launch + } }) runtime.setAutomationService(service) if (input.headless) { 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..de5532bd061b --- /dev/null +++ b/src/main/automations/runtime-chat-run-observer.test.ts @@ -0,0 +1,203 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { + AgentJournalSnapshot, + AgentJournalRenderItem, + AgentJournalSubmission +} from '../../shared/agent-session-journal-types' +import { agentJournalSubmissionKey } 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 { automationRunOperationId } from './automation-run-operation' + +const mocks = vi.hoisted(() => ({ host: { journalSnapshot: vi.fn(), subscribe: vi.fn() } })) +vi.mock('../native-chat/agent-session-wire/structured-agent-session-registry', () => ({ + getStructuredAgentSessionHost: () => 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()) +afterEach(() => vi.useRealTimers()) +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() + expect( + chatAutomationRunObservation(snapshot([turn('human', 'other')]), 'prompt', 'Claude') + ).toBeNull() + }) + it('matches the Orca opener alias and snapshots only the accepted root turn', () => { + const result = chatAutomationRunObservation( + snapshot([ + turn('own', agentJournalSubmissionKey('prompt')), + answer('a', 'own', 'Automation output'), + answer('b', 'human', 'Private later output'), + { ...answer('c', 'own', 'Child output'), agentId: 'child' } + ]), + 'prompt', + 'Codex' + ) + 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('subscribes before snapshot, ignores token deltas, and releases a subscription that arrives after abort', async () => { + const { run, runtime, view } = fixture() + const release = vi.fn() + const subscription = Promise.withResolvers<() => void>() + mocks.host.subscribe.mockReturnValue(subscription.promise) + mocks.host.journalSnapshot.mockResolvedValue(view) + 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.subscribe).toHaveBeenCalledOnce()) + expect(mocks.host.journalSnapshot).not.toHaveBeenCalled() + controller.abort() + await rejected + subscription.resolve(release) + await vi.waitFor(() => expect(release).toHaveBeenCalledOnce()) + }) + it('reattaches from the persisted receipt without sending, observes completion, and unsubscribes', async () => { + const { run, runtime, view } = fixture() + const release = vi.fn() + mocks.host.subscribe.mockResolvedValue(release) + mocks.host.journalSnapshot.mockResolvedValue(view) + const pending = observeAutomationChatRun(runtime, run, new AbortController().signal) + await vi.waitFor(() => expect(mocks.host.journalSnapshot).toHaveBeenCalledOnce()) + const emit = mocks.host.subscribe.mock.calls[0][0].emit + emit({ type: 'batch', batch: { submissions: [], items: [answer('delta', 'own', 'token')] } }) + await Promise.resolve() + expect(mocks.host.journalSnapshot).toHaveBeenCalledOnce() + view.items[0] = turn('own', view.submissions[0].providerItemId!) + emit({ type: 'batch', batch: { submissions: [], items: [view.items[0]] } }) + expect(await pending).toMatchObject({ status: 'completed' }) + expect(release).toHaveBeenCalledOnce() + }) + 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.subscribe).not.toHaveBeenCalled() + }) +}) 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..057e6e53b823 --- /dev/null +++ b/src/main/automations/runtime-chat-run-observer.ts @@ -0,0 +1,190 @@ +import type { AutomationRun } from '../../shared/automations-types' +import type { AgentJournalSnapshot } from '../../shared/agent-session-journal-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 { createHeadlessAutomationOutputSnapshotBuffer } from './headless-dispatch' +import type { AutomationRunCompletionObservation } from './run-completion-watcher' +import { tuiAgentDisplayName } from '../../shared/tui-agent-display-names' + +export function chatAutomationRunObservation( + snapshot: AgentJournalSnapshot, + messageId: string, + agent: string +): AutomationRunCompletionObservation | null { + const submission = snapshot.submissions.find((entry) => entry.clientMessageId === messageId) + if (!submission) { + return null + } + const keys = new Set([ + agentJournalSubmissionKey(messageId), + ...(submission.providerItemId ? [submission.providerItemId] : []) + ]) + const turnItem = 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)) + ) + }) + 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.` + } +} + +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) { + 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 + const finish = (result?: AutomationRunCompletionObservation, error?: unknown): void => { + if (settled) { + return + } + settled = true + 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 read = async (): Promise => { + if (settled) { + return + } + if (reading) { + dirty = true + return + } + reading = true + try { + do { + dirty = false + const observation = chatAutomationRunObservation( + await host.journalSnapshot(sessionId), + messageId, + agent + ) + if (observation) { + finish(observation) + return + } + } while (dirty && !settled) + } catch (error) { + finish(undefined, error) + } finally { + reading = false + } + } + signal.addEventListener('abort', abort, { once: true }) + if (signal.aborted) { + abort() + return + } + void host + .subscribe({ + id: `automation:${run.id}`, + sessionId, + emit: (event) => { + // Token deltas do not change completion; read the full journal only at request/turn boundaries. + if ( + event.type !== 'batch' || + event.batch.submissions.some((entry) => entry.clientMessageId === messageId) || + event.batch.items.some((item) => readAgentJournalTurn(item.body)) + ) { + void read() + } + } + }) + .then( + (unsubscribe) => { + release = unsubscribe + if (settled) { + unsubscribe() + } else { + void read() + } + }, + (error) => finish(undefined, error) + ) + }) +} diff --git a/src/main/automations/service.test.ts b/src/main/automations/service.test.ts index 1fcd8737a10c..31f697ff0767 100644 --- a/src/main/automations/service.test.ts +++ b/src/main/automations/service.test.ts @@ -70,8 +70,8 @@ describe('AutomationService', () => { }) vi.setSystemTime(new Date('2026-05-13T09:01:00')) - const send = vi.fn() - const service = new AutomationService(store, { tickMs: 60_000 }) + const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) + const service = new AutomationService(store, { headlessDispatcher: send, tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, send @@ -80,14 +80,18 @@ describe('AutomationService', () => { service.start() service.setRendererReady() await vi.waitFor(() => - expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.any(Object)) + expect(send).toHaveBeenCalledWith( + expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) + ) ) service.stop() - const [, payload] = send.mock.calls[0] + const [payload] = send.mock.calls[0] expect(payload.automation.id).toBe(automation.id) expect(payload.run.scheduledFor).toBe(new Date('2026-05-13T09:00:00').getTime()) - expect(store.listAutomationRuns(automation.id)[0]?.status).toBe('dispatching') + await vi.waitFor(() => + expect(store.listAutomationRuns(automation.id)[0]?.status).toBe('dispatched') + ) expect(store.listAutomations().find((entry) => entry.id === automation.id)?.nextRunAt).toBe( new Date('2026-05-14T09:00:00').getTime() ) @@ -108,8 +112,8 @@ describe('AutomationService', () => { rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', dtstart: new Date('2026-05-14T00:00:00Z').getTime() }) - const send = vi.fn() - const service = new AutomationService(store, { tickMs: 60_000 }) + const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) + const service = new AutomationService(store, { headlessDispatcher: send, tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, send @@ -118,10 +122,11 @@ describe('AutomationService', () => { const run = await service.runNow(automation.id) - expect(run.status).toBe('dispatching') - expect(store.listAutomationRuns(automation.id)[0]?.status).toBe('dispatching') + expect(run.status).toBe('dispatched') + await vi.waitFor(() => + expect(store.listAutomationRuns(automation.id)[0]?.status).toBe('dispatched') + ) expect(send).toHaveBeenCalledWith( - 'automations:dispatchRequested', expect.objectContaining({ run: expect.objectContaining({ id: run.id, status: 'dispatching' }) }) @@ -153,8 +158,8 @@ describe('AutomationService', () => { } }) const reloaded = await createStore() - const send = vi.fn() - const service = new AutomationService(reloaded, { tickMs: 60_000 }) + const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) + const service = new AutomationService(reloaded, { headlessDispatcher: send, tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, send @@ -194,8 +199,8 @@ describe('AutomationService', () => { } }) const reloaded = await createStore() - const send = vi.fn() - const service = new AutomationService(reloaded, { tickMs: 60_000 }) + const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) + const service = new AutomationService(reloaded, { headlessDispatcher: send, tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, send @@ -233,8 +238,8 @@ describe('AutomationService', () => { rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', dtstart: new Date('2026-05-14T00:00:00Z').getTime() }) - const send = vi.fn() - const service = new AutomationService(store, { tickMs: 60_000 }) + const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) + const service = new AutomationService(store, { headlessDispatcher: send, tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, send @@ -272,8 +277,9 @@ describe('AutomationService', () => { rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', dtstart: new Date('2026-05-14T00:00:00Z').getTime() }) - const send = vi.fn() + const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) const service = new AutomationService(store, { + headlessDispatcher: send, tickMs: 60_000, allowRemoteHostScheduling: true }) @@ -285,9 +291,8 @@ describe('AutomationService', () => { const run = await service.runNow(automation.id) - expect(run.status).toBe('dispatching') + expect(run.status).toBe('dispatched') expect(send).toHaveBeenCalledWith( - 'automations:dispatchRequested', expect.objectContaining({ automation: expect.objectContaining({ schedulerOwner: 'remote_host_service' }), run: expect.objectContaining({ id: run.id, status: 'dispatching' }) @@ -677,20 +682,24 @@ describe('AutomationService', () => { const logged = vi.spyOn(console, 'error').mockImplementation(() => {}) vi.setSystemTime(new Date('2026-05-13T09:01:00')) - const send = vi.fn() - const service = new AutomationService(reloaded, { tickMs: 60_000 }) + const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) + const service = new AutomationService(reloaded, { headlessDispatcher: send, tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, send }) service.start() service.setRendererReady() await vi.waitFor(() => - expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.any(Object)) + expect(send).toHaveBeenCalledWith( + expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) + ) ) service.stop() - const [, payload] = send.mock.calls[0] + const [payload] = send.mock.calls[0] expect(payload.automation.id).toBe(healthy.id) - expect(reloaded.listAutomationRuns(healthy.id)[0]?.status).toBe('dispatching') + await vi.waitFor(() => + expect(reloaded.listAutomationRuns(healthy.id)[0]?.status).toBe('dispatched') + ) const poisonRun = reloaded.listAutomationRuns(poison.id)[0] expect(poisonRun?.status).toBe('skipped_unavailable') expect(poisonRun?.error).toBe( @@ -733,27 +742,31 @@ describe('AutomationService', () => { const logged = vi.spyOn(console, 'error').mockImplementation(() => {}) vi.setSystemTime(new Date('2026-05-13T09:01:00')) - const send = vi.fn() - const service = new AutomationService(reloaded, { tickMs: 60_000 }) + const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) + const service = new AutomationService(reloaded, { headlessDispatcher: send, tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, send }) service.start() service.setRendererReady() await vi.waitFor(() => - expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.any(Object)) + expect(send).toHaveBeenCalledWith( + expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) + ) ) service.stop() - const [, payload] = send.mock.calls[0] + const [payload] = send.mock.calls[0] expect(payload.automation.id).toBe(healthy.id) - expect(reloaded.listAutomationRuns(healthy.id)[0]?.status).toBe('dispatching') + await vi.waitFor(() => + expect(reloaded.listAutomationRuns(healthy.id)[0]?.status).toBe('dispatched') + ) expect(reloaded.listAutomationRuns(poison.id)[0]?.error).toBe( 'Orca could not evaluate this automation and skipped the occurrence.' ) expect(logged).toHaveBeenCalled() }) - it('marks the run dispatch_failed when the renderer send throws', async () => { + it('marks the run dispatch_failed when the host launch throws', async () => { vi.setSystemTime(new Date('2026-05-13T08:59:00')) const store = await createStore() store.addRepo(makeRepo()) @@ -772,10 +785,10 @@ describe('AutomationService', () => { logged.mockClear() vi.setSystemTime(new Date('2026-05-13T09:01:00')) - const send = vi.fn(() => { - throw new Error('renderer is gone') + const send = vi.fn(async () => { + throw new Error('host launch failed') }) - const service = new AutomationService(store, { tickMs: 60_000 }) + const service = new AutomationService(store, { tickMs: 60_000, headlessDispatcher: send }) service.setWebContents({ isDestroyed: () => false, send }) service.start() @@ -786,7 +799,7 @@ describe('AutomationService', () => { const runs = store.listAutomationRuns(automation.id) expect(runs).toHaveLength(1) expect(runs[0]?.status).toBe('dispatch_failed') - expect(runs[0]?.error).toBe('renderer is gone') + expect(runs[0]?.error).toBe('host launch failed') expect(logged).not.toHaveBeenCalled() }) }) diff --git a/src/main/automations/service.ts b/src/main/automations/service.ts index 57a086ec78a3..10d16a055c94 100644 --- a/src/main/automations/service.ts +++ b/src/main/automations/service.ts @@ -43,10 +43,7 @@ import type { PublishAutomationsChanged } from '../../shared/runtime-client-events' -const DEFAULT_TICK_MS = 60 * 1000 - export class AutomationService { - private readonly store: Store private readonly tickMs: number private timer: ReturnType | null = null private webContents: AutomationRendererChannel | null = null @@ -68,7 +65,7 @@ export class AutomationService { externalProbePriority: ((run: () => T) => T) | null = null constructor( - store: Store, + private readonly store: Store, opts: { tickMs?: number claudeUsage?: ClaudeUsageStore @@ -79,8 +76,7 @@ export class AutomationService { onAutomationsChanged?: PublishAutomationsChanged } = {} ) { - this.store = store - this.tickMs = opts.tickMs ?? DEFAULT_TICK_MS + this.tickMs = opts.tickMs ?? 60_000 this.claudeUsage = opts.claudeUsage ?? null this.codexUsage = opts.codexUsage ?? null this.allowRemoteHostScheduling = opts.allowRemoteHostScheduling ?? false @@ -124,7 +120,7 @@ export class AutomationService { this.completionWatcher?.reconcileRetainedRuns(this.store.listAutomationRuns()) reportAutomationScheduleDrift(this.store.listAutomations()) // Headless hosts need startup catch-up without a renderer-ready notification. - if (this.rendererReady || this.headlessDispatcher) { + if (this.rendererReady || (this.allowRemoteHostScheduling && this.headlessDispatcher)) { // Serve adopts PTYs and publishes its graph before start(). this.completionWatcher?.markTerminalSurfaceReady() void this.evaluateDueRuns() @@ -264,7 +260,9 @@ export class AutomationService { // Fold recurring refusals before creating rows so they do not evict real run history. const target = this.resolveTarget(automation) - const canDispatch = this.canDispatchToRenderer() || Boolean(this.headlessDispatcher) + const canDispatch = + this.canDispatchToRenderer() || + Boolean(this.allowRemoteHostScheduling && this.headlessDispatcher) const refusal = describeScheduledRefusal({ target, canDispatch }) // Once WSL owns the schedule, avoid churning skips on the retained local copy. if (refusal === WSL_MOVE_OWNED_BY_HOST) { @@ -313,8 +311,10 @@ export class AutomationService { store: this.store, runs: this.runs, isActive: () => !this.stopped && generation === this.dispatchGeneration, - getRenderer: () => (this.canDispatchToRenderer() ? this.webContents : null), - headlessDispatcher: this.headlessDispatcher, + headlessDispatcher: + this.allowRemoteHostScheduling || this.canDispatchToRenderer() + ? this.headlessDispatcher + : null, resolveTarget: (current) => this.resolveTarget(current), runPrecheck: () => this.runPrecheck(automation.id, run.id), markDispatchResult: (result) => this.markDispatchResult(result), 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/applying-settings/persistence-legacy-automation-twin-host.test.ts b/src/main/persistence/applying-settings/persistence-legacy-automation-twin-host.test.ts index 0a163da988ec..3dc6419fe6d1 100644 --- a/src/main/persistence/applying-settings/persistence-legacy-automation-twin-host.test.ts +++ b/src/main/persistence/applying-settings/persistence-legacy-automation-twin-host.test.ts @@ -116,16 +116,18 @@ describe('legacy automation on a repo id two hosts share', () => { it('captures the only host on its first run, which still launches, and keeps it', async () => { seed([localRow], legacyAutomation({ runContext: null })) const store = createStore() - const send = vi.fn() - const service = new AutomationService(store, { tickMs: 60_000 }) + const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) + const service = new AutomationService(store, { headlessDispatcher: send, tickMs: 60_000 }) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: dispatch reads only isDestroyed and send. service.setWebContents({ isDestroyed: () => false, send } as never) service.setRendererReady() const run = await service.runNow('legacy-1') - expect(run.status).toBe('dispatching') - expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.any(Object)) + expect(run.status).toBe('dispatched') + expect(send).toHaveBeenCalledWith( + expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) + ) const stamped = storedAutomation(store).runContext expect(stamped).toMatchObject({ hostId: 'local', repoId: 'twin', path: '/laptop/twin' }) 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 1b7887573772..6369a73c8974 100644 --- a/src/main/persistence/scheduling-automations/automation-run-operations.ts +++ b/src/main/persistence/scheduling-automations/automation-run-operations.ts @@ -178,6 +178,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-surfaces.ts b/src/main/runtime/rpc/methods/agent-launch-surfaces.ts index 61e88b5da713..6bd1afe945f6 100644 --- a/src/main/runtime/rpc/methods/agent-launch-surfaces.ts +++ b/src/main/runtime/rpc/methods/agent-launch-surfaces.ts @@ -34,6 +34,12 @@ import { type AgentLaunchView } from './agent-launch-tab-publication' +export type AgentLaunchHostPolicy = { + terminalTitle?: string + suppressStartupUpdatePrompt?: true + unprovableHost?: 'write-unless-shell' +} + /** Replay-safe launches keep the nested attach in the same stable caller namespace as the launch. */ export function agentLaunchSurfaceFactory( context: RpcContext, @@ -43,7 +49,8 @@ export function agentLaunchSurfaceFactory( callerPresentsSurface = false, terminalSpawn: TerminalSpawnDispatch = trackTerminalSpawnDispatch(), // Read the early pane at spawn: publication and user close can finish after admission. - view: AgentLaunchView = { early: null, presentation: undefined } + view: AgentLaunchView = { early: null, presentation: undefined }, + policy: AgentLaunchHostPolicy = {} ): AgentLaunchSurfaceFactory { const movesHostWindow = agentLaunchMovesHostWindow(context) const { early: earlyTab, presentation } = view @@ -142,6 +149,8 @@ export function agentLaunchSurfaceFactory( const created = context.runtime.createTerminal(`id:${worktreeId}`, { // Let the runtime build the configured launcher: agent ids are not commands (cursor uses cursor-agent). startupAgent: agent, + ...(policy.terminalTitle ? { title: policy.terminalTitle } : {}), + ...(policy.suppressStartupUpdatePrompt ? { suppressStartupUpdatePrompt: true } : {}), terminalImageViewerSupported: terminalImageViewerSupported(context), // The runtime reports typed-line prompt carry; paste only when the command did not carry it. ...(startupPrompt @@ -208,6 +217,7 @@ export function agentLaunchSurfaceFactory( handle, agent, freshLaunch, + ...(policy.unprovableHost ? { unprovableHost: policy.unprovableHost } : {}), text: prompt.text, ...(signal ? { signal } : {}) }) diff --git a/src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts b/src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts index 88317333bd22..7021024c6e9a 100644 --- a/src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts +++ b/src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts @@ -1,3 +1,4 @@ +import type { AgentLaunchHostPolicy } from './agent-launch-surfaces' /** Terminal launches create agent-first worktrees; structured launches create the workspace without an agent and add chat afterwards. * The executor chooses; setup, default tabs, provenance and lineage use the normal create path. */ @@ -28,7 +29,8 @@ const STRUCTURED_SETUP_WAIT_TIMEOUT_MS = 60_000 export function agentLaunchWorkspaceFactory( context: RpcContext, - agent: TuiAgent + agent: TuiAgent, + policy: AgentLaunchHostPolicy = {} ): AgentLaunchWorkspaceFactory { return { createFolderWorkspace: agentLaunchFolderWorkspaceCreator(context, agent), @@ -96,6 +98,7 @@ export function agentLaunchWorkspaceFactory( ...(accountEnv ? { startupAccountEnv: { ...accountEnv } } : {}), // Record the launch's agent on the workspace even when it has no startup terminal. createdWithAgent: agent, + ...(policy.suppressStartupUpdatePrompt ? { startupSuppressUpdatePrompt: true } : {}), ...(promisedAgentChat ? { promisedAgentChat } : {}), ...(onWorkspaceCreated ? { onWorkspaceCreated } : {}), // Chats have no startup command to sequence after setup; provision setup synchronously and return its completion token. diff --git a/src/main/runtime/rpc/methods/agent-launch.test.ts b/src/main/runtime/rpc/methods/agent-launch.test.ts index d5abaeff03eb..88c2718054d9 100644 --- a/src/main/runtime/rpc/methods/agent-launch.test.ts +++ b/src/main/runtime/rpc/methods/agent-launch.test.ts @@ -28,7 +28,7 @@ vi.mock('./structured-agent-session-create', () => ({ createStructuredSession(args) })) -const { AGENT_LAUNCH_METHODS } = await import('./agent-launch') +const { AGENT_LAUNCH_METHODS, launchAgentOnHost } = await import('./agent-launch') const { WORKTREE_METHODS } = await import('./worktree') const AGENT_LAUNCH = methodNamed(AGENT_LAUNCH_METHODS, 'agent.launch') @@ -694,3 +694,46 @@ describe('launch inputs that cross the wire', () => { expect(result.receipt).toMatchObject({ mode: 'terminal', reason: 'tui_launch_command' }) }) }) + +describe('trusted unattended launch policy', () => { + it('uses the ordinary terminal factory while suppressing updates and retaining the run title', async () => { + const runtime = runtimeStub() + const result = await launchAgentOnHost( + AGENT_LAUNCH.params.parse({ + agent: 'claude', + surface: 'terminal', + presentation: 'background', + target: { kind: 'existing', worktree: 'id:wt-7' } + }), + rpcContext(runtime, {}), + { suppressStartupUpdatePrompt: true, terminalTitle: 'Nightly run 1' } + ) + expect(result.outcome.kind).toBe('terminal') + expect(runtime.createTerminal).toHaveBeenCalledWith( + 'id:wt-7', + expect.objectContaining({ + startupAgent: 'claude', + suppressStartupUpdatePrompt: true, + title: 'Nightly run 1', + presentation: 'background' + }) + ) + }) + it('forwards suppression through the ordinary new-workspace factory without exposing a wire option', async () => { + const runtime = runtimeStub() + const params = AGENT_LAUNCH.params.parse({ + ...CREATE_LAUNCH, + surface: 'terminal', + suppressStartupUpdatePrompt: true + }) + expect(params).not.toHaveProperty('suppressStartupUpdatePrompt') + await launchAgentOnHost(params, rpcContext(runtime, {}), { suppressStartupUpdatePrompt: true }) + expect(runtime.createManagedWorktree).toHaveBeenCalledWith( + expect.objectContaining({ + startupAgent: 'claude', + startupSuppressUpdatePrompt: true, + createdWithAgent: 'claude' + }) + ) + }) +}) diff --git a/src/main/runtime/rpc/methods/agent-launch.ts b/src/main/runtime/rpc/methods/agent-launch.ts index ca7e03404991..88aa9ca968f1 100644 --- a/src/main/runtime/rpc/methods/agent-launch.ts +++ b/src/main/runtime/rpc/methods/agent-launch.ts @@ -32,7 +32,7 @@ import { AgentLaunchReplay, type AgentLaunchParams } from '../../../../shared/rpc-contract/agent-launch-params' -import { agentLaunchSurfaceFactory } from './agent-launch-surfaces' +import { agentLaunchSurfaceFactory, type AgentLaunchHostPolicy } from './agent-launch-surfaces' import { agentLaunchFailureCode, launchFailureWithoutEffectsCode @@ -61,6 +61,8 @@ export function supportsAgentLaunch( ) } +type HostLaunchContext = RpcContext & { agentLaunchPolicy?: AgentLaunchHostPolicy } + /** What a launch admitted under an operation id carries into its execution. */ type ReplaySafeLaunch = { attachOperationId: string @@ -72,7 +74,7 @@ type ReplaySafeLaunch = { async function runAgentLaunch( { intent, decidedMode }: Awaited>, - context: RpcContext, + context: HostLaunchContext, view: AgentLaunchView, replaySafe?: ReplaySafeLaunch ): Promise { @@ -87,9 +89,10 @@ async function runAgentLaunch( replaySafe?.callerKey, callerNavigationId !== null, replaySafe?.terminalSpawn, - view + view, + context.agentLaunchPolicy ), - workspaces: agentLaunchWorkspaceFactory(context, intent.agent), + workspaces: agentLaunchWorkspaceFactory(context, intent.agent, context.agentLaunchPolicy), // The tab is shown as it is published, not after a prompt that can take a minute to land. onSurfacePublished: (surface) => { view.early?.surfacePublished(surface) @@ -106,7 +109,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 () => @@ -152,7 +155,7 @@ function activeAgentLaunchesFor(runtime: OrcaRuntimeService): Map { // The tab is the host's first act: admission has a cold cost the user should not watch. @@ -188,7 +191,7 @@ async function executeReplaySafeAgentLaunch( async function executeAdmittedAgentLaunch( params: AgentLaunchParams & { operationId: string }, - context: RpcContext, + context: HostLaunchContext, admission: Extract< Awaited>, { decision: 'execute' } @@ -238,7 +241,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) @@ -298,29 +301,31 @@ export const AGENT_LAUNCH_METHODS = [ name: 'agent.launch', 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?: AgentLaunchHostPolicy +): 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..7e751ac9c093 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/AutomationSurfaceField.test.tsx b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx new file mode 100644 index 000000000000..82a202552971 --- /dev/null +++ b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx @@ -0,0 +1,50 @@ +// @vitest-environment happy-dom +import { afterEach, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import type { AutomationDraft } from './AutomationEditorDialog' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import { AutomationSurfaceField } from './AutomationSurfaceField' +import { automationDraftSurface } from './automation-launch-surface' +import { buildAutomationEditDraft } from './automation-edit-draft' +import { buildProfileStateCutoverFixture } from '../../../../main/persistence/profile-state-cutover-fixture' + +// 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() + render( + + ) + 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, groupClassName: '', itemClassName: '', onDraftChange: vi.fn() } + const view = render() + expect(screen.getAllByRole('radio').every((radio) => radio.hasAttribute('disabled'))).toBe(true) + view.rerender() + expect(screen.queryByRole('radio')).toBeNull() +}) diff --git a/src/renderer/src/components/automations/AutomationSurfaceField.tsx b/src/renderer/src/components/automations/AutomationSurfaceField.tsx new file mode 100644 index 000000000000..3b9f69329120 --- /dev/null +++ b/src/renderer/src/components/automations/AutomationSurfaceField.tsx @@ -0,0 +1,68 @@ +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, + groupClassName, + itemClassName, + onDraftChange +}: { + draft: AutomationDraft + settings: GlobalSettings | null + supported: boolean | null + groupClassName: string + itemClassName: string + 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/automation-capability-probe.ts b/src/renderer/src/components/automations/automation-capability-probe.ts index d81f1b76a946..fb33497630ed 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 { @@ -179,3 +184,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 76d93b0e3e2d..91804435dd88 100644 --- a/src/renderer/src/components/automations/automation-draft-model.ts +++ b/src/renderer/src/components/automations/automation-draft-model.ts @@ -43,9 +43,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({ @@ -57,9 +57,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 84b49e8c2eb2..2a933f7a6f95 100644 --- a/src/renderer/src/components/automations/automation-edit-draft.ts +++ b/src/renderer/src/components/automations/automation-edit-draft.ts @@ -15,6 +15,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..c2fc5dd4f4bf --- /dev/null +++ b/src/renderer/src/components/automations/automation-launch-surface.ts @@ -0,0 +1,61 @@ +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import { AUTOMATION_SURFACE_RUNTIME_CAPABILITY } from '../../../../shared/automation-runtime-capabilities' +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.entry.owner.selector.kind === 'ssh' + ? `ssh:${ready.entry.owner.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) { + return null + } + if (!input.hostCapabilities.includes(AUTOMATION_SURFACE_RUNTIME_CAPABILITY)) { + return false + } + return structuredAgentLaunchSupport(input).supported +} + +export function automationDraftSurface( + draft: AutomationDraft, + settings: GlobalSettings | null, + chatSupported: boolean | null +): 'chat' | 'terminal' { + return ( + draft.surface ?? + (chatSupported && isNativeChatDefaultFor(settings, draft.agentId) ? 'chat' : 'terminal') + ) +} diff --git a/src/renderer/src/components/automations/automation-orca-save.ts b/src/renderer/src/components/automations/automation-orca-save.ts index bdb0cc938df1..905b6382168f 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, + automationDraftSurface, + automationLaunchWorkspace +} from './automation-launch-surface' import { toast } from 'sonner' import type { Automation, @@ -152,15 +157,27 @@ export async function saveOrcaAutomation( currentAutomation = (reread.ok ? reread.value : null) ?? currentAutomation } + const surface = automationDraftSurface( + draft, + store.settings, + automationChatSupport( + useAppStore.getState(), + draft, + automationLaunchWorkspace(draft, setupResolution ?? undefined) + ) + ) + const launchSetupPatch = { + surface, + ...(hasExtraAgentArgs(draft.extraAgentArgs) || currentAutomation?.extraAgentArgs + ? { arguments: { kind: 'legacy-extras' as const, value: draft.extraAgentArgs } } + : {}) + } 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 } - : {}), + launchSetupPatch, runContext, projectId: draft.projectId, workspaceMode: draft.workspaceMode, @@ -180,7 +197,7 @@ export async function saveOrcaAutomation( prompt: draft.prompt, precheck, agentId: draft.agentId, - ...(hasExtraAgentArgs(draft.extraAgentArgs) ? { extraAgentArgs: draft.extraAgentArgs } : {}), + launchSetupPatch, 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 ce4cc9f7773f..c871919f172d 100644 --- a/src/renderer/src/components/automations/automation-run-view-state.ts +++ b/src/renderer/src/components/automations/automation-run-view-state.ts @@ -1,6 +1,11 @@ import type { Automation, AutomationRun } from '../../../../shared/automations-types' -export type AutomationRunViewAvailability = 'terminal' | 'workspace' | 'snapshot' | 'metadata' +export type AutomationRunViewAvailability = + | 'chat' + | 'terminal' + | 'workspace' + | 'snapshot' + | 'metadata' export type AutomationRunViewState = { availability: AutomationRunViewAvailability @@ -60,6 +65,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: 'View run', + statusLabel: 'Open run chat', + 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..7bd688c526fd 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 @@ -8,6 +8,8 @@ const mocks = vi.hoisted(() => { const state: Record = {} return { state, + openChat: vi.fn(), + readChat: vi.fn(async () => ({})), toastError: vi.fn(), toastMessage: vi.fn(), activateAndRevealWorktree: vi.fn(() => true), @@ -16,6 +18,12 @@ const mocks = vi.hoisted(() => { } }) +vi.mock('@/runtime/structured-agent-session-client', () => ({ + callStructuredAgentSession: mocks.readChat +})) +vi.mock('@/lib/structured-agent-session-launch-surface', () => ({ + openStructuredAgentSessionProvisionalTab: mocks.openChat +})) vi.mock('sonner', () => ({ toast: { error: mocks.toastError, message: mocks.toastMessage } })) vi.mock('@/store', () => ({ useAppStore: { getState: () => mocks.state } })) vi.mock('@/lib/worktree-activation', () => ({ @@ -152,3 +160,56 @@ 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.openChat).toHaveBeenCalledWith({ + worktreeId: WT, + executionHostId: `runtime:${ENV}`, + sessionId: 'codex_recorded_chat', + agent: 'codex' + }) + ) + expect(mocks.readChat).toHaveBeenCalledWith( + { kind: 'environment', environmentId: ENV }, + 'agentSession.history', + { sessionId: 'codex_recorded_chat', direction: 'tail', limit: 1 } + ) +}) + +it('keeps Run Details output and opens the workspace when the recorded chat is gone', async () => { + mocks.openChat.mockClear() + Object.assign(mocks.state, storeState(false)) + mocks.readChat.mockRejectedValueOnce(new Error('gone')) + // 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.openChat).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..b5e518dfb242 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,8 @@ +import { callStructuredAgentSession } from '@/runtime/structured-agent-session-client' +import { openStructuredAgentSessionProvisionalTab } from '@/lib/structured-agent-session-launch-surface' +import type { TuiAgent } from '../../../../shared/tui-agent' +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 +20,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 +55,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, agent, ownerEnvironmentId) + return + } const paneRef = parsePaneKey(run.terminalPaneKey ?? '') if (runViewState.availability === 'terminal' && !terminalTarget) { if (!ownerEnvironmentId || !paneRef) { @@ -84,6 +100,34 @@ export function createAutomationRunWorkspaceAction({ store, list }: AutomationsP } } +async function openRunChat( + worktreeId: string, + sessionId: string, + agent: TuiAgent, + environmentId: string | null +): Promise { + try { + await callStructuredAgentSession( + environmentId ? { kind: 'environment', environmentId } : { kind: 'local' }, + 'agentSession.history', + { sessionId, direction: 'tail', limit: 1 } + ) + openStructuredAgentSessionProvisionalTab({ + worktreeId, + executionHostId: environmentId ? `runtime:${environmentId}` : 'local', + sessionId, + agent + }) + } catch { + 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..2d5d1b333aad 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 (chatSupported === null || (surface === 'chat' && !chatSupported)) { + 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 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-test-harness.tsx b/src/renderer/src/components/automations/automations-page-test-harness.tsx index 0cbae2b23acb..098af1cc767b 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,4 @@ +import { setLocalRuntimeCapabilitiesForTests } from '@/runtime/local-runtime-capabilities' import type { Project, ProjectHostSetup } from '../../../../shared/project-types' /** Record child props to test page orchestration rather than presentation. Import this harness first so shared vi.mock registrations precede AutomationsPage loading. */ @@ -392,6 +393,7 @@ 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() // A prior test's wholesale mockImplementation must not leak forward. @@ -429,5 +431,6 @@ export function installAutomationsPageHarness(): void { roots.splice(0).forEach((root) => root.unmount()) }) document.body.innerHTML = '' + setLocalRuntimeCapabilitiesForTests(null) }) } diff --git a/src/renderer/src/hooks/automation-dispatch-completion.ts b/src/renderer/src/hooks/automation-dispatch-completion.ts deleted file mode 100644 index c0c2b5dc1d04..000000000000 --- a/src/renderer/src/hooks/automation-dispatch-completion.ts +++ /dev/null @@ -1,276 +0,0 @@ -import { - createAutomationRunOutputSnapshotBuffer, - selectAutomationRunOutputSnapshot -} from '@/components/automations/automation-run-output-snapshot' -import { useAppStore } from '@/store' -import type { - AutomationDispatchResult, - AutomationPrecheckResult, - AutomationRun -} from '../../../shared/automations-types' -import type { AgentStateHistoryEntry, AgentStatusEntry } from '../../../shared/agent-status-types' -import { - selectAutomationAgentStatusEntryChange, - UNCHANGED_AUTOMATION_AGENT_STATUS_ENTRY -} from './automation-agent-status-entry-change' -import type { Worktree } from '../../../shared/worktree/types' -import { isProvenProcessExit } from '../../../shared/terminal-exit-cause' -import type { AutomationTerminalOwnership } from '@/lib/automation-terminal-ownership' - -type MarkDispatchResult = (result: AutomationDispatchResult) => Promise - -export function createAutomationDispatchCompletion(args: { - run: AutomationRun - worktree: Worktree - precheckResult: AutomationPrecheckResult | null - markDispatchResult: MarkDispatchResult - releaseTerminalOwnership: () => void - finalizeTerminalOwnership: AutomationTerminalOwnership['finalize'] -}) { - const outputSnapshotBuffer = createAutomationRunOutputSnapshotBuffer() - let latestAssistantMessage: string | null = null - const getOutputSnapshot = () => - selectAutomationRunOutputSnapshot(latestAssistantMessage, outputSnapshotBuffer.snapshot()) - let dispatchMarked = false - let pendingExitCode: number | null = null - let pendingDone = false - let completionMarked = false - let contactLost = false - let unsubscribeAgentStatus = (): void => {} - let unsubscribeSessionObserver = (): void => {} - let releaseReuseDispatchTab = (): void => {} - const cleanupRunObservers = (): void => { - unsubscribeAgentStatus() - unsubscribeSessionObserver() - releaseReuseDispatchTab() - unsubscribeAgentStatus = (): void => {} - unsubscribeSessionObserver = (): void => {} - releaseReuseDispatchTab = (): void => {} - } - const markCompletionResult = async (): Promise => { - if (completionMarked) { - return - } - completionMarked = true - cleanupRunObservers() - try { - await args.markDispatchResult({ - runId: args.run.id, - status: 'completed', - workspaceId: args.worktree.id, - workspaceDisplayName: args.worktree.displayName, - outputSnapshot: getOutputSnapshot(), - precheckResult: args.precheckResult, - error: null - }) - } catch (error) { - args.releaseTerminalOwnership() - throw error - } - await retireRunTerminal() - } - const retireRunTerminal = async (): Promise => { - const retirement = await args.finalizeTerminalOwnership({ - // Why: only a workspace made for this run is its own; a shared one would gather a sleeping tab per run. - preservePane: args.worktree.automationProvenance?.automationRunId === args.run.id - }) - if (!retirement) { - return - } - // Clear stopped-process pointers best-effort; sleeping panes retain resumable tab/pane keys for View run. - try { - await args.markDispatchResult({ - runId: args.run.id, - status: 'completed', - ...(retirement === 'closed' ? { terminalSessionId: null, terminalPaneKey: null } : {}), - terminalPtyId: null - }) - } catch (error) { - console.error('[automations] Failed to clear retired terminal identity:', error) - } - } - /** Lost PTY contact proves no result: retain dispatched state and let main’s watcher report lost-terminal evidence. Never finalize or close unproven-dead work, which could orphan a live remote process. */ - const abandonUnverifiableRun = (code: number): void => { - if (completionMarked || contactLost) { - return - } - contactLost = true - cleanupRunObservers() - args.releaseTerminalOwnership() - console.warn( - `[automations] Lost contact with the process for run ${args.run.id} (code ${code}); leaving the run dispatched rather than reporting an exit.` - ) - } - const markExitResult = async (code: number): Promise => { - if (completionMarked) { - return - } - if (!isProvenProcessExit(code)) { - abandonUnverifiableRun(code) - return - } - completionMarked = true - cleanupRunObservers() - try { - await args.markDispatchResult({ - runId: args.run.id, - status: code === 0 ? 'completed' : 'dispatch_failed', - workspaceId: args.worktree.id, - workspaceDisplayName: args.worktree.displayName, - outputSnapshot: getOutputSnapshot(), - precheckResult: args.precheckResult, - error: code === 0 ? null : `Automation process exited with code ${code}.` - }) - } catch (error) { - args.releaseTerminalOwnership() - throw error - } - if (code === 0) { - await retireRunTerminal() - } else { - args.releaseTerminalOwnership() - } - } - const settleLateResult = (result: Promise): void => { - // Status/exit callbacks have no awaitable caller; release ownership before persistence failures propagate. - void result.catch((error) => { - console.error('[automations] Failed to persist late automation result:', error) - }) - } - const handleAgentDone = (): void => { - if (completionMarked) { - return - } - if (!dispatchMarked) { - pendingDone = true - return - } - settleLateResult(markCompletionResult()) - } - const handleExit = (code: number): void => { - if (completionMarked) { - return - } - if (!dispatchMarked) { - pendingExitCode = code - return - } - settleLateResult(markExitResult(code)) - } - const observeAgentStatus = ( - targetPaneKey: string, - startedAfter: number, - options?: { requireWorkingAfterStart?: boolean } - ): void => { - let sawWorkingAfterStart = false - let observedStateHistory: AgentStateHistoryEntry[] = [] - let observedEntry: AgentStatusEntry | undefined - const checkCurrentStatus = (): void => { - const entryChange = selectAutomationAgentStatusEntryChange( - useAppStore.getState().agentStatusByPaneKey, - targetPaneKey, - observedEntry - ) - if (entryChange === UNCHANGED_AUTOMATION_AGENT_STATUS_ENTRY) { - return - } - const entry = entryChange - observedEntry = entry - if (!entry || entry.updatedAt < startedAfter) { - return - } - const historyOverlap = getAgentStateHistoryOverlap(observedStateHistory, entry.stateHistory) - // Keep sawWorkingAfterStart monotonic: recreated entries lose history and cannot rederive the edge needed by reuseSession. - for (const historicalState of entry.stateHistory.slice(historyOverlap)) { - if (historicalState.startedAt < startedAfter) { - continue - } - if (historicalState.state === 'working') { - sawWorkingAfterStart = true - } - if ( - historicalState.state === 'done' && - (!options?.requireWorkingAfterStart || sawWorkingAfterStart) - ) { - // The done edge left live history; only the entry’s completed slot retains its output. - latestAssistantMessage = - entry.lastCompletedAssistantMessage?.trim() || latestAssistantMessage - handleAgentDone() - return - } - } - observedStateHistory = [...entry.stateHistory] - if (entry.state === 'working') { - sawWorkingAfterStart = true - } - if ( - entry.state === 'done' && - // SessionStart boundary-done means connection before prompt submission; finishing here would record empty output and close the new tab. - entry.sessionBoundary !== true && - (!options?.requireWorkingAfterStart || sawWorkingAfterStart) - ) { - latestAssistantMessage = entry.lastAssistantMessage?.trim() || latestAssistantMessage - handleAgentDone() - } - } - // Codex/Claude completion normally comes from global hook IPC rather than hidden PTY OSC. - unsubscribeAgentStatus = useAppStore.subscribe(checkCurrentStatus) - checkCurrentStatus() - } - - return { - appendOutput: (chunk: string) => outputSnapshotBuffer.append(chunk), - captureAssistantMessage: (message: string | null | undefined) => { - latestAssistantMessage = message?.trim() || latestAssistantMessage - }, - cleanupRunObservers, - handleAgentDone, - handleExit, - observeAgentStatus, - setReuseDispatchTabRelease: (release: () => void) => { - releaseReuseDispatchTab = release - }, - setSessionObserver: (unsubscribe: () => void) => { - unsubscribeSessionObserver = unsubscribe - }, - settlePendingAfterDispatch: async () => { - dispatchMarked = true - if (pendingDone) { - await markCompletionResult() - } else if (pendingExitCode !== null) { - await markExitResult(pendingExitCode) - } - } - } -} - -function agentStateHistoryEntriesEqual( - left: AgentStateHistoryEntry, - right: AgentStateHistoryEntry -): boolean { - return ( - left.state === right.state && - left.prompt === right.prompt && - left.startedAt === right.startedAt && - left.interrupted === right.interrupted - ) -} - -function getAgentStateHistoryOverlap( - previous: AgentStateHistoryEntry[], - current: AgentStateHistoryEntry[] -): number { - for (let overlap = Math.min(previous.length, current.length); overlap > 0; overlap -= 1) { - const previousOffset = previous.length - overlap - if ( - current - .slice(0, overlap) - .every((entry, index) => - agentStateHistoryEntriesEqual(entry, previous[previousOffset + index]) - ) - ) { - return overlap - } - } - return 0 -} diff --git a/src/renderer/src/hooks/automation-dispatch-handler.ts b/src/renderer/src/hooks/automation-dispatch-handler.ts deleted file mode 100644 index 6f101bad103f..000000000000 --- a/src/renderer/src/hooks/automation-dispatch-handler.ts +++ /dev/null @@ -1,241 +0,0 @@ -import { listAutomationRunsForTarget } from '@/components/automations/automation-host-client' -import { translate } from '@/i18n/i18n' -import { submitPromptToAgentPty } from '@/lib/agent-paste-draft' -import { launchAgentBackgroundSession } from '@/lib/launch-agent-background-session' -import { observeExistingAutomationSession } from '@/lib/automation-session-observer' -import { findReusableAutomationSession } from '@/lib/automation-session-reuse' -import type { AutomationTerminalOwnership } from '@/lib/automation-terminal-ownership' -import { useAppStore } from '@/store' -import { captureWorkspaceSelection, restoreWorkspaceSelection } from '@/lib/active-workspace-host' -import type { - AutomationDispatchRequest, - AutomationDispatchResult -} from '../../../shared/automations-types' -import { createAutomationDispatchCompletion } from './automation-dispatch-completion' -import { - prepareAutomationDispatchWorkspace, - resolveAutomationDispatchWorkspace -} from './automation-dispatch-workspace' - -const activeReuseDispatchTabIds = new Set() - -function acquireReuseDispatchTab(tabId: string): (() => void) | null { - if (activeReuseDispatchTabIds.has(tabId)) { - return null - } - activeReuseDispatchTabIds.add(tabId) - return () => activeReuseDispatchTabIds.delete(tabId) -} - -export async function handleAutomationDispatchRequest({ - automation, - run, - dispatchToken -}: AutomationDispatchRequest): Promise { - const markDispatchResult = async (result: AutomationDispatchResult): Promise => { - // The writer publishes host-scoped change before reply; another unscoped emit would invalidate every host. - await window.api.automations.markDispatchResult(result) - } - const state = useAppStore.getState() - const focusBeforeDispatch = { - activeView: state.activeView, - activeWorktreeId: state.activeWorktreeId, - selection: captureWorkspaceSelection(state), - activeTabId: state.activeTabId, - activeTabType: state.activeTabType - } - const resolved = resolveAutomationDispatchWorkspace(state, automation, run) - let terminalOwnership: AutomationTerminalOwnership | null = null - const releaseTerminalOwnership = (): void => { - const ownership = terminalOwnership - terminalOwnership = null - ownership?.release() - } - const finalizeTerminalOwnership: AutomationTerminalOwnership['finalize'] = async (options) => { - const ownership = terminalOwnership - terminalOwnership = null - return (await ownership?.finalize(options)) ?? null - } - - if (!resolved.repo) { - await markDispatchResult({ - runId: run.id, - status: 'skipped_unavailable', - workspaceId: run.workspaceId, - workspaceDisplayName: run.workspaceDisplayName ?? null, - error: translate( - 'auto.hooks.useAutomationDispatchEvents.386db94f3e', - 'The target project is no longer available.' - ) - }) - return - } - - try { - const worktree = await prepareAutomationDispatchWorkspace({ - state, - automation, - run, - dispatchToken, - resolved: { ...resolved, repo: resolved.repo }, - markDispatchResult - }) - if (!worktree) { - return - } - const completion = createAutomationDispatchCompletion({ - run, - worktree, - precheckResult: resolved.context.precheckResult, - markDispatchResult, - releaseTerminalOwnership, - finalizeTerminalOwnership - }) - const dispatchStartedAt = Date.now() - if (automation.reuseSession) { - const reusableSession = findReusableAutomationSession({ - automationId: automation.id, - agentId: automation.agentId, - worktreeId: worktree.id, - currentRunId: run.id, - // Dispatch runs only on desktop authority, so history reads explicitly target the local runtime. - runs: await listAutomationRunsForTarget({ kind: 'local' }, automation.id), - state: useAppStore.getState() - }) - if (reusableSession) { - const releaseTab = acquireReuseDispatchTab(reusableSession.tabId) - if (releaseTab) { - completion.setReuseDispatchTabRelease(releaseTab) - try { - const submitted = await submitPromptToAgentPty({ - tabId: reusableSession.tabId, - ptyId: reusableSession.ptyId, - content: automation.prompt - }) - if (!submitted) { - completion.cleanupRunObservers() - } else { - let reuseSawWorking = false - const handleReusableAgentStatus = (payload: { state: string }): void => { - if (payload.state === 'working') { - reuseSawWorking = true - return - } - if (payload.state === 'done' && reuseSawWorking) { - completion.handleAgentDone() - } - } - const reuseCompletionStartedAt = Date.now() - completion.setSessionObserver( - await observeExistingAutomationSession({ - ptyId: reusableSession.ptyId, - paneKey: reusableSession.paneKey, - runId: run.id, - onData: completion.appendOutput, - onAgentStatus: (payload) => { - completion.captureAssistantMessage(payload.lastAssistantMessage) - handleReusableAgentStatus(payload) - }, - onExit: completion.handleExit - }) - ) - completion.observeAgentStatus(reusableSession.paneKey, reuseCompletionStartedAt, { - requireWorkingAfterStart: true - }) - await markDispatchResult({ - runId: run.id, - status: 'dispatched', - workspaceId: worktree.id, - workspaceDisplayName: worktree.displayName, - terminalSessionId: reusableSession.tabId, - terminalPaneKey: reusableSession.paneKey, - terminalPtyId: reusableSession.ptyId, - precheckResult: resolved.context.precheckResult, - error: null - }) - await completion.settlePendingAfterDispatch() - return - } - } catch (error) { - completion.cleanupRunObservers() - throw error - } - } - } - } - const result = await launchAgentBackgroundSession({ - agent: automation.agentId, - worktreeId: worktree.id, - prompt: automation.prompt, - ...(automation.extraAgentArgs ? { extraAgentArgs: automation.extraAgentArgs } : {}), - launchSource: 'unknown', - title: run.title, - onData: completion.appendOutput, - onAgentStatus: (payload) => { - completion.captureAssistantMessage(payload.lastAssistantMessage) - // Why: session-boundary done = launch connect, not run completion (see observeAgentStatus). - if (payload.state !== 'done' || payload.sessionBoundary === true) { - return - } - completion.handleAgentDone() - }, - onExit: (_ptyId, code) => { - completion.handleExit(code) - } - }) - if (!result) { - throw new Error('Unable to build an agent launch plan.') - } - terminalOwnership = result.terminalOwnership - completion.setSessionObserver(result.releaseRuntimeObservers) - if (automation.reuseSession) { - // Preserve the first fresh-launch seed under the same completion policy as reused tabs. - releaseTerminalOwnership() - } - const launchedTabId = result.tabId - completion.observeAgentStatus(result.paneKey, dispatchStartedAt) - try { - await markDispatchResult({ - runId: run.id, - status: 'dispatched', - workspaceId: worktree.id, - workspaceDisplayName: worktree.displayName, - terminalSessionId: launchedTabId, - terminalPaneKey: result.paneKey, - terminalPtyId: result.ptyId, - precheckResult: resolved.context.precheckResult, - error: null - }) - await completion.settlePendingAfterDispatch() - } catch (error) { - completion.cleanupRunObservers() - throw error - } - const currentState = useAppStore.getState() - // Scheduled/Run Now dispatch stays in background; explicit row clicks alone navigate. - if ( - focusBeforeDispatch.activeWorktreeId !== worktree.id && - currentState.activeWorktreeId === worktree.id - ) { - currentState.setActiveView(focusBeforeDispatch.activeView) - restoreWorkspaceSelection(currentState, focusBeforeDispatch.selection) - if (focusBeforeDispatch.activeTabId) { - currentState.setActiveTab(focusBeforeDispatch.activeTabId) - } - currentState.setActiveTabType( - focusBeforeDispatch.activeTabType, - focusBeforeDispatch.activeWorktreeId - ) - } - } catch (error) { - releaseTerminalOwnership() - await markDispatchResult({ - runId: run.id, - status: 'dispatch_failed', - workspaceId: resolved.context.workspaceId, - workspaceDisplayName: resolved.context.workspaceDisplayName, - precheckResult: resolved.context.precheckResult, - error: error instanceof Error ? error.message : String(error) - }) - } -} diff --git a/src/renderer/src/hooks/automation-dispatch-observer-test-probe.ts b/src/renderer/src/hooks/automation-dispatch-observer-test-probe.ts deleted file mode 100644 index 302c052782c8..000000000000 --- a/src/renderer/src/hooks/automation-dispatch-observer-test-probe.ts +++ /dev/null @@ -1,30 +0,0 @@ -import type { AgentStatusEntry } from '../../../shared/agent-status-types' - -const TARGET_PANE_KEY = 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d' - -export function countUnchangedObserverHistoryReads( - state: { agentStatusByPaneKey: Record }, - subscriber: (() => void) | null -): number { - if (!subscriber) { - throw new Error('agent status observer was not registered') - } - let historyReads = 0 - state.agentStatusByPaneKey = { - [TARGET_PANE_KEY]: { - paneKey: TARGET_PANE_KEY, - state: 'working', - prompt: 'turn', - updatedAt: Date.now() + 1, - stateStartedAt: Date.now() + 1, - get stateHistory() { - historyReads += 1 - return [] - } - } - } - subscriber() - historyReads = 0 - subscriber() - return historyReads -} diff --git a/src/renderer/src/hooks/automation-dispatch-unverifiable-loss.test.ts b/src/renderer/src/hooks/automation-dispatch-unverifiable-loss.test.ts deleted file mode 100644 index a8a525495b92..000000000000 --- a/src/renderer/src/hooks/automation-dispatch-unverifiable-loss.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { AutomationDispatchResult } from '../../../shared/automations-types' -import type { AutomationTerminalOwnership } from '@/lib/automation-terminal-ownership' - -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => ({ agentStatusByPaneKey: {} }), - subscribe: vi.fn(() => () => {}) - } -})) - -const markDispatchResult = vi.fn<(result: AutomationDispatchResult) => Promise>() -const releaseTerminalOwnership = vi.fn() -const finalizeTerminalOwnership = vi.fn(async () => null) - -async function createCompletion() { - const { createAutomationDispatchCompletion } = await import('./automation-dispatch-completion') - const completion = createAutomationDispatchCompletion({ - run: { id: 'run-1' } as never, - worktree: { id: 'wt-1', displayName: 'Automation worktree' } as never, - precheckResult: null, - markDispatchResult, - releaseTerminalOwnership, - finalizeTerminalOwnership - }) - await completion.settlePendingAfterDispatch() - markDispatchResult.mockClear() - return completion -} - -/** - * Loss of contact is never evidence of process death - * (docs/reference/ssh-execution-boundary.md). The exit sentinel these readers - * receive is the same one the terminal panes already classify as unverifiable. - */ -describe('automation dispatch completion on an unverifiable loss', () => { - beforeEach(() => { - vi.clearAllMocks() - markDispatchResult.mockResolvedValue(undefined) - finalizeTerminalOwnership.mockResolvedValue(null) - }) - - it('records no result, so the run keeps its non-final dispatched status', async () => { - // Exit -1 is unobserved relay/host loss, never a witnessed finish; SSH work may still run. - const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const completion = await createCompletion() - - completion.handleExit(-1) - await vi.waitFor(() => expect(releaseTerminalOwnership).toHaveBeenCalledOnce()) - - expect(markDispatchResult).not.toHaveBeenCalled() - // Closing a terminal whose process cannot be proven dead orphans live work. - expect(finalizeTerminalOwnership).not.toHaveBeenCalled() - warnSpy.mockRestore() - }) - - it('still completes and finalizes a genuinely exited process', async () => { - const completion = await createCompletion() - finalizeTerminalOwnership.mockResolvedValue('closed') - - completion.handleExit(0) - await vi.waitFor(() => expect(finalizeTerminalOwnership).toHaveBeenCalledOnce()) - - expect(markDispatchResult).toHaveBeenCalledWith( - expect.objectContaining({ runId: 'run-1', status: 'completed', error: null }) - ) - expect(releaseTerminalOwnership).not.toHaveBeenCalled() - }) - - it('still reports a real automation failure as dispatch_failed', async () => { - const completion = await createCompletion() - - completion.handleExit(9) - await vi.waitFor(() => expect(releaseTerminalOwnership).toHaveBeenCalledOnce()) - - expect(markDispatchResult).toHaveBeenCalledWith( - expect.objectContaining({ - runId: 'run-1', - status: 'dispatch_failed', - error: 'Automation process exited with code 9.' - }) - ) - expect(finalizeTerminalOwnership).not.toHaveBeenCalled() - }) - - it('lets a later done still complete a run whose contact was lost', async () => { - // Loss withholds judgment; later positive evidence must still finish the run. - const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const completion = await createCompletion() - - completion.handleExit(-1) - await vi.waitFor(() => expect(releaseTerminalOwnership).toHaveBeenCalledOnce()) - completion.handleAgentDone() - - await vi.waitFor(() => - expect(markDispatchResult).toHaveBeenCalledWith( - expect.objectContaining({ status: 'completed' }) - ) - ) - warnSpy.mockRestore() - }) -}) diff --git a/src/renderer/src/hooks/automation-dispatch-workspace.ts b/src/renderer/src/hooks/automation-dispatch-workspace.ts deleted file mode 100644 index dcb21ef597e5..000000000000 --- a/src/renderer/src/hooks/automation-dispatch-workspace.ts +++ /dev/null @@ -1,258 +0,0 @@ -import { useAppStore } from '@/store' -import { translate } from '@/i18n/i18n' -import { createBrowserUuid } from '@/lib/browser-uuid' -import { getResolvedExecutionHostIdForWorktree } from '@/lib/resolved-worktree-execution-host' -import type { - Automation, - AutomationDispatchResult, - AutomationPrecheckResult, - AutomationRun -} from '../../../shared/automations-types' -import { getAutomationRunRepoId } from '../../../shared/automation-run-identity' -import { - didAutomationPrecheckPass, - formatAutomationPrecheckFailure -} from '../../../shared/automation-precheck' -import { - getRepoExecutionHostId, - parseExecutionHostId, - toSshExecutionHostId -} from '../../../shared/execution-host' -import { resolveFolderWorkspaceHost } from '../../../shared/folder-workspace-execution-host' -import type { Worktree } from '../../../shared/worktree/types' -import { parseWorkspaceKey } from '../../../shared/workspace-scope' - -type AutomationDispatchStoreState = ReturnType -type MarkDispatchResult = (result: AutomationDispatchResult) => Promise - -export type AutomationDispatchWorkspaceContext = { - workspaceId: string | null - workspaceDisplayName: string | null - precheckResult: AutomationPrecheckResult | null -} - -export function resolveAutomationDispatchWorkspace( - state: AutomationDispatchStoreState, - automation: Automation, - run: AutomationRun -) { - const runRepoId = getAutomationRunRepoId(automation) - const repo = state.repos.find((entry) => entry.id === runRepoId) - const automationWorkspaceScope = parseWorkspaceKey(automation.workspaceId ?? '') - const automationWorktree = automation.workspaceId - ? automationWorkspaceScope?.type === 'folder' - ? state.getKnownWorktreeById(automation.workspaceId) - : state.allWorktrees().find((entry) => entry.id === automation.workspaceId) - : null - const context: AutomationDispatchWorkspaceContext = { - workspaceId: automation.workspaceId, - workspaceDisplayName: automationWorktree?.displayName ?? run.workspaceDisplayName ?? null, - precheckResult: null - } - return { runRepoId, repo, automationWorkspaceScope, automationWorktree, context } -} - -type ResolvedAutomationDispatchWorkspace = ReturnType - -export async function prepareAutomationDispatchWorkspace(args: { - state: AutomationDispatchStoreState - automation: Automation - run: AutomationRun - dispatchToken: string - resolved: ResolvedAutomationDispatchWorkspace & { - repo: NonNullable - } - markDispatchResult: MarkDispatchResult -}): Promise { - const { state, automation, run, dispatchToken, resolved, markDispatchResult } = args - const { repo, runRepoId, automationWorkspaceScope, automationWorktree, context } = resolved - const folderWorkspaceHost = - automationWorkspaceScope?.type === 'folder' - ? resolveFolderWorkspaceHost(state, automationWorkspaceScope.folderWorkspaceId) - : null - const folderWorkspaceConnectionId = - folderWorkspaceHost?.kind === 'ssh' ? folderWorkspaceHost.targetId : null - // A workspace whose host does not resolve to one place is refused, not guessed at. - const folderWorkspaceHostUnresolved = - folderWorkspaceHost !== null && folderWorkspaceHost.kind === 'ambiguous' - const folderWorkspaceHostId = - folderWorkspaceHost && automationWorktree - ? folderWorkspaceConnectionId - ? toSshExecutionHostId(folderWorkspaceConnectionId) - : folderWorkspaceHost.kind === 'local' || folderWorkspaceHost.kind === 'runtime' - ? getResolvedExecutionHostIdForWorktree(state, automationWorktree.id) - : null - : null - const runHostId = - parseExecutionHostId(automation.runContext?.hostId)?.id ?? getRepoExecutionHostId(repo) - const workspaceMatchesRunTarget = - automationWorkspaceScope?.type === 'folder' - ? folderWorkspaceHostId !== null && folderWorkspaceHostId === runHostId - : !automation.runContext?.repoId || - automationWorktree?.repoId === automation.runContext.repoId - if (automation.workspaceMode === 'existing' && automationWorktree && !workspaceMatchesRunTarget) { - await markDispatchResult({ - runId: run.id, - status: 'skipped_unavailable', - workspaceId: automation.workspaceId, - workspaceDisplayName: context.workspaceDisplayName, - error: folderWorkspaceHostUnresolved - ? translate( - 'auto.hooks.useAutomationDispatchEvents.workspaceHostUnresolved', - 'The target workspace spans more than one host, so this run has no single host to use.' - ) - : translate( - 'auto.hooks.useAutomationDispatchEvents.3ad7d77f57', - 'The target workspace is on a different host than this automation run target.' - ) - }) - return null - } - const sshTargetId = - automationWorkspaceScope?.type === 'folder' - ? (folderWorkspaceConnectionId ?? null) - : (repo.connectionId ?? null) - if (sshTargetId) { - const needsPrompt = await window.api.ssh.needsPassphrasePrompt({ - targetId: sshTargetId - }) - if (needsPrompt) { - await markDispatchResult({ - runId: run.id, - status: 'skipped_needs_interactive_auth', - workspaceId: context.workspaceId, - workspaceDisplayName: context.workspaceDisplayName, - error: translate( - 'auto.hooks.useAutomationDispatchEvents.16a21d6413', - 'SSH reconnect requires interactive credentials.' - ) - }) - return null - } - const sshState = await window.api.ssh.getState({ targetId: sshTargetId }) - if (sshState?.status !== 'connected') { - try { - const connected = await window.api.ssh.connect({ targetId: sshTargetId, automatic: true }) - if (connected?.status !== 'connected') { - throw new Error('SSH target is unavailable.') - } - } catch (error) { - await markDispatchResult({ - runId: run.id, - status: 'skipped_unavailable', - workspaceId: context.workspaceId, - workspaceDisplayName: context.workspaceDisplayName, - error: error instanceof Error ? error.message : String(error) - }) - return null - } - } - } - - if (automation.workspaceMode === 'existing' && !automationWorktree) { - await markDispatchResult({ - runId: run.id, - status: 'skipped_unavailable', - workspaceId: automation.workspaceId, - workspaceDisplayName: context.workspaceDisplayName, - error: translate( - 'auto.hooks.useAutomationDispatchEvents.59718b120b', - 'The target workspace is no longer available.' - ) - }) - return null - } - - if (run.trigger === 'scheduled' && automation.precheck) { - context.precheckResult = await window.api.automations.runPrecheck({ - automationId: automation.id, - runId: run.id - }) - if (context.precheckResult && !didAutomationPrecheckPass(context.precheckResult)) { - await markDispatchResult({ - runId: run.id, - status: 'skipped_precheck', - workspaceId: context.workspaceId, - workspaceDisplayName: context.workspaceDisplayName, - precheckResult: context.precheckResult, - error: formatAutomationPrecheckFailure(context.precheckResult) - }) - return null - } - } - - const automationWorkspaceCreateRequestId = createBrowserUuid() - const createResult = - automation.workspaceMode === 'new_per_run' - ? await useAppStore.getState().createWorktree( - runRepoId, - buildAutomationWorkspaceName(run.title, run.scheduledFor), - automation.baseBranch ?? undefined, - automation.setupDecision ?? 'skip', - undefined, - 'unknown', - run.title, - undefined, - undefined, - undefined, - // The automation owns its prompt-bearing tab; createdWithAgent would reopen an empty fallback. - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - { - // Why: only a captured host; with none, a project two hosts publish refuses, never guesses. - executionHostId: parseExecutionHostId(automation.runContext?.hostId)?.id, - automationProvenanceRequest: { - automationId: automation.id, - automationRunId: run.id, - dispatchToken, - createRequestId: automationWorkspaceCreateRequestId - } - } - ) - : null - const worktree = createResult - ? createResult.worktree - : automation.workspaceId - ? automationWorktree - : null - - if (!worktree) { - await markDispatchResult({ - runId: run.id, - status: 'skipped_unavailable', - workspaceId: automation.workspaceId, - workspaceDisplayName: context.workspaceDisplayName, - error: translate( - 'auto.hooks.useAutomationDispatchEvents.59718b120b', - 'The target workspace is no longer available.' - ) - }) - return null - } - context.workspaceId = worktree.id - context.workspaceDisplayName = worktree.displayName - return worktree -} - -function buildAutomationWorkspaceName(runTitle: string, scheduledFor: number): string { - const slug = runTitle - .toLowerCase() - .replace(/[^a-z0-9]+/g, '-') - .replace(/^-|-$/g, '') - .slice(0, 40) - const stamp = new Date(scheduledFor).toISOString().replace(/[-:]/g, '').slice(0, 13) - return `auto-${slug || 'run'}-${stamp}` -} diff --git a/src/renderer/src/hooks/useAutomationDispatchEvents.test.ts b/src/renderer/src/hooks/useAutomationDispatchEvents.test.ts index e5eebaccc62a..8d2bf7960050 100644 --- a/src/renderer/src/hooks/useAutomationDispatchEvents.test.ts +++ b/src/renderer/src/hooks/useAutomationDispatchEvents.test.ts @@ -1,874 +1,17 @@ +import { expect, it, vi } from 'vitest' import type * as ReactModule from 'react' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { AUTOMATIONS_CHANGED_EVENT } from '@/lib/automations-changed-window-event' -import { countUnchangedObserverHistoryReads } from './automation-dispatch-observer-test-probe' -const mockDispatchEvent = vi.fn() - -const mockLaunchAgentBackgroundSession = vi.fn() -const mockFindReusableAutomationSession = vi.fn() -const mockObserveExistingAutomationSession = vi.fn() -const mockSubmitPromptToAgentPty = vi.fn() -const mockCreateWorktree = vi.fn() -const mockMarkDispatchResult = vi.fn() -const mockOnDispatchRequested = vi.fn() -const mockRendererReady = vi.fn() -const mockFinalizeTerminalOwnership = vi.fn() -const mockReleaseTerminalOwnership = vi.fn() -const mockReleaseRuntimeObservers = vi.fn() -const mockSshNeedsPassphrasePrompt = vi.fn() -const mockSshGetState = vi.fn() -const mockSshConnect = vi.fn() -let latestStoreSubscriber: (() => void) | null = null -const mockStoreSubscribe = vi.fn((listener: () => void) => { - latestStoreSubscriber = listener - return () => {} -}) - -const createdWorktree = { - id: 'wt-created', - repoId: 'repo-1', - displayName: 'Automation worktree', - path: '/repo/worktree' -} -type TestWorktree = typeof createdWorktree -type TestRepo = { - id: string - connectionId: string | null - executionHostId: string | null - path: string -} - -function noSelectedHost(): string | null { - return null -} - -const state = { - activeView: 'terminal' as const, - activeWorktreeId: 'wt-active', - activeWorkspaceExecutionHostId: noSelectedHost(), - activeTabId: 'tab-active', - activeTabType: 'terminal' as const, - repos: [{ id: 'repo-1', connectionId: null, executionHostId: null, path: '/repo' }] as TestRepo[], - folderWorkspaces: [] as { - id: string - projectGroupId: string - folderPath: string - connectionId: string | null - }[], - projectGroups: [] as { - id: string - connectionId: string | null - executionHostId?: string | null - }[], - worktreesByRepo: {} as Record, - detectedWorktreesByRepo: {}, - agentStatusByPaneKey: {}, - allWorktrees: vi.fn<() => TestWorktree[]>(() => []), - getKnownWorktreeById: vi.fn<(worktreeId: string) => TestWorktree | undefined>(() => undefined), - createWorktree: mockCreateWorktree, - subscribe: vi.fn(() => () => {}), - setActiveView: vi.fn(), - setActiveWorktree: vi.fn(), - setActiveTab: vi.fn(), - setActiveTabType: vi.fn() -} - -function makeAutomation(overrides: Record = {}) { - return { - id: 'automation-1', - projectId: 'repo-1', - prompt: 'run this', - precheck: null, - agentId: 'claude', - workspaceMode: 'new_per_run', - workspaceId: null, - baseBranch: null, - setupDecision: 'run', - reuseSession: false, - ...overrides - } -} - -function makeRun() { - return { - id: 'run-1', - automationId: 'automation-1', - title: 'Nightly setup run', - scheduledFor: Date.parse('2026-06-24T03:00:00Z'), - trigger: 'scheduled', - workspaceId: null, - workspaceDisplayName: null - } -} - -async function registerAndDispatch(automation = makeAutomation()): Promise { - vi.doMock('react', async () => { - const actual = await vi.importActual('react') - return { - ...actual, - useEffect: (effect: () => void | (() => void)) => { - effect() - } - } - }) - const { useAutomationDispatchEvents: registerAutomationDispatchEvents } = - await import('./useAutomationDispatchEvents') - registerAutomationDispatchEvents() - const handler = mockOnDispatchRequested.mock.calls[0]?.[0] - if (!handler) { - throw new Error('dispatch handler was not registered') - } - await handler({ - automation, - run: makeRun(), - dispatchToken: 'dispatch-token' - }) -} - -vi.mock('@/lib/launch-agent-background-session', () => ({ - launchAgentBackgroundSession: mockLaunchAgentBackgroundSession -})) - -vi.mock('@/lib/agent-paste-draft', () => ({ - submitPromptToAgentPty: mockSubmitPromptToAgentPty -})) - -// The reuse path reads run history over the local runtime target, not IPC. -vi.mock('@/components/automations/automation-host-client', () => ({ - listAutomationRunsForTarget: vi.fn().mockResolvedValue([]) -})) - -vi.mock('@/lib/automation-session-reuse', () => ({ - findReusableAutomationSession: mockFindReusableAutomationSession -})) - -vi.mock('@/lib/automation-session-observer', () => ({ - observeExistingAutomationSession: mockObserveExistingAutomationSession -})) - -vi.mock('@/components/automations/automation-run-output-snapshot', () => ({ - createAutomationRunOutputSnapshotBuffer: () => ({ - append: vi.fn(), - snapshot: () => null - }), - selectAutomationRunOutputSnapshot: ( - assistantMessage: string | null | undefined, - terminalSnapshot: unknown - ) => - assistantMessage - ? { - format: 'plain_text', - content: assistantMessage, - capturedAt: 1, - truncated: false - } - : terminalSnapshot -})) - -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string) => fallback -})) - -vi.mock('@/lib/browser-uuid', () => ({ - createBrowserUuid: () => 'create-request-id' -})) - -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => state, - subscribe: mockStoreSubscribe - } -})) - -describe('useAutomationDispatchEvents setup launch', () => { - beforeEach(() => { - vi.resetModules() - vi.unstubAllGlobals() - vi.clearAllMocks() - state.activeView = 'terminal' - state.activeWorktreeId = 'wt-active' - state.activeWorkspaceExecutionHostId = null - state.activeTabId = 'tab-active' - state.activeTabType = 'terminal' - state.repos = [{ id: 'repo-1', connectionId: null, executionHostId: null, path: '/repo' }] - state.folderWorkspaces = [] - state.projectGroups = [] - state.worktreesByRepo = {} - state.agentStatusByPaneKey = {} - latestStoreSubscriber = null - state.allWorktrees.mockReturnValue([]) - state.getKnownWorktreeById.mockReturnValue(undefined) - mockCreateWorktree.mockResolvedValue({ worktree: createdWorktree }) - mockLaunchAgentBackgroundSession.mockResolvedValue({ - tabId: 'agent-tab', - paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', - ptyId: 'agent-pty', - startupPlan: {}, - releaseRuntimeObservers: mockReleaseRuntimeObservers, - terminalOwnership: { - finalize: mockFinalizeTerminalOwnership, - release: mockReleaseTerminalOwnership - } - }) - mockOnDispatchRequested.mockReturnValue(() => {}) - mockSshNeedsPassphrasePrompt.mockResolvedValue(false) - mockSshGetState.mockResolvedValue({ status: 'connected' }) - mockSshConnect.mockResolvedValue({ status: 'connected' }) - mockSubmitPromptToAgentPty.mockResolvedValue(true) - vi.stubGlobal('window', { - api: { - automations: { - onDispatchRequested: mockOnDispatchRequested, - rendererReady: mockRendererReady, - markDispatchResult: mockMarkDispatchResult, - runPrecheck: vi.fn() - }, - ssh: { - needsPassphrasePrompt: mockSshNeedsPassphrasePrompt, - getState: mockSshGetState, - connect: mockSshConnect - } - }, - dispatchEvent: mockDispatchEvent - }) - }) - - it('restores the prior workspace on the host it was selected on', async () => { - state.activeWorkspaceExecutionHostId = 'ssh:box' - mockLaunchAgentBackgroundSession.mockImplementationOnce(async () => { - state.activeWorktreeId = createdWorktree.id - return { - tabId: 'agent-tab', - paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', - ptyId: 'agent-pty', - startupPlan: {}, - terminalOwnership: { - finalize: mockFinalizeTerminalOwnership, - release: mockReleaseTerminalOwnership - } - } - }) - - await registerAndDispatch() - - expect(state.setActiveWorktree).toHaveBeenCalledWith('wt-active', 'ssh:box') - }) - - // The writer’s host-scoped event is sufficient; extra local emit would invalidate every catalog host. - it('leaves the automationsChanged event to the host that owns the write', async () => { - await registerAndDispatch() - - expect(mockMarkDispatchResult).toHaveBeenCalled() - expect( - mockDispatchEvent.mock.calls.filter(([event]) => event?.type === AUTOMATIONS_CHANGED_EVENT) - ).toEqual([]) - }) - - it('defaults legacy automations without a setup choice to skipping setup', async () => { - await registerAndDispatch(makeAutomation({ setupDecision: undefined })) - - expect(mockCreateWorktree.mock.calls[0][3]).toBe('skip') - expect(mockLaunchAgentBackgroundSession).toHaveBeenCalled() - }) - - it('creates a new-per-run workspace on the captured run host, and names none without one', async () => { - await registerAndDispatch(makeAutomation({ runContext: { repoId: 'repo-1', hostId: 'local' } })) - expect(mockCreateWorktree.mock.calls[0]?.at(-1)).toEqual( - expect.objectContaining({ executionHostId: 'local' }) - ) - - mockCreateWorktree.mockClear() - await registerAndDispatch() - expect(mockCreateWorktree.mock.calls[0]?.at(-1)).toEqual( - expect.objectContaining({ executionHostId: undefined }) - ) - }) - - it('does not stamp the created workspace with an empty agent-launch fallback', async () => { - await registerAndDispatch() - - expect(mockCreateWorktree.mock.calls[0][10]).toBeUndefined() - expect(mockLaunchAgentBackgroundSession).toHaveBeenCalledWith( - expect.objectContaining({ - agent: 'claude', - prompt: 'run this', - worktreeId: 'wt-created' - }) - ) - }) - - it('does not rerun setup for existing-worktree automations', async () => { - const existingWorktree = { - id: 'wt-existing', - repoId: 'repo-1', - displayName: 'Existing workspace', - path: '/repo/existing' - } - state.allWorktrees.mockReturnValue([existingWorktree]) - - await registerAndDispatch( - makeAutomation({ - workspaceMode: 'existing', - workspaceId: 'wt-existing', - setupDecision: 'run' - }) - ) - - expect(mockCreateWorktree).not.toHaveBeenCalled() - expect(mockLaunchAgentBackgroundSession).toHaveBeenCalledWith( - expect.objectContaining({ - worktreeId: 'wt-existing', - prompt: 'run this' - }) - ) - }) - - it('dispatches an existing SSH folder workspace on its resolved host', async () => { - const folderWorkspace = { - id: 'folder:fw-1', - repoId: 'folder-workspace:group-1', - displayName: 'SSH folder', - path: '/srv/project' - } - state.repos = [ - { - id: 'repo-1', - connectionId: 'ssh-folder', - executionHostId: null, - path: '/srv/project/repo' - } - ] - state.folderWorkspaces = [ - { - id: 'fw-1', - projectGroupId: 'group-1', - folderPath: '/srv/project', - connectionId: 'ssh-folder' - } - ] - state.projectGroups = [{ id: 'group-1', connectionId: 'ssh-folder' }] - state.getKnownWorktreeById.mockReturnValue(folderWorkspace) - mockSshGetState.mockResolvedValue({ status: 'disconnected' }) - - await registerAndDispatch( - makeAutomation({ - workspaceMode: 'existing', - workspaceId: folderWorkspace.id, - setupDecision: 'skip', - runContext: { repoId: 'repo-1', hostId: 'ssh:ssh-folder' } - }) - ) - - expect(state.allWorktrees).not.toHaveBeenCalled() - expect(mockSshConnect).toHaveBeenCalledWith({ targetId: 'ssh-folder', automatic: true }) - expect(mockLaunchAgentBackgroundSession).toHaveBeenCalledWith( - expect.objectContaining({ - worktreeId: folderWorkspace.id, - prompt: 'run this' - }) - ) - expect(mockMarkDispatchResult).toHaveBeenCalledWith( - expect.objectContaining({ - status: 'dispatched', - workspaceId: folderWorkspace.id, - workspaceDisplayName: folderWorkspace.displayName - }) - ) - }) - - it('dispatches a local folder workspace without SSH', async () => { - const folderWorkspace = { - id: 'folder:fw-local', - repoId: 'folder-workspace:group-local', - displayName: 'Local folder', - path: '/project' - } - state.folderWorkspaces = [ - { - id: 'fw-local', - projectGroupId: 'group-local', - folderPath: '/project', - connectionId: null - } - ] - state.projectGroups = [{ id: 'group-local', connectionId: null }] - state.getKnownWorktreeById.mockReturnValue(folderWorkspace) - - await registerAndDispatch( - makeAutomation({ - workspaceMode: 'existing', - workspaceId: folderWorkspace.id, - runContext: { repoId: 'repo-1', hostId: 'local' } - }) - ) - - expect(mockSshNeedsPassphrasePrompt).not.toHaveBeenCalled() - expect(mockLaunchAgentBackgroundSession).toHaveBeenCalledWith( - expect.objectContaining({ worktreeId: folderWorkspace.id }) - ) - }) - - it('skips a folder workspace owned by a different host', async () => { - const folderWorkspace = { - id: 'folder:fw-other', - repoId: 'folder-workspace:group-other', - displayName: 'Other host', - path: '/srv/other' - } - state.folderWorkspaces = [ - { - id: 'fw-other', - projectGroupId: 'group-other', - folderPath: '/srv/other', - connectionId: 'ssh-other' - } - ] - state.projectGroups = [{ id: 'group-other', connectionId: 'ssh-other' }] - state.getKnownWorktreeById.mockReturnValue(folderWorkspace) - - await registerAndDispatch( - makeAutomation({ - workspaceMode: 'existing', - workspaceId: folderWorkspace.id, - runContext: { repoId: 'repo-1', hostId: 'local' } - }) - ) - - expect(mockLaunchAgentBackgroundSession).not.toHaveBeenCalled() - expect(mockMarkDispatchResult).toHaveBeenCalledWith( - expect.objectContaining({ status: 'skipped_unavailable' }) - ) - }) - - it('keeps detected-only non-folder workspaces unavailable', async () => { - state.getKnownWorktreeById.mockReturnValue({ - id: 'wt-detected', - repoId: 'repo-1', - displayName: 'Detected', - path: '/repo/detected' - }) - - await registerAndDispatch( - makeAutomation({ - workspaceMode: 'existing', - workspaceId: 'wt-detected' - }) - ) - - expect(state.getKnownWorktreeById).not.toHaveBeenCalled() - expect(mockLaunchAgentBackgroundSession).not.toHaveBeenCalled() - expect(mockMarkDispatchResult).toHaveBeenCalledWith( - expect.objectContaining({ status: 'skipped_unavailable' }) - ) - }) - - it.each([ - { - workspace: 'a shared workspace', - provenanceRunId: undefined, - retirement: 'closed', - cleared: { terminalSessionId: null, terminalPaneKey: null, terminalPtyId: null } - }, - { - // Why: the slept pane still holds the run's session, so only its stopped process is dropped. - workspace: 'a workspace made for this run', - provenanceRunId: 'run-1', - retirement: 'hibernated', - cleared: { terminalPtyId: null } - } - ])( - 'retires the terminal in $workspace only after completed result persistence', - async ({ provenanceRunId, retirement, cleared }) => { - const order: string[] = [] - let launchArgs: { onAgentStatus?: (payload: { state: string }) => void } = {} - mockCreateWorktree.mockResolvedValue({ - worktree: provenanceRunId - ? { ...createdWorktree, automationProvenance: { automationRunId: provenanceRunId } } - : createdWorktree - }) - mockMarkDispatchResult.mockImplementation(async (result: { status: string }) => { - // Retirement reuses completed state while clearing terminal identity; distinguish it for ordering assertions. - order.push( - result.status === 'completed' && Object.hasOwn(result, 'terminalPtyId') - ? 'clear-terminal-identity' - : `persist:${result.status}` - ) - }) - mockFinalizeTerminalOwnership.mockImplementationOnce(async () => { - order.push('finalize') - return retirement - }) - mockLaunchAgentBackgroundSession.mockImplementation(async (args) => { - launchArgs = args - return { - tabId: 'agent-tab', - paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', - ptyId: 'agent-pty', - startupPlan: {}, - releaseRuntimeObservers: mockReleaseRuntimeObservers, - terminalOwnership: { - finalize: mockFinalizeTerminalOwnership, - release: mockReleaseTerminalOwnership - } - } - }) - - await registerAndDispatch() - launchArgs.onAgentStatus?.({ state: 'done' }) - await vi.waitFor(() => expect(mockFinalizeTerminalOwnership).toHaveBeenCalledOnce()) - - expect(order).toEqual([ - 'persist:dispatched', - 'persist:completed', - 'finalize', - 'clear-terminal-identity' - ]) - expect(mockReleaseTerminalOwnership).not.toHaveBeenCalled() - expect(mockFinalizeTerminalOwnership).toHaveBeenCalledWith({ - preservePane: provenanceRunId !== undefined - }) - // Why: the retired process is gone; "View run" must not dead-end on a pointer to it. - expect(mockMarkDispatchResult).toHaveBeenLastCalledWith({ - runId: expect.any(String), - status: 'completed', - ...cleared - }) - } - ) - - it('ignores a session-boundary done so a connecting agent cannot complete the run (STA-3386)', async () => { - let launchArgs: { - onAgentStatus?: (payload: { state: string; sessionBoundary?: boolean }) => void - } = {} - mockLaunchAgentBackgroundSession.mockImplementation(async (args) => { - launchArgs = args - return { - tabId: 'agent-tab', - paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', - ptyId: 'agent-pty', - startupPlan: {}, - releaseRuntimeObservers: mockReleaseRuntimeObservers, - terminalOwnership: { - finalize: mockFinalizeTerminalOwnership, - release: mockReleaseTerminalOwnership - } - } - }) - - await registerAndDispatch() - // SessionStart boundary-done precedes prompt submission; treating it as completion closes an empty run. - launchArgs.onAgentStatus?.({ state: 'done', sessionBoundary: true }) - await Promise.resolve() - expect(mockFinalizeTerminalOwnership).not.toHaveBeenCalled() - - launchArgs.onAgentStatus?.({ state: 'done' }) - await vi.waitFor(() => expect(mockFinalizeTerminalOwnership).toHaveBeenCalledOnce()) - }) - - it('skips unchanged status and persists batched working→done→working output', async () => { - const paneKey = 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d' - - await registerAndDispatch() - expect(countUnchangedObserverHistoryReads(state, latestStoreSubscriber)).toBe(0) - const transitionStartedAt = Date.now() + 1 - state.agentStatusByPaneKey = { - [paneKey]: { - paneKey, - state: 'working', - prompt: 'second turn', - agentType: 'claude', - updatedAt: transitionStartedAt + 2, - stateStartedAt: transitionStartedAt + 2, - lastCompletedAssistantMessage: 'Summary.\n\nDetails.', - stateHistory: [ - { state: 'working', prompt: 'first turn', startedAt: transitionStartedAt }, - { state: 'done', prompt: 'first turn', startedAt: transitionStartedAt + 1 } - ] - } - } - if (!latestStoreSubscriber) { - throw new Error('agent status observer was not registered') - } - latestStoreSubscriber() - - await vi.waitFor(() => expect(mockFinalizeTerminalOwnership).toHaveBeenCalledOnce()) - expect(mockMarkDispatchResult).toHaveBeenCalledWith( - expect.objectContaining({ - runId: 'run-1', - status: 'completed', - outputSnapshot: { - format: 'plain_text', - content: 'Summary.\n\nDetails.', - capturedAt: 1, - truncated: false - } - }) - ) - }) - - it('does not let later working authorize an earlier historical done on rescan', async () => { - const paneKey = 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d' - mockFindReusableAutomationSession.mockReturnValue({ - tabId: 'agent-tab', - paneKey, - ptyId: 'agent-pty' - }) - mockObserveExistingAutomationSession.mockResolvedValue(() => {}) - - await registerAndDispatch(makeAutomation({ reuseSession: true })) - const transitionStartedAt = Date.now() + 1 - state.agentStatusByPaneKey = { - [paneKey]: { - paneKey, - state: 'working', - prompt: 'new turn', - agentType: 'claude', - updatedAt: transitionStartedAt + 1, - stateStartedAt: transitionStartedAt + 1, - stateHistory: [{ state: 'done', prompt: 'old turn', startedAt: transitionStartedAt }] - } - } - if (!latestStoreSubscriber) { - throw new Error('agent status observer was not registered') - } - - latestStoreSubscriber() - latestStoreSubscriber() - await Promise.resolve() - - expect(mockMarkDispatchResult).not.toHaveBeenCalledWith( - expect.objectContaining({ status: 'completed' }) - ) - }) - - // Recreated entries lose history; preserve the observer’s working edge through transport loss, PTY exit and cap eviction. - it('completes a reuse-session run when the entry is recreated with no history', async () => { - const paneKey = 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d' - mockFindReusableAutomationSession.mockReturnValue({ - tabId: 'agent-tab', - paneKey, - ptyId: 'agent-pty' - }) - mockObserveExistingAutomationSession.mockResolvedValue(() => {}) - - await registerAndDispatch(makeAutomation({ reuseSession: true })) - const workingStartedAt = Date.now() + 1 - state.agentStatusByPaneKey = { - [paneKey]: { - paneKey, - state: 'working', - prompt: 'turn', - agentType: 'claude', - updatedAt: workingStartedAt, - stateStartedAt: workingStartedAt, - stateHistory: [{ state: 'working', prompt: 'turn', startedAt: workingStartedAt }] - } - } - if (!latestStoreSubscriber) { - throw new Error('agent status observer was not registered') - } - latestStoreSubscriber() - await Promise.resolve() - - state.agentStatusByPaneKey = { - [paneKey]: { - paneKey, - state: 'done', - prompt: 'turn', - agentType: 'claude', - updatedAt: workingStartedAt + 2, - stateStartedAt: workingStartedAt + 2, - stateHistory: [] - } - } - latestStoreSubscriber() - await Promise.resolve() - - expect(mockMarkDispatchResult).toHaveBeenCalledWith( - expect.objectContaining({ status: 'completed' }) - ) - }) - - it('consumes duplicate done and zero-exit completion through one finalizer', async () => { - let launchArgs: { - onAgentStatus?: (payload: { state: string }) => void - onExit?: (ptyId: string, code: number) => void - } = {} - mockLaunchAgentBackgroundSession.mockImplementation(async (args) => { - launchArgs = args - return { - tabId: 'agent-tab', - paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', - ptyId: 'agent-pty', - startupPlan: {}, - releaseRuntimeObservers: mockReleaseRuntimeObservers, - terminalOwnership: { - finalize: mockFinalizeTerminalOwnership, - release: mockReleaseTerminalOwnership - } - } - }) - - await registerAndDispatch() - launchArgs.onAgentStatus?.({ state: 'done' }) - launchArgs.onExit?.('agent-pty', 0) - launchArgs.onAgentStatus?.({ state: 'done' }) - await vi.waitFor(() => expect(mockFinalizeTerminalOwnership).toHaveBeenCalledOnce()) - - expect( - mockMarkDispatchResult.mock.calls.filter( - ([result]) => result.status === 'completed' && result.terminalPaneKey !== null - ) - ).toHaveLength(1) - expect(mockReleaseTerminalOwnership).not.toHaveBeenCalled() - }) - - it('releases ownership on nonzero exit without finalizing the tab', async () => { - let onExit: ((ptyId: string, code: number) => void) | undefined - mockLaunchAgentBackgroundSession.mockImplementation(async (args) => { - onExit = args.onExit - return { - tabId: 'agent-tab', - paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', - ptyId: 'agent-pty', - startupPlan: {}, - releaseRuntimeObservers: mockReleaseRuntimeObservers, - terminalOwnership: { - finalize: mockFinalizeTerminalOwnership, - release: mockReleaseTerminalOwnership - } - } - }) - - await registerAndDispatch() - onExit?.('agent-pty', 9) - await vi.waitFor(() => expect(mockReleaseTerminalOwnership).toHaveBeenCalledOnce()) - - expect(mockFinalizeTerminalOwnership).not.toHaveBeenCalled() - expect(mockMarkDispatchResult).toHaveBeenCalledWith( - expect.objectContaining({ status: 'dispatch_failed' }) - ) - }) - - it('releases ownership when dispatched result persistence rejects', async () => { - mockMarkDispatchResult.mockRejectedValueOnce(new Error('persistence unavailable')) - - await registerAndDispatch() - - expect(mockReleaseTerminalOwnership).toHaveBeenCalledOnce() - expect(mockFinalizeTerminalOwnership).not.toHaveBeenCalled() - expect(mockMarkDispatchResult).toHaveBeenLastCalledWith( - expect.objectContaining({ status: 'dispatch_failed' }) - ) - }) - - it('releases ownership when completed result persistence rejects', async () => { - mockMarkDispatchResult - .mockResolvedValueOnce(undefined) - .mockRejectedValueOnce(new Error('completion persistence unavailable')) - .mockResolvedValueOnce(undefined) - mockLaunchAgentBackgroundSession.mockImplementation(async (args) => { - args.onAgentStatus?.({ state: 'done' }) - return { - tabId: 'agent-tab', - paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', - ptyId: 'agent-pty', - startupPlan: {}, - releaseRuntimeObservers: mockReleaseRuntimeObservers, - terminalOwnership: { - finalize: mockFinalizeTerminalOwnership, - release: mockReleaseTerminalOwnership - } - } - }) - - await registerAndDispatch() - - expect(mockReleaseTerminalOwnership).toHaveBeenCalledOnce() - expect(mockFinalizeTerminalOwnership).not.toHaveBeenCalled() - expect(mockMarkDispatchResult).toHaveBeenLastCalledWith( - expect.objectContaining({ status: 'dispatch_failed' }) - ) - }) - - it('diagnoses a late completed-persistence rejection once without terminal cleanup', async () => { - let onAgentStatus: ((payload: { state: string }) => void) | undefined - const persistenceError = new Error('late completion persistence unavailable') - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined) - mockMarkDispatchResult.mockResolvedValueOnce(undefined).mockRejectedValueOnce(persistenceError) - mockLaunchAgentBackgroundSession.mockImplementation(async (args) => { - onAgentStatus = args.onAgentStatus - return { - tabId: 'agent-tab', - paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', - ptyId: 'agent-pty', - startupPlan: {}, - releaseRuntimeObservers: mockReleaseRuntimeObservers, - terminalOwnership: { - finalize: mockFinalizeTerminalOwnership, - release: mockReleaseTerminalOwnership - } - } - }) - - await registerAndDispatch() - onAgentStatus?.({ state: 'done' }) - onAgentStatus?.({ state: 'done' }) - await vi.waitFor(() => expect(errorSpy).toHaveBeenCalledOnce()) - - expect(errorSpy).toHaveBeenCalledWith( - '[automations] Failed to persist late automation result:', - persistenceError - ) - expect(mockReleaseTerminalOwnership).toHaveBeenCalledOnce() - expect(mockFinalizeTerminalOwnership).not.toHaveBeenCalled() - expect( - mockMarkDispatchResult.mock.calls.filter( - ([result]) => result.status === 'completed' && result.terminalPaneKey !== null - ) - ).toHaveLength(1) - errorSpy.mockRestore() - }) - - it('preserves a fresh reuse-enabled session as the future reuse seed', async () => { - mockFindReusableAutomationSession.mockReturnValue(null) - - await registerAndDispatch(makeAutomation({ reuseSession: true })) - - expect(mockReleaseTerminalOwnership).toHaveBeenCalledOnce() - expect(mockFinalizeTerminalOwnership).not.toHaveBeenCalled() - }) - - it('releases the launch runtime observers once when a kept-open run completes', async () => { - mockFindReusableAutomationSession.mockReturnValue(null) - let launchArgs: { onAgentStatus?: (payload: { state: string }) => void } = {} - mockLaunchAgentBackgroundSession.mockImplementation(async (args) => { - launchArgs = args - return { - tabId: 'agent-tab', - paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', - ptyId: 'agent-pty', - startupPlan: {}, - releaseRuntimeObservers: mockReleaseRuntimeObservers, - terminalOwnership: { - finalize: mockFinalizeTerminalOwnership, - release: mockReleaseTerminalOwnership - } - } - }) - - await registerAndDispatch(makeAutomation({ reuseSession: true })) - expect(mockReleaseRuntimeObservers).not.toHaveBeenCalled() - launchArgs.onAgentStatus?.({ state: 'done' }) - launchArgs.onAgentStatus?.({ state: 'done' }) - - await vi.waitFor(() => - expect(mockMarkDispatchResult).toHaveBeenCalledWith( - expect.objectContaining({ status: 'completed' }) - ) - ) - expect(mockReleaseRuntimeObservers).toHaveBeenCalledOnce() - expect(mockFinalizeTerminalOwnership).not.toHaveBeenCalled() - }) +it('marks desktop scheduling ready without installing a renderer-only launcher', async () => { + vi.doMock('react', async () => ({ + ...(await vi.importActual('react')), + useEffect: (effect: () => void) => effect() + })) + const rendererReady = vi.fn() + const onDispatchRequested = vi.fn() + vi.stubGlobal('window', { api: { automations: { rendererReady, onDispatchRequested } } }) + const { useAutomationDispatchEvents } = await import('./useAutomationDispatchEvents') + useAutomationDispatchEvents() + expect(rendererReady).toHaveBeenCalledOnce() + expect(onDispatchRequested).not.toHaveBeenCalled() + vi.unstubAllGlobals() }) diff --git a/src/renderer/src/hooks/useAutomationDispatchEvents.ts b/src/renderer/src/hooks/useAutomationDispatchEvents.ts index f4963a6dea74..0ade53d6d9e9 100644 --- a/src/renderer/src/hooks/useAutomationDispatchEvents.ts +++ b/src/renderer/src/hooks/useAutomationDispatchEvents.ts @@ -1,10 +1,7 @@ import { useEffect } from 'react' -import { handleAutomationDispatchRequest } from './automation-dispatch-handler' export function useAutomationDispatchEvents(): void { useEffect(() => { - const unsubscribe = window.api.automations.onDispatchRequested(handleAutomationDispatchRequest) void window.api.automations.rendererReady() - return unsubscribe }, []) } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 96c5150f7955..56a3cee3d6a1 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -20344,7 +20344,11 @@ "caution": "Caution" }, "automations": { - "runTerminalUnavailable": "Run terminal is unavailable." + "runTerminalUnavailable": "Run terminal is unavailable.", + "openIn": "Open in", + "chat": "Chat", + "terminal": "Terminal", + "runChatUnavailable": "Run chat is unavailable. Showing its workspace; any saved output remains in Run Details." }, "agentCombobox": { "clearSelection": "Clear agent selection", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 533a16cbf253..64b9d52ef00e 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -19932,7 +19932,11 @@ "caution": "Precaución" }, "automations": { - "runTerminalUnavailable": "La terminal de ejecución no está disponible." + "runTerminalUnavailable": "La terminal de ejecución no está disponible.", + "openIn": "Abrir en", + "chat": "Chat", + "terminal": "Terminal", + "runChatUnavailable": "El chat de la ejecución no está disponible. Se muestra su espacio de trabajo; la salida guardada sigue en Detalles de la ejecución." }, "jiraIssueTitleField": { "generate": "Generar título a partir de la descripción", diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 031bd8a90e67..6cf5d42af50e 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -20072,7 +20072,11 @@ "caution": "Attention" }, "automations": { - "runTerminalUnavailable": "Le terminal d'exécution est indisponible." + "runTerminalUnavailable": "Le terminal d'exécution est indisponible.", + "openIn": "Ouvrir dans", + "chat": "Chat", + "terminal": "Terminal", + "runChatUnavailable": "Le chat de cette exécution est indisponible. Son espace de travail est affiché ; toute sortie enregistrée reste dans les détails de l’exécution." }, "jiraIssueTitleField": { "generate": "Générer le titre à partir de la description", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 41bd5c286f59..ce86acea485a 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -19932,7 +19932,11 @@ "caution": "注意" }, "automations": { - "runTerminalUnavailable": "実行ターミナルを利用できません。" + "runTerminalUnavailable": "実行ターミナルを利用できません。", + "openIn": "開く場所", + "chat": "チャット", + "terminal": "ターミナル", + "runChatUnavailable": "実行チャットを利用できません。ワークスペースを表示しています。保存済みの出力は実行の詳細に残っています。" }, "jiraIssueTitleField": { "generate": "説明からタイトルを生成", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 75e3c573bebb..e20025185af9 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -19931,7 +19931,11 @@ "caution": "주의" }, "automations": { - "runTerminalUnavailable": "실행 터미널을 사용할 수 없습니다." + "runTerminalUnavailable": "실행 터미널을 사용할 수 없습니다.", + "openIn": "열기 방식", + "chat": "채팅", + "terminal": "터미널", + "runChatUnavailable": "실행 채팅을 사용할 수 없습니다. 작업 공간을 표시합니다. 저장된 출력은 실행 세부 정보에 남아 있습니다." }, "jiraIssueTitleField": { "generate": "설명에서 제목 생성", diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index b1e62f753fff..6bddfe02bb61 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -20438,7 +20438,11 @@ "caution": "Cuidado" }, "automations": { - "runTerminalUnavailable": "O terminal da execução está indisponível." + "runTerminalUnavailable": "O terminal da execução está indisponível.", + "openIn": "Abrir em", + "chat": "Chat", + "terminal": "Terminal", + "runChatUnavailable": "O chat da execução está indisponível. O espaço de trabalho está aberto; a saída salva continua nos detalhes da execução." }, "agentCombobox": { "clearSelection": "Limpar seleção de agente", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 3973e5d3bde6..2fd1c307f262 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -19932,7 +19932,11 @@ "caution": "注意" }, "automations": { - "runTerminalUnavailable": "运行终端不可用。" + "runTerminalUnavailable": "运行终端不可用。", + "openIn": "打开方式", + "chat": "聊天", + "terminal": "终端", + "runChatUnavailable": "运行聊天不可用。正在显示其工作区;已保存的输出仍可在运行详情中查看。" }, "jiraIssueTitleField": { "generate": "根据描述生成标题", 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 50fe89cb23b7..9413f5ce3a37 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. */ @@ -177,6 +184,7 @@ export type AutomationCreateInput = { prompt: string precheck?: AutomationPrecheck | null agentId: TuiAgent + launchSetupPatch?: AutomationLaunchSetupPatch /** Empty or whitespace means no extras. */ extraAgentArgs?: string runContext?: WorkspaceRunContext | null @@ -196,7 +204,7 @@ export type AutomationCreateInput = { missedRunGraceMinutes?: number } -export type AutomationUpdateInput = Partial< +export type AutomationUpdateInput = { launchSetupPatch?: AutomationLaunchSetupPatch } & Partial< Pick< Automation, | 'name' @@ -228,6 +236,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 5b989c2cc3ff..649330967bf4 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, From e8b0992247784e282ae411af474ed1bf897a5355 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 27 Oct 2026 07:07:41 -0700 Subject: [PATCH 02/23] Preserve automation targets and complete owned terminal lifecycles --- .../automations/automation-run-receipt.ts | 27 +- .../desktop-run-terminal-lifecycle.ts | 303 ++++++ .../automations/desktop-run-terminal-stop.ts | 87 ++ .../headless-automation-agent-launch.test.ts | 66 +- .../headless-automation-agent-launch.ts | 114 ++- .../automations/headless-dispatch-runner.ts | 4 + src/main/automations/headless-dispatch.ts | 9 + src/main/automations/precheck-runner.ts | 34 + .../runtime-automation-service.test.ts | 115 ++- .../automations/runtime-automation-service.ts | 115 ++- .../runtime-chat-run-observer.test.ts | 345 ++++++- .../automations/runtime-chat-run-observer.ts | 114 ++- .../automations/service-lifecycle.test.ts | 72 ++ src/main/automations/service.ts | 42 +- ...adapter-history-shutdown-admission.test.ts | 85 ++ src/main/daemon/daemon-pty-session-control.ts | 218 ++-- .../daemon/daemon-pty-session-liveness.ts | 106 ++ src/main/ipc/pty/provider/shutdown-detect.ts | 8 +- src/main/ipc/pty/runtime/controller-deps.ts | 2 +- src/main/ipc/pty/runtime/kill.ts | 24 +- .../agent-session-subscriber-catch-up.ts | 5 +- ...ctured-agent-session-actionable-prompts.ts | 55 ++ ...d-agent-session-background-task-channel.ts | 11 + ...uctured-agent-session-current-work.test.ts | 26 + .../structured-agent-session-current-work.ts | 43 +- .../structured-agent-session-host.ts | 9 +- src/main/providers/local-pty-provider.ts | 2 +- src/main/providers/local-pty-termination.ts | 35 +- src/main/providers/pty-provider-contract.ts | 25 +- src/main/pty-descendant-snapshot.ts | 40 + .../pty-descendant-stop-authorization.test.ts | 45 + src/main/pty-descendant-termination.ts | 77 +- .../rpc/methods/agent-launch-replay.ts | 2 +- .../rpc/methods/agent-launch-surfaces.ts | 8 +- .../agent-launch-target-authorization.ts | 11 + .../methods/agent-launch-worktree-creation.ts | 9 +- .../runtime/rpc/methods/agent-launch.test.ts | 68 ++ src/main/runtime/rpc/methods/agent-launch.ts | 21 +- .../runtime-pty-controller-contract.ts | 6 +- .../stop/worktree-terminal-stop-targets.ts | 11 +- src/main/window/runtime-window-lifecycle.ts | 66 +- .../terminal-tab-close-request-relay.ts | 73 +- src/preload/api/automation-api.ts | 8 + src/preload/api/automations-bridge.ts | 17 + ...run-workspace-action.paired-server.test.ts | 30 + .../terminal-presentation-ipc-bridge.ts | 46 +- .../terminal-presentation-pane-title.test.ts | 10 +- .../terminal-tab-mount-ipc-bridge.ts | 28 + .../lib/adopt-agent-background-session-tab.ts | 114 --- .../lib/agent-background-session-contract.ts | 28 - .../lib/automation-terminal-ownership.test.ts | 935 +++++++++++++----- .../src/lib/automation-terminal-ownership.ts | 368 ++++--- ...gent-background-session-extra-args.test.ts | 151 --- ...t-background-session-launch-parity.test.ts | 121 --- ...ch-agent-background-session-remote.test.ts | 487 --------- .../launch-agent-background-session.test.ts | 642 ------------ .../lib/launch-agent-background-session.ts | 310 ------ .../src/store/terminals/terminal-actions.ts | 7 + .../terminal-pane-hibernation-commit.ts | 92 ++ .../terminals/terminal-pane-hibernation.ts | 149 ++- src/shared/automation-terminal-lifecycle.ts | 78 ++ 61 files changed, 3437 insertions(+), 2722 deletions(-) create mode 100644 src/main/automations/desktop-run-terminal-lifecycle.ts create mode 100644 src/main/automations/desktop-run-terminal-stop.ts create mode 100644 src/main/automations/service-lifecycle.test.ts create mode 100644 src/main/daemon/daemon-pty-session-liveness.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts create mode 100644 src/main/pty-descendant-snapshot.ts create mode 100644 src/main/pty-descendant-stop-authorization.test.ts create mode 100644 src/renderer/src/hooks/ipc-events/terminal-tab-mount-ipc-bridge.ts delete mode 100644 src/renderer/src/lib/adopt-agent-background-session-tab.ts delete mode 100644 src/renderer/src/lib/agent-background-session-contract.ts delete mode 100644 src/renderer/src/lib/launch-agent-background-session-extra-args.test.ts delete mode 100644 src/renderer/src/lib/launch-agent-background-session-launch-parity.test.ts delete mode 100644 src/renderer/src/lib/launch-agent-background-session-remote.test.ts delete mode 100644 src/renderer/src/lib/launch-agent-background-session.test.ts delete mode 100644 src/renderer/src/lib/launch-agent-background-session.ts create mode 100644 src/renderer/src/store/terminals/terminal-pane-hibernation-commit.ts create mode 100644 src/shared/automation-terminal-lifecycle.ts diff --git a/src/main/automations/automation-run-receipt.ts b/src/main/automations/automation-run-receipt.ts index 270789ee9311..02b1070cf741 100644 --- a/src/main/automations/automation-run-receipt.ts +++ b/src/main/automations/automation-run-receipt.ts @@ -5,15 +5,22 @@ 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 } + | { + kind: 'chat' + sessionId: string + workspaceId: string + messageId: string | null + accepted: boolean + } | { kind: 'terminal' + accepted: boolean launch: AgentLaunchResult & { outcome: Extract } } -/** Recover only recorded acceptance; a restart never sends the prompt again. */ +/** Publication and acceptance are separate receipts; neither recovery path sends again. */ export function readAutomationRunReceipt( store: Pick, run: Pick @@ -28,16 +35,21 @@ export function readAutomationRunReceipt( return null } const launch = row.outcome.launch - if (launch.outcome.kind === 'structured' && launch.prompt?.outcome === 'journaled') { + if (launch.outcome.kind === 'structured') { return { kind: 'chat', sessionId: launch.outcome.sessionId, workspaceId: launch.worktreeId, - messageId: launch.prompt.messageId + messageId: launch.prompt?.outcome === 'journaled' ? launch.prompt.messageId : null, + accepted: launch.prompt?.outcome === 'journaled' } } - if (launch.outcome.kind === 'terminal' && launch.prompt?.outcome === 'handed-to-terminal') { - return { kind: 'terminal', launch: { ...launch, outcome: launch.outcome } } + if (launch.outcome.kind === 'terminal') { + return { + kind: 'terminal', + accepted: launch.prompt?.outcome === 'handed-to-terminal', + launch: { ...launch, outcome: launch.outcome } + } } return null } @@ -52,7 +64,8 @@ export function readAutomationRunReceipt( kind: 'chat', sessionId: send.outcome.sessionId, workspaceId: conversation.location.workspaceId, - messageId + messageId, + accepted: true } : null } diff --git a/src/main/automations/desktop-run-terminal-lifecycle.ts b/src/main/automations/desktop-run-terminal-lifecycle.ts new file mode 100644 index 000000000000..f19d12e5dd2b --- /dev/null +++ b/src/main/automations/desktop-run-terminal-lifecycle.ts @@ -0,0 +1,303 @@ +import { + stopDesktopRunTerminal, + watchDesktopTerminalStop, + stopRevokers +} from './desktop-run-terminal-stop' +import { randomUUID } from 'node:crypto' +import type { + Automation, + AutomationDispatchResult, + AutomationRun +} from '../../shared/automations-types' +import type { + AutomationTerminalCorrelation, + AutomationTerminalLifecycleRequest, + AutomationTerminalLifecycleResponse, + AutomationTerminalTarget +} from '../../shared/automation-terminal-lifecycle' +import { makePaneKey, parsePaneKey } from '../../shared/stable-pane-id' +import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import type { Store } from '../persistence' +import { requestAutomationTerminalLifecycle } from '../window/terminal-tab-close-request-relay' +import { terminalPresentationRequest } from '../window/runtime-window-lifecycle' +import type { AgentLaunchHostPolicy } from '../runtime/rpc/methods/agent-launch-surfaces' + +export { cancelDesktopTerminalRetirement } from './desktop-run-terminal-stop' + +export function createDesktopRunTerminalLifecycle( + runtime: OrcaRuntimeService, + store: Store, + inLane: (automationId: string, operation: () => Promise) => Promise +) { + const generation = randomUUID() + const registrations = new Map>() + function register( + automation: Automation, + run: Pick, + operationId: string + ) { + const window = runtime.getAuthoritativeWindow() + const web = window.webContents + const frame = web.mainFrame + const abort = new AbortController() + const registrationId = randomUUID() + const paneKey = makePaneKey(randomUUID(), randomUUID()) + const pane = parsePaneKey(paneKey)! + let epoch: string | null = null + let target: AutomationTerminalTarget | null = null + let ptyId: string | null = null + let incarnationId: string | undefined + let finalizing = false + let enrollment = Promise.resolve() + const listeners: (() => void)[] = [] + const valid = (): boolean => { + try { + return ( + !abort.signal.aborted && + !window.isDestroyed() && + !web.isDestroyed() && + web.mainFrame === frame && + runtime.getAuthoritativeWindow() === window + ) + } catch { + return false + } + } + type Operation = R extends AutomationTerminalCorrelation + ? Omit + : never + const correlation = { + registrationId, + runId: run.id, + operationId, + serviceGeneration: generation + } + const envelope = (operation: Operation): AutomationTerminalLifecycleRequest => ({ + ...correlation, + requestId: randomUUID(), + documentEpoch: epoch, + ...operation + }) + const request = (operation: Operation): Promise => + requestAutomationTerminalLifecycle(window, envelope(operation), abort.signal, valid).then( + (reply) => { + if ( + !valid() || + Object.entries(correlation).some(([key, value]) => Reflect.get(reply, key) !== value) || + (epoch !== null && reply.documentEpoch !== epoch) + ) { + throw new Error('terminal_lifecycle_owner_lost') + } + return reply + } + ) + const release = (): void => { + if (abort.signal.aborted) { + return + } + // Enqueue release to this document only; cancellation cannot retarget a new window. + try { + if (valid()) { + web.send('automations:terminalLifecycleRequest', envelope({ operation: 'release' })) + } + } catch { + /* The document is already unreachable. */ + } + abort.abort() + for (const dispose of listeners) { + dispose() + } + stopRevokers.delete(registrationId) + registrations.delete(run.id) + } + listeners.push(...watchDesktopTerminalStop(window, web, release)) + const revoker: { ptyId: string | null; release: () => void } = { ptyId, release } + stopRevokers.set(registrationId, revoker) + const reserve = (worktreeId: string): void => { + if (target || !valid()) { + return + } + target = { worktreeId, tabId: pane.tabId, leafId: pane.leafId, paneKey } + try { + enrollment = request({ operation: 'arm', target }).then((reply) => { + if (reply.disposition !== 'armed' || !reply.documentEpoch) { + throw new Error('terminal_lifecycle_not_armed') + } + epoch = reply.documentEpoch + }) + void enrollment.catch(release) + } catch { + release() + } + } + const policy: AgentLaunchHostPolicy = { + onWorkspaceCreated: reserve, + onSurfacePublished: (surface) => { + if ( + surface.outcome.kind !== 'terminal' || + !target || + surface.worktreeId !== target.worktreeId || + surface.outcome.paneKey !== paneKey || + ptyId + ) { + release() + return + } + ptyId = runtime.getTerminalPtyIdForHandle(surface.outcome.handle) + if (!ptyId) { + release() + return + } + const metadata = runtime.getPtyExecutionHostMetadata(ptyId) + incarnationId = metadata.incarnationId + if (!incarnationId || metadata.executionHostId !== LOCAL_EXECUTION_HOST_ID) { + release() + return + } + revoker.ptyId = ptyId + web.send( + 'ui:createTerminal', + terminalPresentationRequest(target.worktreeId, { + ptyId, + tabId: pane.tabId, + leafId: pane.leafId, + presentation: 'background', + surfaceOwner: false, + activate: false, + expectedProcessIdentity: { terminalHandle: surface.outcome.handle, incarnationId } + }) + ) + enrollment = enrollment.then(async () => { + const reply = await request({ + operation: 'bind', + ptyId: ptyId!, + incarnationId: incarnationId!, + hostId: LOCAL_EXECUTION_HOST_ID + }) + if (reply.disposition !== 'bound') { + release() + } + }) + void enrollment.catch(release) + } + } + return { + paneKey, + policy, + reserve, + release, + finalize: async (completed: AutomationRun): Promise => { + if (finalizing) { + return null + } + finalizing = true + try { + await enrollment + if ( + !valid() || + completed.status !== 'completed' || + completed.terminalPtyId !== ptyId || + !target || + !ptyId || + !incarnationId + ) { + return null + } + const { worktreeId } = target + const expectedPtyId = ptyId + const expectedIncarnationId = incarnationId + return await inLane(automation.id, async () => { + const eligible = (): boolean => + valid() && + runtime.getTerminalPtyIdForHandle( + runtime.getTerminalHandleForPaneKey(paneKey) ?? '' + ) === expectedPtyId && + runtime.getPtyExecutionHostMetadata(expectedPtyId).incarnationId === + expectedIncarnationId && + runtime.terminalRunFacts.readLastDrivingInputAt(expectedPtyId) === null + if (!eligible()) { + return null + } + const prepared = await request({ + operation: 'finalize', + phase: 'prepare', + preservePane: + store.getWorktreeMeta(worktreeId)?.automationProvenance?.automationRunId === run.id + }) + if (prepared.disposition !== 'prepared') { + return null + } + const proof = await stopDesktopRunTerminal( + runtime, + worktreeId, + expectedPtyId, + expectedIncarnationId, + async () => { + if (!eligible()) { + return false + } + const answer = await request({ operation: 'finalize', phase: 'authorize' }) + return answer.disposition === 'authorized' && eligible() + } + ) + let disposition: AutomationTerminalLifecycleResponse['disposition'] = 'unproven' + try { + disposition = (await request({ operation: 'finalize', phase: 'stop-settled', proof })) + .disposition + } catch { + /* Keep recovery identity when acknowledgement is lost. */ + } + return proof === 'stopped' + ? { + runId: run.id, + status: completed.status, + terminalPtyId: null, + ...(disposition === 'closed' + ? { terminalPaneKey: null, terminalSessionId: null } + : {}) + } + : null + }) + } catch { + return null + } finally { + release() + } + } + } + } + return { + begin: ( + automation: Automation, + run: Pick, + operationId: string + ) => { + if (automation.reuseSession || (automation.surface ?? 'terminal') !== 'terminal') { + return null + } + try { + const registration = register(automation, run, operationId) + registrations.set(run.id, registration) + return registration + } catch { + return null + } + }, + finalize: (run: AutomationRun) => + registrations.get(run.id)?.finalize(run) ?? Promise.resolve(null), + reconcile: () => { + for (const [id, owner] of registrations) { + const run = store.listAutomationRuns().find((entry) => entry.id === id) + if (!run || !['dispatching', 'dispatched', 'completed'].includes(run.status)) { + owner.release() + } + } + }, + stop: () => { + for (const owner of registrations.values()) { + owner.release() + } + } + } +} diff --git a/src/main/automations/desktop-run-terminal-stop.ts b/src/main/automations/desktop-run-terminal-stop.ts new file mode 100644 index 000000000000..858e523b3ebe --- /dev/null +++ b/src/main/automations/desktop-run-terminal-stop.ts @@ -0,0 +1,87 @@ +import type { BrowserWindow, WebContents } from 'electron' +import { addFanoutListener, addFanoutListeners } from '../event-listener-fanout' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' + +// Ordinary Stop revokes the same registration, including a pending provider authorization. +export const stopRevokers = new Map void }>() +export function cancelDesktopTerminalRetirement(ptyId: string): void { + for (const owner of stopRevokers.values()) { + if (owner.ptyId === ptyId) { + owner.release() + } + } +} + +export async function stopDesktopRunTerminal( + runtime: OrcaRuntimeService, + worktreeId: string, + expectedPtyId: string, + expectedIncarnationId: string, + authorizeStop: () => Promise +): Promise<'stopped' | 'live' | 'unproven'> { + let dispatched = false + let proof: 'stopped' | 'live' | 'unproven' = 'live' + try { + const stopped = await runtime.stopExactTerminalsForWorktree( + `id:${worktreeId}`, + [expectedPtyId], + { + keepHistory: true, + targetOnly: true, + expectedIncarnationId, + authorizeStop: async () => { + dispatched = await authorizeStop() + return dispatched + } + } + ) + proof = + stopped.postStopVerified && stopped.stoppedPtyIds.includes(expectedPtyId) + ? 'stopped' + : 'unproven' + } catch { + proof = 'live' + if (dispatched) { + proof = 'unproven' + try { + const inventory = await runtime.listTerminals(`id:${worktreeId}`, 1000, { + requireFreshPtyLiveness: true + }) + if ( + inventory.terminals.some( + (entry) => + entry.ptyId === expectedPtyId && + entry.incarnationId === expectedIncarnationId && + entry.connected + ) + ) { + proof = 'live' + } + } catch { + /* Unavailable inventory cannot prove a live rollback. */ + } + } + } + + return proof +} + +export function watchDesktopTerminalStop( + window: BrowserWindow, + web: WebContents, + release: () => void +): (() => void)[] { + return [ + addFanoutListener(window, 'closed', release), + addFanoutListeners(web, ['destroyed', 'render-process-gone'], release), + addFanoutListener( + web, + 'did-start-navigation', + (_event: unknown, _url: string, sameDocument: boolean, mainFrame: boolean) => { + if (mainFrame && !sameDocument) { + release() + } + } + ) + ] +} diff --git a/src/main/automations/headless-automation-agent-launch.test.ts b/src/main/automations/headless-automation-agent-launch.test.ts index c838012fb5cb..01d56591ca5e 100644 --- a/src/main/automations/headless-automation-agent-launch.test.ts +++ b/src/main/automations/headless-automation-agent-launch.test.ts @@ -100,11 +100,12 @@ describe('automations through agent.launch', () => { target: { kind: 'existing', worktree: 'id:wt-1' } }), expect.objectContaining({ runtime }), - { + expect.objectContaining({ terminalTitle: run.title, suppressStartupUpdatePrompt: true, - unprovableHost: 'write-unless-shell' - } + unprovableHost: 'write-unless-shell', + onSurfacePublished: expect.any(Function) + }) ) expect(result).toMatchObject({ sessionKind: 'terminal', @@ -312,3 +313,62 @@ describe('automations through agent.launch', () => { expect(mocks.launch).toHaveBeenCalledTimes(1) }) }) + +it.each(['terminal', 'chat', 'reuse-terminal'] as const)( + 'preserves published %s identity for refused, uncertain and throwing settlement', + async (kind) => { + const { runtime } = 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'] as const) { + mocks.launch.mockImplementationOnce(async (_params, _context, policy) => { + policy.onSurfacePublished(published) + if (outcome === 'throw') { + throw new Error('settlement transport lost') + } + return { ...published, prompt: { delivery: 'submit', outcome } } + }) + const result = await launchHeadlessAutomationAgent(runtime, { + automation: { + ...automation, + surface: kind === 'chat' ? 'chat' : 'terminal', + reuseSession: kind === 'reuse-terminal' + }, + run, + target, + runs: + kind === 'reuse-terminal' + ? [ + { + ...run, + id: 'old', + status: 'completed', + workspaceId: 'wt-1', + sessionKind: 'terminal', + terminalPaneKey: 'old:leaf', + terminalPtyId: 'pty-1' + } + ] + : [] + }).catch((error) => error) + expect(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(3) + expect(mocks.host.send).not.toHaveBeenCalled() + } +) diff --git a/src/main/automations/headless-automation-agent-launch.ts b/src/main/automations/headless-automation-agent-launch.ts index 4fae9b5c7e53..59d515809603 100644 --- a/src/main/automations/headless-automation-agent-launch.ts +++ b/src/main/automations/headless-automation-agent-launch.ts @@ -1,12 +1,17 @@ import type { Automation, AutomationRun } from '../../shared/automations-types' import type { AgentLaunchResult } from '../../shared/agent-launch-intent' +import type { createDesktopRunTerminalLifecycle } from './desktop-run-terminal-lifecycle' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { launchAgentOnHost } from '../runtime/rpc/methods/agent-launch' import { findReusableAutomationRun } from '../../shared/automation-session-reuse' import { reuseAutomationChat } from './automation-chat-session-reuse' import { buildHeadlessAutomationWorkspaceName } from './headless-workspace-create' import type { AutomationRunTargetResult } from './run-target-resolution' -import type { HeadlessAutomationDispatchLaunch } from './headless-dispatch' +import { + AutomationRunLaunchError, + type HeadlessAutomationDispatchLaunch +} from './headless-dispatch' +import { parsePaneKey } from '../../shared/stable-pane-id' import { automationRunOperationId, AUTOMATION_AGENT_CALLER } from './automation-run-operation' import { createAutomationDispatchToken } from './dispatch-tokens' import { mergeExtraAgentArgs, hasExtraAgentArgs } from '../../shared/automation-extra-agent-args' @@ -32,11 +37,13 @@ export type AutomationAgentLaunchRequest = { export async function launchHeadlessAutomationAgent( runtime: OrcaRuntimeService, - request: AutomationAgentLaunchRequest + request: AutomationAgentLaunchRequest, + lifecycle?: ReturnType['begin']> ): Promise { try { - return await launchAutomationAgent(runtime, request) + return await launchAutomationAgent(runtime, request, lifecycle) } catch (error) { + lifecycle?.release() if (error instanceof AutomationRunLaunchError) { throw error } @@ -47,16 +54,21 @@ export async function launchHeadlessAutomationAgent( } } -class AutomationRunLaunchError extends Error {} - async function launchAutomationAgent( runtime: OrcaRuntimeService, - request: AutomationAgentLaunchRequest + request: AutomationAgentLaunchRequest, + lifecycle?: ReturnType['begin']> ): Promise { const { automation, run, target } = request const surface = automation.surface ?? 'terminal' const context = { runtime, caller: AUTOMATION_AGENT_CALLER } + let published: HeadlessAutomationAgentLaunch | undefined const policy = { + ...lifecycle?.policy, + onSurfacePublished: (result: AgentLaunchResult) => { + published = publishedLaunchTarget(runtime, result) + lifecycle?.policy.onSurfacePublished?.(result) + }, terminalTitle: run.title, suppressStartupUpdatePrompt: true, unprovableHost: 'write-unless-shell' @@ -101,15 +113,21 @@ async function launchAutomationAgent( context, policy ) + published ??= publishedLaunchTarget(runtime, result) if (result.prompt?.outcome === 'handed-to-terminal') { return launchOutcome(runtime, result) } - if (result.prompt?.outcome !== 'not-delivered') { + throw new AutomationRunLaunchError( + `${tuiAgentDisplayName(automation.agentId)} could not confirm this run's prompt. Open the terminal before running again.`, + published + ) + } catch (error) { + if (published) { throw new AutomationRunLaunchError( - `${tuiAgentDisplayName(automation.agentId)} could not confirm this run's prompt. Open the terminal before running again.` + `${tuiAgentDisplayName(automation.agentId)} could not confirm this run's prompt. Open the terminal before running again.`, + published ) } - } catch (error) { const records = await runtime.openAgentSessionRecordStore() const row = records.getOperationRow( rpcCallerOperationKey(AUTOMATION_AGENT_CALLER), @@ -145,11 +163,15 @@ async function launchAutomationAgent( `${tuiAgentDisplayName(automation.agentId)} could not start. ${merged.error}` ) } + if (automation.workspaceMode === 'existing' && automation.workspaceId) { + lifecycle?.reserve(automation.workspaceId) + } try { const result = await launchAgentOnHost( { agent: automation.agentId, operationId, + ...(lifecycle ? { paneKey: lifecycle.paneKey } : {}), surface, presentation: 'background', prompt: { text: automation.prompt, delivery: 'submit' }, @@ -179,7 +201,8 @@ async function launchAutomationAgent( ) 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.` + `${tuiAgentDisplayName(automation.agentId)} started, but Orca could not confirm this run's prompt. Open the run before trying again.`, + published ?? publishedLaunchTarget(runtime, result) ) } return launchOutcome(runtime, result) @@ -194,38 +217,65 @@ async function launchAutomationAgent( `${tuiAgentDisplayName(automation.agentId)} could not start because this run waited too long. Run the automation again.` ) } + if (published && !(error instanceof AutomationRunLaunchError)) { + throw new AutomationRunLaunchError( + `${tuiAgentDisplayName(automation.agentId)} started, but Orca could not confirm this run's prompt. Open the run before trying again.`, + published + ) + } throw error } } -async function launchOutcome( - runtime: OrcaRuntimeService, +export function publishedLaunchTarget( + runtime: Pick, result: AgentLaunchResult -): Promise { - const shown = await runtime.showManagedWorktree(`id:${result.worktreeId}`) - if (result.outcome.kind === 'structured') { - return { - workspaceId: result.worktreeId, - workspaceDisplayName: shown.displayName ?? null, - sessionKind: 'chat', - chatSessionId: result.outcome.sessionId, - terminalHandle: null, - terminalSessionId: null, - terminalPaneKey: null, - terminalPtyId: null +): HeadlessAutomationAgentLaunch { + 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. */ } } - const terminal = await runtime.showTerminal(result.outcome.handle) return { workspaceId: result.worktreeId, - workspaceDisplayName: shown.displayName ?? null, - sessionKind: 'terminal', - chatSessionId: null, - terminalHandle: result.outcome.handle, - terminalSessionId: terminal.tabId ?? null, - terminalPaneKey: result.outcome.paneKey ?? runtime.getTerminalPaneKey(result.outcome.handle), - terminalPtyId: runtime.getTerminalPtyIdForHandle(result.outcome.handle) + 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 + } +} + +async function launchOutcome( + runtime: OrcaRuntimeService, + result: AgentLaunchResult +): Promise { + const target = publishedLaunchTarget(runtime, result) + try { + const shown = await runtime.showManagedWorktree(`id:${result.worktreeId}`) + target.workspaceDisplayName = shown.displayName ?? null + } catch { + // Publication already owns the target; optional display metadata cannot erase it. + } + if (result.outcome.kind === 'terminal' && !target.terminalSessionId) { + try { + target.terminalSessionId = (await runtime.showTerminal(result.outcome.handle)).tabId ?? null + } catch { + // Keep the published pane and process identity when its presentation is unavailable. + } } + return target } /** A pane may have been reused by a later process. */ diff --git a/src/main/automations/headless-dispatch-runner.ts b/src/main/automations/headless-dispatch-runner.ts index 946850a4f0aa..5c1ac50efe41 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' @@ -59,6 +60,9 @@ export async function runHeadlessAutomationDispatch( status: error instanceof AutomationDispatchRefusedError ? 'skipped_unavailable' : 'dispatch_failed', workspaceId: automation.workspaceId, + ...(error instanceof AutomationRunLaunchError ? error.target : {}), + dispatchedAt, + precheckResult, error: describeDispatchError(error) }) } diff --git a/src/main/automations/headless-dispatch.ts b/src/main/automations/headless-dispatch.ts index 3ee046734eab..7682ab20653a 100644 --- a/src/main/automations/headless-dispatch.ts +++ b/src/main/automations/headless-dispatch.ts @@ -28,6 +28,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/precheck-runner.ts b/src/main/automations/precheck-runner.ts index 099362756418..31cf40d1113e 100644 --- a/src/main/automations/precheck-runner.ts +++ b/src/main/automations/precheck-runner.ts @@ -1,3 +1,6 @@ +import type { Store } from '../persistence' +import type { Automation } from '../../shared/automations-types' +import type { AutomationRunTargetResult } from './run-target-resolution' import { spawn, type ChildProcess } from 'node:child_process' import type { ClientChannel } from 'ssh2' import type { AutomationPrecheck, AutomationPrecheckResult } from '../../shared/automations-types' @@ -277,3 +280,34 @@ export async function runAutomationPrecheck(args: { } return await runLocalPrecheck(args.precheck, args.target) } + +export async function runAutomationRunPrecheck( + store: Store, + automationId: string, + runId: string, + resolveTarget: (automation: Automation) => AutomationRunTargetResult, + executePrecheck: typeof runAutomationPrecheck +): 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 executePrecheck({ + 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/runtime-automation-service.test.ts b/src/main/automations/runtime-automation-service.test.ts index 2f1ab559fd61..a7863c73f651 100644 --- a/src/main/automations/runtime-automation-service.test.ts +++ b/src/main/automations/runtime-automation-service.test.ts @@ -56,8 +56,8 @@ function fixture(headless: boolean) { location: { workspaceId: 'wt-1' } }) }), - getTerminalHandleForPaneKey: vi.fn(() => null), - getTerminalPtyIdForHandle: vi.fn(() => 'pty-1'), + 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' ), @@ -156,6 +156,7 @@ describe('host-owned automation execution', () => { ) it('recovers a terminal reuse receipt without a pane key and never launches again', async () => { const { rows, runtime } = fixture(false) + const originalRun = { ...run, terminalPtyId: 'pty-1' } rows.set(automationRunOperationId(run, 'reuse-terminal-launch'), { outcome: { status: 'succeeded', @@ -175,8 +176,8 @@ describe('host-owned automation execution', () => { runtime.waitForTerminal.mockRejectedValueOnce(new Error('test-stop')) const observer = captured.options.terminalObserver! await expect( - observer.observeCompletion(observer.resolveRunTerminal(run)!, { - run, + observer.observeCompletion(observer.resolveRunTerminal(originalRun)!, { + run: originalRun, signal: new AbortController().signal }) ).rejects.toThrow('test-stop') @@ -191,6 +192,112 @@ describe('host-owned automation execution', () => { ) expect(captured.launch).not.toHaveBeenCalled() }) + it.each(['same-process', 'replacement', 'unknown', 'same-id-replacement'] as const)( + 'projects an adopted live handle with independent %s evidence', + async (proof) => { + const { rows, runtime } = fixture(false) + runtime.getTerminalHandleForPaneKey.mockReturnValue('term-adopted') + runtime.getTerminalPtyIdForHandle.mockImplementation((handle) => + handle === 'term-adopted' + ? proof === 'same-process' || proof === 'same-id-replacement' + ? 'original-pty' + : proof === 'replacement' + ? 'replacement-pty' + : null + : proof === 'same-id-replacement' + ? null + : 'original-pty' + ) + const ownRun = { + ...run, + status: 'dispatched' as const, + sessionKind: 'terminal' as const, + terminalPaneKey: 'tab:leaf', + terminalPtyId: 'original-pty' + } + rows.set(automationRunOperationId(run, 'fresh-launch'), { + outcome: { + status: 'succeeded', + launch: { + worktreeId: 'wt-1', + outcome: { kind: 'terminal', handle: 'term-old', paneKey: 'tab:leaf' }, + receipt: { + mode: 'terminal', + preferred: 'terminal', + reason: 'requested', + detail: 'Terminal' + }, + prompt: { delivery: 'submit', outcome: 'handed-to-terminal' } + } + } + }) + const observer = captured.options.terminalObserver! + runtime.waitForTerminal.mockRejectedValueOnce(new Error('observed-current-handle')) + const pending = observer.observeCompletion(observer.resolveRunTerminal(ownRun)!, { + run: ownRun, + signal: new AbortController().signal + }) + if (proof === 'same-process') { + await expect(pending).rejects.toThrow('observed-current-handle') + } else { + expect(await pending).toMatchObject({ status: 'dispatch_failed' }) + expect(runtime.waitForTerminal).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: kind === 'chat' ? 'structured' : 'terminal', + 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' } }) diff --git a/src/main/automations/runtime-automation-service.ts b/src/main/automations/runtime-automation-service.ts index ece048ba7685..4dfd7dd49014 100644 --- a/src/main/automations/runtime-automation-service.ts +++ b/src/main/automations/runtime-automation-service.ts @@ -1,7 +1,9 @@ +import { createDesktopRunTerminalLifecycle } from './desktop-run-terminal-lifecycle' +import { automationRunOperationId } from './automation-run-operation' import { observeAutomationChatRun } from './runtime-chat-run-observer' import { readAutomationRunReceipt } from './automation-run-receipt' +import { withLiveTerminalHandle } from '../runtime/rpc/methods/agent-launch-replay' import { tuiAgentDisplayName } from '../../shared/tui-agent-display-names' -import { parsePaneKey } from '../../shared/stable-pane-id' import type { ClaudeUsageStore } from '../claude-usage/store' import type { CodexUsageStore } from '../codex-usage/store' import type { Store } from '../persistence' @@ -13,7 +15,11 @@ import { isTuiAgent, TUI_AGENT_CONFIG } from '../../shared/tui-agent-config' -import { launchHeadlessAutomationAgent, runOwnHandle } from './headless-automation-agent-launch' +import { + launchHeadlessAutomationAgent, + publishedLaunchTarget, + runOwnHandle +} from './headless-automation-agent-launch' import { AGENT_HOOKS_REVIEW_BLOCKED_ERROR, createRuntimeAutomationRunTerminalObserver @@ -40,19 +46,23 @@ export function createRuntimeAutomationService(input: { store.listAutomations().find((entry) => entry.id === run.automationId)?.agentId ) }) + let desktop: ReturnType | undefined const service = new AutomationService(store, { claudeUsage, codexUsage, + onRunFinalized: (run) => desktop?.finalize(run) ?? Promise.resolve(null), terminalObserver: { ...observer, resolveRunTerminal: (run) => run.sessionKind === 'chat' || run.status === 'dispatching' ? `automation:${run.id}` - : ((run.terminalPaneKey ? launchedHandles.get(run.terminalPaneKey) : undefined) ?? + : (runOwnHandle(runtime, run) ?? + (run.terminalPaneKey ? launchedHandles.get(run.terminalPaneKey) : undefined) ?? observer.resolveRunTerminal(run)), observeCompletion: async (handle, options) => { let run = options.run - if (run && handle.startsWith('automation:')) { + let originalHandle: string | undefined + if (run && (handle.startsWith('automation:') || run.sessionKind !== 'chat')) { if (!run.chatSessionId) { const records = await runtime.openAgentSessionRecordStore() const receipt = readAutomationRunReceipt(records, run) @@ -67,24 +77,42 @@ export function createRuntimeAutomationService(input: { error: `${agent} could not confirm this run after Orca restarted. Open its workspace before running again.` } } - const terminal = receipt.kind === 'terminal' ? receipt.launch.outcome : null - const terminalPaneKey = terminal - ? (terminal.paneKey ?? runtime.getTerminalPaneKey(terminal.handle)) - : null + const originalPtyId = + receipt.kind === 'terminal' + ? runtime.getTerminalPtyIdForHandle(receipt.launch.outcome.handle) + : null + const projected = + receipt.kind === 'terminal' ? withLiveTerminalHandle(receipt.launch, runtime) : null + const terminal = projected?.outcome.kind === 'terminal' ? projected.outcome : null + const observable = + receipt.accepted && + (!terminal || + (originalPtyId !== null && + (!run.terminalPtyId || run.terminalPtyId === originalPtyId) && + runtime.getTerminalPtyIdForHandle(terminal.handle) === originalPtyId)) + const target = projected + ? publishedLaunchTarget(runtime, projected) + : { + workspaceId: receipt.kind === 'chat' ? receipt.workspaceId : null, + sessionKind: 'chat' as const, + chatSessionId: receipt.kind === 'chat' ? receipt.sessionId : null, + terminalPaneKey: null, + terminalSessionId: null + } run = await service.markDispatchResult({ + ...target, runId: run.id, - status: 'dispatched', - workspaceId: - receipt.kind === 'chat' ? receipt.workspaceId : receipt.launch.worktreeId, - sessionKind: receipt.kind, - chatSessionId: receipt.kind === 'chat' ? receipt.sessionId : null, - terminalSessionId: terminal - ? (parsePaneKey(terminalPaneKey ?? '')?.tabId ?? null) - : null, - terminalPaneKey, - terminalPtyId: terminal ? runtime.getTerminalPtyIdForHandle(terminal.handle) : null + status: observable ? 'dispatched' : 'dispatch_failed', + error: observable + ? null + : `${agent} could not confirm this run's prompt or original process. Open the run before trying again.`, + terminalPtyId: originalPtyId }) - if (terminal) { + if (!observable) { + return { status: 'dispatch_failed', error: run.error } + } + if (terminal && receipt.kind === 'terminal') { + originalHandle = receipt.launch.outcome.handle handle = terminal.handle } } @@ -108,7 +136,25 @@ export function createRuntimeAutomationService(input: { } } } + const originalProcessMissing = (): boolean => + Boolean( + run?.terminalPtyId && + (runtime.getTerminalPtyIdForHandle(handle) !== run.terminalPtyId || + (originalHandle !== undefined && + runtime.getTerminalPtyIdForHandle(originalHandle) !== run.terminalPtyId)) + ) + const processLost = { + status: 'dispatch_failed' as const, + error: + 'The agent’s original process is no longer available. Open the run before trying again.' + } + if (originalProcessMissing()) { + return processLost + } const observation = await observer.observeCompletion(handle, { ...options, run }) + if (originalProcessMissing()) { + return processLost + } if (options.run && observation.error === AGENT_HOOKS_REVIEW_BLOCKED_ERROR) { const markDispatchResult = service.markDispatchResult.bind(service) void closeEarlierHookReviewRunTerminals( @@ -121,13 +167,25 @@ export function createRuntimeAutomationService(input: { return observation } }, - onAutomationsChanged: (payload) => runtime.notifyAutomationsChanged(payload), + onAutomationsChanged: (payload) => { + desktop?.reconcile() + runtime.notifyAutomationsChanged(payload) + }, allowRemoteHostScheduling: input.headless, headlessDispatcher: async (request) => { - const { terminalHandle, ...launch } = await launchHeadlessAutomationAgent(runtime, { - ...request, - runs: store.listAutomationRuns(request.automation.id) - }) + const lifecycle = desktop?.begin( + request.automation, + request.run, + automationRunOperationId(request.run, 'fresh-launch') + ) + const { terminalHandle, ...launch } = await launchHeadlessAutomationAgent( + runtime, + { + ...request, + runs: store.listAutomationRuns(request.automation.id) + }, + lifecycle + ) if (launch.terminalPaneKey && terminalHandle) { launchedHandles.set(launch.terminalPaneKey, terminalHandle) if (launchedHandles.size > MAX_REMEMBERED_LAUNCHES) { @@ -141,6 +199,15 @@ export function createRuntimeAutomationService(input: { runtime.setAutomationService(service) if (input.headless) { bindHeadlessRunTerminalRetention(service, store, runtime) + } else { + desktop = createDesktopRunTerminalLifecycle(runtime, store, (id, operation) => + service.runInAutomationLane(id, operation) + ) + const stop = service.stop.bind(service) + service.stop = () => { + desktop?.stop() + stop() + } } return service } diff --git a/src/main/automations/runtime-chat-run-observer.test.ts b/src/main/automations/runtime-chat-run-observer.test.ts index de5532bd061b..408e3e1d6a7d 100644 --- a/src/main/automations/runtime-chat-run-observer.test.ts +++ b/src/main/automations/runtime-chat-run-observer.test.ts @@ -8,11 +8,25 @@ import { agentJournalSubmissionKey } from '../../shared/agent-session-journal-it 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 { 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(() => ({ host: { journalSnapshot: vi.fn(), subscribe: vi.fn() } })) +const mocks = vi.hoisted(() => ({ + actualHost: null as StructuredAgentSessionHost | null, + host: { journalSnapshot: vi.fn(), subscribe: vi.fn(), queuedSendAnswer: vi.fn(async () => null) } +})) vi.mock('../native-chat/agent-session-wire/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => mocks.host + getStructuredAgentSessionHost: () => mocks.actualHost ?? mocks.host })) const submission: AgentJournalSubmission = { clientMessageId: 'prompt', @@ -61,8 +75,14 @@ function snapshot(items: AgentJournalRenderItem[] = []): AgentJournalSnapshot { submissions: [submission] } } -beforeEach(() => vi.clearAllMocks()) -afterEach(() => vi.useRealTimers()) +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( @@ -201,3 +221,320 @@ describe('restart observation and disposal', () => { expect(mocks.host.subscribe).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 rig = await createQueuedMessageTestRig({ restartable: true }) + mocks.actualHost = rig.host + const controller = new AbortController() + try { + const working = await rig.workingSend() + let sink = rig.providerEvents() + for (let n = 0; n < history; n++) { + 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 journal = rig.host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)!.journal + let projections = 0, + projectedRows = 0, + scannedRows = 0 + const materialized = new WeakSet() + const realPublicRead = journal.publicRead.bind(journal) + 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 result + } + } + }) + const visitItems = journal.visitItems.bind(journal) + 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') + let visited = 0 + const realSnapshot = journal.snapshot.bind(journal) + const full = vi.spyOn(journal, 'snapshot').mockImplementation((...args) => { + const value = realSnapshot(...args) + visited += value.items.length + value.submissions.length + return value + }) + 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 deltaBaseline = [deltas.mock.calls.length, deltaRows] + const beforeBaseline = full.mock.calls.length + const projectionBaseline = [projections, projectedRows, scannedRows] + const visitedBeforeBaseline = visited + await tokenBurst() + const baselineDeltas = [ + deltas.mock.calls.length - deltaBaseline[0], + deltaRows - deltaBaseline[1] + ] + const baselineSnapshots = full.mock.calls.length - beforeBaseline + const baselineVisited = visited - visitedBeforeBaseline + const baselineProjection = [projections, projectedRows, scannedRows].map( + (v, i) => v - projectionBaseline[i] + ) + const releases: (() => void)[] = [] + const eventTypes: Record = {} + const latest: unknown[] = [] + const observerReads = vi.spyOn(rig.host, 'journalSnapshot') + const realSubscribe = rig.host.subscribe.bind(rig.host) + const subscribe = vi.spyOn(rig.host, 'subscribe').mockImplementation(async (...args) => { + const input = args[0] + const release = await realSubscribe({ + ...input, + emit: (event) => { + eventTypes[event.type] = (eventTypes[event.type] ?? 0) + 1 + if (event.type !== 'end') { + latest.push(event.type === 'batch' ? event.latestTurn : event.page.latestTurn) + } + input.emit(event) + } + }) + const wrapped = vi.fn(release) + releases.push(wrapped) + return wrapped + }) + // SAFETY: only receipt acquisition is a transport stand-in; the observer uses the actual host below. + const runtime = { + 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' } }) + }) + } as unknown as OrcaRuntimeService + let pending = observeAutomationChatRun(runtime, run, controller.signal) + void pending.catch(() => {}) + await eventually(() => expect(subscribe).toHaveBeenCalledOnce()) + await rig.host.flushStreamedEvents(HOST_TEST_SESSION) + await eventually(() => expect(full.mock.calls.length).toBeGreaterThan(0)) + const beforeTokens = full.mock.calls.length + const projectionTokens = [projections, projectedRows, scannedRows] + const tokenDeltas = [deltas.mock.calls.length, deltaRows] + const readsBeforeTokens = observerReads.mock.calls.length + const visitedBeforeTokens = visited + await tokenBurst() + expect(observerReads.mock.calls.length).toBe(readsBeforeTokens) + expect(full.mock.calls.length - beforeTokens).toBeLessThanOrEqual(baselineSnapshots) + expect(visited - visitedBeforeTokens).toBeLessThanOrEqual(baselineVisited) + expect( + [projections, projectedRows, scannedRows].map((v, i) => v - projectionTokens[i]) + ).toEqual(baselineProjection) + // One row per token in ordinary catch-up and one in prompt-cache invalidation. + expect([deltas.mock.calls.length - tokenDeltas[0], deltaRows - tokenDeltas[1]]).toEqual([ + baselineDeltas[0] + 50, + baselineDeltas[1] + 50 + ]) + controller.abort() + await expect(pending).rejects.toThrow('request_aborted') + expect(releases[0]).toHaveBeenCalledOnce() + pending = observeAutomationChatRun(runtime, run, new AbortController().signal) + await eventually(() => expect(subscribe).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) + await eventually(async () => expect(await rig.handoff(q)).toBeDefined()) + const sent = await rig.handoffId(q) + expect(sent).not.toBe(q) + await eventually(() => expect(journal.submission(sent)?.handedOverAt).toBeDefined()) + await rig.settleAccepted(sent, 'automation') + const accepted = await rig.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.publish({ lifecycle: true }) + expect(await sink.written?.()).toEqual({ ok: true }) + await rig.host.flushStreamedEvents(HOST_TEST_SESSION) + expect(await pending).toMatchObject({ status: 'completed' }) + expect(rig.dispatch).toHaveBeenCalledTimes(2) + expect(releases).toHaveLength(2) + for (const release of releases) { + expect(release).toHaveBeenCalledOnce() + } + expect(latest).toContainEqual( + expect.objectContaining({ + turn: expect.objectContaining({ turnId: 'turn-automation', state: 'completed' }) + }) + ) + 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) + } + } + // Fixed work includes both hydrations, canonical queue handoff and accepted root completion. + expect(full.mock.calls.length - 2 * baselineSnapshots).toBe(23) + expect(visited - 2 * baselineVisited).toBeLessThan((history + 30) * 23) + process.stdout.write( + `${JSON.stringify({ + history, + baselineSnapshots, + baselineVisited, + baselineProjection, + baselineDeltas, + projections, + projectedRows, + scannedRows, + deltaReads: deltas.mock.calls.length, + deltaRows, + observerReads: observerReads.mock.calls.length, + eventTypes, + fullSnapshots: full.mock.calls.length, + visited, + subscriptions: subscribe.mock.calls.length + })}\n` + ) + } finally { + controller.abort() + mocks.actualHost = null + await rig.dispose() + } + } + ) + it.each(['withdraw', 'return'] as const)( + 'settles a queue-only %s without resending', + async (outcome) => { + const rig = await createQueuedMessageTestRig() + mocks.actualHost = rig.host + try { + await rig.workingSend() + const queued = rig.send('queued', 'queue-if-active') + await queued.result + const q = queued.id + const run = { + ...buildProfileStateCutoverFixture('/fixture').automationRuns[0], + createdAt: Date.now(), + chatSessionId: HOST_TEST_SESSION + } + // Exercise canonical queue answers directly as well as live publisher observation above. + expect( + chatAutomationRunObservation( + await rig.host.journalSnapshot(HOST_TEST_SESSION), + q, + 'Codex', + await rig.host.queuedSendAnswer(HOST_TEST_SESSION, q) + ) + ).toBeNull() + await rig.stop() + expect( + chatAutomationRunObservation( + await rig.host.journalSnapshot(HOST_TEST_SESSION), + q, + 'Codex', + await rig.host.queuedSendAnswer(HOST_TEST_SESSION, q) + ) + ).toBeNull() + 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(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 index 057e6e53b823..80520632cc53 100644 --- a/src/main/automations/runtime-chat-run-observer.ts +++ b/src/main/automations/runtime-chat-run-observer.ts @@ -1,5 +1,6 @@ import type { AutomationRun } from '../../shared/automations-types' 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, @@ -15,14 +16,26 @@ import { tuiAgentDisplayName } from '../../shared/tui-agent-display-names' export function chatAutomationRunObservation( snapshot: AgentJournalSnapshot, messageId: string, - agent: string + agent: string, + queued: AgentSessionSendResult | null = null ): AutomationRunCompletionObservation | null { - const submission = snapshot.submissions.find((entry) => entry.clientMessageId === messageId) + 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 + } + const submission = + queued && 'submission' in queued + ? queued.submission + : snapshot.submissions.find((entry) => entry.clientMessageId === messageId) if (!submission) { return null } const keys = new Set([ - agentJournalSubmissionKey(messageId), + agentJournalSubmissionKey(submission.clientMessageId), ...(submission.providerItemId ? [submission.providerItemId] : []) ]) const turnItem = snapshot.items.find((item) => { @@ -91,7 +104,12 @@ export async function observeAutomationChatRun( const receipt = readAutomationRunReceipt(store, run) const agent = tuiAgentDisplayName(store.getConversation(run.chatSessionId)?.provider ?? 'Agent') ?? 'Agent' - if (receipt?.kind !== 'chat' || receipt.sessionId !== run.chatSessionId) { + 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.` @@ -104,6 +122,12 @@ export async function observeAutomationChatRun( let settled = false let reading = false let dirty = false + let submissionSignature = '' + let turnSignature = '' + let queueSignature = '' + let submissionId = messageId + let providerItemId: string | null = null + let turnItemId: string | null = null const finish = (result?: AutomationRunCompletionObservation, error?: unknown): void => { if (settled) { return @@ -127,6 +151,38 @@ export async function observeAutomationChatRun( }), Math.max(1, (run.dispatchedAt ?? run.createdAt) + 6 * 60 * 60 * 1000 - Date.now()) ) + const rememberSubmission = (entry: AgentJournalSnapshot['submissions'][number]): boolean => { + const signature = JSON.stringify([ + entry.clientMessageId, + entry.dispatchState, + entry.providerItemId, + entry.answeredInTurn + ]) + const changed = signature !== submissionSignature + submissionSignature = signature + submissionId = entry.clientMessageId + providerItemId = entry.providerItemId + turnItemId = entry.answeredInTurn?.via === 'start' ? entry.answeredInTurn.turnItemId : null + return changed + } + const rememberTurn = (item: AgentJournalSnapshot['items'][number]): boolean => { + const turn = readAgentJournalTurn(item.body) + if ( + !turn || + item.agentId || + !( + item.itemId === turnItemId || + (providerItemId !== null && turn.userItemId === providerItemId) || + turn.userItemId === agentJournalSubmissionKey(submissionId) + ) + ) { + return false + } + const signature = JSON.stringify([item.itemId, turn.state, readAgentJournalTurnOutcome(turn)]) + const changed = signature !== turnSignature + turnSignature = signature + return changed + } const read = async (): Promise => { if (settled) { return @@ -139,11 +195,19 @@ export async function observeAutomationChatRun( try { do { dirty = false - const observation = chatAutomationRunObservation( - await host.journalSnapshot(sessionId), - messageId, - agent - ) + const snapshot = await host.journalSnapshot(sessionId) + const queued = await host.queuedSendAnswer(sessionId, messageId) + const submission = + queued && 'submission' in queued + ? queued.submission + : snapshot.submissions.find((entry) => entry.clientMessageId === messageId) + if (submission) { + rememberSubmission(submission) + } + for (const item of snapshot.items) { + rememberTurn(item) + } + const observation = chatAutomationRunObservation(snapshot, messageId, agent, queued) if (observation) { finish(observation) return @@ -165,12 +229,36 @@ export async function observeAutomationChatRun( id: `automation:${run.id}`, sessionId, emit: (event) => { - // Token deltas do not change completion; read the full journal only at request/turn boundaries. + let changed = event.type !== 'batch' + const rows = + event.type === 'batch' ? event.batch : event.type === 'end' ? null : event.page + for (const entry of rows?.submissions ?? []) { + if (entry.clientMessageId !== messageId && entry.queuedMessageId !== messageId) { + continue + } + changed = rememberSubmission(entry) || changed + } + for (const item of rows?.items ?? []) { + changed = rememberTurn(item) || changed + } if ( - event.type !== 'batch' || - event.batch.submissions.some((entry) => entry.clientMessageId === messageId) || - event.batch.items.some((item) => readAgentJournalTurn(item.body)) + event.type === 'batch' && + turnItemId && + event.batch.removedItemIds?.includes(turnItemId) ) { + changed = true + } + if (event.type !== 'end' && event.queuedMessages !== undefined) { + const card = event.queuedMessages?.find((entry) => entry.messageId === messageId) + const signature = JSON.stringify( + card ? [card.messageId, card.state, card.consumedAs] : null + ) + if (signature !== queueSignature) { + changed = true + queueSignature = signature + } + } + if (changed) { void read() } } diff --git a/src/main/automations/service-lifecycle.test.ts b/src/main/automations/service-lifecycle.test.ts new file mode 100644 index 000000000000..e470a3ff67b1 --- /dev/null +++ b/src/main/automations/service-lifecycle.test.ts @@ -0,0 +1,72 @@ +import { 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' + +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', + 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, { headlessDispatcher: 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 }) + } + } +) diff --git a/src/main/automations/service.ts b/src/main/automations/service.ts index 10d16a055c94..d4be95f615d7 100644 --- a/src/main/automations/service.ts +++ b/src/main/automations/service.ts @@ -14,7 +14,7 @@ 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 { runAutomationRunPrecheck, runAutomationPrecheck } from './precheck-runner' import { captureLegacyRunTarget, resolveAutomationRunTarget, @@ -58,6 +58,9 @@ export class AutomationService { private readonly automationLanes = new Map>() /** Close unused completed terminals on headless hosts; return the count. */ releaseFinishedRunTerminals: (() => Promise) | null = null + private readonly onRunFinalized: + | ((run: AutomationRun) => Promise) + | undefined private readonly publish: PublishAutomationsChanged | null private readonly runs: AutomationRunWriter private readonly completionWatcher: AutomationRunCompletionWatcher | null @@ -67,6 +70,7 @@ export class AutomationService { constructor( private readonly store: Store, opts: { + onRunFinalized?: (run: AutomationRun) => Promise tickMs?: number claudeUsage?: ClaudeUsageStore codexUsage?: CodexUsageStore @@ -76,6 +80,7 @@ export class AutomationService { onAutomationsChanged?: PublishAutomationsChanged } = {} ) { + this.onRunFinalized = opts.onRunFinalized this.tickMs = opts.tickMs ?? 60_000 this.claudeUsage = opts.claudeUsage ?? null this.codexUsage = opts.codexUsage ?? null @@ -163,32 +168,17 @@ 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 runAutomationRunPrecheck( + this.store, + automationId, + runId, + (automation) => this.resolveTarget(automation), + runAutomationPrecheck + ) } async markDispatchResult(result: AutomationDispatchResult): Promise { - const run = await this.runs.updateRun(result) + let run = await this.runs.updateRun(result) clearAutomationDispatchTokens(run.automationId, run.id) if (!isFinalAutomationRunStatus(run.status)) { if (run.status === 'dispatched') { @@ -196,6 +186,10 @@ export class AutomationService { } return run } + const retirement = await this.onRunFinalized?.(run) + if (retirement) { + run = await this.runs.updateRun(retirement) + } this.completionWatcher?.forget(run.id) // Duplicate completion effects must not recalculate usage with a later attribution window. if (run.usage) { diff --git a/src/main/daemon/daemon-pty-adapter-history-shutdown-admission.test.ts b/src/main/daemon/daemon-pty-adapter-history-shutdown-admission.test.ts index 6df79da759a8..3720bb24d256 100644 --- a/src/main/daemon/daemon-pty-adapter-history-shutdown-admission.test.ts +++ b/src/main/daemon/daemon-pty-adapter-history-shutdown-admission.test.ts @@ -77,3 +77,88 @@ it('drains keepHistory shutdowns admitted before connection preparation complete rmSync(harness.dir, { recursive: true, force: true }) } }) + +it.each(['cwd', 'checkpoint', 'lock'] as const)( + 'authorizes only after real daemon %s preparation and preserves live history on veto', + async (pause) => { + const subprocess = createMockSubprocess() + const harness = await startDaemonAdapterHarness(() => subprocess) + const adapter = new DaemonPtyAdapter({ + socketPath: harness.socketPath, + tokenPath: harness.tokenPath, + historyPath: join(harness.dir, 'history') + }) + try { + const { id, incarnationId } = await adapter.spawn({ + cols: 80, + rows: 24, + sessionId: `veto-${pause}` + }) + subprocess._simulateData('keep this live history\r\n') + // SAFETY: protected adapter owners are exposed only to pause their real preparation, not replace stop dispatch. + const inside = adapter as unknown as { + readLiveSleepCwd(id: string, deadline?: number): Promise + checkpointSessions( + ids: string[], + opts: { final: boolean; teardown: boolean } + ): Promise + withHistorySpawnLock(id: string, operation: () => Promise): Promise + coldRestoreCache: Map + sleepRestoreSessionIds: Set + sessionIncarnations: Map + historyManager: { hasWriter(id: string): boolean } + } + const entered = Promise.withResolvers() + const resume = Promise.withResolvers() + if (pause === 'cwd') { + const actual = inside.readLiveSleepCwd.bind(adapter) + vi.spyOn(inside, 'readLiveSleepCwd').mockImplementationOnce(async (...args) => { + entered.resolve() + await resume.promise + return actual(...args) + }) + } else if (pause === 'checkpoint') { + const actual = inside.checkpointSessions.bind(adapter) + vi.spyOn(inside, 'checkpointSessions').mockImplementationOnce(async (...args) => { + entered.resolve() + await resume.promise + return actual(...args) + }) + } else { + const actual = inside.withHistorySpawnLock.bind(adapter) + vi.spyOn(inside, 'withHistorySpawnLock').mockImplementationOnce(async (key, operation) => { + entered.resolve() + await resume.promise + return actual(key, operation) + }) + } + let untouched = true + const authorizeStop = vi.fn(async () => untouched) + const shutdown = adapter.shutdown(id, { + immediate: true, + keepHistory: true, + expectedIncarnationId: incarnationId, + authorizeStop + }) + const denied = expect(shutdown).rejects.toThrow('terminal_stop_declined') + await entered.promise + expect(authorizeStop).not.toHaveBeenCalled() + untouched = false + resume.resolve() + await denied + expect(subprocess.kill).not.toHaveBeenCalled() + expect(adapter.getActiveSessionIds()).toContain(id) + expect(inside.coldRestoreCache.has(id)).toBe(false) + expect(inside.sleepRestoreSessionIds.has(id)).toBe(false) + expect(inside.historyManager.hasWriter(id)).toBe(true) + // An ordinary Stop does not require the rejected automatic authority. + await adapter.shutdown(id, { immediate: true, keepHistory: true }) + expect(subprocess.forceKill).toHaveBeenCalledOnce() + } finally { + adapter.dispose() + harness.adapter.dispose() + await harness.server.shutdown() + rmSync(harness.dir, { recursive: true, force: true }) + } + } +) diff --git a/src/main/daemon/daemon-pty-session-control.ts b/src/main/daemon/daemon-pty-session-control.ts index d6970fbac0eb..5c3a50124f84 100644 --- a/src/main/daemon/daemon-pty-session-control.ts +++ b/src/main/daemon/daemon-pty-session-control.ts @@ -1,104 +1,30 @@ import { coldRestorePayloadFromInfo, type ColdRestorePayload } from './cold-restore-payload-cache' -import { isUnknownRequestTypeError } from './daemon-endpoint-errors' -import { GET_SIZE_PROTOCOL_VERSION } from './daemon-protocol-version' -import { readDaemonAppliedPtySize, type DaemonAppliedPtySize } from './daemon-pty-applied-size' +import { isPtyFencedTerminationOutcome } from '../../shared/pty-fenced-termination' +import type { DaemonEndpointIdentity } from './daemon-hello-protocol' +import { sameEndpointIdentity } from './daemon-endpoint-incarnation' +import { FENCED_TERMINATION_PROTOCOL_VERSION } from './daemon-protocol-version' import { FinalCheckpointWaitExpiredError } from './daemon-pty-lifecycle-errors' -import { DaemonPtySessionInput } from './daemon-pty-session-input' +import { DaemonPtySessionLiveness } from './daemon-pty-session-liveness' +export { LIVENESS_PROBE_TIMEOUT_MS } from './daemon-pty-session-liveness' import { remainingDaemonRequestTimeoutMs, teardownReadBudgetMs } from './daemon-request-deadline' import type { ColdRestoreInfo } from './history-reader' import { normalizeWslColdRestoreCwd } from './wsl-cold-restore-cwd' import { readDaemonWslSleepCwd } from './daemon-wsl-sleep-cwd' import * as unlistedSession from './daemon-unlisted-session' -import { SessionNotFoundError, type ListSessionsResult } from './types' +import { SessionNotFoundError } from './types' import { resolveSafePtyDefaultCwd } from '../providers/pty-default-cwd' -import type { PtySpawnResult } from '../providers/pty-provider-contract' - -export const LIVENESS_PROBE_TIMEOUT_MS = 2_000 +import type { PtyShutdownOptions } from '../providers/pty-provider-contract' const MAX_TOMBSTONES = 1000 // A busy daemon must not eat the final checkpoint's share of the Sleep deadline. const LIVE_SLEEP_CWD_BUDGET_MS = 1_500 -export abstract class DaemonPtySessionControl extends DaemonPtySessionInput { +export abstract class DaemonPtySessionControl extends DaemonPtySessionLiveness { protected abstract adoptListedSessionForSleep( sessionId: string, deadlineMs?: number ): Promise - async attach(id: string): Promise | void> { - await this.ensureConnected() - if (!this.canDelegateBackgroundToDaemon) { - this.setPtyBackgrounded(id, false) - } - - // Attach at the proven live size; default geometry could resize an agent TUI or accidentally create a shell. - // Preserve transport errors: treating lost contact as absence could duplicate or retire a live owner. - const size = await this.readAppliedSize(id, 'preserve') - if (!size) { - throw new SessionNotFoundError(id) - } - const result = await this.spawn({ - sessionId: id, - cols: size.cols, - rows: size.rows, - attachOnly: true - }) - if (result.exitedBeforeSpawnReply) { - throw new SessionNotFoundError(id) - } - // A restarted runtime has never seen the surviving session's title. - return result.providerSequence || result.lastTitle - ? { - ...(result.providerSequence ? { providerSequence: result.providerSequence } : {}), - ...(result.lastTitle ? { lastTitle: result.lastTitle } : {}) - } - : undefined - } - - hasPty(id: string): boolean { - return this.activeSessionIds.has(id) - } - - /** Use the same saved-history probe as spawn. */ - hasRestorableHistory(id: string): boolean { - return this.historyReader?.hasRestorableHistory(id) ?? false - } - - async probePtyLiveness(id: string): Promise { - try { - if (!this.getSizeUnsupported && this.protocolVersion >= GET_SIZE_PROTOCOL_VERSION) { - try { - const result = await this.client.request<{ size: { cols: number; rows: number } | null }>( - 'getSize', - { sessionId: id }, - LIVENESS_PROBE_TIMEOUT_MS - ) - return result.size !== null - } catch (error) { - // getSize shipped without a protocol bump; remember rejection instead of trusting the version alone. - if (!isUnknownRequestTypeError(error)) { - throw error - } - this.getSizeUnsupported = true - } - } - // Legacy listSessions can prove absence; request it directly to avoid publishing inventory audit observations. - const { sessions } = await this.client.request( - 'listSessions', - undefined, - LIVENESS_PROBE_TIMEOUT_MS - ) - return sessions.some((session) => session.sessionId === id && session.isAlive) - } catch { - return null - } - } - - /** Whether this daemon lists the session at all, alive or not; null when it can't answer. */ - listsSession(id: string): Promise { - return unlistedSession.readDaemonSessionListing(this.client, id, LIVENESS_PROBE_TIMEOUT_MS) - } - /** The daemons that share this history dir and can answer for it; a router widens this. */ private listingDaemons: () => readonly unlistedSession.SessionListingDaemon[] = () => [this] @@ -108,20 +34,21 @@ export abstract class DaemonPtySessionControl extends DaemonPtySessionInput { async shutdown( id: string, - opts: { immediate?: boolean; keepHistory?: boolean; deadlineMs?: number } + opts: PtyShutdownOptions, + endpoint: DaemonEndpointIdentity | null = this.client.getDaemonIdentity() ): Promise { if (opts.keepHistory && this.disconnectOnlyPromise) { throw new Error('Cannot keep history after daemon disconnect has started') } if (!opts.keepHistory) { - await this.withHistorySpawnLock(id, () => this.shutdownWithHistoryLock(id, opts)) + await this.withHistorySpawnLock(id, () => this.shutdownWithHistoryLock(id, opts, endpoint)) return } const shutdown = Promise.resolve().then(async () => { // Outside the spawn lock, which adopting the session's history takes itself. await this.ensureConnected(opts.deadlineMs) await this.adoptListedSessionForSleep(id, opts.deadlineMs).catch(() => {}) - await this.withHistorySpawnLock(id, () => this.shutdownWithHistoryLock(id, opts)) + await this.withHistorySpawnLock(id, () => this.shutdownWithHistoryLock(id, opts, endpoint)) }) this.keepHistoryShutdowns.add(shutdown) try { @@ -133,8 +60,24 @@ export abstract class DaemonPtySessionControl extends DaemonPtySessionInput { protected async shutdownWithHistoryLock( id: string, - opts: { immediate?: boolean; keepHistory?: boolean; deadlineMs?: number } + opts: PtyShutdownOptions, + endpoint: DaemonEndpointIdentity | null = this.client.getDaemonIdentity() ): Promise { + const original = opts.expectedIncarnationId + if ( + opts.authorizeStop && + (!original || + !endpoint || + this.protocolVersion < FENCED_TERMINATION_PROTOCOL_VERSION || + this.sessionIncarnations.get(id) !== original) + ) { + throw new Error('terminal_stop_identity_unavailable') + } + const previousRestore = this.coldRestoreCache.get(id) + const previouslySlept = this.sleepRestoreSessionIds.has(id) + const hadWriter = this.historyManager?.hasWriter(id) + let installedRestore: ColdRestorePayload | null = null + let sleepCommit: (() => void) | undefined // Connect lazily, sharing one deadline with checkpoint waits and kill; durable writes themselves remain unbounded. await this.ensureConnected(opts.deadlineMs) // Sleep may precede the first periodic checkpoint; persist the screen before killing. @@ -186,27 +129,83 @@ export abstract class DaemonPtySessionControl extends DaemonPtySessionInput { } : null const coldRestore = restoreInfo ? this.buildColdRestorePayload(restoreInfo) : null - if (coldRestore) { - this.coldRestoreCache.set(id, coldRestore) - if (this.coldRestoreCache.has(id)) { - this.sleepRestoreSessionIds.add(id) + sleepCommit = () => { + if (coldRestore) { + installedRestore = coldRestore + this.coldRestoreCache.set(id, coldRestore) + if (this.coldRestoreCache.has(id)) { + this.sleepRestoreSessionIds.add(id) + } + // Intentional sleep keeps the final checkpoint authoritative; physical exit must not mark history clean. + this.historyManager?.suspendSession(id) + } else if ( + detection?.status === 'unreadable' || + (detection?.status === 'restored' && detection.hasUnreadableRecovery) + ) { + this.historyManager?.suspendSession(id) } - // Intentional sleep keeps the final checkpoint authoritative; physical exit must not mark history clean. - this.historyManager?.suspendSession(id) - } else if ( - detection?.status === 'unreadable' || - (detection?.status === 'restored' && detection.hasUnreadableRecovery) + } + } + if (opts.authorizeStop) { + if (!(await opts.authorizeStop())) { + throw new Error('terminal_stop_declined') + } + const current = this.client.getDaemonIdentity() + if ( + !current || + !endpoint || + !sameEndpointIdentity(current, endpoint) || + this.sessionIncarnations.get(id) !== original ) { - this.historyManager?.suspendSession(id) + throw new Error('terminal_stop_identity_changed') } } + sleepCommit?.() try { - await this.client.request( + const result = await this.client.request( 'kill', - { sessionId: id, immediate: opts.immediate ?? false }, + { + sessionId: id, + immediate: opts.immediate ?? false, + ...(opts.authorizeStop + ? { + expectedIncarnationId: original, + requireNoAgentOwner: false, + requireUnattached: false + } + : {}) + }, remainingDaemonRequestTimeoutMs(opts.deadlineMs) ) + if ( + opts.authorizeStop && + (!isPtyFencedTerminationOutcome(result) || result.outcome === 'refused') + ) { + throw new Error('terminal_stop_unproven') + } } catch (error) { + if ( + opts.authorizeStop && + (await this.probePtyLiveness(id)) === true && + this.sessionIncarnations.get(id) === original && + endpoint && + this.client.getDaemonIdentity() && + sameEndpointIdentity(this.client.getDaemonIdentity(), endpoint) + ) { + if (installedRestore && this.coldRestoreCache.get(id) === installedRestore) { + if (previousRestore) { + this.coldRestoreCache.set(id, previousRestore) + } else { + this.coldRestoreCache.delete(id) + } + if (!previouslySlept) { + this.sleepRestoreSessionIds.delete(id) + } + } + if (hadWriter) { + this.historyManager?.registerWriter(id) + } + } // Gone is known for a session this adapter lost, or (after a relaunch forgot that) one whose // history is unended and that no daemon sharing the history dir may still run. if ( @@ -327,25 +326,4 @@ export abstract class DaemonPtySessionControl extends DaemonPtySessionInput { async getInitialCwd(id: string): Promise { return this.initialCwds.get(id) ?? '' } - - // Resize notifications can be dropped; report applied dimensions so the renderer can repair drift. - async getAppliedSize(id: string): Promise<{ cols: number; rows: number } | null> { - return await this.readAppliedSize(id, 'suppress') - } - - private async readAppliedSize( - id: string, - failureMode: 'preserve' | 'suppress' - ): Promise { - return await readDaemonAppliedPtySize({ - client: this.client, - protocolVersion: this.protocolVersion, - sessionId: id, - failureMode, - getSizeUnsupported: this.getSizeUnsupported, - markGetSizeUnsupported: () => { - this.getSizeUnsupported = true - } - }) - } } diff --git a/src/main/daemon/daemon-pty-session-liveness.ts b/src/main/daemon/daemon-pty-session-liveness.ts new file mode 100644 index 000000000000..87748d5e794f --- /dev/null +++ b/src/main/daemon/daemon-pty-session-liveness.ts @@ -0,0 +1,106 @@ +import { DaemonPtySessionInput } from './daemon-pty-session-input' +import { isUnknownRequestTypeError } from './daemon-endpoint-errors' +import { GET_SIZE_PROTOCOL_VERSION } from './daemon-protocol-version' +import { readDaemonAppliedPtySize, type DaemonAppliedPtySize } from './daemon-pty-applied-size' +import { SessionNotFoundError, type ListSessionsResult } from './types' +import type { PtySpawnResult } from '../providers/pty-provider-contract' +import * as unlistedSession from './daemon-unlisted-session' + +export const LIVENESS_PROBE_TIMEOUT_MS = 2_000 + +export abstract class DaemonPtySessionLiveness extends DaemonPtySessionInput { + async attach(id: string): Promise | void> { + await this.ensureConnected() + if (!this.canDelegateBackgroundToDaemon) { + this.setPtyBackgrounded(id, false) + } + + // Attach at the proven live size; default geometry could resize an agent TUI or accidentally create a shell. + // Preserve transport errors: treating lost contact as absence could duplicate or retire a live owner. + const size = await this.readAppliedSize(id, 'preserve') + if (!size) { + throw new SessionNotFoundError(id) + } + const result = await this.spawn({ + sessionId: id, + cols: size.cols, + rows: size.rows, + attachOnly: true + }) + if (result.exitedBeforeSpawnReply) { + throw new SessionNotFoundError(id) + } + // A restarted runtime has never seen the surviving session's title. + return result.providerSequence || result.lastTitle + ? { + ...(result.providerSequence ? { providerSequence: result.providerSequence } : {}), + ...(result.lastTitle ? { lastTitle: result.lastTitle } : {}) + } + : undefined + } + + hasPty(id: string): boolean { + return this.activeSessionIds.has(id) + } + + /** Use the same saved-history probe as spawn. */ + hasRestorableHistory(id: string): boolean { + return this.historyReader?.hasRestorableHistory(id) ?? false + } + + async probePtyLiveness(id: string): Promise { + try { + if (!this.getSizeUnsupported && this.protocolVersion >= GET_SIZE_PROTOCOL_VERSION) { + try { + const result = await this.client.request<{ size: { cols: number; rows: number } | null }>( + 'getSize', + { sessionId: id }, + LIVENESS_PROBE_TIMEOUT_MS + ) + return result.size !== null + } catch (error) { + // getSize shipped without a protocol bump; remember rejection instead of trusting the version alone. + if (!isUnknownRequestTypeError(error)) { + throw error + } + this.getSizeUnsupported = true + } + } + // Legacy listSessions can prove absence; request it directly to avoid publishing inventory audit observations. + const { sessions } = await this.client.request( + 'listSessions', + undefined, + LIVENESS_PROBE_TIMEOUT_MS + ) + return sessions.some((session) => session.sessionId === id && session.isAlive) + } catch { + return null + } + } + + /** Whether this daemon lists the session at all, alive or not; null when it can't answer. */ + listsSession(id: string): Promise { + return unlistedSession.readDaemonSessionListing(this.client, id, LIVENESS_PROBE_TIMEOUT_MS) + } + + // Resize notifications can be dropped; report applied dimensions so the renderer can repair drift. + async getAppliedSize(id: string): Promise<{ cols: number; rows: number } | null> { + return await this.readAppliedSize(id, 'suppress') + } + + protected async readAppliedSize( + id: string, + failureMode: 'preserve' | 'suppress' + ): Promise { + return await readDaemonAppliedPtySize({ + client: this.client, + protocolVersion: this.protocolVersion, + sessionId: id, + failureMode, + getSizeUnsupported: this.getSizeUnsupported, + markGetSizeUnsupported: () => { + this.getSizeUnsupported = true + } + }) + } +} diff --git a/src/main/ipc/pty/provider/shutdown-detect.ts b/src/main/ipc/pty/provider/shutdown-detect.ts index b43928355aca..ccb16b1e0216 100644 --- a/src/main/ipc/pty/provider/shutdown-detect.ts +++ b/src/main/ipc/pty/provider/shutdown-detect.ts @@ -1,13 +1,17 @@ +import { cancelDesktopTerminalRetirement } from '../../../automations/desktop-run-terminal-lifecycle' import type { IPtyProvider } from '../../../providers/pty-provider-contract' import { ptyIncarnationById } from './ownership-state' export async function shutdownProviderAndDetectExit( provider: IPtyProvider, id: string, - opts: { immediate?: boolean; keepHistory?: boolean; deadlineMs?: number } + opts: Parameters[1] ): Promise { + if (!opts.authorizeStop) { + cancelDesktopTerminalRetirement(id) + } let providerExitObserved = false - const expectedIncarnationId = ptyIncarnationById.get(id) + const expectedIncarnationId = opts.expectedIncarnationId ?? ptyIncarnationById.get(id) const unsubscribe = provider.onExit((payload) => { if ( payload.id === id && diff --git a/src/main/ipc/pty/runtime/controller-deps.ts b/src/main/ipc/pty/runtime/controller-deps.ts index 667900bf474c..22aac962c711 100644 --- a/src/main/ipc/pty/runtime/controller-deps.ts +++ b/src/main/ipc/pty/runtime/controller-deps.ts @@ -45,7 +45,7 @@ export type PtyRuntimeControllerDeps = PtySpawnCodexResumeDeps & { shutdownProviderAndDetectExit: ( provider: IPtyProvider, id: string, - opts: { immediate?: boolean; keepHistory?: boolean; deadlineMs?: number } + opts: Parameters[1] ) => Promise rememberSyntheticKillExit: (id: string, incarnationId?: string) => void rememberRetiredRejectedPty: (id: string) => void diff --git a/src/main/ipc/pty/runtime/kill.ts b/src/main/ipc/pty/runtime/kill.ts index cc7c39c1f1bb..b3228cf1e44c 100644 --- a/src/main/ipc/pty/runtime/kill.ts +++ b/src/main/ipc/pty/runtime/kill.ts @@ -180,7 +180,10 @@ export function retireRejectedPtyFromRuntimeController( export async function stopAndWaitPtyFromRuntimeController( deps: PtyRuntimeControllerDeps, ptyId: string, - opts?: { keepHistory?: boolean; deadlineMs?: number } + opts?: Pick< + Parameters[1], + 'keepHistory' | 'deadlineMs' | 'expectedIncarnationId' | 'authorizeStop' + > ): Promise { // A final relay stop is owed until the relay proves it, so an unproven one still reads as closing. const relayOwesStop = @@ -200,7 +203,10 @@ export async function stopAndWaitPtyFromRuntimeController( async function stopAndWaitPty( deps: PtyRuntimeControllerDeps, ptyId: string, - opts?: { keepHistory?: boolean; deadlineMs?: number } + opts?: Pick< + Parameters[1], + 'keepHistory' | 'deadlineMs' | 'expectedIncarnationId' | 'authorizeStop' + > ): Promise { const { runtime, @@ -209,7 +215,10 @@ async function stopAndWaitPty( shutdownProviderAndDetectExit, finishPtyShutdown } = deps - runtime?.markPtyStopRequested?.(ptyId) + if (!opts?.authorizeStop) { + runtime?.markPtyStopRequested?.(ptyId) + } + const expectedIncarnationId = opts?.expectedIncarnationId const connectionId = getPtySshConnectionId(ptyId) if (connectionId && isLegacyRelayBridgedPty(ptyId)) { // A reversible stop must not leave the bridge's durable stop behind, so the pane stays live. @@ -264,13 +273,18 @@ async function stopAndWaitPty( } return false } - const stoppingIncarnationId = ptyIncarnationById.get(ptyId) + const stoppingIncarnationId = expectedIncarnationId ?? ptyIncarnationById.get(ptyId) + if (expectedIncarnationId && ptyIncarnationById.get(ptyId) !== expectedIncarnationId) { + return false + } let providerExitObserved = false try { providerExitObserved = await shutdownProviderAndDetectExit(provider, ptyId, { immediate: true, keepHistory: opts?.keepHistory ?? false, - deadlineMs + deadlineMs, + expectedIncarnationId, + authorizeStop: opts?.authorizeStop }) } catch (err) { if (!isPtyAlreadyGoneError(err)) { 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..a44213f4df5c --- /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 canReusePromptProjection( + journal: Partial>, + prior: PromptProjection | undefined, + cursor: Pick, + liveFence: number | null +): prior is PromptProjection { + if ( + prior?.epoch === cursor.epoch && + prior.sequence === cursor.sequence && + prior.fence === liveFence + ) { + return true + } + 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 true + } + } + return false +} 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-current-work.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts index bae602d898fa..566de5fd3827 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 @@ -243,3 +243,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..464854145a20 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 { + canReusePromptProjection, + 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,26 @@ 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 - ) { + if (canReusePromptProjection(this.journal, prior, cursor, this.liveFence)) { return prior.items } + 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 +262,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.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts index bb7b6f88ba41..d650c9d4558f 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 @@ -9,7 +9,6 @@ import { createRestartReconciler } from './structured-agent-session-restart-reco 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' @@ -312,14 +311,14 @@ export class StructuredAgentSessionHost { }) /** 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: StructuredAgentSessionBackgroundTaskChannel['history'] = (...args) => this.backgroundTasks.history(...args) - /** 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() + journalSnapshot = (sessionId: string) => this.backgroundTasks.journalSnapshot(sessionId) + queuedSendAnswer = (sessionId: string, messageId: string) => + this.backgroundTasks.queuedSendAnswer(sessionId, messageId) currentWork = this.clientDelivery.readCurrentWork readCurrentRequests: StructuredAgentSessionBackgroundTaskChannel['currentRequests'] = (...args) => diff --git a/src/main/providers/local-pty-provider.ts b/src/main/providers/local-pty-provider.ts index e8b6c27ec88b..496238b572c7 100644 --- a/src/main/providers/local-pty-provider.ts +++ b/src/main/providers/local-pty-provider.ts @@ -107,7 +107,7 @@ export class LocalPtyProvider implements IPtyProvider { return getLocalPtyAppliedSize(id) } - shutdown(id: string, opts: { immediate?: boolean; keepHistory?: boolean }): Promise { + shutdown(id: string, opts: Parameters[1]): Promise { return shutdownLocalPty(id, opts) } diff --git a/src/main/providers/local-pty-termination.ts b/src/main/providers/local-pty-termination.ts index ddf12a2622b0..b3bda3fd66af 100644 --- a/src/main/providers/local-pty-termination.ts +++ b/src/main/providers/local-pty-termination.ts @@ -1,3 +1,4 @@ +import type { PtyShutdownOptions } from './pty-provider-contract' import type * as pty from 'node-pty' import { PhysicalExitTracker } from '../../shared/physical-exit-tracker' import { killWithDescendantSweep } from '../pty-descendant-termination' @@ -13,6 +14,7 @@ import { ptyForceKillTimers, ptyPhysicalExits, ptyProcesses, + ptyIncarnations, ptyShutdownOperations, ptyTerminationMode, ptyLoadGeneration, @@ -157,9 +159,17 @@ function requestTrackedPtyShutdown(id: string, proc: pty.IPty, immediate: boolea async function shutdownTrackedPty( id: string, proc: pty.IPty, - operation: PtyShutdownOperation + operation: PtyShutdownOperation, + opts: PtyShutdownOptions ): Promise { const physicalExit = ptyPhysicalExits.get(id) + const authorize = opts.authorizeStop + const authorizeStop = authorize + ? async (): Promise => + (await authorize()) && + ptyProcesses.get(id) === proc && + ptyIncarnations.get(id) === opts.expectedIncarnationId + : undefined const signalRoot = (): void => { // Natural exit can race descendant capture; never signal after losing this PTY handle. if (ptyProcesses.get(id) !== proc) { @@ -174,21 +184,28 @@ async function shutdownTrackedPty( // Typed agents also detach tool process groups; immediate close must snapshot before root exit. await killWithDescendantSweep(proc.pid, signalRoot, { ownsRoot: () => ptyProcesses.get(id) === proc, + authorizeStop, terminateOwnedTree: () => terminatePtyJob(proc), terminateDescendants: terminateShutdownDescendants, // Group SIGKILL must wait out the SIGTERM grace so agents can run exit hooks (Claude SessionEnd). awaitEscalation: () => operation.immediate }) } else { + if (authorizeStop && !(await authorizeStop())) { + throw new Error('terminal_stop_declined') + } signalRoot() } await waitForPtyPhysicalExit(id, physicalExit) } -export async function shutdownLocalPty( - id: string, - opts: { immediate?: boolean; keepHistory?: boolean } -): Promise { +export async function shutdownLocalPty(id: string, opts: PtyShutdownOptions): Promise { + if ( + opts.authorizeStop && + (!opts.expectedIncarnationId || ptyIncarnations.get(id) !== opts.expectedIncarnationId) + ) { + throw new Error('terminal_stop_identity_changed') + } cancelPendingLocalPtySpawns(id) const pending = ptyShutdownOperations.get(id) if (pending) { @@ -198,6 +215,12 @@ export async function shutdownLocalPty( requestTrackedPtyShutdown(id, pending.proc, true) } } + if (!opts.authorizeStop && !pending.rootSignalled && ptyProcesses.get(id) === pending.proc) { + pending.rootSignalled = true + requestTrackedPtyShutdown(id, pending.proc, opts.immediate === true) + await waitForPtyPhysicalExit(id, ptyPhysicalExits.get(id)) + return + } await pending.promise return } @@ -211,7 +234,7 @@ export async function shutdownLocalPty( rootSignalled: false, proc } - entry.promise = shutdownTrackedPty(id, proc, entry) + entry.promise = shutdownTrackedPty(id, proc, entry, opts) ptyShutdownOperations.set(id, entry) try { await entry.promise diff --git a/src/main/providers/pty-provider-contract.ts b/src/main/providers/pty-provider-contract.ts index ebf8dd132370..4e116093c91c 100644 --- a/src/main/providers/pty-provider-contract.ts +++ b/src/main/providers/pty-provider-contract.ts @@ -167,18 +167,7 @@ export type IPtyProvider = { supportsForegroundProcessEvidence?(options?: { signal?: AbortSignal }): Promise // Absolute deadlines bound leaf RPCs within the destructive sweep budget; each leaf converts to a relative timeout. - shutdown( - id: string, - opts: { - immediate?: boolean - keepHistory?: boolean - deadlineMs?: number - expectedIncarnationId?: PtyIncarnationId - /** Require the host-attested creator and current authenticated client to match before destructive ownership-based stops. - * Optional/ignored on older hosts; ordinary teardown and unattested revived PTYs may omit it. */ - expectedOwnerClientInstanceId?: string - } - ): Promise + shutdown(id: string, opts: PtyShutdownOptions): Promise sendSignal(id: string, signal: string): Promise getCwd(id: string): Promise getInitialCwd(id: string): Promise @@ -228,3 +217,15 @@ export type IPtyProvider = { }) => void ): () => void } + +export type PtyShutdownOptions = { + immediate?: boolean + keepHistory?: boolean + deadlineMs?: number + expectedIncarnationId?: PtyIncarnationId + /** Require the host-attested creator and current authenticated client to match before destructive ownership-based stops. + * Optional/ignored on older hosts; ordinary teardown and unattested revived PTYs may omit it. */ + expectedOwnerClientInstanceId?: string + /** In-process final veto after provider preparation; never serialized. */ + authorizeStop?: () => Promise +} diff --git a/src/main/pty-descendant-snapshot.ts b/src/main/pty-descendant-snapshot.ts new file mode 100644 index 000000000000..65ba1dc85524 --- /dev/null +++ b/src/main/pty-descendant-snapshot.ts @@ -0,0 +1,40 @@ +import { execFile } from 'node:child_process' +import { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' + +export const DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000 +// Busy hosts can exceed execFile’s 1MB default; truncated output would omit descendants. +const PS_MAX_BUFFER_BYTES = 32 * 1024 * 1024 + +export type ProcessTableCapture = { + rows: ProcessTableRow[] + /** Start boundary of the scan that produced rows, never a later consumer's time. */ + capturedAtMs: number +} + +export type ProcessTableReader = (timeoutMs?: number) => Promise +export function readFreshProcessTable( + timeoutMs = DESCENDANT_SNAPSHOT_TIMEOUT_MS +): Promise { + // Stamp before ps starts so a capture-second PID cannot appear older after a clock rollover. + const capturedAtMs = Date.now() + return new Promise((resolve, reject) => { + execFile( + 'ps', + ['-axo', 'pid=,ppid=,pgid=,tpgid=,lstart='], + { + maxBuffer: PS_MAX_BUFFER_BYTES, + timeout: timeoutMs, + killSignal: 'SIGKILL', + // Pin lstart’s locale so delayed identity checks parse it consistently. + env: { ...process.env, LANG: 'C', LC_ALL: 'C' } + }, + (error, stdout) => { + if (error) { + reject(error) + return + } + resolve({ rows: parseProcessTable(stdout), capturedAtMs }) + } + ) + }) +} diff --git a/src/main/pty-descendant-stop-authorization.test.ts b/src/main/pty-descendant-stop-authorization.test.ts new file mode 100644 index 000000000000..191b2236ae64 --- /dev/null +++ b/src/main/pty-descendant-stop-authorization.test.ts @@ -0,0 +1,45 @@ +import { it, expect, vi } from 'vitest' +import { killWithDescendantSweep } from './pty-descendant-termination' + +it.each(['linux', 'win32'] as const)( + 'runs the last veto after %s process preparation and outside destructive finally', + async (platform) => { + const prepared = Promise.withResolvers() + const release = Promise.withResolvers() + const authorizeStop = vi.fn(async () => false) + const killRoot = vi.fn() + const terminateOwnedTree = vi.fn(() => 'terminated' as const) + const killWindowsTree = vi.fn(async () => {}) + const sendSignal = vi.fn() + const pending = killWithDescendantSweep(4242, killRoot, { + platform, + authorizeStop, + killWindowsTree, + terminateOwnedTree, + sendSignal, + readTable: async () => { + prepared.resolve() + await release.promise + return { + rows: [{ pid: 4242, ppid: 1, pgid: 4242, startedAt: 'Tue Jul 14 12:00:00 2026' }], + capturedAtMs: Date.parse('Tue Jul 14 12:01:00 2026') + } + }, + verifyTreeKillTarget: async () => { + prepared.resolve() + await release.promise + return 'own' + } + }) + const denied = expect(pending).rejects.toThrow('terminal_stop_declined') + await prepared.promise + expect(authorizeStop).not.toHaveBeenCalled() + release.resolve() + await denied + expect(authorizeStop).toHaveBeenCalledOnce() + expect(killRoot).not.toHaveBeenCalled() + expect(terminateOwnedTree).not.toHaveBeenCalled() + expect(killWindowsTree).not.toHaveBeenCalled() + expect(sendSignal).not.toHaveBeenCalled() + } +) diff --git a/src/main/pty-descendant-termination.ts b/src/main/pty-descendant-termination.ts index a46ca7d65894..5b55a7dbb33a 100644 --- a/src/main/pty-descendant-termination.ts +++ b/src/main/pty-descendant-termination.ts @@ -1,18 +1,25 @@ -import { execFile } from 'node:child_process' import type { JobTerminationOutcome } from './windows/windows-pty-job' import { terminateWindowsProcessTree, type WindowsTreeKiller } from './windows-process-tree-kill' import { verifyWindowsTreeKillTarget, type WindowsTreeKillTarget } from './windows-pty-root-identity' -import { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' +import type { ProcessTableRow } from './pty-process-table-parser' +import { + readFreshProcessTable, + DESCENDANT_SNAPSHOT_TIMEOUT_MS, + type ProcessTableCapture, + type ProcessTableReader +} from './pty-descendant-snapshot' export { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' +export { + DESCENDANT_SNAPSHOT_TIMEOUT_MS, + type ProcessTableCapture, + type ProcessTableReader +} from './pty-descendant-snapshot' export const DESCENDANT_KILL_GRACE_MS = 2_000 -export const DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000 -// Busy hosts can exceed execFile’s 1MB default; truncated output would omit descendants. -const PS_MAX_BUFFER_BYTES = 32 * 1024 * 1024 export type PosixProcessIdentity = Pick @@ -28,42 +35,8 @@ export type DescendantSnapshot = { reDerivedPids?: ReadonlySet } -export type ProcessTableCapture = { - rows: ProcessTableRow[] - /** Start boundary of the scan that produced rows, never a later consumer's time. */ - capturedAtMs: number -} - -export type ProcessTableReader = (timeoutMs?: number) => Promise export type SignalSender = (pid: number, signal: NodeJS.Signals) => void -function readFreshProcessTable( - timeoutMs = DESCENDANT_SNAPSHOT_TIMEOUT_MS -): Promise { - // Stamp before ps starts so a capture-second PID cannot appear older after a clock rollover. - const capturedAtMs = Date.now() - return new Promise((resolve, reject) => { - execFile( - 'ps', - ['-axo', 'pid=,ppid=,pgid=,tpgid=,lstart='], - { - maxBuffer: PS_MAX_BUFFER_BYTES, - timeout: timeoutMs, - killSignal: 'SIGKILL', - // Pin lstart’s locale so delayed identity checks parse it consistently. - env: { ...process.env, LANG: 'C', LC_ALL: 'C' } - }, - (error, stdout) => { - if (error) { - reject(error) - return - } - resolve({ rows: parseProcessTable(stdout), capturedAtMs }) - } - ) - }) -} - /** Share only scans not yet started; later requests need fresh identities before signalling. */ export function createProcessTableSnapshotReader( readFresh: ProcessTableReader @@ -124,6 +97,12 @@ export function readProcessTableBeforeDeadline( }) } +type SnapshotDeps = { + readTable?: ProcessTableReader + platform?: NodeJS.Platform + timeoutMs?: number +} + export function collectDescendantRows( rootPid: number, table: ProcessTableRow[], @@ -174,12 +153,6 @@ export function collectDescendantRows( } } -type SnapshotDeps = { - readTable?: ProcessTableReader - platform?: NodeJS.Platform - timeoutMs?: number -} - /** Capture before signalling the root: exited parents’ descendants reparent and become unfindable; failure returns null. */ export async function captureDescendantSnapshot( rootPid: number, @@ -202,6 +175,7 @@ export async function captureDescendantSnapshot( type KillSweepDeps = SnapshotDeps & TerminateDeps & { ownsRoot?: () => boolean + authorizeStop?: () => Promise /** Shutdown can retain the owner until descendant escalation finishes. */ terminateDescendants?: (snapshot: DescendantSnapshot) => void | Promise awaitEscalation?: boolean | (() => boolean) @@ -219,6 +193,13 @@ export async function killWithDescendantSweep( ): Promise { const platform = deps.platform ?? process.platform if (platform === 'win32') { + const verify = deps.verifyTreeKillTarget ?? verifyWindowsTreeKillTarget + const preparedTarget = deps.authorizeStop + ? await verify(rootPid).catch((): WindowsTreeKillTarget => 'unknown') + : null + if (deps.authorizeStop && !(await deps.authorizeStop())) { + throw new Error('terminal_stop_declined') + } try { if ((deps.ownsRoot?.() ?? true) && Number.isInteger(rootPid) && rootPid > 0) { // Owned jobs survive PID reuse and include descendants reparented away from the shell. @@ -227,7 +208,8 @@ export async function killWithDescendantSweep( } // ConPTY closes the shell handle before JS sees exit; require OS identity to reject recycled PIDs. const verify = deps.verifyTreeKillTarget ?? verifyWindowsTreeKillTarget - const target = await verify(rootPid).catch((): WindowsTreeKillTarget => 'unknown') + const target = + preparedTarget ?? (await verify(rootPid).catch((): WindowsTreeKillTarget => 'unknown')) // Re-check ownership: the identity query awaits, so exit can land meanwhile. if (target === 'own' && (deps.ownsRoot?.() ?? true)) { const killTree = @@ -244,6 +226,9 @@ export async function killWithDescendantSweep( } const snapshot = await captureDescendantSnapshot(rootPid, deps) + if (deps.authorizeStop && !(await deps.authorizeStop())) { + throw new Error('terminal_stop_declined') + } let descendants: void | Promise = undefined const awaitEscalation = typeof deps.awaitEscalation === 'function' ? deps.awaitEscalation() : deps.awaitEscalation diff --git a/src/main/runtime/rpc/methods/agent-launch-replay.ts b/src/main/runtime/rpc/methods/agent-launch-replay.ts index ad576489731b..55db3e86f52f 100644 --- a/src/main/runtime/rpc/methods/agent-launch-replay.ts +++ b/src/main/runtime/rpc/methods/agent-launch-replay.ts @@ -101,7 +101,7 @@ function readsUnconfirmedLaunchPrompt( /** Resolve the current handle by durable pane key when PTY incarnation or host re-adoption changed it. * Keep the recorded handle for an unknown pane: shipped clients require one, and an exited terminal is truthful. */ -function withLiveTerminalHandle( +export function withLiveTerminalHandle( recorded: AgentLaunchResult, runtime: Pick ): AgentLaunchResult { diff --git a/src/main/runtime/rpc/methods/agent-launch-surfaces.ts b/src/main/runtime/rpc/methods/agent-launch-surfaces.ts index 6bd1afe945f6..c8d9bc718e99 100644 --- a/src/main/runtime/rpc/methods/agent-launch-surfaces.ts +++ b/src/main/runtime/rpc/methods/agent-launch-surfaces.ts @@ -1,3 +1,4 @@ +import type { AgentLaunchResult } from '../../../../shared/agent-launch-intent' import { terminalImageViewerSupported } from '../../terminal-image-viewer-env' /** Use ordinary user-facing terminal/chat creation; worker factories add redrive, mailbox and background-tab behavior. * The executor selects surface and prompt delivery; this factory supplies the wire-shaped runtime calls. */ @@ -38,6 +39,8 @@ export type AgentLaunchHostPolicy = { terminalTitle?: string suppressStartupUpdatePrompt?: true unprovableHost?: 'write-unless-shell' + onWorkspaceCreated?: (worktreeId: string) => void + onSurfacePublished?: (result: AgentLaunchResult) => void } /** Replay-safe launches keep the nested attach in the same stable caller namespace as the launch. */ @@ -209,7 +212,10 @@ export function agentLaunchSurfaceFactory( return runtime.deliverStartupFollowup( handle, { agent, prompt: prompt.text }, - { agentLaunch: true, ...(signal ? { signal } : {}) } + { + agentLaunch: policy.unprovableHost !== 'write-unless-shell', + ...(signal ? { signal } : {}) + } ) } return deliverTerminalAgentLaunchPrompt({ 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-worktree-creation.ts b/src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts index 7021024c6e9a..23a5432344fa 100644 --- a/src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts +++ b/src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts @@ -100,7 +100,14 @@ export function agentLaunchWorkspaceFactory( createdWithAgent: agent, ...(policy.suppressStartupUpdatePrompt ? { startupSuppressUpdatePrompt: true } : {}), ...(promisedAgentChat ? { promisedAgentChat } : {}), - ...(onWorkspaceCreated ? { onWorkspaceCreated } : {}), + onWorkspaceCreated: (id) => { + try { + policy.onWorkspaceCreated?.(id) + } catch (error) { + console.warn('[agent-launch] workspace bookkeeping failed', error) + } + onWorkspaceCreated?.(id) + }, // Chats have no startup command to sequence after setup; provision setup synchronously and return its completion token. awaitTerminalProvisioning: true, observeSetupCompletion: true diff --git a/src/main/runtime/rpc/methods/agent-launch.test.ts b/src/main/runtime/rpc/methods/agent-launch.test.ts index 88c2718054d9..1901690dfb60 100644 --- a/src/main/runtime/rpc/methods/agent-launch.test.ts +++ b/src/main/runtime/rpc/methods/agent-launch.test.ts @@ -1,6 +1,7 @@ /** Exercise RPC authorization, parsing and all surface factories; structured creates must omit startupAgent while legacy worktree.create retains its terminal contract. */ import { beforeEach, describe, expect, it, vi } from 'vitest' +import { deliverStartupFollowupPrompt } from '../../runtime-worktree-startup-readiness' import { AGENT_LAUNCH_RUNTIME_CAPABILITY } from '../../../../shared/agent-launch-runtime-capability' import type { RpcContext } from '../core' import { @@ -737,3 +738,70 @@ describe('trusted unattended launch policy', () => { ) }) }) + +it.each([ + ['fresh', true, false, true], + ['fresh', false, false, false], + ['fresh', true, true, false], + ['reuse', true, false, true], + ['reuse', false, false, false] +] as const)( + 'uses actual readiness for %s trusted=%s provenShell=%s', + async (mode, trusted, shell, delivered) => { + const runtime = runtimeStub() + const write = vi.fn() + const boundary = { + ...runtime, + waitForFreshWorkerComposer: async () => ({ satisfied: true, status: 'running' as const }), + waitForTerminal: async () => ({ satisfied: true, status: 'idle' as const }), + readLaunchedAgentForeground: async () => (shell ? ('shell' as const) : ('unknown' as const)), + subscribeToTerminalData: () => () => {}, + launchedAgentHostProvesAgent: () => false, + launchedAgentHostProvesShellAlone: () => shell, + sendTerminalAgentPrompt: async ( + _handle: string, + text: string, + opts: { beforeWrite?: (ptyId: string) => Promise } + ) => { + await opts.beforeWrite?.('pty-1') + write(text) + return { handle: 'term_1', accepted: true, bytesWritten: text.length } + } + } + const host = { + getPtyId: () => 'pty-1', + getForegroundProcess: async () => 'kimi', + subscribeToData: () => () => {}, + readRecentOutput: () => undefined, + write + } + // SAFETY: only the OS/read/write boundary is a stand-in; both launch and readiness/guard owners execute. + Object.assign(runtime, boundary, { + deliverStartupFollowup: ( + handle: string, + followup: { agent: 'kimi'; prompt: string }, + opts: { agentLaunch?: boolean } + ) => + deliverStartupFollowupPrompt( + boundary as unknown as Parameters[0], + host, + handle, + followup, + opts + ) + }) + const result = await launchAgentOnHost( + AGENT_LAUNCH.params.parse({ + agent: 'kimi', + surface: 'terminal', + prompt: { text: 'go', delivery: 'submit' }, + target: { kind: 'existing', worktree: 'id:wt-7' }, + ...(mode === 'reuse' ? { reuseTerminal: { handle: 'term_1' } } : {}) + }), + rpcContext(runtime, {}), + trusted ? { unprovableHost: 'write-unless-shell' } : {} + ) + expect(result.prompt?.outcome).toBe(delivered ? 'handed-to-terminal' : 'not-delivered') + expect(write).toHaveBeenCalledTimes(delivered ? 1 : 0) + } +) diff --git a/src/main/runtime/rpc/methods/agent-launch.ts b/src/main/runtime/rpc/methods/agent-launch.ts index 88aa9ca968f1..f260f57f8dd7 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 { AgentLaunchTabClosedError } from '../../../../shared/agent-launch-tab-closed' import { computeAgentLaunchFingerprint } from '../../../../shared/agent-launch-operation' import type { AgentLaunchResult } from '../../../../shared/agent-launch-intent' @@ -43,7 +42,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, @@ -51,15 +53,7 @@ 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' type HostLaunchContext = RpcContext & { agentLaunchPolicy?: AgentLaunchHostPolicy } @@ -95,6 +89,11 @@ async function runAgentLaunch( workspaces: agentLaunchWorkspaceFactory(context, intent.agent, context.agentLaunchPolicy), // 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') { diff --git a/src/main/runtime/runtime-pty-controller-contract.ts b/src/main/runtime/runtime-pty-controller-contract.ts index c9d2a7e6e380..b842ab50cde9 100644 --- a/src/main/runtime/runtime-pty-controller-contract.ts +++ b/src/main/runtime/runtime-pty-controller-contract.ts @@ -21,6 +21,7 @@ import type { ExecutionHostId } from '../../shared/execution-host' import type { PtyProviderBufferSnapshot, PtyProcessInfo, + PtyShutdownOptions, PtySpawnResult } from '../providers/pty-provider-contract' import type { PtyProcessInspection } from '../providers/pty-process-inspection' @@ -144,7 +145,10 @@ export type RuntimePtyController = { retireRejectedPty?(ptyId: string, stopConfirmed: boolean, incarnationId: string | undefined): void stopAndWait?( ptyId: string, - opts?: { keepHistory?: boolean; deadlineMs?: number } + opts?: Pick< + PtyShutdownOptions, + 'keepHistory' | 'deadlineMs' | 'expectedIncarnationId' | 'authorizeStop' + > ): Promise getCwd?(ptyId: string): Promise getForegroundProcess(ptyId: string): Promise diff --git a/src/main/runtime/terminal/stop/worktree-terminal-stop-targets.ts b/src/main/runtime/terminal/stop/worktree-terminal-stop-targets.ts index 50e9d6cfd7b7..ecbbb4a7eda3 100644 --- a/src/main/runtime/terminal/stop/worktree-terminal-stop-targets.ts +++ b/src/main/runtime/terminal/stop/worktree-terminal-stop-targets.ts @@ -1,3 +1,4 @@ +import type { PtyShutdownOptions } from '../../../providers/pty-provider-contract' import { setTimeout as delay } from 'node:timers/promises' import { OrcaRuntimeWithSleepResolvedWorktreeTerminals } from './worktree-terminal-sleep' import { setsEqual } from '../../runtime-worktree-binding-index' @@ -19,7 +20,9 @@ export abstract class OrcaRuntimeWithStopExactTerminalsForWorktree extends OrcaR async stopExactTerminalsForWorktree( worktreeSelector: string, expectedPtyIds: readonly string[], - opts: { keepHistory?: boolean; targetOnly?: boolean } = {} + opts: Pick & { + targetOnly?: boolean + } = {} ): Promise<{ stopped: number stoppedPtyIds: string[] @@ -69,7 +72,11 @@ export abstract class OrcaRuntimeWithStopExactTerminalsForWorktree extends OrcaR : null let stopped = false try { - stopped = await this.ptyController.stopAndWait(ptyId, { keepHistory: opts.keepHistory }) + stopped = await this.ptyController.stopAndWait(ptyId, { + keepHistory: opts.keepHistory, + expectedIncarnationId: opts.expectedIncarnationId, + authorizeStop: opts.authorizeStop + }) } finally { settleStop?.(stopped) } diff --git a/src/main/window/runtime-window-lifecycle.ts b/src/main/window/runtime-window-lifecycle.ts index 942fa1b64b3c..588538ca41cf 100644 --- a/src/main/window/runtime-window-lifecycle.ts +++ b/src/main/window/runtime-window-lifecycle.ts @@ -8,6 +8,7 @@ import type { RuntimeMobileSessionTabMove } from '../../shared/runtime-types' import type { TerminalTabCreateReply } from '../../shared/terminal-reveal-identity' import { runWorktreeChangeInvalidators } from '../ipc/worktree-change-invalidators' import { requestAgentLaunchTabPublishFromRenderer } from './agent-launch-tab-publish-relay' +import type { RuntimeNotifier } from '../runtime/runtime-notifier-contract' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { registerRendererDocumentNavigation } from './renderer-document-navigation' import { createRuntimeRendererNotificationSender } from './runtime-renderer-notification-sender' @@ -117,33 +118,10 @@ export function registerRuntimeWindowLifecycle( }) } ipcMain.on('terminal:tabCreateReply', handler) - const sent = send('ui:createTerminal', { - requestId, - worktreeId, - ptyId: opts.ptyId, - title: opts.title ?? undefined, - ...(opts.cwd ? { cwd: opts.cwd } : {}), - ...(opts.launchConfig ? { launchConfig: opts.launchConfig } : {}), - ...(opts.launchToken ? { launchToken: opts.launchToken } : {}), - ...(opts.launchAgent ? { launchAgent: opts.launchAgent } : {}), - ...(opts.viewMode ? { viewMode: opts.viewMode } : {}), - ...(opts.targetGroupId ? { targetGroupId: opts.targetGroupId } : {}), - ...(opts.afterTabId ? { afterTabId: opts.afterTabId } : {}), - ...(opts.shellOverride ? { shellOverride: opts.shellOverride } : {}), - activate: opts.activate !== false, - ...(opts.presentation ? { presentation: opts.presentation } : {}), - ...(opts.surfaceOwner === false ? { surfaceOwner: false } : {}), - ...(opts.agentLaunchViewer ? { agentLaunchViewer: opts.agentLaunchViewer } : {}), - // Pre-mint tabId to match the PTY paneKey so hook events reach the correct tab. - ...(opts.tabId !== undefined ? { tabId: opts.tabId } : {}), - ...(opts.leafId !== undefined ? { leafId: opts.leafId } : {}), - ...(opts.splitFromLeafId !== undefined ? { splitFromLeafId: opts.splitFromLeafId } : {}), - ...(opts.splitDirection !== undefined ? { splitDirection: opts.splitDirection } : {}), - ...(opts.splitTelemetrySource !== undefined - ? { splitTelemetrySource: opts.splitTelemetrySource } - : {}), - ...(opts.focus !== undefined ? { focus: opts.focus } : {}) - }) + const sent = send( + 'ui:createTerminal', + terminalPresentationRequest(worktreeId, opts, requestId) + ) if (!sent) { clearTimeout(timer) ipcMain.removeListener('terminal:tabCreateReply', handler) @@ -257,3 +235,37 @@ export function registerRuntimeWindowLifecycle( } }) } + +export function terminalPresentationRequest( + worktreeId: string, + opts: Parameters>[1], + requestId?: string +) { + return { + requestId, + worktreeId, + ptyId: opts.ptyId, + title: opts.title ?? undefined, + ...(opts.cwd ? { cwd: opts.cwd } : {}), + ...(opts.launchConfig ? { launchConfig: opts.launchConfig } : {}), + ...(opts.launchToken ? { launchToken: opts.launchToken } : {}), + ...(opts.launchAgent ? { launchAgent: opts.launchAgent } : {}), + ...(opts.viewMode ? { viewMode: opts.viewMode } : {}), + ...(opts.targetGroupId ? { targetGroupId: opts.targetGroupId } : {}), + ...(opts.afterTabId ? { afterTabId: opts.afterTabId } : {}), + ...(opts.shellOverride ? { shellOverride: opts.shellOverride } : {}), + activate: opts.activate !== false, + ...(opts.presentation ? { presentation: opts.presentation } : {}), + ...(opts.surfaceOwner === false ? { surfaceOwner: false } : {}), + ...(opts.agentLaunchViewer ? { agentLaunchViewer: opts.agentLaunchViewer } : {}), + // Pre-mint tabId to match the PTY paneKey so hook events reach the correct tab. + ...(opts.tabId !== undefined ? { tabId: opts.tabId } : {}), + ...(opts.leafId !== undefined ? { leafId: opts.leafId } : {}), + ...(opts.splitFromLeafId !== undefined ? { splitFromLeafId: opts.splitFromLeafId } : {}), + ...(opts.splitDirection !== undefined ? { splitDirection: opts.splitDirection } : {}), + ...(opts.splitTelemetrySource !== undefined + ? { splitTelemetrySource: opts.splitTelemetrySource } + : {}), + ...(opts.focus !== undefined ? { focus: opts.focus } : {}) + } +} diff --git a/src/main/window/terminal-tab-close-request-relay.ts b/src/main/window/terminal-tab-close-request-relay.ts index b3b7d6d7a656..0d652bbdba1b 100644 --- a/src/main/window/terminal-tab-close-request-relay.ts +++ b/src/main/window/terminal-tab-close-request-relay.ts @@ -6,6 +6,10 @@ import type { TerminalTabCloseRequest, TerminalTabCloseResponse } from '../../shared/terminal-tab-close' +import type { + AutomationTerminalLifecycleRequest, + AutomationTerminalLifecycleResponse +} from '../../shared/automation-terminal-lifecycle' import { addFanoutListener, addFanoutListeners } from '../event-listener-fanout' const TERMINAL_TAB_CLOSE_TIMEOUT_MS = 20_000 @@ -15,6 +19,41 @@ export async function requestTerminalTabCloseFromRenderer( tabId: string, options: { localPtyTeardownOwnedExternally?: boolean; force?: boolean } = {} ): Promise { + const requestId = randomUUID() + const request: TerminalTabCloseRequest = { requestId, tabId, ...options } + const response = await requestWindowTransaction( + mainWindow, + 'ui:terminalTabCloseRequest', + 'ui:terminalTabCloseResponse', + request + ) + if (response.error) { + throw new Error(response.error) + } +} + +export function requestAutomationTerminalLifecycle( + window: BrowserWindow, + request: AutomationTerminalLifecycleRequest, + signal: AbortSignal, + valid: () => boolean +): Promise { + return requestWindowTransaction( + window, + 'automations:terminalLifecycleRequest', + 'automations:terminalLifecycleResponse', + request, + { signal, valid } + ) +} + +function requestWindowTransaction( + mainWindow: BrowserWindow, + requestChannel: string, + responseChannel: string, + request: { requestId: string }, + options: { signal?: AbortSignal; valid?: () => boolean } = {} +): Promise { if (mainWindow.isDestroyed()) { throw new Error('renderer_unavailable') } @@ -22,42 +61,44 @@ export async function requestTerminalTabCloseFromRenderer( if (webContents.isDestroyed()) { throw new Error('renderer_unavailable') } - const requestId = randomUUID() - await new Promise((resolve, reject) => { + return new Promise((resolve, reject) => { let settled = false const releaseListeners: (() => void)[] = [] const onRendererUnavailable = (): void => finish(new Error('renderer_unavailable')) - const finish = (error?: Error): void => { + const finish = (error?: Error, response?: T): void => { if (settled) { return } settled = true clearTimeout(timeout) + options.signal?.removeEventListener('abort', onRendererUnavailable) for (const release of releaseListeners) { release() } if (error) { reject(error) } else { - resolve() + resolve(response!) } } const timeout = setTimeout( () => finish(new Error('terminal_tab_close_timeout')), TERMINAL_TAB_CLOSE_TIMEOUT_MS ) - const onResponse = (event: Electron.IpcMainEvent, response: TerminalTabCloseResponse): void => { + const onResponse = (event: Electron.IpcMainEvent, response: T): void => { // Visible request IDs confer no authority; only the selected window may commit/reject its lifecycle transaction. - if (event.sender !== webContents || response.requestId !== requestId) { + if ( + event.sender !== webContents || + !response || + response.requestId !== request.requestId || + (options.valid && (event.senderFrame !== webContents.mainFrame || !options.valid())) + ) { return } - if (response.error) { - finish(new Error(response.error)) - } else { - finish() - } + finish(undefined, response) } - releaseListeners.push(addFanoutListener(ipcMain, 'ui:terminalTabCloseResponse', onResponse)) + + releaseListeners.push(addFanoutListener(ipcMain, responseChannel, onResponse)) // Lean test windows may lack event methods. if (typeof mainWindow.on === 'function') { releaseListeners.push(addFanoutListener(mainWindow, 'closed', onRendererUnavailable)) @@ -67,9 +108,13 @@ export async function requestTerminalTabCloseFromRenderer( addFanoutListeners(webContents, ['destroyed', 'render-process-gone'], onRendererUnavailable) ) } - const request: TerminalTabCloseRequest = { requestId, tabId, ...options } + options.signal?.addEventListener('abort', onRendererUnavailable, { once: true }) + if (options.signal?.aborted || options.valid?.() === false) { + onRendererUnavailable() + return + } try { - webContents.send('ui:terminalTabCloseRequest', request) + webContents.send(requestChannel, request) } catch { finish(new Error('renderer_unavailable')) } diff --git a/src/preload/api/automation-api.ts b/src/preload/api/automation-api.ts index 6d82279bfe22..2a28f3626287 100644 --- a/src/preload/api/automation-api.ts +++ b/src/preload/api/automation-api.ts @@ -1,4 +1,8 @@ import type { ExecutionHostId } from '../../shared/execution-host' +import type { + AutomationTerminalLifecycleRequest, + AutomationTerminalLifecycleResponse +} from '../../shared/automation-terminal-lifecycle' import type { AutomationDispatchRequest, AutomationDispatchResult, @@ -38,6 +42,10 @@ export type AutomationsApi = { displayName: string }) => Promise rendererReady: () => Promise + onTerminalLifecycleRequest: ( + callback: (request: AutomationTerminalLifecycleRequest) => void + ) => () => void + respondTerminalLifecycle: (response: AutomationTerminalLifecycleResponse) => void onDispatchRequested: (callback: (request: AutomationDispatchRequest) => void) => () => void onChanged: (callback: (payload: AutomationsChangedPayload) => void) => () => void } diff --git a/src/preload/api/automations-bridge.ts b/src/preload/api/automations-bridge.ts index 51b90bedb63d..639a5e7cb9e9 100644 --- a/src/preload/api/automations-bridge.ts +++ b/src/preload/api/automations-bridge.ts @@ -1,4 +1,8 @@ import type { ExecutionHostId } from '../../shared/execution-host' +import type { + AutomationTerminalLifecycleRequest, + AutomationTerminalLifecycleResponse +} from '../../shared/automation-terminal-lifecycle' import { ipcRenderer } from 'electron' import type { ExternalAutomationManagerResult, PreloadApi } from '../api-types' import type { @@ -36,6 +40,19 @@ export const automationsApi = { displayName: string }): Promise => ipcRenderer.invoke('automations:snapshotWorkspaceName', args), rendererReady: (): Promise => ipcRenderer.invoke('automations:rendererReady'), + onTerminalLifecycleRequest: ( + callback: (request: AutomationTerminalLifecycleRequest) => void + ): (() => void) => { + const listener = ( + _event: Electron.IpcRendererEvent, + request: AutomationTerminalLifecycleRequest + ) => callback(request) + ipcRenderer.on('automations:terminalLifecycleRequest', listener) + return () => ipcRenderer.removeListener('automations:terminalLifecycleRequest', listener) + }, + respondTerminalLifecycle: (response: AutomationTerminalLifecycleResponse): void => { + ipcRenderer.send('automations:terminalLifecycleResponse', response) + }, onDispatchRequested: (callback: (request: AutomationDispatchRequest) => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent, request: AutomationDispatchRequest) => callback(request) 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 7bd688c526fd..73948da0b5de 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 @@ -213,3 +213,33 @@ it('keeps Run Details output and opens the workspace when the recorded chat is g ) expect(mocks.openChat).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.openChat.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.openChat : mocks.activateWebRuntimeSessionTab + ).toHaveBeenCalledOnce() + ) + expect(mocks.activateAndRevealWorktree).toHaveBeenCalledWith(WT) + } +) diff --git a/src/renderer/src/hooks/ipc-events/terminal-presentation-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/terminal-presentation-ipc-bridge.ts index 4d97e494a02a..1e444097bc5a 100644 --- a/src/renderer/src/hooks/ipc-events/terminal-presentation-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/terminal-presentation-ipc-bridge.ts @@ -1,7 +1,7 @@ -import { presentAgentLaunchTab } from '@/lib/agent-launch-tab-presentation' import { requestBackgroundTerminalWorktreeMount } from '@/components/terminal/background-terminal-worktree-mount' -import { hasRegisteredRuntimeTerminalTab } from '@/runtime/mounted-terminal-tab-registry' -import { planMobileTerminalTabMount } from '@/lib/mobile-terminal-tab-mount' +import { registerTerminalTabMountIpcBridge } from './terminal-tab-mount-ipc-bridge' +import { registerAutomationTerminalLifecycle } from '@/lib/automation-terminal-ownership' +import { presentAgentLaunchTab } from '@/lib/agent-launch-tab-presentation' import { resolveTerminalTabPtyOwnership } from '@/lib/terminal-tab-for-pty-id' import { SPLIT_TERMINAL_PANE_EVENT } from '@/constants/terminal' import type { SplitTerminalPaneDetail } from '@/constants/terminal' @@ -22,6 +22,7 @@ import { } from './terminal-command-state' export function registerTerminalPresentationIpcBridge(unsubs: (() => void)[]): void { + unsubs.push(registerAutomationTerminalLifecycle()) unsubs.push( window.api.ui.onLaunchRecipe(registerLaunchRecipe), window.api.ui.onCreateTerminal( @@ -95,7 +96,19 @@ export function registerTerminalPresentationIpcBridge(unsubs: (() => void)[]): v ownership.kind === 'owned' ? worktreeTabs.find((candidate) => candidate.id === ownership.tabId) : undefined - let reusedTab = existingTab ?? splitTargetTab + const reservedTab = + tabId && leafId && ptyId && !splitFromLeafId + ? worktreeTabs.find((tab) => { + const root = store.terminalLayoutsByTabId[tab.id]?.root + return ( + tab.id === tabId && + tab.ptyId === null && + root?.type === 'leaf' && + root.leafId === leafId + ) + }) + : undefined + let reusedTab = existingTab ?? splitTargetTab ?? reservedTab // Reuse main’s frame-drawn tab even if stale records make legacy ownership ambiguous. const frameDrawnTab = ORCA_LAYOUT_OWNER_IS_MAIN && !reusedTab && tabId !== undefined @@ -282,30 +295,7 @@ export function registerTerminalPresentationIpcBridge(unsubs: (() => void)[]): v ) ) - // Why: background-mount a mobile-subscribed tab's PTY without navigating the desktop (STA-1840). - unsubs.push( - window.api.ui.onRequestTerminalTabMount(({ worktreeId, tabId, ptyId }) => { - if (!worktreeId) { - return - } - // Why: synthetic pty handles need persisted-tab resolution; a miss must not mount every saved tab in a hidden worktree. - const mount = planMobileTerminalTabMount( - useAppStore.getState(), - { - worktreeId, - ...(tabId ? { tabId } : {}), - ...(ptyId ? { ptyId } : {}) - }, - { - isTabMounted: (tabId, targetWorktreeId) => - hasRegisteredRuntimeTerminalTab(tabId, targetWorktreeId) - } - ) - if (mount) { - requestBackgroundTerminalWorktreeMount(mount) - } - }) - ) + unsubs.push(registerTerminalTabMountIpcBridge()) // Why: CLI-driven terminal creation waits for the tabId reply so it can hand the caller a usable handle immediately. } diff --git a/src/renderer/src/hooks/ipc-events/terminal-presentation-pane-title.test.ts b/src/renderer/src/hooks/ipc-events/terminal-presentation-pane-title.test.ts index 2dce478d7f6e..5f1a1433d53f 100644 --- a/src/renderer/src/hooks/ipc-events/terminal-presentation-pane-title.test.ts +++ b/src/renderer/src/hooks/ipc-events/terminal-presentation-pane-title.test.ts @@ -75,7 +75,14 @@ async function setup(windowHoldsTab: boolean) { : vi.fn() } ) - vi.stubGlobal('window', { dispatchEvent: vi.fn(), api: { ...createStoreSessionMockApi(), ui } }) + vi.stubGlobal('window', { + dispatchEvent: vi.fn(), + api: { + ...createStoreSessionMockApi(), + ui, + automations: { onTerminalLifecycleRequest: () => () => {} } + } + }) const store = createTestStore() mocks.store.current = store seedStore(store, { @@ -121,6 +128,7 @@ async function setup(windowHoldsTab: boolean) { title: 'Build', presentation: 'background' }) + await vi.dynamicImportSettled() return store.getState() } diff --git a/src/renderer/src/hooks/ipc-events/terminal-tab-mount-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/terminal-tab-mount-ipc-bridge.ts new file mode 100644 index 000000000000..9961acab4340 --- /dev/null +++ b/src/renderer/src/hooks/ipc-events/terminal-tab-mount-ipc-bridge.ts @@ -0,0 +1,28 @@ +import { requestBackgroundTerminalWorktreeMount } from '@/components/terminal/background-terminal-worktree-mount' +import { hasRegisteredRuntimeTerminalTab } from '@/runtime/mounted-terminal-tab-registry' +import { planMobileTerminalTabMount } from '@/lib/mobile-terminal-tab-mount' +import { useAppStore } from '../../store' + +export function registerTerminalTabMountIpcBridge(): () => void { + return window.api.ui.onRequestTerminalTabMount(({ worktreeId, tabId, ptyId }) => { + if (!worktreeId) { + return + } + // Why: synthetic pty handles need persisted-tab resolution; a miss must not mount every saved tab in a hidden worktree. + const mount = planMobileTerminalTabMount( + useAppStore.getState(), + { + worktreeId, + ...(tabId ? { tabId } : {}), + ...(ptyId ? { ptyId } : {}) + }, + { + isTabMounted: (tabId, targetWorktreeId) => + hasRegisteredRuntimeTerminalTab(tabId, targetWorktreeId) + } + ) + if (mount) { + requestBackgroundTerminalWorktreeMount(mount) + } + }) +} diff --git a/src/renderer/src/lib/adopt-agent-background-session-tab.ts b/src/renderer/src/lib/adopt-agent-background-session-tab.ts deleted file mode 100644 index d3d6d13ebd79..000000000000 --- a/src/renderer/src/lib/adopt-agent-background-session-tab.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { useAppStore } from '@/store' -import { makePaneKey, parsePaneKey, type PaneKey } from '../../../shared/stable-pane-id' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import type { AgentType } from '../../../shared/agent-status-types' -import { bindAutomationTerminal } from '@/lib/automation-terminal-ownership' -import { createBrowserUuid } from '@/lib/browser-uuid' -import { retireProvider, retireUnownedTerminal } from '@/lib/retire-unowned-background-terminal' -import { isTerminalTabPresent } from '@/store/slices/terminal-tab-retirement' -import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' - -type Store = ReturnType -type RegisterArgs = Parameters - -/** Reserves env-stable tab and pane identities before spawning the PTY. */ -export function reserveAgentBackgroundSessionIdentity(args: { - store: Store - agentType: AgentType - worktreeId: string - launchConfig: RegisterArgs[1] - env: Record | undefined -}): { - reservedTabId: string - leafId: string - paneKey: PaneKey - launchToken: string - launchRegistration: NonNullable - paneEnv: Record -} { - const reservedTabId = createBrowserUuid() - const leafId = createBrowserUuid() - const paneKey = makePaneKey(reservedTabId, leafId) - const launchToken = createBrowserUuid() - const launchRegistration = { - agentType: args.agentType, - launchToken, - tabId: reservedTabId, - leafId - } - args.store.registerAgentLaunchConfig(paneKey, args.launchConfig, launchRegistration) - return { - reservedTabId, - leafId, - paneKey, - launchToken, - launchRegistration, - paneEnv: { - ...args.env, - ORCA_PANE_KEY: paneKey, - ORCA_TAB_ID: reservedTabId, - ORCA_WORKTREE_ID: args.worktreeId, - ORCA_AGENT_LAUNCH_TOKEN: launchToken - } - } -} - -export async function adoptAgentBackgroundSessionTab(args: { - store: Store - worktreeId: string - reservedTabId: string - ptyId: string - paneKey: PaneKey - launchConfig: RegisterArgs[1] - launchRegistration: NonNullable - runtimeTarget: RuntimeClientTarget - runtimeTerminalHandle: string | null - onRetire: () => void - title?: string -}): Promise<{ - tab: ReturnType - paneKey: PaneKey - terminalOwnership: ReturnType -} | null> { - const { store, reservedTabId, ptyId, launchRegistration } = args - // The worktree can disappear while its PTY spawn is pending. - if ( - await retireUnownedTerminal({ - owner: { worktreeId: args.worktreeId }, - ptyId, - runtimeTarget: args.runtimeTarget, - runtimeTerminalHandle: args.runtimeTerminalHandle, - onRetire: args.onRetire - }) - ) { - return null - } - // Re-keying would desynchronize env-baked routing identities; fail closed. - if (isTerminalTabPresent(useAppStore.getState(), reservedTabId)) { - store.clearAgentLaunchConfig(args.paneKey) - args.onRetire() - await retireProvider({ - ptyId, - runtimeTarget: args.runtimeTarget, - runtimeTerminalHandle: args.runtimeTerminalHandle - }) - return null - } - const tab = store.createTab(args.worktreeId, undefined, undefined, { - id: reservedTabId, - initialPtyId: ptyId, - activate: false, - recordInteraction: false, - ...(ORCA_LAYOUT_OWNER_IS_MAIN ? { initialLeafId: parsePaneKey(args.paneKey)?.leafId } : {}) - }) - const paneKey = args.paneKey - store.registerAgentLaunchConfig(paneKey, args.launchConfig, launchRegistration) - const terminalOwnership = bindAutomationTerminal( - tab, - paneKey, - ptyId, - args.runtimeTarget.kind, - args.title - ) - return { tab, paneKey, terminalOwnership } -} diff --git a/src/renderer/src/lib/agent-background-session-contract.ts b/src/renderer/src/lib/agent-background-session-contract.ts deleted file mode 100644 index bda9de8eac16..000000000000 --- a/src/renderer/src/lib/agent-background-session-contract.ts +++ /dev/null @@ -1,28 +0,0 @@ -import type { ParsedAgentStatusPayload } from '../../../shared/agent-status-types' -import type { LaunchSource } from '../../../shared/telemetry-events' -import type { TuiAgent } from '../../../shared/tui-agent' -import type { AgentStartupPlan } from '@/lib/tui-agent-startup' -import type { AutomationTerminalOwnership } from '@/lib/automation-terminal-ownership' - -export type LaunchAgentBackgroundSessionArgs = { - agent: TuiAgent - worktreeId: string - prompt?: string - /** An automation's saved extras, merged over this host's default Arguments. */ - extraAgentArgs?: string - launchSource?: LaunchSource - title?: string - onData?: (chunk: string) => void - onExit?: (ptyId: string, code: number) => void - onAgentStatus?: (payload: ParsedAgentStatusPayload) => void -} - -export type LaunchAgentBackgroundSessionResult = { - tabId: string - paneKey: string - ptyId: string - startupPlan: AgentStartupPlan - terminalOwnership: AutomationTerminalOwnership | null - /** Ends a remote runtime's exit wait and data stream; a no-op for local/SSH PTYs. */ - releaseRuntimeObservers: () => void -} diff --git a/src/renderer/src/lib/automation-terminal-ownership.test.ts b/src/renderer/src/lib/automation-terminal-ownership.test.ts index 836582286904..87c0b9e1c058 100644 --- a/src/renderer/src/lib/automation-terminal-ownership.test.ts +++ b/src/renderer/src/lib/automation-terminal-ownership.test.ts @@ -1,273 +1,718 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { AppState } from '@/store/types' +import type { PtyShutdownOptions } from '../../../main/providers/pty-provider-contract' +import type * as ChildProcess from 'node:child_process' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { OrcaRuntimeWithStopExactTerminalsForWorktree } from '../../../main/runtime/terminal/stop/worktree-terminal-stop-targets' +import { AutomationService } from '../../../main/automations/service' +import { + createStore, + closeTestStores, + testState, + readPersistedStateJson +} from '../../../main/persistence/persistence-test-harness' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { EventEmitter } from 'node:events' +import type * as pty from 'node-pty' +import type { OrcaRuntimeService } from '../../../main/runtime/orca-runtime' +import type { Store } from '../../../main/persistence' +import type { ConnectPanePtySession } from '@/components/terminal-pane/pty-connection/connect-pane-pty-session' +import { buildProfileStateCutoverFixture } from '../../../main/persistence/profile-state-cutover-fixture' +import { + createTestStore, + makeTab, + makeWorktree, + seedStore +} from '@/store/slices/store-test-helpers' +import { createStoreSessionMockApi } from '@/store/slices/store-session-test-harness' import { singlePaneLayoutSnapshot } from '@/store/slices/terminal-helpers' -import type { AgentStatusEntry } from '../../../shared/agent-status-types' import { - createAutomationTerminalOwnership, - type AutomationTerminalOwnershipStore -} from './automation-terminal-ownership' - -const WORKTREE_ID = 'worktree-1' -const TAB_ID = 'tab-1' -const LEAF_ID = '7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d' -const PANE_KEY = `${TAB_ID}:${LEAF_ID}` -const PTY_ID = 'pty-1' -const CREATED_AT = 100 + recordTerminalInputActivity, + flushTerminalInputActivity +} from './terminal-input-activity-coalescing' +import { createAutomationTerminalOwnership } from './automation-terminal-ownership' +import { registerTerminalPresentationIpcBridge } from '@/hooks/ipc-events/terminal-presentation-ipc-bridge' +import { registerAgentLaunchTabIpcBridge } from '@/hooks/ipc-events/agent-launch-tab-ipc-bridge' +import { + createDesktopRunTerminalLifecycle, + cancelDesktopTerminalRetirement +} from '../../../main/automations/desktop-run-terminal-lifecycle' +import { + shutdownLocalPty, + createPtyPhysicalExit +} from '../../../main/providers/local-pty-termination' +import { + ptyProcesses, + ptyIncarnations, + ptyPhysicalExits, + ptyShutdownOperations, + clearPtyState +} from '../../../main/providers/local-pty-provider-state' +import { isPtyDataHandlerShutdownPending } from '@/components/terminal-pane/pty-shutdown-data-suspension' +import { installPtyExitHibernate } from '@/components/terminal-pane/pty-connection/pty-exit-hibernate' +import { installSleepingRecordAccess } from '@/components/terminal-pane/pty-connection/sleeping-record-access' -type OwnershipState = Pick< - AppState, - | 'activeWorktreeId' - | 'activeTabId' - | 'activeTabType' - | 'tabsByWorktree' - | 'ptyIdsByTabId' - | 'terminalLayoutsByTabId' - | 'lastTerminalInputAtByPaneKey' - | 'agentStatusByPaneKey' - | 'retainedAgentsByPaneKey' - | 'sleepingAgentSessionsByPaneKey' - | 'agentLaunchConfigByPaneKey' - | 'closeTab' - | 'shutdownCompletedAgentPaneForHibernation' -> +const mocks = vi.hoisted(() => ({ + store: null as ReturnType | null, + ipc: null as EventEmitter | null, + capture: vi.fn(), + prepare: async () => {} +})) +vi.mock('electron', async () => { + const { EventEmitter } = await import('node:events') + mocks.ipc = new EventEmitter() + return { + ipcMain: mocks.ipc, + app: { getPath: () => testState.dir }, + safeStorage: { + isEncryptionAvailable: () => true, + encryptString: (s: string) => Buffer.from(s), + decryptString: (b: Buffer) => b.toString() + } + } +}) +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => mocks.store!.getState(), + setState: (...args: Parameters['setState']>) => + mocks.store!.setState(...args), + subscribe: (...args: Parameters['subscribe']>) => + mocks.store!.subscribe(...args) + } +})) +vi.mock('node:child_process', async (importOriginal) => ({ + ...(await importOriginal()), + execFile: ( + _file: string, + _args: string[], + _opts: unknown, + callback: (error: unknown, output: string) => void + ) => { + void mocks.prepare().then(() => callback(null, '4242 1 4242 -1 Mon Jul 13 12:00:00 2026')) + } +})) +vi.mock('sonner', () => ({ + toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } +})) +vi.mock('@/lib/focus-terminal-tab-surface', () => ({ focusTerminalTabSurface: vi.fn() })) -// A finished Claude turn whose hook reported its conversation id, as a live run leaves it. -const RESUMABLE_DONE_ENTRY: AgentStatusEntry = { - state: 'done', - prompt: 'Reply with pineapple', - updatedAt: 300, - stateStartedAt: 300, - paneKey: PANE_KEY, - worktreeId: WORKTREE_ID, - agentType: 'claude', - providerSession: { key: 'session_id', id: 'c569e233-595e-4085-8660-5af742f81e59' }, - stateHistory: [] -} +const state = buildProfileStateCutoverFixture('/fixture') +const WT = 'repo1::/repo1/main' +const noop = () => {} +const cleanups: (() => void)[] = [] +beforeEach(() => { + vi.clearAllMocks() + mocks.prepare = async () => {} + vi.spyOn(process, 'kill').mockImplementation(() => true) +}) +afterEach(() => { + for (const cleanup of cleanups.splice(0).toReversed()) { + cleanup() + } + for (const id of ptyProcesses.keys()) { + clearPtyState(id) + } + flushTerminalInputActivity() + vi.restoreAllMocks() +}) -function createStore() { - const closeTab = vi.fn() - const shutdownCompletedAgentPaneForHibernation = vi.fn(async () => {}) - let state: OwnershipState = { - activeWorktreeId: 'other-worktree', +function fixture() { + const store = createTestStore() + mocks.store = store + const api = createStoreSessionMockApi() + const listeners = new EventEmitter() + const events: string[] = [] + const web = Object.assign(new EventEmitter(), { + mainFrame: {}, + isDestroyed: () => false, + send: (channel: string, payload: unknown) => { + events.push( + channel === 'automations:terminalLifecycleRequest' && + typeof payload === 'object' && + payload !== null && + 'operation' in payload + ? `${payload.operation}:${'phase' in payload ? payload.phase : ''}` + : channel + ) + listeners.emit(channel, payload) + } + }) + const win = Object.assign(new EventEmitter(), { webContents: web, isDestroyed: () => false }) + const on = (channel: string) => (listener: (...payload: unknown[]) => void) => { + listeners.on(channel, listener) + return () => { + listeners.off(channel, listener) + } + } + const session = { + set: vi.fn(async () => { + events.push('session:set') + }), + flush: vi.fn(async () => { + events.push('session:flush') + }) + } + vi.stubGlobal('window', { + dispatchEvent: vi.fn(), + api: { + ...api, + session, + automations: { + onTerminalLifecycleRequest: on('automations:terminalLifecycleRequest'), + respondTerminalLifecycle: (reply: unknown) => + mocks.ipc!.emit( + 'automations:terminalLifecycleResponse', + { sender: web, senderFrame: web.mainFrame }, + reply + ) + }, + ui: { + onLaunchRecipe: on('recipe'), + onCreateTerminal: on('ui:createTerminal'), + onRequestTerminalTabMount: on('mount'), + onPublishAgentLaunchTab: on('ui:publishAgentLaunchTab'), + onAgentLaunchPaneVerdict: on('verdict'), + replyAgentLaunchTabPublish: vi.fn(), + replyTerminalCreate: vi.fn() + } + } + }) + seedStore(store, { + worktreesByRepo: { repo1: [makeWorktree({ id: WT, repoId: 'repo1', path: '/repo1/main' })] }, + activeWorktreeId: 'other', activeTabId: 'other-tab', - activeTabType: 'terminal' as const, - tabsByWorktree: { - [WORKTREE_ID]: [ - { - id: TAB_ID, - worktreeId: WORKTREE_ID, - ptyId: PTY_ID, - title: 'Automation', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: CREATED_AT + activeTabType: 'terminal', + tabsByWorktree: { [WT]: [makeTab({ id: 'sibling', worktreeId: WT, ptyId: 'setup' })] }, + ptyIdsByTabId: { sibling: ['setup'] } + }) + const unsubs: (() => void)[] = [] + registerTerminalPresentationIpcBridge(unsubs) + registerAgentLaunchTabIpcBridge(unsubs) + cleanups.push(() => unsubs.forEach((release) => release())) + // SAFETY: the sibling has a fake physical process; every exercised stop owner must leave it live. + ptyProcesses.set('setup', { + pid: 4343, + kill: () => { + throw new Error('sibling stopped') + } + } as unknown as pty.IPty) + ptyIncarnations.set('setup', 'setup') + let expectedPty = '' + let expectedPane = '' + let provenance: string | undefined + let stopFailure: 'live' | 'unproven' | null = null + const runtime = { + getAuthoritativeWindow: () => win, + getTerminalPtyIdForHandle: () => expectedPty, + getTerminalHandleForPaneKey: () => 'term-current', + getPtyExecutionHostMetadata: () => ({ incarnationId: 'original', executionHostId: 'local' }), + terminalRunFacts: { readLastDrivingInputAt: () => null }, + stopExactTerminalsForWorktree: vi.fn( + async ( + _selector: string, + ids: string[], + opts: NonNullable[2]> + ) => { + if (stopFailure) { + expect(await opts.authorizeStop!()).toBe(true) + if (stopFailure === 'unproven') { + ptyProcesses.delete(expectedPty) + throw new Error('lost reply') + } + throw new Error('still alive') } - ] - }, - ptyIdsByTabId: { [TAB_ID]: [PTY_ID] }, - terminalLayoutsByTabId: { - [TAB_ID]: singlePaneLayoutSnapshot(LEAF_ID, PTY_ID) - }, - lastTerminalInputAtByPaneKey: {}, - agentStatusByPaneKey: { [PANE_KEY]: RESUMABLE_DONE_ENTRY }, - retainedAgentsByPaneKey: {}, - sleepingAgentSessionsByPaneKey: {}, - agentLaunchConfigByPaneKey: {}, - closeTab, - shutdownCompletedAgentPaneForHibernation + // Actual exact-stop owner proves the target exited while retaining the live sibling. + const inventory = new Map([ + [ids[0], { worktreeId: WT, ptyId: ids[0], connected: true, incarnationId: 'original' }], + ['setup', { worktreeId: WT, ptyId: 'setup', connected: true, incarnationId: 'setup' }] + ]) + const exact = Object.assign( + Object.create(OrcaRuntimeWithStopExactTerminalsForWorktree.prototype), + { + captureReadyGraphEpoch: noop, + assertStableReadyGraph: noop, + resolveWorktreeSelector: async () => ({ id: WT }), + getResolvedWorktreeMap: async () => new Map(), + refreshPtyWorktreeRecordsFromController: async () => + new Set([...ptyProcesses.keys(), 'setup']), + leaves: new Map(), + ptysById: inventory, + intentionalPtyStops: { mark: () => noop }, + ptyController: { + stopAndWait: async (id: string, options: PtyShutdownOptions) => { + events.push('provider:prepare') + await shutdownLocalPty(id, { ...options, immediate: true }) + events.push('provider:stopped') + return true + } + } + } + ) + return exact.stopExactTerminalsForWorktree(_selector, ids, opts) + } + ), + listTerminals: async () => ({ + terminals: [...ptyProcesses.keys()].map((ptyId) => ({ + ptyId, + connected: true, + incarnationId: 'original' + })) + }) } - const listeners = new Set<(state: AppState, previousState: AppState) => void>() - const store: AutomationTerminalOwnershipStore = { - getState: () => state as unknown as AppState, - subscribe: (listener) => { - listeners.add(listener) - return () => listeners.delete(listener) + // SAFETY: transport/window and OS doubles implement the exercised runtime/store boundaries; lifecycle and local stop are real. + const lifecycle = createDesktopRunTerminalLifecycle( + runtime as unknown as OrcaRuntimeService, + { + getWorktreeMeta: () => ({ automationProvenance: { automationRunId: provenance } }), + listAutomationRuns: () => [] + } as unknown as Store, + async (_id, operation) => operation() + ) + cleanups.push(lifecycle.stop) + function publish( + index = 1, + preserve = true, + early = true, + saved?: (typeof state.automationRuns)[number] + ) { + const run = { + ...state.automationRuns[0], + id: `run-${index}`, + ...saved, + workspaceId: WT, + terminalPtyId: `pty-${index}`, + status: 'completed' as const } - } - const update = (patch: Partial): void => { - const previousState = state - state = { ...state, ...patch } - for (const listener of listeners) { - listener(state as unknown as AppState, previousState as unknown as AppState) + provenance = preserve ? run.id : undefined + const owner = lifecycle.begin( + { ...state.automations[0], reuseSession: false }, + run, + `operation-${index}` + )! + expectedPty = run.terminalPtyId + expectedPane = owner.paneKey + const [tabId, leafId] = expectedPane.split(':') + if (early) { + owner.reserve(WT) + } else { + owner.policy.onWorkspaceCreated!(WT) + } + if (early) { + web.send('ui:publishAgentLaunchTab', { + requestId: 'publish', + worktreeId: WT, + tabId, + leafId, + viewer: 'background', + launchAgent: 'codex' + }) } + // SAFETY: node-pty's destructive OS boundary is a fake; exit and exact process maps are the real owner state. + ptyProcesses.set(expectedPty, { + pid: 4242, + kill: () => { + events.push('os:exit') + ptyPhysicalExits.get(run.terminalPtyId)?.markExited() + clearPtyState(run.terminalPtyId) + } + } as unknown as pty.IPty) + ptyIncarnations.set(expectedPty, 'original') + createPtyPhysicalExit(expectedPty) + owner.policy.onSurfacePublished!({ + worktreeId: WT, + outcome: { kind: 'terminal', paneKey: expectedPane, handle: 'term-original' } + } as never) + store + .getState() + .setAgentStatus( + expectedPane, + { state: 'done', prompt: 'resume', agentType: 'codex' }, + 'Codex', + { updatedAt: 2000, stateStartedAt: 1000 }, + { tabId, worktreeId: WT }, + { providerSession: { key: 'session_id', id: `session-${index}` } } + ) + return { run, owner, tabId, leafId, paneKey: expectedPane } } return { - closeTab, - getState: () => state, - shutdownCompletedAgentPaneForHibernation, store, - update + session, + runtime, + lifecycle, + publish, + events, + web, + listeners, + prepare: (fn: () => Promise) => { + mocks.prepare = fn + }, + failStop: (kind: typeof stopFailure) => { + stopFailure = kind + } } } -function own( - store: AutomationTerminalOwnershipStore, - overrides: Partial[0]> = {} -) { - return createAutomationTerminalOwnership({ - store, - worktreeId: WORKTREE_ID, - tabId: TAB_ID, - paneKey: PANE_KEY, - ptyId: PTY_ID, - tabCreatedAt: CREATED_AT, - runtimeKind: 'desktop', - ...overrides +describe('desktop completion through local publication and process owner', () => { + it('composes durable service completion with publication, exact stop and local sleep', async () => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-34332-composition-')) + const disk = await createStore() + try { + disk.addRepo({ ...state.repos[0], id: 'r1', path: '/fixture' }) + const automation = disk.createAutomation({ + name: 'Composition', + prompt: 'check', + agentId: 'codex', + projectId: 'r1', + workspaceMode: 'existing', + workspaceId: WT, + timezone: 'UTC', + rrule: 'FREQ=DAILY', + dtstart: 1 + }) + const saved = disk.createAutomationRun(automation, Date.now(), 'manual') + const f = fixture() + const t = f.publish(1, true, true, saved) + const phases: string[] = [] + const service = new AutomationService(disk, { + onRunFinalized: async (run) => { + phases.push('finalize') + expect(disk.listAutomationRuns()[0]).toMatchObject({ + id: saved.id, + status: 'completed', + terminalPtyId: t.run.terminalPtyId + }) + const persisted = JSON.parse( + readPersistedStateJson(join(testState.dir, 'orca-data.json')) + ) + expect(JSON.stringify(persisted)).toContain('completed') + return f.lifecycle.finalize(run) + }, + codexUsage: { + getAutomationRunUsage: async () => { + phases.push('usage') + expect(disk.listAutomationRuns()[0].terminalPtyId).toBeNull() + return null + } + } as never + }) + expect( + await service.markDispatchResult({ + runId: saved.id, + status: 'completed', + workspaceId: WT, + terminalPtyId: t.run.terminalPtyId, + terminalPaneKey: t.paneKey, + terminalSessionId: t.tabId + }) + ).toMatchObject({ terminalPtyId: null, terminalPaneKey: t.paneKey, status: 'completed' }) + expect(f.store.getState().sleepingAgentSessionsByPaneKey[t.paneKey].origin).toBe( + 'worktree-sleep' + ) + expect([...ptyProcesses.keys()]).toEqual(['setup']) + expect(phases).toEqual(['finalize', 'usage']) + service.stop() + } finally { + await closeTestStores() + rmSync(testState.dir, { recursive: true, force: true }) + } }) -} - -describe('automation terminal ownership', () => { - beforeEach(() => vi.clearAllMocks()) - - it('closes the exact fresh desktop tab once after the PTY exit binding is cleared', async () => { - const { closeTab, store, update } = createStore() - const ownership = own(store) - update({ - ptyIdsByTabId: { [TAB_ID]: [] }, - tabsByWorktree: { - [WORKTREE_ID]: [{ ...store.getState().tabsByWorktree[WORKTREE_ID]![0]!, ptyId: null }] + it.each([true, false])( + 'retires only an untouched original, early publication=%s', + async (early) => { + const f = fixture() + const target = f.publish(1, true, early) + const patch = await f.lifecycle.finalize(target.run) + expect(patch).toMatchObject({ terminalPtyId: null }) + expect(f.events.indexOf('arm:')).toBeLessThan( + f.events.indexOf(early ? 'ui:publishAgentLaunchTab' : 'ui:createTerminal') + ) + expect(f.events.indexOf('session:flush')).toBeLessThan(f.events.indexOf('os:exit')) + expect(f.store.getState().ptyIdsByTabId[target.tabId]).toEqual([]) + expect(f.store.getState().ptyIdsByTabId.sibling).toEqual(['setup']) + expect(f.store.getState().sleepingAgentSessionsByPaneKey[target.paneKey]).toMatchObject({ + origin: 'worktree-sleep', + providerSession: { id: 'session-1' } + }) + expect(f.store.getState().activeWorktreeId).toBe('other') + expect(f.web.eventNames()).toEqual([]) + expect(mocks.ipc!.eventNames()).toEqual([]) + expect(ptyShutdownOperations.size).toBe(0) + expect(isPtyDataHandlerShutdownPending(target.run.terminalPtyId)).toBe(false) + } + ) + it.each([false, true])( + 'ordinary wake consumes the captured pane once, reveal racing exit=%s', + async (racing) => { + const f = fixture() + const t = f.publish() + await f.lifecycle.finalize(t.run) + const visible = { current: racing } + let currentPty: string | null = t.run.terminalPtyId + const transport = { getPtyId: () => currentPty } + // SAFETY: pane rendering and physical resume are the boundaries; actual ordinary exit/sleep-record/wake owners execute. + const session = { + pane: { id: 1, leafId: t.leafId }, + paneStartup: {}, + cacheKey: t.paneKey, + disposed: false, + runtimeEnvironmentId: null, + transport, + manager: { setPaneGpuRendering: noop, getActivePane: () => null }, + deps: { + tabId: t.tabId, + worktreeId: WT, + isVisibleRef: visible, + paneTransportsRef: { current: new Map([[1, transport]]) }, + isPtyShutdownPending: isPtyDataHandlerShutdownPending, + consumeSuppressedPtyExit: (id: string) => f.store.getState().consumeSuppressedPtyExit(id), + clearTabPtyId: (tab: string, id: string) => f.store.getState().clearTabPtyId(tab, id), + clearRuntimePaneTitle: noop, + setCacheTimerStartedAt: noop + }, + resetRendererOrderedSeqForPtyExit: noop, + agentCompletionCoordinator: { dispose: noop }, + dropSideEffectFactConsumer: noop, + releaseHiddenRendererPtyDelivery: noop, + clearPanePtyFitBinding: noop, + clearExitedPanePtyLayoutBinding: noop, + writeInputModeGround: noop + } as unknown as ConnectPanePtySession + installSleepingRecordAccess(session) + installPtyExitHibernate(session) + const resume = vi.fn(async () => { + const record = session.getSleepingRecordForPane(f.store.getState()) + expect(record.record.providerSession.id).toBe('session-1') + session.clearSleepingRecordProviderDuplicates(f.store.getState(), record) + currentPty = 'resumed' + f.store.getState().updateTabPtyId(t.tabId, currentPty) + return currentPty + }) + session.wakeHibernatedAgentPane = resume + // A persisted pre-stop record with a live binding does not itself cause another spawn. + expect(resume).not.toHaveBeenCalled() + session.onExit(t.run.terminalPtyId, 0) + await Promise.resolve() + if (!racing) { + expect(resume).not.toHaveBeenCalled() + visible.current = true + session.consumeHibernatedAgentWake() } + await Promise.resolve() + expect(resume).toHaveBeenCalledOnce() + session.consumeHibernatedAgentWake() + expect(resume).toHaveBeenCalledOnce() + expect(f.store.getState().sleepingAgentSessionsByPaneKey[t.paneKey]).toBeUndefined() + expect(f.store.getState().ptyIdsByTabId.sibling).toEqual(['setup']) + } + ) + it.each(['prepare-persist', 'commit-persist'] as const)( + 'keeps recovery truthful on %s failure', + async (point) => { + const f = fixture() + const t = f.publish() + if (point === 'prepare-persist') { + f.session.flush.mockRejectedValueOnce(new Error('disk unavailable')) + } + if (point === 'commit-persist') { + f.session.flush + .mockResolvedValueOnce(undefined) + .mockRejectedValueOnce(new Error('commit unavailable')) + } + const patch = await f.lifecycle.finalize(t.run) + if (point === 'prepare-persist') { + expect(patch).toBeNull() + expect(f.events).not.toContain('os:exit') + } else { + expect(patch).toMatchObject({ terminalPtyId: null }) + expect(f.store.getState().sleepingAgentSessionsByPaneKey[t.paneKey]).toBeDefined() + } + expect(f.store.getState().tabsByWorktree[WT].some((tab) => tab.id === t.tabId)).toBe(true) + } + ) + it('closes a shared-workspace tab only after exact physical stop', async () => { + const f = fixture() + const t = f.publish(1, false) + f.prepare(async () => + expect(f.store.getState().tabsByWorktree[WT].some((tab) => tab.id === t.tabId)).toBe(true) + ) + expect(await f.lifecycle.finalize(t.run)).toMatchObject({ + terminalPtyId: null, + terminalPaneKey: null, + terminalSessionId: null }) - - expect(await ownership.finalize({ preservePane: false })).toBe('closed') - expect(await ownership.finalize({ preservePane: false })).toBeNull() - expect(closeTab).toHaveBeenCalledTimes(1) - expect(closeTab).toHaveBeenCalledWith(TAB_ID, { - recordInteraction: false, - reason: 'cleanup' - }) + expect(f.store.getState().tabsByWorktree[WT].map((tab) => tab.id)).toEqual(['sibling']) + expect(window.api.pty.kill).not.toHaveBeenCalled() }) - - it('preserves a tab activated after launch even when focus later moves away', async () => { - const { closeTab, store, update } = createStore() - const ownership = own(store) - - update({ activeWorktreeId: WORKTREE_ID, activeTabId: TAB_ID }) - update({ activeWorktreeId: 'other-worktree', activeTabId: 'other-tab' }) - - expect(await ownership.finalize({ preservePane: false })).toBeNull() - expect(closeTab).not.toHaveBeenCalled() - }) - - it('preserves a tab that received user input after launch', async () => { - const { closeTab, store, update } = createStore() - const ownership = own(store) - - update({ lastTerminalInputAtByPaneKey: { [PANE_KEY]: 200 } }) - - expect(await ownership.finalize({ preservePane: false })).toBeNull() - expect(closeTab).not.toHaveBeenCalled() - }) - it.each([ - ['tab PTY', { tabsByWorktree: undefined, ptyIdsByTabId: undefined, layoutPty: undefined }], - [ - 'PTY index', - { tabsByWorktree: null, ptyIdsByTabId: ['pty-replacement'], layoutPty: undefined } - ], - [ - 'pane layout', - { tabsByWorktree: null, ptyIdsByTabId: undefined, layoutPty: 'pty-replacement' } - ] - ])('refuses a replacement identity in the %s binding', async (_label, drift) => { - const { closeTab, getState, store, update } = createStore() - const ownership = own(store) - const tab = getState().tabsByWorktree[WORKTREE_ID]![0]! - update({ - ...(drift.tabsByWorktree === undefined - ? { tabsByWorktree: { [WORKTREE_ID]: [{ ...tab, ptyId: 'pty-replacement' }] } } - : {}), - ...(drift.ptyIdsByTabId ? { ptyIdsByTabId: { [TAB_ID]: drift.ptyIdsByTabId } } : {}), - ...(drift.layoutPty - ? { - terminalLayoutsByTabId: { - [TAB_ID]: { - ...getState().terminalLayoutsByTabId[TAB_ID]!, - ptyIdsByLeafId: { [LEAF_ID]: drift.layoutPty } - } - } + 'view', + 'pending-input', + 'replacement', + 'process', + 'new-record', + 'recreate', + 'move', + 'split', + 'reload', + 'ordinary-stop' + ] as const)('keeps the original on %s during preparation', async (reason) => { + const f = fixture() + const t = f.publish() + f.prepare(async () => { + const s = f.store.getState() + if (reason === 'view') { + f.store.setState({ activeWorktreeId: WT, activeTabId: t.tabId, activeTabType: 'terminal' }) + f.store.setState({ activeWorktreeId: 'other', activeTabId: 'other-tab' }) + } else if (reason === 'pending-input') { + const commit = { insert: () => {}, refreshExisting: () => {} } + f.store.setState({ lastTerminalInputAtByPaneKey: { [t.paneKey]: 100 } }) + recordTerminalInputActivity({ paneKey: t.paneKey, timestamp: 100, commit }) + recordTerminalInputActivity({ paneKey: t.paneKey, timestamp: 101, commit }) + } else if (reason === 'replacement') { + s.updateTabPtyId(t.tabId, 'replacement') + } else if (reason === 'process') { + ptyIncarnations.set(t.run.terminalPtyId, 'replacement') + } else if (reason === 'new-record') { + f.store.setState({ + sleepingAgentSessionsByPaneKey: { + [t.paneKey]: { ...s.sleepingAgentSessionsByPaneKey[t.paneKey], origin: 'live' } } - : {}) - }) - - expect(await ownership.finalize({ preservePane: false })).toBeNull() - expect(closeTab).not.toHaveBeenCalled() - }) - - it('refuses a tab recreated with the same id', async () => { - const { closeTab, getState, store, update } = createStore() - const ownership = own(store) - update({ - tabsByWorktree: { - [WORKTREE_ID]: [ - { ...getState().tabsByWorktree[WORKTREE_ID]![0]!, createdAt: CREATED_AT + 1 } - ] + }) + } else if (reason === 'recreate') { + const original = s.tabsByWorktree[WT].find((tab) => tab.id === t.tabId)! + f.store.setState({ + tabsByWorktree: { [WT]: s.tabsByWorktree[WT].filter((tab) => tab.id !== t.tabId) } + }) + f.store.setState({ tabsByWorktree: { [WT]: [...s.tabsByWorktree[WT]] } }) + expect(original.createdAt).toBeDefined() + } else if (reason === 'move') { + f.store.setState({ tabsByWorktree: { [WT]: [], elsewhere: s.tabsByWorktree[WT] } }) + } else if (reason === 'split') { + s.setTabLayout(t.tabId, { + ...singlePaneLayoutSnapshot(t.leafId, t.run.terminalPtyId), + root: { + type: 'split', + direction: 'horizontal', + first: { type: 'leaf', leafId: t.leafId }, + second: { type: 'leaf', leafId: 'second' } + } + }) + } else if (reason === 'reload') { + f.web.emit('did-start-navigation', {}, 'reload', false, true) + } else { + cancelDesktopTerminalRetirement(t.run.terminalPtyId) } }) - - expect(await ownership.finalize({ preservePane: false })).toBeNull() - expect(closeTab).not.toHaveBeenCalled() - }) - - it.each([ - ['remote runtime', { runtimeKind: 'environment' as const }], - ['remote PTY identity', { ptyId: 'remote:env-1@@terminal-1' }] - ])('never owns a %s terminal', async (_label, overrides) => { - const { closeTab, store } = createStore() - const ownership = own(store, overrides) - - expect(await ownership.finalize({ preservePane: false })).toBeNull() - expect(closeTab).not.toHaveBeenCalled() - }) - - it('sleeps a resumable pane in a workspace the run owns instead of closing it', async () => { - const { closeTab, shutdownCompletedAgentPaneForHibernation, store } = createStore() - const ownership = own(store) - - expect(await ownership.finalize({ preservePane: true })).toBe('hibernated') - expect(shutdownCompletedAgentPaneForHibernation).toHaveBeenCalledExactlyOnceWith(WORKTREE_ID, { - paneKey: PANE_KEY, - tabId: TAB_ID, - leafId: LEAF_ID, - ptyId: PTY_ID - }) - expect(closeTab).not.toHaveBeenCalled() + expect(await f.lifecycle.finalize(t.run)).toBeNull() + expect(f.events).not.toContain('os:exit') + expect(ptyProcesses.has(t.run.terminalPtyId)).toBe(true) + expect(isPtyDataHandlerShutdownPending(t.run.terminalPtyId)).toBe(false) }) - - it.each([ - ['the agent reported no conversation id', { providerSession: undefined }, [PTY_ID]], - ['the run ended by its process exiting', {}, []] - ])('closes the tab when %s', async (_label, entryPatch, livePtyIds) => { - const { closeTab, shutdownCompletedAgentPaneForHibernation, store, update } = createStore() - const ownership = own(store) - update({ - agentStatusByPaneKey: { [PANE_KEY]: { ...RESUMABLE_DONE_ENTRY, ...entryPatch } }, - ptyIdsByTabId: { [TAB_ID]: livePtyIds } - }) - - expect(await ownership.finalize({ preservePane: true })).toBe('closed') - expect(shutdownCompletedAgentPaneForHibernation).not.toHaveBeenCalled() - expect(closeTab).toHaveBeenCalledTimes(1) - }) - - it('keeps the terminal running when its stop fails', async () => { - const { closeTab, shutdownCompletedAgentPaneForHibernation, store } = createStore() - shutdownCompletedAgentPaneForHibernation.mockRejectedValueOnce(new Error('kill failed')) - vi.spyOn(console, 'error').mockImplementation(() => {}) - const ownership = own(store) - - expect(await ownership.finalize({ preservePane: true })).toBeNull() - expect(closeTab).not.toHaveBeenCalled() + it.each(['live', 'unproven'] as const)( + 'preserves truthful recovery after a %s stop failure', + async (proof) => { + const f = fixture() + const t = f.publish() + f.failStop(proof) + expect(await f.lifecycle.finalize(t.run)).toBeNull() + expect(f.store.getState().tabsByWorktree[WT].some((tab) => tab.id === t.tabId)).toBe(true) + expect(f.store.getState().sleepingAgentSessionsByPaneKey[t.paneKey]?.origin).toBe( + proof === 'live' ? 'live' : 'worktree-sleep' + ) + expect(isPtyDataHandlerShutdownPending(t.run.terminalPtyId)).toBe(false) + } + ) + it.each(['view', 'input'] as const)( + 'retains synchronous %s takeover before prompt settlement', + async (kind) => { + const f = fixture() + const t = f.publish() + if (kind === 'view') { + f.store.setState({ activeWorktreeId: WT, activeTabId: t.tabId, activeTabType: 'terminal' }) + f.store.setState({ activeWorktreeId: 'other', activeTabId: 'other-tab' }) + } else { + recordTerminalInputActivity({ + paneKey: t.paneKey, + timestamp: Date.now(), + commit: { + insert: (key, stamp) => + f.store.setState({ lastTerminalInputAtByPaneKey: { [key]: stamp } }), + refreshExisting: noop + } + }) + } + expect(await f.lifecycle.finalize(t.run)).toBeNull() + expect(f.events).not.toContain('os:exit') + expect(ptyProcesses.has(t.run.terminalPtyId)).toBe(true) + } + ) + it.each(['generation', 'frame-loss'] as const)( + 'releases unknown eligibility after %s and ignores a late reply', + async (reason) => { + const f = fixture() + const respond = window.api.automations.respondTerminalLifecycle + let late: Parameters[0] | undefined + window.api.automations.respondTerminalLifecycle = (reply) => { + if (reply.operation !== 'arm') { + return respond(reply) + } + late = reply + if (reason === 'generation') { + respond({ ...reply, serviceGeneration: 'different-service' }) + } else { + mocks.ipc!.emit( + 'automations:terminalLifecycleResponse', + { sender: f.web, senderFrame: {} }, + reply + ) + } + } + const t = f.publish() + if (reason === 'frame-loss') { + f.web.emit('render-process-gone') + } + expect(await f.lifecycle.finalize(t.run)).toBeNull() + if (late) { + respond(late) + } + expect(f.events).not.toContain('os:exit') + expect(mocks.ipc!.eventNames()).toEqual([]) + expect(f.web.eventNames()).toEqual([]) + expect(ptyProcesses.has(t.run.terminalPtyId)).toBe(true) + } + ) + it('never enrolls an already materialized or restarted surface as untouched', () => { + const f = fixture() + const t = f.publish() + const owner = createAutomationTerminalOwnership(f.store, { worktreeId: WT, ...t }) + expect(owner.bind(t.run.terminalPtyId)).toBe(false) + owner.release() + expect( + f.lifecycle.begin({ ...state.automations[0], reuseSession: true }, t.run, 'reuse') + ).toBeNull() }) - - it('release consumes ownership without closing the terminal', async () => { - const { closeTab, store } = createStore() - const ownership = own(store) - - ownership.release() - - expect(await ownership.finalize({ preservePane: false })).toBeNull() - expect(closeTab).not.toHaveBeenCalled() + it.each([5, 50])('bounds repeated cleanup resources at N=%i', async (count) => { + const f = fixture() + for (let n = 1; n <= count; n++) { + const t = f.publish(n, n % 2 === 0, n % 3 === 0) + expect(await f.lifecycle.finalize(t.run)).toMatchObject({ terminalPtyId: null }) + expect([...ptyProcesses.keys()]).toEqual(['setup']) + expect(f.web.eventNames()).toEqual([]) + expect(mocks.ipc!.eventNames()).toEqual([]) + expect(isPtyDataHandlerShutdownPending(t.run.terminalPtyId)).toBe(false) + } + expect(f.store.getState().tabsByWorktree[WT]).toHaveLength(1 + Math.floor(count / 2)) + expect( + Object.values(f.store.getState().sleepingAgentSessionsByPaneKey).filter( + (r) => r.origin === 'worktree-sleep' + ) + ).toHaveLength(Math.floor(count / 2)) + console.info( + JSON.stringify({ + desktopRuns: count, + livePtys: ptyProcesses.size, + shutdowns: ptyShutdownOperations.size, + relayListeners: mocks.ipc!.eventNames().length + }) + ) }) }) diff --git a/src/renderer/src/lib/automation-terminal-ownership.ts b/src/renderer/src/lib/automation-terminal-ownership.ts index 1443312a6358..c507f61e45dc 100644 --- a/src/renderer/src/lib/automation-terminal-ownership.ts +++ b/src/renderer/src/lib/automation-terminal-ownership.ts @@ -1,40 +1,31 @@ +import { + automationTerminalLifecycleResponse, + isCurrentAutomationTerminalRequest +} from '../../../shared/automation-terminal-lifecycle' import { isRemoteRuntimePtyId } from '../../../shared/remote-runtime/remote-runtime-pty-id' +import type { + AutomationTerminalLifecycleOwner, + AutomationTerminalTarget, + AutomationTerminalLifecycleResponse +} from '../../../shared/automation-terminal-lifecycle' import { useAppStore } from '@/store' import type { AppState } from '@/store/types' -import type { TerminalTab } from '../../../shared/terminal-tab-types' import { parsePaneKey } from '../../../shared/stable-pane-id' -import '@/store/slices/agent-status/agent-status' -import { collectSleepingAgentSessionRecordsForWorktree } from '@/store/slices/agent-status/agent-status-recovery-collection' -import { singlePaneLayoutSnapshot } from '@/store/slices/terminal-helpers' +import { mobilePublicationEpoch } from '@/runtime/sync-runtime-graph/graph-state' import { readLastTerminalInputAt } from './terminal-input-activity-coalescing' +import { persistWorkspaceSessionByHost } from './workspace-session-host-persistence' +import { buildWorkspaceSessionPayload } from './workspace-session' +import { closeTerminalTab } from '@/components/terminal/terminal-tab-actions' +import { isUnifiedTabPinned } from '@/store/pinned-tab-close-guard' export type AutomationTerminalOwnershipStore = { getState: () => AppState subscribe: (listener: (state: AppState, previousState: AppState) => void) => () => void } -/** How finalize retired the run's terminal; null when it left the terminal as it was. */ -export type AutomationTerminalRetirement = 'closed' | 'hibernated' | null - -export type AutomationTerminalOwnership = { - /** `preservePane` sleeps a resumable pane in place instead of closing its tab. */ - finalize: (options: { preservePane: boolean }) => Promise - release: () => void -} - -type CreateAutomationTerminalOwnershipArgs = { - store: AutomationTerminalOwnershipStore - worktreeId: string - tabId: string - paneKey: string - ptyId: string - tabCreatedAt: number - runtimeKind: 'desktop' | 'environment' -} - function isOwnedTabIdentityCurrent( state: AppState, - args: Omit + args: AutomationTerminalTarget & { ptyId: string; tabCreatedAt: number } ): boolean { const parsedPane = parsePaneKey(args.paneKey) if (!parsedPane || parsedPane.tabId !== args.tabId) { @@ -76,129 +67,240 @@ function isOwnedTabIdentityCurrent( return layoutPtyId === undefined || layoutPtyId === args.ptyId } -function canHibernateOwnedPane( - state: AppState, - args: Pick -): boolean { - // Why: a run that ended by exiting has no process left to stop in place. - if (!(state.ptyIdsByTabId[args.tabId] ?? []).includes(args.ptyId)) { - return false - } - return Boolean( - collectSleepingAgentSessionRecordsForWorktree(state, args.worktreeId, { - paneKeys: [args.paneKey], - captureMode: 'completed-agent-hibernation' - })[args.paneKey] - ) -} - export function createAutomationTerminalOwnership( - args: CreateAutomationTerminalOwnershipArgs -): AutomationTerminalOwnership { - let consumed = false - let userTookOver = false - // Include coalesced pending keystrokes or a recent user takeover can be missed. - const inputAtLaunch = readLastTerminalInputAt( - args.store.getState().lastTerminalInputAtByPaneKey, - args.paneKey - ) - const observeTakeover = (): void => { - const state = args.store.getState() - if ( - (state.activeWorktreeId === args.worktreeId && - state.activeTabId === args.tabId && - state.activeTabType === 'terminal') || - readLastTerminalInputAt(state.lastTerminalInputAtByPaneKey, args.paneKey) !== inputAtLaunch - ) { - userTookOver = true - } + store: AutomationTerminalOwnershipStore, + target: AutomationTerminalTarget +) { + let taken = false + let lost = false + let materialized = false + let createdAt = 0 + let ptyId: string | null = null + const initial = store.getState() + const input = readLastTerminalInputAt(initial.lastTerminalInputAtByPaneKey, target.paneKey) + let tabs = initial.tabsByWorktree[target.worktreeId] + let layout = initial.terminalLayoutsByTabId[target.tabId] + let ptys = initial.ptyIdsByTabId[target.tabId] + // Enrollment cannot infer the history of a surface that already existed. + if (tabs?.some((tab) => tab.id === target.tabId)) { + lost = true } - const unsubscribe = args.store.subscribe(observeTakeover) - observeTakeover() - - const release = (): void => { - if (consumed) { + const observe = (state: AppState): void => { + taken ||= + (state.activeWorktreeId === target.worktreeId && + state.activeTabId === target.tabId && + state.activeTabType === 'terminal') || + readLastTerminalInputAt(state.lastTerminalInputAtByPaneKey, target.paneKey) !== input + const nextTabs = state.tabsByWorktree[target.worktreeId] + const nextLayout = state.terminalLayoutsByTabId[target.tabId] + const nextPtys = state.ptyIdsByTabId[target.tabId] + if (tabs === nextTabs && layout === nextLayout && ptys === nextPtys) { return } - consumed = true - unsubscribe() + tabs = nextTabs + layout = nextLayout + ptys = nextPtys + const tab = tabs?.find((candidate) => candidate.id === target.tabId) + if (!materialized && tab) { + materialized = true + createdAt = tab.createdAt + } else if (materialized && (!tab || tab.createdAt !== createdAt)) { + lost = true + } + if (ptyId && !isOwnedTabIdentityCurrent(state, { ...target, ptyId, tabCreatedAt: createdAt })) { + lost = true + } + } + const release = store.subscribe(observe) + observe(initial) + const eligible = (): boolean => { + observe(store.getState()) + return ( + !taken && + !lost && + materialized && + ptyId !== null && + isOwnedTabIdentityCurrent(store.getState(), { ...target, ptyId, tabCreatedAt: createdAt }) + ) } - return { release, - finalize: async ({ preservePane }) => { - if (consumed) { - return null - } - // Consume before identity checks: completion and exit can race to retire the same session. - consumed = true - unsubscribe() - observeTakeover() - if (args.runtimeKind !== 'desktop' || isRemoteRuntimePtyId(args.ptyId) || userTookOver) { - return null - } - const state = args.store.getState() - const leafId = parsePaneKey(args.paneKey)?.leafId - if (!leafId || !isOwnedTabIdentityCurrent(state, args)) { - return null - } - if (preservePane && canHibernateOwnedPane(state, args)) { - try { - // Why: sleeping keeps the tab and its resume record, so opening the run resumes it. - await state.shutdownCompletedAgentPaneForHibernation(args.worktreeId, { - paneKey: args.paneKey, - tabId: args.tabId, - leafId, - ptyId: args.ptyId - }) - } catch (error) { - // Failed stop rolls back to a live agent; closing would discard the session it preserved. - console.error('[automations] Failed to hibernate owned automation terminal:', error) - return null - } - return 'hibernated' - } - try { - // Use closeTab’s provider/pane teardown authority rather than adding a second direct-kill path. - state.closeTab(args.tabId, { recordInteraction: false, reason: 'cleanup' }) - } catch (error) { - // A throwing close leaves the terminal live; retain its valid identity and report not-closed. - console.error('[automations] Failed to close owned automation terminal:', error) - return null + eligible, + bind: (original: string): boolean => { + if (ptyId || isRemoteRuntimePtyId(original)) { + return false } - return 'closed' + ptyId = original + return eligible() } } } -export function bindAutomationTerminal( - tab: TerminalTab, - paneKey: string, - ptyId: string, - runtimeKind: 'local' | 'environment', - title?: string -): AutomationTerminalOwnership | null { - const parsedPane = parsePaneKey(paneKey) - if (!parsedPane || parsedPane.tabId !== tab.id) { - throw new Error('Automation terminal pane identity is invalid.') +export function registerAutomationTerminalLifecycle( + store: AutomationTerminalOwnershipStore = useAppStore +): () => void { + const api = window.api.automations + if (!api.onTerminalLifecycleRequest) { + return () => {} + } + const owners = new Map< + string, + AutomationTerminalLifecycleOwner> + >() + const persist = async (): Promise => { + const state = store.getState() + await persistWorkspaceSessionByHost( + window.api.session, + buildWorkspaceSessionPayload(state), + state + ) } - const store = useAppStore.getState() - if (title) { - store.setTabCustomTitle(tab.id, title, { recordInteraction: false }) + const dispose = (id: string): void => { + const owner = owners.get(id) + owners.delete(id) + owner?.ownership.release() + owner?.settle?.(owner.authorized ? 'unproven' : 'live') } - store.updateTabPtyId(tab.id, ptyId) - store.setTabLayout(tab.id, singlePaneLayoutSnapshot(parsedPane.leafId, ptyId)) - const ownership = - runtimeKind === 'local' - ? createAutomationTerminalOwnership({ - store: useAppStore, - worktreeId: tab.worktreeId, - tabId: tab.id, - paneKey, + const release = api.onTerminalLifecycleRequest((request) => { + const respond = (disposition: AutomationTerminalLifecycleResponse['disposition']): void => + api.respondTerminalLifecycle( + automationTerminalLifecycleResponse(request, mobilePublicationEpoch, disposition) + ) + if (request.operation === 'arm') { + if (owners.has(request.registrationId) || request.documentEpoch !== null) { + respond('kept') + return + } + owners.set(request.registrationId, { + request, + target: request.target, + ownership: createAutomationTerminalOwnership(store, request.target), + ptyId: null, + prepared: false, + authorized: false + }) + respond('armed') + return + } + const owner = owners.get(request.registrationId) + if (!isCurrentAutomationTerminalRequest(owner, request, mobilePublicationEpoch)) { + respond('kept') + return + } + if (request.operation === 'release') { + dispose(request.registrationId) + respond('released') + return + } + if (request.operation === 'bind') { + if (owner.ptyId || !owner.ownership.bind(request.ptyId)) { + respond('kept') + return + } + owner.ptyId = request.ptyId + respond('bound') + return + } + if (request.phase === 'authorize') { + const allowed = + owner.prepared && + !owner.authorized && + owner.transactionCurrent?.() === true && + owner.ownership.eligible() + owner.authorized ||= allowed + respond(allowed ? 'authorized' : 'kept') + return + } + if (request.phase === 'stop-settled') { + if (!owner.prepared || !owner.completion || !owner.settle) { + respond('unproven') + return + } + const proof = request.proof === 'stopped' && !owner.authorized ? 'unproven' : request.proof + owner.proof = proof + owner.settle(proof) + void owner.completion.then(respond).finally(() => dispose(request.registrationId)) + return + } + const state = store.getState() + const { target, ptyId } = owner + if (owner.completion || !ptyId || !owner.ownership.eligible()) { + respond('kept') + return + } + let preservePane = request.preservePane + owner.completion = (async () => { + try { + await state.shutdownCompletedAgentPaneForHibernation(target.worktreeId, { + ...target, ptyId, - tabCreatedAt: tab.createdAt, - runtimeKind: 'desktop' + lifecycle: { + preservePane, + stop: async (captured, transactionCurrent) => { + owner.transactionCurrent = transactionCurrent + preservePane = captured + if ( + !preservePane && + isUnifiedTabPinned(store.getState(), target.worktreeId, target.tabId) + ) { + return 'live' + } + await persist() + if (!owner.ownership.eligible() || owners.get(request.registrationId) !== owner) { + return 'live' + } + const settlement = new Promise<'stopped' | 'live' | 'unproven'>((resolve) => { + owner.settle = resolve + }) + owner.prepared = true + respond('prepared') + return settlement + } + } }) - : null - return ownership + if (!preservePane) { + if (!owner.ownership.eligible()) { + return 'stopped-but-uncommitted' + } + let closed = false + closeTerminalTab(target.tabId, { + reason: 'cleanup', + rejectPinned: true, + skipRunningProcessConfirm: true, + localPtyTeardownOwnedExternally: true, + onClosed: () => { + closed = true + } + }) + if (!closed) { + return 'stopped-but-uncommitted' + } + } + await persist() + return preservePane ? 'hibernated' : 'closed' + } catch { + if (!owner.prepared) { + respond('kept') + } + try { + await persist() + } catch { + /* Preserve the captured record on an uncertain commit. */ + } + return owner.proof === 'stopped' + ? 'stopped-but-uncommitted' + : owner.proof === 'live' + ? 'kept-live' + : owner.authorized + ? 'unproven' + : 'kept-live' + } + })() + }) + return () => { + release() + for (const id of owners.keys()) { + dispose(id) + } + } } diff --git a/src/renderer/src/lib/launch-agent-background-session-extra-args.test.ts b/src/renderer/src/lib/launch-agent-background-session-extra-args.test.ts deleted file mode 100644 index 7139347aeeb1..000000000000 --- a/src/renderer/src/lib/launch-agent-background-session-extra-args.test.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { - createAgentBackgroundSessionTestState, - resetAgentBackgroundSessionTestHarness, - useRemoteAgentBackgroundRuntime -} from '@/lib/agent-background-session-test-state' - -const mockSpawn = vi.fn() -const mockKill = vi.fn() -const mockWrite = vi.fn() -const mockRuntimeEnvironmentCall = vi.fn() -const mockRuntimeEnvironmentTransportCall = vi.fn() -const mockRuntimeEnvironmentSubscribe = vi.fn() -const mockCreateTab = vi.fn() -const mockSetTabCustomTitle = vi.fn() -const mockUpdateTabPtyId = vi.fn() -const mockCloseTab = vi.fn() -const mockSetTabLayout = vi.fn() -const mockRegisterAgentLaunchConfig = vi.fn() -const mockRegisterEagerPtyBuffer = vi.fn() -const mockSubscribeToPtyData = vi.fn() -const mockSubscribeToPtyExit = vi.fn() -const mockPasteDraftWhenAgentReady = vi.fn() -const mockDispatchEvent = vi.fn() -const mockGetAgentLaunchPlatformForRepo = vi.fn<() => NodeJS.Platform>() -const state = createAgentBackgroundSessionTestState({ - createTab: mockCreateTab, - setTabCustomTitle: mockSetTabCustomTitle, - updateTabPtyId: mockUpdateTabPtyId, - closeTab: mockCloseTab, - setTabLayout: mockSetTabLayout, - registerAgentLaunchConfig: mockRegisterAgentLaunchConfig -}) -let currentStoreState = state - -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => currentStoreState, - subscribe: vi.fn(() => () => {}) - } -})) - -// Why: the background mount's sleeping-agent scan reads store state these launches never seed. -vi.mock('@/lib/sleeping-agent-wake-requests', () => ({ requestSleepingAgentWakeOnMount: vi.fn() })) - -vi.mock('@/lib/telemetry', () => ({ - track: vi.fn(), - tuiAgentToAgentKind: (agent: string) => agent -})) - -vi.mock('@/lib/agent-paste-draft', () => ({ - pasteDraftWhenAgentReady: mockPasteDraftWhenAgentReady -})) - -vi.mock('@/lib/execution-host-facts', async (importOriginal) => { - const hostFact = () => ({ - kind: 'known' as const, - platform: mockGetAgentLaunchPlatformForRepo(), - hostKind: 'local' as const - }) - return { - ...(await importOriginal>()), - resolveRepoExecutionHostPlatform: hostFact, - resolveWorktreeExecutionHostPlatform: hostFact - } -}) - -vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({ - registerEagerPtyBuffer: mockRegisterEagerPtyBuffer, - subscribeToPtyExit: mockSubscribeToPtyExit -})) - -vi.mock('@/components/terminal-pane/pty-data-sidecar-subscriptions', () => ({ - subscribeToPtyData: mockSubscribeToPtyData -})) - -describe('launchAgentBackgroundSession with automation extras', () => { - beforeEach(() => { - currentStoreState = state - resetAgentBackgroundSessionTestHarness({ - state, - createTab: mockCreateTab, - closeTab: mockCloseTab, - getLaunchPlatform: mockGetAgentLaunchPlatformForRepo, - runtimeCall: mockRuntimeEnvironmentCall, - runtimeTransportCall: mockRuntimeEnvironmentTransportCall, - runtimeSubscribe: mockRuntimeEnvironmentSubscribe, - subscribeToData: mockSubscribeToPtyData, - subscribeToExit: mockSubscribeToPtyExit, - setTabLayout: mockSetTabLayout, - updateTabPtyId: mockUpdateTabPtyId, - dispatchEvent: mockDispatchEvent, - kill: mockKill, - spawn: mockSpawn, - write: mockWrite - }) - }) - - it('merges extras over the default arguments, before the prompt', async () => { - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - mockSpawn.mockResolvedValue({ id: 'pty-1' }) - - await launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run the automation', - extraAgentArgs: '--model opus --add-dir "my docs"' - }) - - expect(mockSpawn.mock.calls[0]?.[0]).toMatchObject({ - command: - "claude '--dangerously-skip-permissions' '--model' 'opus' '--add-dir' 'my docs' 'run the automation'", - launchConfig: { - agentArgs: "'--dangerously-skip-permissions' '--model' 'opus' '--add-dir' 'my docs'" - } - }) - }) - - it('fails before reserving a tab or spawning when the extras are refused', async () => { - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await expect( - launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run the automation', - extraAgentArgs: '--permission-mode bypassPermissions' - }) - ).rejects.toThrow('"--permission-mode"') - expect(mockSpawn).not.toHaveBeenCalled() - expect(mockCreateTab).not.toHaveBeenCalled() - expect(mockRegisterAgentLaunchConfig).not.toHaveBeenCalled() - }) - - it('refuses a client-side launch that would drop extras on a paired server', async () => { - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - useRemoteAgentBackgroundRuntime(state) - - await expect( - launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run the automation', - extraAgentArgs: '--model opus' - }) - ).rejects.toThrow("Extra arguments can't be applied to a paired server's workspace from here.") - expect(mockRuntimeEnvironmentCall).not.toHaveBeenCalled() - expect(mockSpawn).not.toHaveBeenCalled() - expect(mockRegisterAgentLaunchConfig).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/lib/launch-agent-background-session-launch-parity.test.ts b/src/renderer/src/lib/launch-agent-background-session-launch-parity.test.ts deleted file mode 100644 index d181c3347beb..000000000000 --- a/src/renderer/src/lib/launch-agent-background-session-launch-parity.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -import type * as TransportFixtureModule from '@/runtime/layout-apply-test-transport.test-fixture' -import { - launchWorkspaceState, - perClientLoader, - type LaunchStoreHolder -} from '@/lib/launch-parity-renderer.test-fixture' -import { getDefaultSettings } from '../../../shared/constants' -import { - AUTOMATION_LAUNCH_CASES, - AUTOMATION_PROMPT, - automationPhoneTab, - automationSpawnRequest, - type AutomationLaunchCase -} from '../../../shared/launch-parity-automation-cases.test-fixture' -import { - LAUNCH_LEAF_ID, - LAUNCH_TAB_ID, - LAUNCH_TOKEN, - launchWorkspaceId -} from '../../../shared/launch-parity-window-request.test-fixture' - -// Keep main’s mocked layout transport outside module resets so each rebuilt client still reaches it. -type TransportFixture = typeof TransportFixtureModule -const main = vi.hoisted((): { transport: TransportFixture['layoutApplyTestTransport'] | null } => ({ - transport: null -})) -vi.mock('@/runtime/runtime-rpc-client', async (importOriginal) => { - const fixture = await import('@/runtime/layout-apply-test-transport.test-fixture') - main.transport = fixture.layoutApplyTestTransport - return fixture.runtimeRpcClientWithLayoutApply(await importOriginal()) -}) - -const holder = vi.hoisted((): LaunchStoreHolder => ({ store: null })) -vi.mock('@/store', async () => - (await import('@/lib/launch-parity-renderer.test-fixture')).launchStoreModuleMock(holder) -) -// The stdin-after-start paste is pinned by launch-agent-background-session.test.ts. -vi.mock('@/lib/agent-paste-draft', () => ({ pasteDraftWhenAgentReady: vi.fn() })) -vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({ - registerEagerPtyBuffer: vi.fn(), - subscribeToPtyExit: vi.fn(() => () => {}) -})) -vi.mock('@/components/terminal-pane/pty-data-sidecar-subscriptions', () => ({ - subscribeToPtyData: vi.fn(() => () => {}) -})) - -const load = perClientLoader(async () => ({ - launch: await import('./launch-agent-background-session'), - phone: await import('@/runtime/sync-runtime-graph/mobile-session-snapshots'), - switch: await import('../../../shared/layout-owner-switch') -})) - -async function runAutomation(c: AutomationLaunchCase) { - const modules = await load(c.client) - const store = modules.createStore() - holder.store = store - store.setState( - launchWorkspaceState(c.workspace, { ...getDefaultSettings('/home/alice'), ...c.settings }) - ) - const spawn = vi.fn(async (_request: Record) => ({ id: 'pty-1' })) - vi.stubGlobal('window', { - dispatchEvent: vi.fn(), - api: { pty: { spawn, write: vi.fn(), kill: vi.fn() }, runtime: { call: vi.fn() } } - }) - await modules.launch.launchAgentBackgroundSession({ - agent: c.agent, - worktreeId: launchWorkspaceId(c.workspace), - prompt: AUTOMATION_PROMPT, - launchSource: 'unknown', - title: c.title - }) - const phone = modules.phone.buildMobileSessionTabSnapshots(store.getState(), false) - if (modules.switch.ORCA_LAYOUT_OWNER_IS_MAIN) { - const tabBarId = store.getState().unifiedTabsByWorktree[launchWorkspaceId(c.workspace)]![0]!.id - expect(main.transport?.sentOfType('renameTab').at(-1)).toEqual( - expect.objectContaining({ tabId: tabBarId, kind: 'custom', title: c.title }) - ) - for (const snapshot of phone) { - snapshot.tabs = snapshot.tabs.map((tab) => ({ ...tab, title: c.title })) - } - } - return { spawn, phone } -} - -function withFixedIds(value: unknown): unknown { - const text = JSON.stringify(value) - const ids = [ - ...new Set(text.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g)) - ] - const fixed = [LAUNCH_TAB_ID, LAUNCH_LEAF_ID, LAUNCH_TOKEN] - return JSON.parse(ids.reduce((out, id, index) => out.replaceAll(id, fixed[index] ?? id), text)) -} - -// Pin automation pty:spawn and mobile-tab behavior as the convergence baseline before C7 replaces this producer. -describe('row 5: desktop automation pty:spawn request', () => { - beforeAll(async () => { - await load('darwin') - await load('linux') - await load('win32') - }, 240_000) - afterEach(() => vi.unstubAllGlobals()) - - it.each(AUTOMATION_LAUNCH_CASES)('$name', async (c) => { - const { spawn, phone } = await runAutomation(c) - expect(withFixedIds(spawn.mock.calls[0]?.[0])).toEqual(automationSpawnRequest(c)) - expect( - phone.map(({ tabs }) => - tabs.map((tab) => ({ - title: tab.title, - launchAgent: recordOf(tab).launchAgent, - isActive: tab.isActive - })) - ) - ).toEqual([[automationPhoneTab(c)]]) - }) -}) - -function recordOf(value: unknown): Record { - return value && typeof value === 'object' ? { ...value } : {} -} diff --git a/src/renderer/src/lib/launch-agent-background-session-remote.test.ts b/src/renderer/src/lib/launch-agent-background-session-remote.test.ts deleted file mode 100644 index 27f4339f3499..000000000000 --- a/src/renderer/src/lib/launch-agent-background-session-remote.test.ts +++ /dev/null @@ -1,487 +0,0 @@ -import { createCompatibleRuntimeStatusResponseIfNeeded } from '@/runtime/runtime-compatibility-test-fixture' -import { AGENT_SESSION_KEYBOARD_RUNTIME_CAPABILITY } from '../../../shared/protocol-version' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { - AGENT_BACKGROUND_SESSION_UUID_RE as UUID_RE, - createAgentBackgroundSessionTestState, - resetAgentBackgroundSessionTestHarness, - useRemoteAgentBackgroundRuntime -} from '@/lib/agent-background-session-test-state' - -const mockSpawn = vi.fn() -const mockKill = vi.fn() -const mockWrite = vi.fn() -const mockRuntimeEnvironmentCall = vi.fn() -const mockRuntimeEnvironmentTransportCall = vi.fn() -const mockRuntimeEnvironmentSubscribe = vi.fn() -const mockCreateTab = vi.fn() -const mockSetTabCustomTitle = vi.fn() -const mockUpdateTabPtyId = vi.fn() -const mockCloseTab = vi.fn() -const mockSetTabLayout = vi.fn() -const mockRegisterAgentLaunchConfig = vi.fn() -const mockRegisterEagerPtyBuffer = vi.fn() -const mockSubscribeToPtyData = vi.fn() -const mockSubscribeToPtyExit = vi.fn() -const mockPasteDraftWhenAgentReady = vi.fn() -const mockDispatchEvent = vi.fn() -const mockGetAgentLaunchPlatformForRepo = vi.fn<() => NodeJS.Platform>() -const state = createAgentBackgroundSessionTestState({ - createTab: mockCreateTab, - setTabCustomTitle: mockSetTabCustomTitle, - updateTabPtyId: mockUpdateTabPtyId, - closeTab: mockCloseTab, - setTabLayout: mockSetTabLayout, - registerAgentLaunchConfig: mockRegisterAgentLaunchConfig -}) - -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => state, - subscribe: vi.fn(() => () => {}) - } -})) - -// Why: the background mount's sleeping-agent scan reads store state these launches never seed. -vi.mock('@/lib/sleeping-agent-wake-requests', () => ({ requestSleepingAgentWakeOnMount: vi.fn() })) - -vi.mock('@/lib/telemetry', () => ({ - track: vi.fn(), - tuiAgentToAgentKind: (agent: string) => agent -})) - -vi.mock('@/lib/agent-paste-draft', () => ({ - pasteDraftWhenAgentReady: mockPasteDraftWhenAgentReady -})) - -vi.mock('@/lib/execution-host-facts', async (importOriginal) => { - const hostFact = () => ({ - kind: 'known' as const, - platform: mockGetAgentLaunchPlatformForRepo(), - hostKind: 'local' as const - }) - return { - ...(await importOriginal>()), - resolveRepoExecutionHostPlatform: hostFact, - resolveWorktreeExecutionHostPlatform: hostFact - } -}) - -vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({ - registerEagerPtyBuffer: mockRegisterEagerPtyBuffer, - subscribeToPtyExit: mockSubscribeToPtyExit -})) - -vi.mock('@/components/terminal-pane/pty-data-sidecar-subscriptions', () => ({ - subscribeToPtyData: mockSubscribeToPtyData -})) - -describe('launchAgentBackgroundSession remote runtime and SSH startup delivery', () => { - beforeEach(() => { - resetAgentBackgroundSessionTestHarness({ - state, - createTab: mockCreateTab, - closeTab: mockCloseTab, - getLaunchPlatform: mockGetAgentLaunchPlatformForRepo, - runtimeCall: mockRuntimeEnvironmentCall, - runtimeTransportCall: mockRuntimeEnvironmentTransportCall, - runtimeSubscribe: mockRuntimeEnvironmentSubscribe, - subscribeToData: mockSubscribeToPtyData, - subscribeToExit: mockSubscribeToPtyExit, - setTabLayout: mockSetTabLayout, - updateTabPtyId: mockUpdateTabPtyId, - dispatchEvent: mockDispatchEvent, - kill: mockKill, - spawn: mockSpawn, - write: mockWrite - }) - }) - - it('closes a runtime terminal when its worktree disappears before creation resolves', async () => { - useRemoteAgentBackgroundRuntime(state) - let resolveCreate!: (result: { - ok: true - result: { terminal: { handle: string; worktreeId: string; title: null } } - }) => void - const createResult = new Promise<{ - ok: true - result: { terminal: { handle: string; worktreeId: string; title: null } } - }>((resolve) => { - resolveCreate = resolve - }) - mockRuntimeEnvironmentCall.mockImplementation((args: { method: string }) => { - if (args.method === 'terminal.createAgentSession') { - return createResult - } - return Promise.resolve({ ok: true, result: {} }) - }) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - const launch = launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run remotely' - }) - await vi.waitFor(() => - expect(mockRuntimeEnvironmentCall).toHaveBeenCalledWith( - expect.objectContaining({ method: 'terminal.createAgentSession' }) - ) - ) - state.worktreesByRepo['repo-1'] = [] - resolveCreate({ - ok: true, - result: { terminal: { handle: 'terminal-after-close', worktreeId: 'wt-1', title: null } } - }) - - await expect(launch).resolves.toBeNull() - expect(mockRuntimeEnvironmentCall).toHaveBeenCalledWith( - expect.objectContaining({ - method: 'terminal.close', - params: { terminal: 'terminal-after-close' } - }) - ) - expect(mockCreateTab).not.toHaveBeenCalled() - expect(mockUpdateTabPtyId).not.toHaveBeenCalled() - expect(mockRuntimeEnvironmentSubscribe).not.toHaveBeenCalled() - expect(mockDispatchEvent).not.toHaveBeenCalled() - }) - - it('forwards Hermes startup queries through SSH command transport', async () => { - state.repos = [{ id: 'repo-1', connectionId: 'ssh-1', path: '/repo' }] - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent: 'hermes', - worktreeId: 'wt-1', - prompt: 'remote automation prompt' - }) - - expect(mockSpawn).toHaveBeenCalledWith( - expect.objectContaining({ - command: expect.stringContaining('ORCA_HERMES_STARTUP_QUERY'), - connectionId: 'ssh-1', - env: expect.objectContaining({ ORCA_HERMES_STARTUP_QUERY: 'remote automation prompt' }) - }) - ) - }) - - it.each(['claude', 'codex'] as const)( - 'has the relay type the %s launch line instead of writing it from the renderer', - async (agent) => { - vi.useFakeTimers() - try { - state.repos = [{ id: 'repo-1', connectionId: 'ssh-1', path: '/repo' }] - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent, - worktreeId: 'wt-1', - prompt: 'run the automation' - }) - - expect(mockSpawn.mock.calls[0]?.[0]).toEqual( - expect.objectContaining({ - command: expect.stringContaining("'run the automation'"), - connectionId: 'ssh-1', - commandDelivery: 'provider', - startupCommandDelivery: 'shell-ready' - }) - ) - const dataSidecar = mockSubscribeToPtyData.mock.calls[0]?.[1] as (data: string) => void - dataSidecar('\x1b]777;orca-shell-ready\x07user@remote repo % ') - vi.advanceTimersByTime(20_000) - expect(mockWrite).not.toHaveBeenCalled() - } finally { - vi.useRealTimers() - } - } - ) - - it('has the relay type a promptless SSH background launch too', async () => { - state.repos = [{ id: 'repo-1', connectionId: 'ssh-1', path: '/repo' }] - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ agent: 'codex', worktreeId: 'wt-1' }) - - expect(mockSpawn.mock.calls[0]?.[0]).toEqual( - expect.objectContaining({ - commandDelivery: 'provider', - startupCommandDelivery: 'shell-ready' - }) - ) - }) - - it.each([true, false])( - 'creates background sessions with negotiated keyboard support: %s', - async (keyboardSupported) => { - useRemoteAgentBackgroundRuntime(state) - mockRuntimeEnvironmentTransportCall.mockImplementation((request: { method: string }) => { - const status = createCompatibleRuntimeStatusResponseIfNeeded(request) - if (status?.ok) { - return Promise.resolve({ - ...status, - result: { - ...status.result, - capabilities: status.result.capabilities?.filter( - (capability) => - keyboardSupported || capability !== AGENT_SESSION_KEYBOARD_RUNTIME_CAPABILITY - ) - } - }) - } - return mockRuntimeEnvironmentCall(request) - }) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - const result = await launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run the automation' - }) - - expect(mockSpawn).not.toHaveBeenCalled() - const params = mockRuntimeEnvironmentCall.mock.calls[0]?.[0]?.params - if (keyboardSupported) { - expect(params).toHaveProperty('terminalKittyKeyboardProtocol', true) - } else { - expect(params).not.toHaveProperty('terminalKittyKeyboardProtocol') - } - const leafId = params?.placement?.leafId - const tabId = params?.placement?.tabId - expect(leafId).toMatch(UUID_RE) - expect(tabId).toMatch(UUID_RE) - // Why: background launches have no explicit recipe override, so remote host settings win. - expect(params).not.toHaveProperty('agentArgs') - expect(mockRegisterAgentLaunchConfig).toHaveBeenCalledWith( - `${tabId}:${leafId}`, - { - agentCommand: "claude '--dangerously-skip-permissions'", - agentArgs: '--dangerously-skip-permissions', - agentEnv: {} - }, - { - agentType: 'claude', - launchToken: expect.stringMatching(UUID_RE), - tabId, - leafId - } - ) - expect(mockSetTabLayout).toHaveBeenCalledWith( - tabId, - expect.objectContaining({ - root: { type: 'leaf', leafId }, - activeLeafId: leafId, - ptyIdsByLeafId: { [leafId]: 'remote:env-1@@terminal-1' } - }) - ) - expect(mockRuntimeEnvironmentCall).toHaveBeenCalledWith({ - selector: 'env-1', - method: 'terminal.createAgentSession', - params: expect.objectContaining({ - clientOperationId: expect.stringMatching(/^\d{13}-[0-9a-f]{32}$/), - worktree: 'id:wt-1', - agent: 'claude', - prompt: 'run the automation', - promptDelivery: 'auto-submit', - placement: { tabId, leafId }, - presentation: 'background' - }), - timeoutMs: 15_000 - }) - expect(mockUpdateTabPtyId).toHaveBeenCalledWith(tabId, 'remote:env-1@@terminal-1') - expect(mockRegisterEagerPtyBuffer).not.toHaveBeenCalled() - expect(mockRuntimeEnvironmentSubscribe).toHaveBeenCalledWith( - expect.objectContaining({ - selector: 'env-1', - method: 'terminal.multiplex', - params: {} - }), - expect.any(Object) - ) - expect(result).toMatchObject({ - tabId, - paneKey: `${tabId}:${leafId}`, - ptyId: 'remote:env-1@@terminal-1', - terminalOwnership: null - }) - } - ) - - it('advertises keyboard support for a background OMP launch', async () => { - useRemoteAgentBackgroundRuntime(state) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - await launchAgentBackgroundSession({ agent: 'omp', worktreeId: 'wt-1', prompt: 'review' }) - expect(mockRuntimeEnvironmentCall).toHaveBeenCalledWith( - expect.objectContaining({ - method: 'terminal.createAgentSession', - params: expect.objectContaining({ - agent: 'omp', - terminalKittyKeyboardProtocol: true, - presentation: 'background' - }) - }) - ) - }) - - it('aborts the remote exit wait and closes the stream when run observers are released', async () => { - useRemoteAgentBackgroundRuntime(state) - const streamSend = vi.fn() - const waitUnsubscribe = vi.fn() - mockRuntimeEnvironmentSubscribe.mockImplementation(async (request, callbacks) => { - if (request.method === 'terminal.multiplex') { - queueMicrotask(() => callbacks.onResponse({ ok: true, result: { type: 'ready' } })) - return { unsubscribe: vi.fn(), sendBinary: streamSend } - } - if (request.method === 'terminal.wait') { - return { unsubscribe: waitUnsubscribe, sendBinary: vi.fn() } - } - throw new Error(`Unexpected runtime subscription: ${request.method}`) - }) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - const result = await launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run the automation' - }) - await vi.waitFor(() => - expect(mockRuntimeEnvironmentSubscribe).toHaveBeenCalledWith( - expect.objectContaining({ method: 'terminal.wait' }), - expect.any(Object) - ) - ) - const sendsBeforeRelease = streamSend.mock.calls.length - - result?.releaseRuntimeObservers() - result?.releaseRuntimeObservers() - - await vi.waitFor(() => expect(waitUnsubscribe).toHaveBeenCalledOnce()) - // One unsubscribe frame for the terminal's data stream. - expect(streamSend.mock.calls.length).toBe(sendsBeforeRelease + 1) - }) - - it('preserves the legacy background spawn on an old remote host', async () => { - useRemoteAgentBackgroundRuntime(state) - mockRuntimeEnvironmentTransportCall.mockImplementation((request: { method: string }) => { - if (request.method === 'status.get') { - return Promise.resolve({ - id: 'status', - ok: true, - result: { - runtimeId: 'old-runtime', - graphStatus: 'ready', - runtimeProtocolVersion: 3, - minCompatibleRuntimeClientVersion: 2, - capabilities: [] - } - }) - } - return Promise.resolve({ - id: 'create', - ok: true, - result: { terminal: { handle: 'legacy-terminal-1' } } - }) - }) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await expect( - launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run remotely' - }) - ).resolves.toMatchObject({ ptyId: 'remote:env-1@@legacy-terminal-1' }) - - expect(mockRuntimeEnvironmentTransportCall).toHaveBeenCalledWith( - expect.objectContaining({ - method: 'terminal.create', - params: expect.objectContaining({ - worktree: 'id:wt-1', - command: "claude '--dangerously-skip-permissions' 'run remotely'", - terminalKittyKeyboardProtocol: true, - launchAgent: 'claude', - presentation: 'background' - }) - }) - ) - }) - - it('closes a created runtime terminal when its data subscription fails', async () => { - useRemoteAgentBackgroundRuntime(state) - mockRuntimeEnvironmentSubscribe.mockRejectedValueOnce(new Error('subscription failed')) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await expect( - launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run the automation' - }) - ).rejects.toThrow('subscription failed') - - expect(mockRuntimeEnvironmentCall).toHaveBeenCalledWith({ - selector: 'env-1', - method: 'terminal.close', - params: { terminal: 'terminal-1' }, - timeoutMs: undefined - }) - const tabId = mockRuntimeEnvironmentCall.mock.calls[0]?.[0]?.params?.placement?.tabId - expect(tabId).toMatch(UUID_RE) - expect(state.clearTabPtyId).toHaveBeenCalledWith(tabId, 'remote:env-1@@terminal-1') - expect(state.clearAgentLaunchConfig).toHaveBeenCalledWith( - expect.stringMatching(new RegExp(`^${tabId}:`)) - ) - expect(mockCloseTab).toHaveBeenCalledWith(tabId, { - recordInteraction: false, - reason: 'cleanup' - }) - expect(mockDispatchEvent).not.toHaveBeenCalled() - }) - - it('spawns an SSH folder-workspace automation on the owning host, not locally', async () => { - // Folder workspaces have no repo row, so launch ownership comes from their scope. - state.repos = [ - { id: 'repo-1', connectionId: 'ssh-1', path: '/srv/proj/api', projectGroupId: 'grp-1' } - ] - state.projectGroups = [{ id: 'grp-1', parentGroupId: null, connectionId: 'ssh-1' }] - state.folderWorkspaces = [ - { id: 'fw-1', projectGroupId: 'grp-1', folderPath: '/srv/proj', connectionId: 'ssh-1' } - ] - state.getKnownWorktreeById = (worktreeId: string) => - worktreeId === 'folder:fw-1' ? { id: 'folder:fw-1', path: '/srv/proj' } : undefined - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent: 'codex', - worktreeId: 'folder:fw-1', - prompt: 'run the automation' - }) - - expect(mockSpawn).toHaveBeenCalledWith( - expect.objectContaining({ connectionId: 'ssh-1', cwd: '/srv/proj' }) - ) - }) - - it('keeps a local folder workspace on the local host', async () => { - state.repos = [ - { id: 'repo-1', connectionId: null, path: '/home/me/proj/api', projectGroupId: 'grp-1' } - ] - state.projectGroups = [{ id: 'grp-1', parentGroupId: null, connectionId: null }] - state.folderWorkspaces = [ - { id: 'fw-1', projectGroupId: 'grp-1', folderPath: '/home/me/proj', connectionId: null } - ] - state.getKnownWorktreeById = (worktreeId: string) => - worktreeId === 'folder:fw-1' ? { id: 'folder:fw-1', path: '/home/me/proj' } : undefined - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'folder:fw-1', - prompt: 'run the automation' - }) - - expect(mockSpawn).toHaveBeenCalledWith( - expect.objectContaining({ connectionId: null, cwd: '/home/me/proj' }) - ) - }) -}) diff --git a/src/renderer/src/lib/launch-agent-background-session.test.ts b/src/renderer/src/lib/launch-agent-background-session.test.ts deleted file mode 100644 index 4896500c6be0..000000000000 --- a/src/renderer/src/lib/launch-agent-background-session.test.ts +++ /dev/null @@ -1,642 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { BACKGROUND_MOUNT_TERMINAL_WORKTREE_EVENT } from '@/constants/terminal' -import { toAppSshPtyId } from '../../../shared/ssh-pty-id' -import { - AGENT_BACKGROUND_SESSION_UUID_RE as UUID_RE, - createAgentBackgroundSessionTestState, - expectReservedAgentBackgroundTabId, - expectStableAgentBackgroundPaneSpawn, - resetAgentBackgroundSessionTestHarness -} from '@/lib/agent-background-session-test-state' - -const mockSpawn = vi.fn() -const mockKill = vi.fn() -const mockWrite = vi.fn() -const mockRuntimeEnvironmentCall = vi.fn() -const mockRuntimeEnvironmentTransportCall = vi.fn() -const mockRuntimeEnvironmentSubscribe = vi.fn() -const mockCreateTab = vi.fn() -const mockSetTabCustomTitle = vi.fn() -const mockUpdateTabPtyId = vi.fn() -const mockCloseTab = vi.fn() -const mockSetTabLayout = vi.fn() -const mockRegisterAgentLaunchConfig = vi.fn() -const mockRegisterEagerPtyBuffer = vi.fn() -const mockSubscribeToPtyData = vi.fn() -const mockSubscribeToPtyExit = vi.fn() -const mockPasteDraftWhenAgentReady = vi.fn() -const mockDispatchEvent = vi.fn() -const mockGetAgentLaunchPlatformForRepo = vi.fn<() => NodeJS.Platform>() -const mockHostKind = vi.fn<() => 'local' | 'runtime'>(() => 'local') -const state = createAgentBackgroundSessionTestState({ - createTab: mockCreateTab, - setTabCustomTitle: mockSetTabCustomTitle, - updateTabPtyId: mockUpdateTabPtyId, - closeTab: mockCloseTab, - setTabLayout: mockSetTabLayout, - registerAgentLaunchConfig: mockRegisterAgentLaunchConfig -}) -let currentStoreState = state - -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => currentStoreState, - subscribe: vi.fn(() => () => {}) - } -})) - -// Why: the background mount's sleeping-agent scan reads store state these launches never seed. -vi.mock('@/lib/sleeping-agent-wake-requests', () => ({ requestSleepingAgentWakeOnMount: vi.fn() })) - -vi.mock('@/lib/telemetry', () => ({ - track: vi.fn(), - tuiAgentToAgentKind: (agent: string) => agent -})) - -vi.mock('@/lib/agent-paste-draft', () => ({ - pasteDraftWhenAgentReady: mockPasteDraftWhenAgentReady -})) - -vi.mock('@/lib/execution-host-facts', async (importOriginal) => { - const hostFact = () => ({ - kind: 'known' as const, - platform: mockGetAgentLaunchPlatformForRepo(), - hostKind: mockHostKind() - }) - return { - ...(await importOriginal>()), - resolveRepoExecutionHostPlatform: hostFact, - resolveWorktreeExecutionHostPlatform: hostFact - } -}) - -vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({ - registerEagerPtyBuffer: mockRegisterEagerPtyBuffer, - subscribeToPtyExit: mockSubscribeToPtyExit -})) - -vi.mock('@/components/terminal-pane/pty-data-sidecar-subscriptions', () => ({ - subscribeToPtyData: mockSubscribeToPtyData -})) - -describe('launchAgentBackgroundSession', () => { - beforeEach(() => { - currentStoreState = state - resetAgentBackgroundSessionTestHarness({ - state, - createTab: mockCreateTab, - closeTab: mockCloseTab, - getLaunchPlatform: mockGetAgentLaunchPlatformForRepo, - runtimeCall: mockRuntimeEnvironmentCall, - runtimeTransportCall: mockRuntimeEnvironmentTransportCall, - runtimeSubscribe: mockRuntimeEnvironmentSubscribe, - subscribeToData: mockSubscribeToPtyData, - subscribeToExit: mockSubscribeToPtyExit, - setTabLayout: mockSetTabLayout, - updateTabPtyId: mockUpdateTabPtyId, - dispatchEvent: mockDispatchEvent, - kill: mockKill, - spawn: mockSpawn, - write: mockWrite - }) - }) - - it('spawns a PTY first and creates the inactive tab already bound to it', async () => { - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - mockSpawn.mockResolvedValue({ id: 'pty-1', incarnationId: 'inc-fresh' }) - - const result = await launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run the automation', - title: 'Nightly audit' - }) - - const tabId = expectReservedAgentBackgroundTabId(mockSpawn) - // A store-visible PTY-less run tab fresh-spawns a shell (#2989). - expect(mockSpawn.mock.invocationCallOrder[0]).toBeLessThan( - mockCreateTab.mock.invocationCallOrder[0] ?? 0 - ) - expect(mockCreateTab).toHaveBeenCalledWith('wt-1', undefined, undefined, { - id: tabId, - initialPtyId: 'pty-1', - activate: false, - recordInteraction: false - }) - expect(mockDispatchEvent).toHaveBeenCalledWith( - expect.objectContaining({ - type: BACKGROUND_MOUNT_TERMINAL_WORKTREE_EVENT, - detail: { worktreeId: 'wt-1', tabIds: [tabId] } - }) - ) - expect(mockUpdateTabPtyId.mock.invocationCallOrder[0]).toBeLessThan( - mockDispatchEvent.mock.invocationCallOrder[0] ?? 0 - ) - expect(mockSpawn).toHaveBeenCalledWith( - expect.objectContaining({ - cwd: '/repo/worktree', - command: "claude '--dangerously-skip-permissions' 'run the automation'", - env: expect.objectContaining({ - ORCA_TAB_ID: tabId, - ORCA_WORKTREE_ID: 'wt-1' - }), - connectionId: null, - worktreeId: 'wt-1', - tabId, - placement: { kind: 'new-tab', row: { customTitle: 'Nightly audit' } } - }) - ) - const paneKey = expectStableAgentBackgroundPaneSpawn(mockSpawn) - const leafId = paneKey.slice(`${tabId}:`.length) - expect(mockSetTabLayout).toHaveBeenCalledWith( - tabId, - expect.objectContaining({ - root: { type: 'leaf', leafId }, - activeLeafId: leafId, - ptyIdsByLeafId: { [leafId]: 'pty-1' } - }) - ) - expect(mockSetTabLayout.mock.calls.at(-1)?.[1]).not.toHaveProperty('titlesByLeafId') - expect(mockSpawn.mock.calls[0]?.[0]).toMatchObject({ - launchConfig: { - agentCommand: "claude '--dangerously-skip-permissions'", - agentArgs: '--dangerously-skip-permissions', - agentEnv: {} - }, - launchAgent: 'claude', - launchToken: expect.stringMatching(UUID_RE) - }) - expect(mockSpawn.mock.calls[0]?.[0].launchToken).toBe( - mockSpawn.mock.calls[0]?.[0].env.ORCA_AGENT_LAUNCH_TOKEN - ) - expect(mockSetTabCustomTitle).toHaveBeenCalledWith(tabId, 'Nightly audit', { - recordInteraction: false - }) - expect(mockUpdateTabPtyId).toHaveBeenCalledWith(tabId, 'pty-1') - // Keep incarnation so recycled relay IDs cannot deliver a prior owner’s exit into the new session. - expect(mockRegisterEagerPtyBuffer).toHaveBeenCalledWith( - 'pty-1', - expect.any(Function), - 'inc-fresh' - ) - expect(mockSubscribeToPtyData).toHaveBeenCalledWith('pty-1', expect.any(Function)) - expect(mockSubscribeToPtyExit).toHaveBeenCalledWith('pty-1', expect.any(Function)) - expect(result).toMatchObject({ tabId, paneKey, ptyId: 'pty-1' }) - }) - - it('does not create or mount the tab while the explicit PTY spawn is unresolved', async () => { - let resolveSpawn!: (result: { id: string }) => void - mockSpawn.mockReturnValueOnce( - new Promise<{ id: string }>((resolve) => { - resolveSpawn = resolve - }) - ) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - const launch = launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run slowly' - }) - await Promise.resolve() - - // Publishing a PTY-less tab here reproduces #2989. - expect(mockCreateTab).not.toHaveBeenCalled() - expect(mockDispatchEvent).not.toHaveBeenCalled() - - resolveSpawn({ id: 'pty-slow' }) - await expect(launch).resolves.toMatchObject({ ptyId: 'pty-slow' }) - const tabId = expectReservedAgentBackgroundTabId(mockSpawn) - expect(mockCreateTab.mock.calls[0]?.[3]).toMatchObject({ - id: tabId, - initialPtyId: 'pty-slow' - }) - expect(mockUpdateTabPtyId).toHaveBeenCalledWith(tabId, 'pty-slow') - expect(mockDispatchEvent).toHaveBeenCalledWith( - expect.objectContaining({ detail: { worktreeId: 'wt-1', tabIds: [tabId] } }) - ) - }) - - it('kills a local PTY when its worktree disappears before spawn resolves', async () => { - let resolveSpawn!: (result: { id: string }) => void - mockSpawn.mockReturnValueOnce( - new Promise<{ id: string }>((resolve) => { - resolveSpawn = resolve - }) - ) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - const launch = launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run slowly' - }) - await vi.waitFor(() => expect(mockSpawn).toHaveBeenCalledOnce()) - state.worktreesByRepo['repo-1'] = [] - resolveSpawn({ id: 'pty-after-close' }) - - await expect(launch).resolves.toBeNull() - expect(mockKill).toHaveBeenCalledWith('pty-after-close') - expect(mockCreateTab).not.toHaveBeenCalled() - expect(mockUpdateTabPtyId).not.toHaveBeenCalled() - expect(mockSubscribeToPtyData).not.toHaveBeenCalled() - expect(mockDispatchEvent).not.toHaveBeenCalled() - }) - - it('launches into a folder workspace that is absent from worktreesByRepo throughout', async () => { - // Folder workspaces never appear in worktreesByRepo. - state.worktreesByRepo['repo-1'] = [] - state.folderWorkspaces = [ - { id: 'fw-1', projectGroupId: 'grp-1', folderPath: '/tmp/folder-workspace' } - ] - state.projectGroups = [{ id: 'grp-1', connectionId: null }] - state.getKnownWorktreeById = (worktreeId: string) => - worktreeId === 'folder:fw-1' - ? { id: 'folder:fw-1', path: '/tmp/folder-workspace' } - : undefined - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - const launch = launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'folder:fw-1', - prompt: 'run in a folder workspace' - }) - - await expect(launch).resolves.toMatchObject({ ptyId: 'pty-1' }) - expect(mockKill).not.toHaveBeenCalled() - expect(mockCreateTab).toHaveBeenCalledOnce() - }) - - it('launches a local WSL folder through wsl.exe', async () => { - const folderPath = '\\\\wsl.localhost\\Ubuntu\\home\\me\\project' - state.worktreesByRepo['repo-1'] = [] - state.folderWorkspaces = [ - { id: 'fw-wsl', projectGroupId: 'grp-wsl', folderPath, connectionId: null } - ] - state.projectGroups = [{ id: 'grp-wsl', connectionId: null }] - state.getKnownWorktreeById = (worktreeId: string) => - worktreeId === 'folder:fw-wsl' ? { id: worktreeId, path: folderPath } : undefined - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'folder:fw-wsl', - prompt: 'run the automation' - }) - - expect(mockSpawn).toHaveBeenCalledWith( - expect.objectContaining({ - cwd: folderPath, - shellOverride: 'wsl.exe', - command: "claude '--dangerously-skip-permissions' 'run the automation'" - }) - ) - }) - - it('records effective launch config returned by local PTY spawn', async () => { - const effectiveLaunchConfig = { - agentCommand: "claude '--dangerously-skip-permissions'", - agentArgs: '--dangerously-skip-permissions', - agentEnv: { ORCA_AGENT_TEAMS_TEAM_ID: 'team-fresh' } - } - mockSpawn.mockResolvedValue({ id: 'pty-1', launchConfig: effectiveLaunchConfig }) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run the automation' - }) - - const paneKey = expectStableAgentBackgroundPaneSpawn(mockSpawn) - const tabId = expectReservedAgentBackgroundTabId(mockSpawn) - const leafId = paneKey.slice(`${tabId}:`.length) - expect(mockRegisterAgentLaunchConfig).toHaveBeenLastCalledWith(paneKey, effectiveLaunchConfig, { - agentType: 'claude', - launchToken: mockSpawn.mock.calls[0]?.[0].env.ORCA_AGENT_LAUNCH_TOKEN, - tabId, - leafId - }) - }) - - it('uses WSL launch quoting for Windows-path projects forced to WSL', async () => { - state.endpointProjects = [ - { - id: 'repo-1', - localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' } - } - ] - state.repos = [{ id: 'repo-1', connectionId: null, path: 'C:\\Users\\jinwo\\repo' }] - state.worktreesByRepo = { - 'repo-1': [ - { - id: 'wt-1', - repoId: 'repo-1', - projectId: 'repo-1', - path: 'C:\\Users\\jinwo\\repo\\feature', - displayName: 'feature' - } - ] - } - - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: "don't use powershell quoting" - }) - - expect(mockSpawn).toHaveBeenCalledWith( - expect.objectContaining({ - cwd: 'C:\\Users\\jinwo\\repo\\feature', - command: `claude '--dangerously-skip-permissions' 'don'"'"'t use powershell quoting'`, - connectionId: null, - worktreeId: 'wt-1', - tabId: expect.stringMatching(UUID_RE) - }) - ) - }) - - it('stamps hidden SSH status from renderer fallback when the kill switch is off', async () => { - // With main authority disabled, this hidden SSH sidecar is the sole OSC 9999 store writer. - state.settings.terminalMainSideEffectAuthority = false - state.repos = [{ id: 'repo-1', connectionId: 'ssh-a', path: '/repo' }] - state.sshConnectionStates = new Map([['ssh-a', { status: 'connected' }]]) - mockSpawn.mockResolvedValue({ id: toAppSshPtyId('ssh-a', 'pty-1') }) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run the automation' - }) - - const dataSidecar = mockSubscribeToPtyData.mock.calls[0]?.[1] as (data: string) => void - dataSidecar('\x1b]9999;{"state":"done","prompt":"ok","agentType":"codex"}\x07') - - const paneKey = expectStableAgentBackgroundPaneSpawn(mockSpawn) - expect(state.setAgentStatus).toHaveBeenCalledWith( - paneKey, - expect.objectContaining({ state: 'done', prompt: 'ok', agentType: 'codex' }), - undefined, - undefined, - { connectionId: 'ssh-a' }, - { launchToken: expect.stringMatching(UUID_RE) } - ) - }) - - it('skips the duplicate OSC store write under main side-effect authority', async () => { - // Main already owns OSC 9999 store writes; avoid races while retaining automation completion callbacks. - const onAgentStatus = vi.fn() - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run the automation', - onAgentStatus - }) - - const dataSidecar = mockSubscribeToPtyData.mock.calls[0]?.[1] as (data: string) => void - dataSidecar('\x1b]9999;{"state":"done","prompt":"ok","agentType":"codex"}\x07') - - expect(state.setAgentStatus).not.toHaveBeenCalled() - expect(onAgentStatus).toHaveBeenCalledWith( - expect.objectContaining({ state: 'done', prompt: 'ok', agentType: 'codex' }) - ) - }) - - it('stamps a working status for SSH Command Code prompt launches', async () => { - state.repos = [{ id: 'repo-1', connectionId: 'ssh-a', path: '/repo' }] - state.sshConnectionStates = new Map([['ssh-a', { status: 'connected' }]]) - mockSpawn.mockResolvedValue({ id: toAppSshPtyId('ssh-a', 'pty-1') }) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent: 'command-code', - worktreeId: 'wt-1', - prompt: 'check the status spinner' - }) - - const paneKey = expectStableAgentBackgroundPaneSpawn(mockSpawn) - expect(state.setAgentStatus).toHaveBeenCalledWith( - paneKey, - { - state: 'working', - prompt: 'check the status spinner', - agentType: 'command-code', - // Why: Orca launched this hidden session, so the seed predates any provider signal (STA-4293). - observation: expect.objectContaining({ origin: 'launch', kind: 'transition' }) - }, - undefined, - undefined, - { connectionId: 'ssh-a' }, - { - launchConfig: { - agentCommand: "command-code --trust '--yolo'", - agentArgs: '--yolo', - agentEnv: {} - }, - launchToken: expect.stringMatching(UUID_RE) - } - ) - }) - - it('uses a sidecar exit watcher so completion survives terminal attachment', async () => { - const unsubscribe = vi.fn() - mockSubscribeToPtyExit.mockReturnValue(unsubscribe) - const onExit = vi.fn() - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run the automation', - onExit - }) - - const sidecar = mockSubscribeToPtyExit.mock.calls[0]?.[1] as (code: number) => void - sidecar(0) - - const tabId = expectReservedAgentBackgroundTabId(mockSpawn) - expect(state.clearTabPtyId).toHaveBeenCalledWith(tabId, 'pty-1') - expect(state.clearAgentLaunchConfig).toHaveBeenCalledWith( - expect.stringMatching(new RegExp(`^${tabId}:`)) - ) - expect(onExit).toHaveBeenCalledWith('pty-1', 0) - expect(unsubscribe).toHaveBeenCalled() - expect(state.markUnverifiedPtyLoss).not.toHaveBeenCalled() - }) - - it('keeps the tab bound to its PTY when contact was lost rather than observed', async () => { - // Synthetic -1 loss retires transport only; retain bindings for reconnect adoption and orphan-cleanup protection. - mockSubscribeToPtyExit.mockReturnValue(vi.fn()) - const onExit = vi.fn() - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run the automation', - onExit - }) - - const sidecar = mockSubscribeToPtyExit.mock.calls[0]?.[1] as (code: number) => void - sidecar(-1) - - const tabId = expectReservedAgentBackgroundTabId(mockSpawn) - expect(state.clearTabPtyId).not.toHaveBeenCalled() - expect(state.markUnverifiedPtyLoss).toHaveBeenCalledWith(tabId) - expect(onExit).toHaveBeenCalledWith('pty-1', -1) - }) - - it('leaves no tab behind if PTY spawn fails', async () => { - mockSpawn.mockRejectedValueOnce(new Error('spawn failed')) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await expect( - launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run the automation' - }) - ).rejects.toThrow('spawn failed') - - // Why: the tab is only created once a PTY is live, so a failed spawn has nothing to close. - expect(mockCreateTab).not.toHaveBeenCalled() - expect(mockCloseTab).not.toHaveBeenCalled() - expect(state.clearAgentLaunchConfig).toHaveBeenCalledWith( - expect.stringMatching(new RegExp(`^${expectReservedAgentBackgroundTabId(mockSpawn)}:`)) - ) - expect(mockUpdateTabPtyId).not.toHaveBeenCalled() - }) - - it('closes the adopted tab if binding fails after the PTY is live', async () => { - mockSubscribeToPtyData.mockImplementationOnce(() => { - throw new Error('subscribe failed') - }) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await expect( - launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run the automation' - }) - ).rejects.toThrow('subscribe failed') - - const tabId = expectReservedAgentBackgroundTabId(mockSpawn) - expect(mockCloseTab).toHaveBeenCalledWith(tabId, { - recordInteraction: false, - reason: 'cleanup' - }) - expect(mockKill).toHaveBeenCalledWith('pty-1') - }) - - it('retires the launch instead of adopting a colliding tab id', async () => { - mockSpawn.mockImplementationOnce((args: { tabId: string }) => { - currentStoreState = { - ...state, - tabsByWorktree: { - ...state.tabsByWorktree, - 'wt-1': [{ id: args.tabId, title: 'Squatter' }] - } - } - return Promise.resolve({ id: 'pty-1' }) - }) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await expect( - launchAgentBackgroundSession({ - agent: 'claude', - worktreeId: 'wt-1', - prompt: 'run the automation' - }) - ).resolves.toBeNull() - - expect(mockCreateTab).not.toHaveBeenCalled() - expect(mockKill).toHaveBeenCalledWith('pty-1') - expect(state.clearAgentLaunchConfig).toHaveBeenCalledWith( - expectStableAgentBackgroundPaneSpawn(mockSpawn) - ) - }) - - it('submits prompts for stdin-after-start agents in background mode', async () => { - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent: 'aider', - worktreeId: 'wt-1', - prompt: 'run the automation' - }) - - expect(mockSpawn).toHaveBeenCalledWith( - expect.objectContaining({ command: "aider '--yes-always'" }) - ) - expect(mockPasteDraftWhenAgentReady).toHaveBeenCalledWith( - expect.objectContaining({ - tabId: expectReservedAgentBackgroundTabId(mockSpawn), - content: 'run the automation', - agent: 'aider', - submit: true - }) - ) - }) - - it('passes Hermes automation prompts through the native startup query', async () => { - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent: 'hermes', - worktreeId: 'wt-1', - prompt: 'run the automation' - }) - - expect(mockSpawn).toHaveBeenCalledWith( - expect.objectContaining({ - command: expect.stringContaining('ORCA_HERMES_STARTUP_QUERY'), - env: expect.objectContaining({ ORCA_HERMES_STARTUP_QUERY: 'run the automation' }) - }) - ) - expect(mockPasteDraftWhenAgentReady).not.toHaveBeenCalled() - }) - - it('uses the configured cmd shell for Windows Hermes background launches', async () => { - mockGetAgentLaunchPlatformForRepo.mockReturnValue('win32') - Object.assign(state.settings, { terminalWindowsShell: 'cmd.exe' }) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent: 'hermes', - worktreeId: 'wt-1', - prompt: 'run the automation' - }) - - expect(mockSpawn).toHaveBeenCalledWith( - expect.objectContaining({ - command: expect.stringContaining('powershell.exe -NoProfile -EncodedCommand'), - env: expect.objectContaining({ ORCA_HERMES_STARTUP_QUERY: 'run the automation' }) - }) - ) - }) - - it("keeps this client's Git Bash setting off a Windows Orca server's launch", async () => { - mockGetAgentLaunchPlatformForRepo.mockReturnValue('win32') - mockHostKind.mockReturnValueOnce('runtime') - Object.assign(state.settings, { terminalWindowsShell: 'bash.exe' }) - const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') - - await launchAgentBackgroundSession({ - agent: 'hermes', - worktreeId: 'wt-1', - prompt: 'run the automation' - }) - - expect(mockSpawn).toHaveBeenCalledWith( - expect.objectContaining({ - command: expect.stringContaining('powershell.exe -NoProfile -EncodedCommand') - }) - ) - }) -}) diff --git a/src/renderer/src/lib/launch-agent-background-session.ts b/src/renderer/src/lib/launch-agent-background-session.ts deleted file mode 100644 index 4885497dca58..000000000000 --- a/src/renderer/src/lib/launch-agent-background-session.ts +++ /dev/null @@ -1,310 +0,0 @@ -import { useAppStore } from '@/store' -import { runtimeTargetForOwnerEnvironment } from '@/runtime/runtime-client-target' -import { buildAgentStartupPlan } from '@/lib/tui-agent-startup' -import type { - LaunchAgentBackgroundSessionArgs, - LaunchAgentBackgroundSessionResult -} from '@/lib/agent-background-session-contract' -import { tuiAgentToAgentKind } from '@/lib/telemetry' -import { scheduleAgentBackgroundDraft } from '@/lib/agent-background-draft-delivery' -import { requestBackgroundTerminalWorktreeMount } from '@/components/terminal/background-terminal-worktree-mount' -import { resolveAgentStartupPlanInputs } from '../../../shared/agent-startup-plan-inputs' -import { requireTuiAgentConfig } from '../../../shared/require-tui-agent-config' -import { resolveAgentBackgroundLaunchHost } from '@/lib/agent-background-session-launch-host' -import { makePaneKey } from '../../../shared/stable-pane-id' -import { - registerEagerPtyBuffer, - subscribeToPtyExit, - type EagerPtyHandle -} from '@/components/terminal-pane/pty-dispatcher' -import { subscribeToPtyData } from '@/components/terminal-pane/pty-data-sidecar-subscriptions' -import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' -import { runtimeEnvironmentIdOrLocalUnlessTwin } from '@/lib/worktree-runtime-owner' -import { retireProvider } from '@/lib/retire-unowned-background-terminal' -import { createRuntimeAgentBackgroundTerminal } from '@/lib/runtime-agent-background-create' -import { subscribeToRuntimeTerminalData } from '@/runtime/runtime-terminal-stream' -import { toRemoteRuntimePtyId } from '../../../shared/remote-runtime/remote-runtime-pty-id' -import { isMainTerminalSideEffectAuthorityForPty } from '@/components/terminal-pane/terminal-side-effect-facts-handler' -import { hasExtraAgentArgs } from '../../../shared/automation-extra-agent-args' -import { runBestEffortAgentBackgroundCleanups } from '@/lib/agent-background-session-cleanup' -import type { bindAutomationTerminal } from '@/lib/automation-terminal-ownership' -import { - adoptAgentBackgroundSessionTab, - reserveAgentBackgroundSessionIdentity -} from '@/lib/adopt-agent-background-session-tab' -import { createBackgroundAgentStatusConsumer } from '@/lib/background-agent-status-consumer' -import { isWslUncPath } from '../../../shared/wsl-paths' -import { runtimeWaitExitCode, settleTabPtyBinding } from '@/lib/agent-background-session-exit' - -export async function launchAgentBackgroundSession( - args: LaunchAgentBackgroundSessionArgs -): Promise { - const { agent, worktreeId, prompt, launchSource, title, onData, onExit, onAgentStatus } = args - const store = useAppStore.getState() - // Folder workspaces exist only in getKnownWorktreeById (#2989). - const worktree = store.getKnownWorktreeById(worktreeId) - const repo = worktree ? store.repos.find((entry) => entry.id === worktree.repoId) : null - if (!worktree) { - throw new Error('The target workspace is no longer available.') - } - // Folder launch ownership cannot be derived from a repo row (#2989). - const launchHost = resolveAgentBackgroundLaunchHost({ - store, - worktreeId, - worktreePath: worktree.path, - repo - }) - const { platform: launchPlatform, isRemote, isLocalHost } = launchHost - // Route by the worktree's owner host, not the focused runtime. - const runtimeTarget = runtimeTargetForOwnerEnvironment( - runtimeEnvironmentIdOrLocalUnlessTwin(store, worktreeId) - ) - if (hasExtraAgentArgs(args.extraAgentArgs) && runtimeTarget.kind === 'environment') { - // Why: that server rebuilds the command from its own settings and would drop the extras. - throw new Error("Extra arguments can't be applied to a paired server's workspace from here.") - } - // Why before any tab or PTY: an invalid launch must fail the run without creating a terminal. - const planInputs = resolveAgentStartupPlanInputs({ - agent, - // Why: the client's Windows shell setting describes this machine, not a remote host. - settings: isLocalHost - ? (store.settings ?? {}) - : { ...store.settings, terminalWindowsShell: undefined }, - platform: launchPlatform, - isRemote, - // The window quotes by its Settings shell, which its pane's spawn also reads. - shell: undefined, - extraAgentArgs: args.extraAgentArgs - }) - const trimmedPrompt = prompt?.trim() ?? '' - const hasPrompt = trimmedPrompt.length > 0 - const isFollowupPath = requireTuiAgentConfig(agent).promptInjectionMode === 'stdin-after-start' - - const pasteDraftAfterLaunch = hasPrompt && isFollowupPath ? trimmedPrompt : null - const startupPlan = buildAgentStartupPlan({ - ...planInputs, - prompt: hasPrompt && !isFollowupPath ? trimmedPrompt : '', - allowEmptyPromptLaunch: !hasPrompt || isFollowupPath - }) - if (!startupPlan) { - return null - } - - // A hidden run tab must never be store-visible without its PTY (#2989). - const { reservedTabId, leafId, launchToken, launchRegistration, paneEnv } = - reserveAgentBackgroundSessionIdentity({ - store, - agentType: agent, - worktreeId, - launchConfig: startupPlan.launchConfig, - env: startupPlan.env - }) - let paneKey = makePaneKey(reservedTabId, leafId) - const sshConnectionId = launchHost.connectionId - let ptyId = '', - runtimeTerminalHandle: string | null = null - // Capture local/SSH incarnation and actual launch config for later steps; runtime terminals supply neither. - let spawned: { incarnationId?: string; launchConfig?: typeof startupPlan.launchConfig } = {} - let tab: ReturnType | null = null - let exitHandled = false, - eagerPtyBuffer: EagerPtyHandle | null = null - let terminalOwnership: ReturnType = null - let unsubscribeExit = (): void => {}, - unsubscribeData = (): void => {}, - releaseRuntimeObservers = (): void => {} - const handleExit = (exitPtyId: string, code: number): void => { - if (exitHandled) { - return - } - exitHandled = true - unsubscribeExit() - unsubscribeData() - if (tab) { - settleTabPtyBinding(tab.id, exitPtyId, code) - } - useAppStore.getState().clearAgentLaunchConfig(paneKey) - onExit?.(exitPtyId, code) - } - // Main owns local/SSH status scanning; runtime bytes still need renderer-side writes. - const mainOwnsAgentStatusWrites = isMainTerminalSideEffectAuthorityForPty({ - settings: store.settings, - runtimeEnvironmentId: runtimeTarget.kind === 'environment' ? runtimeTarget.environmentId : null - }) - const agentStatusConsumer = createBackgroundAgentStatusConsumer({ - paneKey, - launchToken, - mainOwnsAgentStatusWrites, - expectedConnectionId: launchHost.expectedConnectionId, - runtimeEnvironmentId: runtimeTarget.kind === 'environment' ? runtimeTarget.environmentId : null, - getPtyId: () => ptyId, - onAgentStatus - }) - const handleData = (data: string): void => { - onData?.(data) - agentStatusConsumer.consume(data) - } - try { - if (runtimeTarget.kind === 'environment') { - // Runtime workspaces execute on their server; local pty.spawn would run automation on this client. - const created = await createRuntimeAgentBackgroundTerminal({ - environmentId: runtimeTarget.environmentId, - worktreeId, - tabId: reservedTabId, - leafId, - agent, - ...(hasPrompt && !isFollowupPath ? { prompt: trimmedPrompt } : {}), - ...(startupPlan.sessionOptions ? { sessionOptions: startupPlan.sessionOptions } : {}), - legacy: { - command: startupPlan.launchCommand, - env: paneEnv, - ...(startupPlan.startupCommandDelivery - ? { startupCommandDelivery: startupPlan.startupCommandDelivery } - : {}), - launchConfig: startupPlan.launchConfig, - launchToken, - ...(title ? { title } : {}) - } - }) - runtimeTerminalHandle = created.terminal.handle - ptyId = toRemoteRuntimePtyId(runtimeTerminalHandle, runtimeTarget.environmentId) - } else { - const result = await window.api.pty.spawn({ - cols: 120, - rows: 40, - cwd: worktree.path, - command: startupPlan.launchCommand, - ...(!sshConnectionId && isWslUncPath(worktree.path) ? { shellOverride: 'wsl.exe' } : {}), - // Why: the relay types, waits for the shell and stages long lines on the host that owns the PTY. - ...(sshConnectionId - ? { commandDelivery: 'provider' as const, startupCommandDelivery: 'shell-ready' as const } - : startupPlan.startupCommandDelivery - ? { startupCommandDelivery: startupPlan.startupCommandDelivery } - : {}), - env: paneEnv, - launchConfig: startupPlan.launchConfig, - launchToken, - launchAgent: agent, - connectionId: sshConnectionId, - worktreeId, - tabId: reservedTabId, - leafId, - // Why no launchAgent: the adopted tab is created without one, and the row must match it. - placement: { kind: 'new-tab', ...(title ? { row: { customTitle: title } } : {}) }, - telemetry: { - agent_kind: tuiAgentToAgentKind(agent), - launch_source: launchSource ?? 'unknown', - request_kind: 'new' - } - }) - ptyId = result.id - spawned = result - } - const adopted = await adoptAgentBackgroundSessionTab({ - store, - worktreeId, - reservedTabId, - ptyId, - paneKey, - launchConfig: spawned.launchConfig ?? startupPlan.launchConfig, - launchRegistration, - runtimeTarget, - runtimeTerminalHandle, - onRetire: () => { - exitHandled = true - store.clearAgentLaunchConfig(paneKey) - }, - ...(title ? { title } : {}) - }) - if (!adopted) { - return null - } - tab = adopted.tab - paneKey = adopted.paneKey - terminalOwnership = adopted.terminalOwnership - if (agent === 'command-code' && hasPrompt && !isFollowupPath) { - // Command Code lacks prompt-start hooks; seed working for hidden prompt launches until real status arrives. - const routing = agentStatusConsumer.resolveRouting() - if (routing) { - const observation = agentStatusConsumer.observeLaunchIngress() - store.setAgentStatus( - paneKey, - { state: 'working', prompt: trimmedPrompt, agentType: agent, observation }, - undefined, - undefined, - routing, - { launchConfig: startupPlan.launchConfig, launchToken } - ) - } - } - - if (runtimeTarget.kind === 'environment') { - if (!runtimeTerminalHandle) { - throw new Error('Runtime terminal id is invalid.') - } - unsubscribeData = await subscribeToRuntimeTerminalData( - ptyId, - `desktop:background:${tab.id}`, - handleData - ) - const exitWait = new AbortController() - // Kept-open terminals never exit; cancel their server wait instead of retaining a 24h long-wait slot. - releaseRuntimeObservers = () => { - releaseRuntimeObservers = (): void => {} - exitWait.abort() - const closeData = unsubscribeData - unsubscribeData = (): void => {} - closeData() - } - void callRuntimeRpc<{ wait: { exitCode?: number | null } }>( - runtimeTarget, - 'terminal.wait', - { terminal: runtimeTerminalHandle, for: 'exit' }, - { timeoutMs: 24 * 60 * 60 * 1000, signal: exitWait.signal } - ) - .then((result) => handleExit(ptyId, runtimeWaitExitCode(result.wait))) - .catch(() => {}) - } else { - // Incarnation prevents recycled relay IDs from delivering the previous session’s exit. - eagerPtyBuffer = registerEagerPtyBuffer(ptyId, handleExit, spawned.incarnationId) - unsubscribeData = subscribeToPtyData(ptyId, handleData) - // A mounted transport disposes the eager exit handler; this sidecar preserves completion tracking across hidden/visible transitions. - unsubscribeExit = subscribeToPtyExit(ptyId, (code) => handleExit(ptyId, code)) - } - // Bind PTY/ownership before mount to prevent duplicate spawn without missing user takeover. - requestBackgroundTerminalWorktreeMount({ worktreeId, tabIds: [tab.id] }) - - if (pasteDraftAfterLaunch !== null) { - scheduleAgentBackgroundDraft(tab.id, pasteDraftAfterLaunch, agent) - } - - return { - tabId: tab.id, - paneKey, - ptyId, - startupPlan, - terminalOwnership, - releaseRuntimeObservers: () => releaseRuntimeObservers() - } - } catch (error) { - // Creation and subscription are separate RPCs; failure between them must clean up the invisible runtime terminal. - exitHandled = true - terminalOwnership?.release() - const createdTab = tab - runBestEffortAgentBackgroundCleanups(unsubscribeExit, unsubscribeData) - runBestEffortAgentBackgroundCleanups(() => eagerPtyBuffer?.dispose()) - if (createdTab) { - runBestEffortAgentBackgroundCleanups(() => store.clearTabPtyId(createdTab.id, ptyId)) - } - runBestEffortAgentBackgroundCleanups(() => store.clearAgentLaunchConfig(paneKey)) - if (ptyId) { - await retireProvider({ ptyId, runtimeTarget, runtimeTerminalHandle }) - } - if (createdTab) { - // Cleanup closes must not enter the reopen stack. - runBestEffortAgentBackgroundCleanups(() => - store.closeTab(createdTab.id, { recordInteraction: false, reason: 'cleanup' }) - ) - } - throw error - } -} diff --git a/src/renderer/src/store/terminals/terminal-actions.ts b/src/renderer/src/store/terminals/terminal-actions.ts index d29531762d6b..1d16f419377f 100644 --- a/src/renderer/src/store/terminals/terminal-actions.ts +++ b/src/renderer/src/store/terminals/terminal-actions.ts @@ -170,6 +170,13 @@ export type TerminalActions = { leafId: string ptyId: string expectedRuntimePtyId?: string + lifecycle?: { + preservePane: boolean + stop: ( + preservePane: boolean, + transactionCurrent: () => boolean + ) => Promise<'stopped' | 'live' | 'unproven'> + } } ) => Promise suppressPtyExit: (ptyId: string) => void diff --git a/src/renderer/src/store/terminals/terminal-pane-hibernation-commit.ts b/src/renderer/src/store/terminals/terminal-pane-hibernation-commit.ts new file mode 100644 index 000000000000..71037dcad9e1 --- /dev/null +++ b/src/renderer/src/store/terminals/terminal-pane-hibernation-commit.ts @@ -0,0 +1,92 @@ +import type { TerminalSlice, TerminalStoreGet, TerminalStoreSet } from './terminal-state' +import { removePanesAttention } from '../slices/workspace-attention/subject-attention-transitions' +import { settleAttentionRemovedBy } from '../slices/workspace-attention/attention-removal-follow-up' + +export function commitHibernatedPane({ + set, + get, + worktreeId, + opts, + state, + rendererShutdownPtyIds, + exitGuardPtyIds +}: { + set: TerminalStoreSet + get: TerminalStoreGet + worktreeId: string + opts: Parameters[1] + state: ReturnType + rendererShutdownPtyIds: string[] + exitGuardPtyIds: string[] +}): void { + settleAttentionRemovedBy(set, get, () => + set((s) => { + const existingPtyIds = s.ptyIdsByTabId[opts.tabId] ?? [] + const shutdownPtyIdSet = new Set(rendererShutdownPtyIds) + const remainingPtyIds = existingPtyIds.filter((ptyId) => !shutdownPtyIdSet.has(ptyId)) + const nextTabsByWorktree = { ...s.tabsByWorktree } + const tabs = nextTabsByWorktree[worktreeId] ?? [] + const tabIndex = tabs.findIndex((candidate) => candidate.id === opts.tabId) + if (tabIndex !== -1) { + const nextTabs = [...tabs] + nextTabs[tabIndex] = { + ...nextTabs[tabIndex], + ptyId: remainingPtyIds.at(-1) ?? null + } + nextTabsByWorktree[worktreeId] = nextTabs + } + const nextCodexRestartNoticeByPtyId = { ...s.codexRestartNoticeByPtyId } + for (const ptyId of exitGuardPtyIds) { + delete nextCodexRestartNoticeByPtyId[ptyId] + } + const nextLastKnownRelay = + remainingPtyIds.length === 0 + ? { ...s.lastKnownRelayPtyIdByTabId } + : s.lastKnownRelayPtyIdByTabId + if (remainingPtyIds.length === 0) { + delete nextLastKnownRelay[opts.tabId] + } + let nextRuntimePaneTitlesByTabId = s.runtimePaneTitlesByTabId + const numericPaneId = Number(opts.leafId) + if ( + Number.isInteger(numericPaneId) && + s.runtimePaneTitlesByTabId[opts.tabId]?.[numericPaneId] + ) { + const nextByPane = { ...s.runtimePaneTitlesByTabId[opts.tabId] } + delete nextByPane[numericPaneId] + nextRuntimePaneTitlesByTabId = { ...s.runtimePaneTitlesByTabId } + if (Object.keys(nextByPane).length > 0) { + nextRuntimePaneTitlesByTabId[opts.tabId] = nextByPane + } else { + delete nextRuntimePaneTitlesByTabId[opts.tabId] + } + } + const nextLastTerminalInputAtByPaneKey = { ...s.lastTerminalInputAtByPaneKey } + if ( + !opts.lifecycle || + s.lastTerminalInputAtByPaneKey[opts.paneKey] === + state.lastTerminalInputAtByPaneKey[opts.paneKey] + ) { + delete nextLastTerminalInputAtByPaneKey[opts.paneKey] + } + return { + tabsByWorktree: nextTabsByWorktree, + ptyIdsByTabId: { + ...s.ptyIdsByTabId, + [opts.tabId]: remainingPtyIds + }, + lastKnownRelayPtyIdByTabId: nextLastKnownRelay, + suppressedPtyExitIds: { + ...s.suppressedPtyExitIds, + ...Object.fromEntries(exitGuardPtyIds.map((ptyId) => [ptyId, true] as const)) + }, + codexRestartNoticeByPtyId: nextCodexRestartNoticeByPtyId, + ...(nextRuntimePaneTitlesByTabId !== s.runtimePaneTitlesByTabId + ? { runtimePaneTitlesByTabId: nextRuntimePaneTitlesByTabId } + : {}), + ...removePanesAttention(s, new Set([opts.paneKey])), + lastTerminalInputAtByPaneKey: nextLastTerminalInputAtByPaneKey + } + }) + ) +} diff --git a/src/renderer/src/store/terminals/terminal-pane-hibernation.ts b/src/renderer/src/store/terminals/terminal-pane-hibernation.ts index 40f0b15f4032..35fe21232905 100644 --- a/src/renderer/src/store/terminals/terminal-pane-hibernation.ts +++ b/src/renderer/src/store/terminals/terminal-pane-hibernation.ts @@ -1,3 +1,4 @@ +import { commitHibernatedPane } from './terminal-pane-hibernation-commit' import { isRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id' import { parsePaneKey } from '../../../../shared/stable-pane-id' import { @@ -16,8 +17,6 @@ import type { TerminalSlice, TerminalStoreGet, TerminalStoreSet } from './termin import { equalStringSets, sortedUniquePtyIds } from './terminal-pty-identities' import { resolveTerminalPtyOwner } from '@/lib/terminal-worktree-route' import { resolveTerminalTeardownOwner } from './terminal-teardown-owner' -import { removePanesAttention } from '../slices/workspace-attention/subject-attention-transitions' -import { settleAttentionRemovedBy } from '../slices/workspace-attention/attention-removal-follow-up' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' import { recordPaneSleepThroughLayoutOwner } from './terminal-sleep-layout-owner' @@ -67,20 +66,22 @@ export function createTerminalPaneHibernationActions( ) { throw new Error('agent_hibernation_pane_binding_mismatch') } - const sleepingAgentSessionRecords = collectSleepingAgentSessionRecordsForWorktree( - state, - worktreeId, - { - paneKeys, - captureMode: 'completed-agent-hibernation' - } - ) + const sleepingAgentSessionRecords: ReturnType< + typeof collectSleepingAgentSessionRecordsForWorktree + > = + opts.lifecycle?.preservePane === false + ? {} + : collectSleepingAgentSessionRecordsForWorktree(state, worktreeId, { + paneKeys, + captureMode: 'completed-agent-hibernation' + }) const retainedCompletionEvidence = collectHibernatedCompletionEvidenceForWorktree( state, worktreeId, paneKeys ) - if (!sleepingAgentSessionRecords[opts.paneKey]) { + const preservePane = Boolean(sleepingAgentSessionRecords[opts.paneKey]) + if (!opts.lifecycle && !preservePane) { // Why: killing the PTY with no persisted resume record strands the pane unwakeable; abort instead of hibernating unrecoverably. throw new Error('agent_hibernation_capture_missing') } @@ -102,14 +103,35 @@ export function createTerminalPaneHibernationActions( replacedSleepingRecords[key] = existing } } + const transactionCurrent = (): boolean => { + const current = get() + return ( + current.terminalLayoutsByTabId[opts.tabId]?.ptyIdsByLeafId?.[opts.leafId] === + opts.ptyId && + (!preservePane || + current.sleepingAgentSessionsByPaneKey[opts.paneKey] === + sleepingAgentSessionRecords[opts.paneKey]) + ) + } const rollbackTargetShutdownState = (): void => { set((s) => { const next = { ...s.suppressedPtyExitIds } for (const ptyId of exitGuardPtyIds) { - delete next[ptyId] + if ( + !state.suppressedPtyExitIds[ptyId] && + s.terminalLayoutsByTabId[opts.tabId]?.ptyIdsByLeafId?.[opts.leafId] === opts.ptyId && + (!sleepingRecordKeys.length || + s.sleepingAgentSessionsByPaneKey[opts.paneKey] === + sleepingAgentSessionRecords[opts.paneKey]) + ) { + delete next[ptyId] + } } const nextSleeping = { ...s.sleepingAgentSessionsByPaneKey } for (const key of sleepingRecordKeys) { + if (nextSleeping[key] !== sleepingAgentSessionRecords[key]) { + continue + } const replaced = replacedSleepingRecords[key] if (replaced) { nextSleeping[key] = replaced @@ -180,8 +202,22 @@ export function createTerminalPaneHibernationActions( // Why: pty.kill can flush final data before exit; unregister first so stale handlers can't fire phantom notifications during hibernation. const handlerSnapshots = unregisterPtyDataHandlers(rendererShutdownPtyIds) ?? [] try { - await window.api.pty.kill(opts.ptyId, { keepHistory: true }) + if (opts.lifecycle) { + const proof = await opts.lifecycle.stop(preservePane, transactionCurrent) + if (proof === 'unproven') { + throw new Error('terminal_stop_unproven') + } + if (proof !== 'stopped') { + throw new Error('terminal_stop_still_live') + } + } else { + await window.api.pty.kill(opts.ptyId, { keepHistory: true }) + } } catch (err) { + if (opts.lifecycle && err instanceof Error && err.message === 'terminal_stop_unproven') { + restorePtyDataHandlersAfterFailedShutdown(handlerSnapshots) + throw err + } restorePtyDataHandlersAfterFailedShutdown(handlerSnapshots) rollbackTargetShutdownState() throw err @@ -190,74 +226,33 @@ export function createTerminalPaneHibernationActions( snapshot.commit?.() } } + if (opts.lifecycle) { + if (!transactionCurrent()) { + throw new Error('terminal_sleep_binding_changed') + } + if (!preservePane) { + return + } + } // Switch point: main records the sleep this window decided, once the stop settled. if (ORCA_LAYOUT_OWNER_IS_MAIN) { recordPaneSleepThroughLayoutOwner(get(), worktreeId, sleepingAgentSessionRecords) } - settleAttentionRemovedBy(set, get, () => - set((s) => { - const existingPtyIds = s.ptyIdsByTabId[opts.tabId] ?? [] - const shutdownPtyIdSet = new Set(rendererShutdownPtyIds) - const remainingPtyIds = existingPtyIds.filter((ptyId) => !shutdownPtyIdSet.has(ptyId)) - const nextTabsByWorktree = { ...s.tabsByWorktree } - const tabs = nextTabsByWorktree[worktreeId] ?? [] - const tabIndex = tabs.findIndex((candidate) => candidate.id === opts.tabId) - if (tabIndex !== -1) { - const nextTabs = [...tabs] - nextTabs[tabIndex] = { - ...nextTabs[tabIndex], - ptyId: remainingPtyIds.at(-1) ?? null - } - nextTabsByWorktree[worktreeId] = nextTabs - } - const nextCodexRestartNoticeByPtyId = { ...s.codexRestartNoticeByPtyId } - for (const ptyId of exitGuardPtyIds) { - delete nextCodexRestartNoticeByPtyId[ptyId] - } - const nextLastKnownRelay = - remainingPtyIds.length === 0 - ? { ...s.lastKnownRelayPtyIdByTabId } - : s.lastKnownRelayPtyIdByTabId - if (remainingPtyIds.length === 0) { - delete nextLastKnownRelay[opts.tabId] - } - let nextRuntimePaneTitlesByTabId = s.runtimePaneTitlesByTabId - const numericPaneId = Number(opts.leafId) - if ( - Number.isInteger(numericPaneId) && - s.runtimePaneTitlesByTabId[opts.tabId]?.[numericPaneId] - ) { - const nextByPane = { ...s.runtimePaneTitlesByTabId[opts.tabId] } - delete nextByPane[numericPaneId] - nextRuntimePaneTitlesByTabId = { ...s.runtimePaneTitlesByTabId } - if (Object.keys(nextByPane).length > 0) { - nextRuntimePaneTitlesByTabId[opts.tabId] = nextByPane - } else { - delete nextRuntimePaneTitlesByTabId[opts.tabId] - } - } - const nextLastTerminalInputAtByPaneKey = { ...s.lastTerminalInputAtByPaneKey } - delete nextLastTerminalInputAtByPaneKey[opts.paneKey] - return { - tabsByWorktree: nextTabsByWorktree, - ptyIdsByTabId: { - ...s.ptyIdsByTabId, - [opts.tabId]: remainingPtyIds - }, - lastKnownRelayPtyIdByTabId: nextLastKnownRelay, - suppressedPtyExitIds: { - ...s.suppressedPtyExitIds, - ...Object.fromEntries(exitGuardPtyIds.map((ptyId) => [ptyId, true] as const)) - }, - codexRestartNoticeByPtyId: nextCodexRestartNoticeByPtyId, - ...(nextRuntimePaneTitlesByTabId !== s.runtimePaneTitlesByTabId - ? { runtimePaneTitlesByTabId: nextRuntimePaneTitlesByTabId } - : {}), - ...removePanesAttention(s, new Set([opts.paneKey])), - lastTerminalInputAtByPaneKey: nextLastTerminalInputAtByPaneKey - } - }) - ) + commitHibernatedPane({ + set, + get, + worktreeId, + opts, + state, + rendererShutdownPtyIds, + exitGuardPtyIds + }) + if ( + opts.lifecycle && + get().agentStatusByPaneKey[opts.paneKey] !== state.agentStatusByPaneKey[opts.paneKey] + ) { + return + } get().dropHibernatedAgentStatusPane(worktreeId, opts.paneKey, { retainedCompletionEvidence }) diff --git a/src/shared/automation-terminal-lifecycle.ts b/src/shared/automation-terminal-lifecycle.ts new file mode 100644 index 000000000000..bab7ac7b1d4c --- /dev/null +++ b/src/shared/automation-terminal-lifecycle.ts @@ -0,0 +1,78 @@ +/** Local desktop IPC only; resume records stay with the ordinary session owner. */ +export type AutomationTerminalTarget = { + worktreeId: string + tabId: string + leafId: string + paneKey: string +} + +export type AutomationTerminalCorrelation = { + requestId: string + registrationId: string + runId: string + operationId: string + serviceGeneration: string + documentEpoch: string | null +} + +export type AutomationTerminalLifecycleRequest = AutomationTerminalCorrelation & + ( + | { operation: 'arm'; target: AutomationTerminalTarget } + | { operation: 'bind'; ptyId: string; incarnationId: string; hostId: string } + | { operation: 'finalize'; phase: 'prepare'; preservePane: boolean } + | { operation: 'finalize'; phase: 'authorize' } + | { operation: 'finalize'; phase: 'stop-settled'; proof: 'stopped' | 'live' | 'unproven' } + | { operation: 'release' } + ) + +export type AutomationTerminalLifecycleResponse = AutomationTerminalCorrelation & { + disposition: + | 'armed' + | 'bound' + | 'prepared' + | 'authorized' + | 'released' + | 'kept' + | 'closed' + | 'hibernated' + | 'kept-live' + | 'stopped-but-uncommitted' + | 'unproven' +} + +export function automationTerminalLifecycleResponse( + request: AutomationTerminalLifecycleRequest, + documentEpoch: string, + disposition: AutomationTerminalLifecycleResponse['disposition'] +): AutomationTerminalLifecycleResponse { + return { ...request, documentEpoch, disposition } +} + +export function isCurrentAutomationTerminalRequest< + T extends { request: AutomationTerminalCorrelation } +>( + owner: T | undefined, + request: AutomationTerminalLifecycleRequest, + documentEpoch: string +): owner is T { + return ( + !!owner && + (request.documentEpoch === documentEpoch || request.operation === 'release') && + owner.request.runId === request.runId && + owner.request.operationId === request.operationId && + owner.request.serviceGeneration === request.serviceGeneration + ) +} + +export type AutomationTerminalLifecycleOwner = { + request: AutomationTerminalLifecycleRequest + target: AutomationTerminalTarget + ownership: Ownership + ptyId: string | null + prepared: boolean + transactionCurrent?: () => boolean + authorized: boolean + proof?: 'stopped' | 'live' | 'unproven' + settle?: (proof: 'stopped' | 'live' | 'unproven') => void + completion?: Promise +} From 94468679ef5673f606bec2233e9572635fa5c3bf Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 27 Oct 2026 07:09:42 -0700 Subject: [PATCH 03/23] Keep stale prompt projection available when recomputing --- .../structured-agent-session-actionable-prompts.ts | 10 +++++----- .../structured-agent-session-current-work.ts | 7 ++++--- 2 files changed, 9 insertions(+), 8 deletions(-) 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 index a44213f4df5c..44ffbe9b9268 100644 --- 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 @@ -14,18 +14,18 @@ export type PromptProjection = { dependencies: Set } -export function canReusePromptProjection( +export function reusePromptProjection( journal: Partial>, prior: PromptProjection | undefined, cursor: Pick, liveFence: number | null -): prior is PromptProjection { +): AgentJournalRenderItem[] | undefined { if ( prior?.epoch === cursor.epoch && prior.sequence === cursor.sequence && prior.fence === liveFence ) { - return true + return prior.items } if (prior?.epoch === cursor.epoch && prior.fence === liveFence && journal.readSince) { const delta = journal.readSince(prior, 200) @@ -48,8 +48,8 @@ export function canReusePromptProjection( ) ) { prior.sequence = cursor.sequence - return true + return prior.items } } - return false + return undefined } 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 464854145a20..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,5 +1,5 @@ import { - canReusePromptProjection, + reusePromptProjection, type PromptProjection } from './structured-agent-session-actionable-prompts' import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' @@ -232,8 +232,9 @@ export class StructuredAgentSessionCurrentWork { actionablePrompts(): AgentJournalRenderItem[] { const cursor = this.journal.cursor() const prior = promptProjections.get(this.journal) - if (canReusePromptProjection(this.journal, prior, cursor, 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[] = [] From cf9d32cf6e1a067211d02ebe6519d31658d58ed3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 27 Oct 2026 07:13:00 -0700 Subject: [PATCH 04/23] Count repeated desktop lifecycle resource cleanup --- .../lib/automation-terminal-ownership.test.ts | 36 ++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/src/renderer/src/lib/automation-terminal-ownership.test.ts b/src/renderer/src/lib/automation-terminal-ownership.test.ts index 87c0b9e1c058..8574b047f784 100644 --- a/src/renderer/src/lib/automation-terminal-ownership.test.ts +++ b/src/renderer/src/lib/automation-terminal-ownership.test.ts @@ -1,3 +1,4 @@ +import { stopRevokers } from '../../../main/automations/desktop-run-terminal-stop' import type { PtyShutdownOptions } from '../../../main/providers/pty-provider-contract' import type * as ChildProcess from 'node:child_process' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -118,6 +119,16 @@ afterEach(() => { function fixture() { const store = createTestStore() + let subscribers = 0 + const subscribe = store.subscribe + vi.spyOn(store, 'subscribe').mockImplementation((listener) => { + const release = subscribe(listener) + subscribers++ + return () => { + subscribers-- + release() + } + }) mocks.store = store const api = createStoreSessionMockApi() const listeners = new EventEmitter() @@ -336,6 +347,7 @@ function fixture() { } return { store, + activeSubscribers: () => subscribers, session, runtime, lifecycle, @@ -691,11 +703,16 @@ describe('desktop completion through local publication and process owner', () => ).toBeNull() }) it.each([5, 50])('bounds repeated cleanup resources at N=%i', async (count) => { + const timers = vi.spyOn(globalThis, 'setTimeout') + const cleared = vi.spyOn(globalThis, 'clearTimeout') const f = fixture() for (let n = 1; n <= count; n++) { const t = f.publish(n, n % 2 === 0, n % 3 === 0) expect(await f.lifecycle.finalize(t.run)).toMatchObject({ terminalPtyId: null }) expect([...ptyProcesses.keys()]).toEqual(['setup']) + expect(ptyShutdownOperations.size).toBe(0) + expect(stopRevokers.size).toBe(0) + expect(f.activeSubscribers()).toBe(0) expect(f.web.eventNames()).toEqual([]) expect(mocks.ipc!.eventNames()).toEqual([]) expect(isPtyDataHandlerShutdownPending(t.run.terminalPtyId)).toBe(false) @@ -706,13 +723,24 @@ describe('desktop completion through local publication and process owner', () => (r) => r.origin === 'worktree-sleep' ) ).toHaveLength(Math.floor(count / 2)) - console.info( - JSON.stringify({ + const protocolTimers = timers.mock.calls.flatMap((args, index) => + args[1] === 20_000 ? [timers.mock.results[index].value] : [] + ) + expect(protocolTimers.length).toBeGreaterThan(0) + expect(protocolTimers.length).toBeLessThanOrEqual(5 * count) + for (const timer of protocolTimers) { + expect(cleared).toHaveBeenCalledWith(timer) + } + process.stdout.write( + `${JSON.stringify({ desktopRuns: count, livePtys: ptyProcesses.size, shutdowns: ptyShutdownOperations.size, - relayListeners: mocks.ipc!.eventNames().length - }) + registrations: stopRevokers.size, + subscribers: f.activeSubscribers(), + relayListeners: mocks.ipc!.eventNames().length, + protocolTimers: protocolTimers.length + })}\n` ) }) }) From 62ca31617e2dd79ecef49f5885e3862292dade60 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:44:18 -0700 Subject: [PATCH 05/23] Preserve automation targets and observe committed chat work --- .../automation-agent-run-result.ts | 93 +++ .../automation-chat-session-reuse.ts | 58 +- .../desktop-run-terminal-lifecycle.ts | 2 +- .../headless-automation-agent-launch.test.ts | 262 +++++- .../headless-automation-agent-launch.ts | 88 +- .../runtime-chat-run-observer.test.ts | 755 ++++++++++++------ .../automations/runtime-chat-run-observer.ts | 221 ++--- .../journal-stop-marks.ts | 10 +- .../agent-session-journal/journal-store.ts | 18 +- ...tructured-agent-session-client-delivery.ts | 12 +- ...ctured-agent-session-conversations.test.ts | 144 +++- .../structured-agent-session-conversations.ts | 146 +++- .../structured-agent-session-host.ts | 27 +- ...ctured-agent-session-publication-wiring.ts | 29 + ...ructured-agent-session-subscribers.test.ts | 2 +- ...omation-terminal-ownership-test-harness.ts | 292 +++++++ .../lib/automation-terminal-ownership.test.ts | 552 ++++++------- 17 files changed, 1915 insertions(+), 796 deletions(-) create mode 100644 src/main/automations/automation-agent-run-result.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-publication-wiring.ts create mode 100644 src/renderer/src/lib/automation-terminal-ownership-test-harness.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..9c2cb976a5aa --- /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 { HeadlessAutomationAgentLaunch } from './headless-automation-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 +): HeadlessAutomationAgentLaunch { + 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: HeadlessAutomationAgentLaunch +): 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: HeadlessAutomationAgentLaunch | 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-session-reuse.ts b/src/main/automations/automation-chat-session-reuse.ts index cfae6142495f..c5a505c67b30 100644 --- a/src/main/automations/automation-chat-session-reuse.ts +++ b/src/main/automations/automation-chat-session-reuse.ts @@ -11,7 +11,7 @@ import { structuredAgentSessionMessageSendMutation, structuredAgentSessionSendBody } from '../../shared/structured-agent-session-send-mutation' -import { tuiAgentDisplayName } from '../../shared/tui-agent-display-names' +import { automationRunAcceptedTarget } from './automation-agent-run-result' export async function reuseAutomationChat( runtime: OrcaRuntimeService, @@ -53,17 +53,30 @@ export async function reuseAutomationChat( if (!current || !work || work.working()) { continue } - const sent = await host.send( - { callerKey: rpcCallerOperationKey(AUTOMATION_AGENT_CALLER) }, - structuredAgentSessionMessageSendMutation({ - sessionId: id, - clientOperationId: automationRunOperationId(run, 'reuse-send'), - expectedRuntimeFence: current.currentFence, - delivery: 'queue-if-active', - body: structuredAgentSessionSendBody(automation.prompt, []) - }) - ) - if (!sent.ok) { + const target: HeadlessAutomationAgentLaunch = { + workspaceId: record.location.workspaceId, + workspaceDisplayName: null, + sessionKind: 'chat', + chatSessionId: id, + terminalHandle: null, + terminalSessionId: null, + terminalPaneKey: null, + terminalPtyId: null + } + try { + const sent = await host.send( + { callerKey: rpcCallerOperationKey(AUTOMATION_AGENT_CALLER) }, + structuredAgentSessionMessageSendMutation({ + sessionId: id, + clientOperationId: automationRunOperationId(run, 'reuse-send'), + expectedRuntimeFence: current.currentFence, + delivery: 'queue-if-active', + body: structuredAgentSessionSendBody(automation.prompt, []) + }) + ) + if (sent.ok) { + return target + } const row = store.getOperationRow( rpcCallerOperationKey(AUTOMATION_AGENT_CALLER), automationRunOperationId(run, 'reuse-send') @@ -71,20 +84,15 @@ export async function reuseAutomationChat( if (sent.refusal.code === 'agent_session_conflict' || row?.outcome.status === 'failed') { return null } - throw new Error( - `${tuiAgentDisplayName(automation.agentId)} could not accept this automation run. Open the chat and try again.` + return automationRunAcceptedTarget( + runtime, + run, + target, + new Error('send refused'), + automation.agentId ) - } - const shown = await runtime.showManagedWorktree(`id:${automation.workspaceId}`) - return { - workspaceId: automation.workspaceId!, - workspaceDisplayName: shown.displayName ?? null, - sessionKind: 'chat', - chatSessionId: id, - terminalHandle: null, - terminalSessionId: null, - terminalPaneKey: null, - terminalPtyId: null + } catch (error) { + return automationRunAcceptedTarget(runtime, run, target, error, automation.agentId) } } return null diff --git a/src/main/automations/desktop-run-terminal-lifecycle.ts b/src/main/automations/desktop-run-terminal-lifecycle.ts index f19d12e5dd2b..27b4fd3a828a 100644 --- a/src/main/automations/desktop-run-terminal-lifecycle.ts +++ b/src/main/automations/desktop-run-terminal-lifecycle.ts @@ -273,7 +273,7 @@ export function createDesktopRunTerminalLifecycle( run: Pick, operationId: string ) => { - if (automation.reuseSession || (automation.surface ?? 'terminal') !== 'terminal') { + if (automation.reuseSession) { return null } try { diff --git a/src/main/automations/headless-automation-agent-launch.test.ts b/src/main/automations/headless-automation-agent-launch.test.ts index 01d56591ca5e..fda3edb49839 100644 --- a/src/main/automations/headless-automation-agent-launch.test.ts +++ b/src/main/automations/headless-automation-agent-launch.test.ts @@ -1,4 +1,25 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { agentJournalSubmissionKey } from '../../shared/agent-session-journal-item-key' +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 { hostTestAttachParams } from '../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { runHeadlessAutomationDispatch } from './headless-dispatch-runner' +import { observeAutomationChatRun } from './runtime-chat-run-observer' +import { createAutomationRunWriter } from './automation-run-writer' +import { + createStore, + closeTestStores, + testState, + readPersistedStateJson +} from '../persistence/persistence-test-harness' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createAutomationRunWorkspaceAction } from '../../renderer/src/components/automations/automation-run-workspace-action' +import type { AutomationsPageActionContext } from '../../renderer/src/components/automations/automations-page-action-context' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { AgentLaunchResult } from '../../shared/agent-launch-intent' import { buildProfileStateCutoverFixture } from '../persistence/profile-state-cutover-fixture' @@ -7,13 +28,36 @@ import { tokenizeStartupCommand } from '../../shared/tui-agent-startup-shell' import { launchHeadlessAutomationAgent } from './headless-automation-agent-launch' const mocks = vi.hoisted(() => ({ + actualHost: null as StructuredAgentSessionHost | null, + openChat: vi.fn(), + readChat: vi.fn(async () => ({})), launch: vi.fn(), host: { journalSnapshot: vi.fn(), currentWork: vi.fn(), send: vi.fn() } })) vi.mock('../runtime/rpc/methods/agent-launch', () => ({ launchAgentOnHost: mocks.launch })) vi.mock('../native-chat/agent-session-wire/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => mocks.host + getStructuredAgentSessionHost: () => mocks.actualHost ?? mocks.host })) +vi.mock('@/runtime/structured-agent-session-client', () => ({ + callStructuredAgentSession: (...args: unknown[]) => mocks.readChat(...args) +})) +vi.mock('@/lib/structured-agent-session-launch-surface', () => ({ + openStructuredAgentSessionProvisionalTab: (...args: unknown[]) => mocks.openChat(...args) +})) +vi.mock('@/lib/worktree-activation', () => ({ activateAndRevealWorktree: () => true })) +vi.mock('@/store', () => ({ + useAppStore: { + 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 = { @@ -75,6 +119,7 @@ function fixture() { } beforeEach(() => { vi.clearAllMocks() + mocks.actualHost = null mocks.launch.mockResolvedValue(terminal) mocks.host.currentWork.mockReturnValue({ working: () => false }) mocks.host.send.mockResolvedValue({ ok: true }) @@ -108,6 +153,7 @@ describe('automations through agent.launch', () => { }) ) expect(result).toMatchObject({ + workspaceDisplayName: 'Audit', sessionKind: 'terminal', chatSessionId: null, terminalPtyId: 'pty-1' @@ -258,7 +304,7 @@ describe('automations through agent.launch', () => { } ] }) - ).rejects.toThrow('Open its workspace before running again.') + ).rejects.toMatchObject({ target: { workspaceId: 'wt-1', sessionKind: 'terminal' } }) expect(mocks.launch).toHaveBeenCalledTimes(1) }) it('reuses only a completed compatible idle chat and derives a separate send identity', async () => { @@ -317,15 +363,27 @@ describe('automations through agent.launch', () => { it.each(['terminal', 'chat', 'reuse-terminal'] as const)( 'preserves published %s identity for refused, uncertain and throwing settlement', async (kind) => { - const { runtime } = fixture() + 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'] as const) { + 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, + kind === 'reuse-terminal' ? 'reuse-terminal-launch' : 'fresh-launch' + ) + ? { outcome: { status: 'succeeded', launch: published } } + : undefined + ) + throw new Error('accepted reply lost') + } if (outcome === 'throw') { throw new Error('settlement transport lost') } @@ -354,7 +412,7 @@ it.each(['terminal', 'chat', 'reuse-terminal'] as const)( ] : [] }).catch((error) => error) - expect(result).toMatchObject({ + expect(outcome === 'accepted-throw' ? { target: result } : result).toMatchObject({ target: { workspaceId: 'wt-1', sessionKind: kind === 'chat' ? 'chat' : 'terminal', @@ -368,7 +426,197 @@ it.each(['terminal', 'chat', 'reuse-terminal'] as const)( } }) } - expect(mocks.launch).toHaveBeenCalledTimes(3) + expect(mocks.launch).toHaveBeenCalledTimes(4) expect(mocks.host.send).not.toHaveBeenCalled() } ) + +it('keeps accepted reused Chat through throwing metadata/reply, real runner persistence, observation and normal Details', async () => { + vi.spyOn(Date, 'now').mockReturnValue(1_800_000_000_000) + const rig = await createQueuedMessageTestRig({ restartable: true }) + mocks.actualHost = rig.host + const root = mkdtempSync(join(tmpdir(), 'orca-34332-accepted-')) + testState.dir = root + const disk = createStore() + const id = 'codex_reused' + const initial = hostTestAttachParams(null) + const controller = new AbortController() + try { + expect( + await rig.host.create( + { callerKey: 'initial' }, + hostTestAttachParams(null, { + envelope: { ...initial.envelope, sessionId: id }, + location: { ...initial.location, workspaceId: 'wt-1' } + }) + ) + ).toMatchObject({ ok: true }) + disk.addRepo(state.repos[0]) + const saved = disk.createAutomation({ + ...automation, + agentId: 'codex', + surface: 'chat', + reuseSession: true, + projectId: state.repos[0].id + }) + const writer = createAutomationRunWriter(disk, null) + const sent = rig.host.send.bind(rig.host) + for (const lostReply of [false, true]) { + const current = await writer.createRun(saved, Date.now(), 'manual') + const previous = { + ...current, + id: 'previous', + status: 'completed' as const, + workspaceId: 'wt-1', + sessionKind: 'chat' as const, + chatSessionId: id + } + const send = vi.spyOn(rig.host, 'send').mockImplementationOnce(async (...args) => { + const answer = await sent(...args) + expect(answer.ok).toBe(true) + if (lostReply) { + throw new Error('accepted reply lost') + } + return answer + }) + // SAFETY: runtime transport/metadata only; send, receipt, result, runner, writer and observer use their actual owners. + const runtime = { + ensureStructuredAgentSessionHost: async () => {}, + openAgentSessionRecordStore: async () => rig.store, + showManagedWorktree: async () => { + throw new Error('optional display unavailable') + } + } as unknown as OrcaRuntimeService + const dispatched = await runHeadlessAutomationDispatch({ + automation: saved, + run: current, + target, + runs: writer, + dispatcher: () => + launchHeadlessAutomationAgent(runtime, { + automation: saved, + run: current, + target, + runs: [previous] + }), + runPrecheck: async () => null, + markDispatchResult: writer.updateRun, + watchRun: () => {} + }) + expect(send).toHaveBeenCalledOnce() + expect(dispatched).toMatchObject({ + status: 'dispatched', + sessionKind: 'chat', + chatSessionId: id + }) + const pending = observeAutomationChatRun(runtime, dispatched, controller.signal) + const journal = rig.host.collaboratorsForTests().sessions.get(id)!.journal + const message = automationRunOperationId(current, 'reuse-send') + await eventually(() => expect(journal.submission(message)).toBeDefined()) + const item = await journal.appendItem( + { provider: 'orca', clientMessageId: `turn-${current.id}` }, + { + kind: 'turn', + turnId: current.id, + userItemId: agentJournalSubmissionKey(message), + state: 'running' + }, + { fence: 1, turnScope: { kind: 'thread' } } + ) + await journal.resolveDispatch({ + clientMessageId: message, + state: 'accepted', + providerIdentity: { provider: 'orca', clientMessageId: message }, + fence: 1 + }) + await journal.appendItem( + { provider: 'orca', clientMessageId: `answer-${current.id}` }, + { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: 'Exact automation output' }] + }, + { fence: 1, turnScope: { kind: 'turn', turnItemId: item.itemId } } + ) + await journal.appendItem( + { provider: 'orca', clientMessageId: `turn-${current.id}` }, + { + kind: 'turn', + turnId: current.id, + userItemId: agentJournalSubmissionKey(message), + state: 'completed', + outcome: 'success' + }, + { fence: 1, turnScope: { kind: 'thread' } } + ) + const observation = await pending + const completed = await writer.updateRun({ runId: current.id, ...observation }) + expect(completed).toMatchObject({ + status: 'completed', + chatSessionId: id, + outputSnapshot: { content: 'Exact automation output' } + }) + const persisted = JSON.parse(readPersistedStateJson(join(root, 'orca-data.json'))) + expect( + persisted.automationRuns.find((row: { id: string }) => row.id === current.id) + ).toMatchObject({ chatSessionId: id, status: 'completed' }) + // SAFETY: normal action's surrounding page context is scripted; actual Details action executes. + const context = { + store: { + repoForRow: () => undefined, + worktreeForRow: () => ({ id: 'wt-1', hostId: 'local' }) + }, + list: { selectedRow: { key: 'row' } } + } as unknown as AutomationsPageActionContext + createAutomationRunWorkspaceAction(context)(completed) + await eventually(() => + expect(mocks.openChat).toHaveBeenCalledWith( + expect.objectContaining({ sessionId: id, agent: 'codex' }) + ) + ) + send.mockRestore() + mocks.openChat.mockClear() + } + } finally { + controller.abort() + mocks.actualHost = null + await rig.dispose() + await closeTestStores() + rmSync(root, { recursive: true, force: true }) + } +}) + +it.each(['unknown', 'refused'] 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: 'agent_session_operation_unknown' } } + }) + records.getOperationRow.mockReturnValue(undefined) + await expect( + launchHeadlessAutomationAgent(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/src/main/automations/headless-automation-agent-launch.ts b/src/main/automations/headless-automation-agent-launch.ts index 59d515809603..e5c4a56e506f 100644 --- a/src/main/automations/headless-automation-agent-launch.ts +++ b/src/main/automations/headless-automation-agent-launch.ts @@ -11,7 +11,12 @@ import { AutomationRunLaunchError, type HeadlessAutomationDispatchLaunch } from './headless-dispatch' -import { parsePaneKey } from '../../shared/stable-pane-id' +import { + publishedLaunchTarget, + enrichAutomationRunTarget, + automationRunAcceptedTarget +} from './automation-agent-run-result' +export { publishedLaunchTarget } from './automation-agent-run-result' import { automationRunOperationId, AUTOMATION_AGENT_CALLER } from './automation-run-operation' import { createAutomationDispatchToken } from './dispatch-tokens' import { mergeExtraAgentArgs, hasExtraAgentArgs } from '../../shared/automation-extra-agent-args' @@ -41,7 +46,10 @@ export async function launchHeadlessAutomationAgent( lifecycle?: ReturnType['begin']> ): Promise { try { - return await launchAutomationAgent(runtime, request, lifecycle) + return await enrichAutomationRunTarget( + runtime, + await launchAutomationAgent(runtime, request, lifecycle) + ) } catch (error) { lifecycle?.release() if (error instanceof AutomationRunLaunchError) { @@ -98,6 +106,10 @@ async function launchAutomationAgent( liveSession: (previous) => runOwnHandle(runtime, previous) }) if (reused) { + published = publishedLaunchTarget(runtime, { + worktreeId: automation.workspaceId, + outcome: { kind: 'terminal', handle: reused } + }) const operationId = automationRunOperationId(run, 'reuse-terminal-launch') try { const result = await launchAgentOnHost( @@ -115,19 +127,13 @@ async function launchAutomationAgent( ) published ??= publishedLaunchTarget(runtime, result) if (result.prompt?.outcome === 'handed-to-terminal') { - return launchOutcome(runtime, result) + return publishedLaunchTarget(runtime, result) } throw new AutomationRunLaunchError( `${tuiAgentDisplayName(automation.agentId)} could not confirm this run's prompt. Open the terminal before running again.`, published ) } catch (error) { - if (published) { - throw new AutomationRunLaunchError( - `${tuiAgentDisplayName(automation.agentId)} could not confirm this run's prompt. Open the terminal before running again.`, - published - ) - } const records = await runtime.openAgentSessionRecordStore() const row = records.getOperationRow( rpcCallerOperationKey(AUTOMATION_AGENT_CALLER), @@ -135,8 +141,9 @@ async function launchAutomationAgent( ) // Only the launch owner's durable no-effect verdict permits a different launch. if (row?.outcome.status !== 'failed') { - throw error + return automationRunAcceptedTarget(runtime, run, published, error, automation.agentId) } + published = undefined } } } @@ -205,7 +212,7 @@ async function launchAutomationAgent( published ?? publishedLaunchTarget(runtime, result) ) } - return launchOutcome(runtime, result) + return publishedLaunchTarget(runtime, result) } catch (error) { if ( error instanceof Error && @@ -217,65 +224,8 @@ async function launchAutomationAgent( `${tuiAgentDisplayName(automation.agentId)} could not start because this run waited too long. Run the automation again.` ) } - if (published && !(error instanceof AutomationRunLaunchError)) { - throw new AutomationRunLaunchError( - `${tuiAgentDisplayName(automation.agentId)} started, but Orca could not confirm this run's prompt. Open the run before trying again.`, - published - ) - } - throw error - } -} - -export function publishedLaunchTarget( - runtime: Pick, - result: AgentLaunchResult -): HeadlessAutomationAgentLaunch { - 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 - } -} - -async function launchOutcome( - runtime: OrcaRuntimeService, - result: AgentLaunchResult -): Promise { - const target = publishedLaunchTarget(runtime, result) - try { - const shown = await runtime.showManagedWorktree(`id:${result.worktreeId}`) - target.workspaceDisplayName = shown.displayName ?? null - } catch { - // Publication already owns the target; optional display metadata cannot erase it. - } - if (result.outcome.kind === 'terminal' && !target.terminalSessionId) { - try { - target.terminalSessionId = (await runtime.showTerminal(result.outcome.handle)).tabId ?? null - } catch { - // Keep the published pane and process identity when its presentation is unavailable. - } + return automationRunAcceptedTarget(runtime, run, published, error, automation.agentId) } - return target } /** A pane may have been reused by a later process. */ diff --git a/src/main/automations/runtime-chat-run-observer.test.ts b/src/main/automations/runtime-chat-run-observer.test.ts index 408e3e1d6a7d..6e886042968e 100644 --- a/src/main/automations/runtime-chat-run-observer.test.ts +++ b/src/main/automations/runtime-chat-run-observer.test.ts @@ -8,6 +8,7 @@ import { agentJournalSubmissionKey } from '../../shared/agent-session-journal-it 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, @@ -23,7 +24,11 @@ import { automationRunOperationId } from './automation-run-operation' const mocks = vi.hoisted(() => ({ actualHost: null as StructuredAgentSessionHost | null, - host: { journalSnapshot: vi.fn(), subscribe: vi.fn(), queuedSendAnswer: vi.fn(async () => null) } + host: { + journalSnapshot: vi.fn(), + observeJournalPublications: vi.fn(), + queuedSendAnswer: vi.fn(async () => null) + } })) vi.mock('../native-chat/agent-session-wire/structured-agent-session-registry', () => ({ getStructuredAgentSessionHost: () => mocks.actualHost ?? mocks.host @@ -180,45 +185,114 @@ describe('restart observation and disposal', () => { view.submissions = [{ ...submission, clientMessageId: messageId }] return { run, records, runtime, view } } - it('subscribes before snapshot, ignores token deltas, and releases a subscription that arrives after abort', async () => { + it('registers synchronously before read and abort wins over a late read', async () => { const { run, runtime, view } = fixture() const release = vi.fn() - const subscription = Promise.withResolvers<() => void>() - mocks.host.subscribe.mockReturnValue(subscription.promise) - mocks.host.journalSnapshot.mockResolvedValue(view) + const read = Promise.withResolvers() + mocks.host.observeJournalPublications.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.subscribe).toHaveBeenCalledOnce()) - expect(mocks.host.journalSnapshot).not.toHaveBeenCalled() + await vi.waitFor(() => expect(mocks.host.journalSnapshot).toHaveBeenCalledOnce()) controller.abort() await rejected - subscription.resolve(release) - await vi.waitFor(() => expect(release).toHaveBeenCalledOnce()) + read.resolve(view) + await Promise.resolve() + expect(release).toHaveBeenCalledOnce() + expect(mocks.host.queuedSendAnswer).not.toHaveBeenCalled() }) - it('reattaches from the persisted receipt without sending, observes completion, and unsubscribes', async () => { + it('fences replacement and row-free changes across both awaits without losing exact completion', async () => { const { run, runtime, view } = fixture() const release = vi.fn() - mocks.host.subscribe.mockResolvedValue(release) - mocks.host.journalSnapshot.mockResolvedValue(view) + const source = {} + let notify: (hint: JournalPublication) => void = () => {} + mocks.host.observeJournalPublications.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()) - const emit = mocks.host.subscribe.mock.calls[0][0].emit - emit({ type: 'batch', batch: { submissions: [], items: [answer('delta', 'own', 'token')] } }) - await Promise.resolve() - 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!) - emit({ type: 'batch', batch: { submissions: [], items: [view.items[0]] } }) + 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.observeJournalPublications.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.subscribe).not.toHaveBeenCalled() + expect(mocks.host.observeJournalPublications).not.toHaveBeenCalled() }) }) @@ -227,276 +301,395 @@ 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 rig = await createQueuedMessageTestRig({ restartable: true }) - mocks.actualHost = rig.host - const controller = new AbortController() - try { - const working = await rig.workingSend() - let sink = rig.providerEvents() - for (let n = 0; n < history; n++) { - 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 journal = rig.host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)!.journal - let projections = 0, - projectedRows = 0, - scannedRows = 0 - const materialized = new WeakSet() - const realPublicRead = journal.publicRead.bind(journal) - 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 result + 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?.() } } - }) - const visitItems = journal.visitItems.bind(journal) - 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 + await sink.written?.() + const run = { + ...buildProfileStateCutoverFixture('/fixture').automationRuns[0], + createdAt: Date.now(), + dispatchedAt: Date.now(), + sessionKind: 'chat' as const, + chatSessionId: HOST_TEST_SESSION } - return value - }) - const timers = vi.spyOn(globalThis, 'setTimeout'), - cleared = vi.spyOn(globalThis, 'clearTimeout') - let visited = 0 - const realSnapshot = journal.snapshot.bind(journal) - const full = vi.spyOn(journal, 'snapshot').mockImplementation((...args) => { - const value = realSnapshot(...args) - visited += value.items.length + value.submissions.length - return value - }) - const tokenBurst = async () => { - for (let n = 0; n < 25; n++) { - sink.appendItem( - { provider: 'codex', threadId: HOST_TEST_THREAD, turnId: 'unrelated', ordinal: 1 }, + 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' }, { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: `token-${n}` }] - }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ...fields, + envelope: rig.envelope(fields, 'agentSession.send', q) + } ) - sink.publish() - await sink.written?.() - await rig.host.flushStreamedEvents(HOST_TEST_SESSION) - } - } - const deltaBaseline = [deltas.mock.calls.length, deltaRows] - const beforeBaseline = full.mock.calls.length - const projectionBaseline = [projections, projectedRows, scannedRows] - const visitedBeforeBaseline = visited - await tokenBurst() - const baselineDeltas = [ - deltas.mock.calls.length - deltaBaseline[0], - deltaRows - deltaBaseline[1] - ] - const baselineSnapshots = full.mock.calls.length - beforeBaseline - const baselineVisited = visited - visitedBeforeBaseline - const baselineProjection = [projections, projectedRows, scannedRows].map( - (v, i) => v - projectionBaseline[i] - ) - const releases: (() => void)[] = [] - const eventTypes: Record = {} - const latest: unknown[] = [] - const observerReads = vi.spyOn(rig.host, 'journalSnapshot') - const realSubscribe = rig.host.subscribe.bind(rig.host) - const subscribe = vi.spyOn(rig.host, 'subscribe').mockImplementation(async (...args) => { - const input = args[0] - const release = await realSubscribe({ - ...input, - emit: (event) => { - eventTypes[event.type] = (eventTypes[event.type] ?? 0) + 1 - if (event.type !== 'end') { - latest.push(event.type === 'batch' ? event.latestTurn : event.page.latestTurn) + ).toMatchObject({ ok: true, value: { queued: { messageId: q, state: 'waiting' } } }) + 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 result } - input.emit(event) } }) - const wrapped = vi.fn(release) - releases.push(wrapped) - return wrapped - }) - // SAFETY: only receipt acquisition is a transport stand-in; the observer uses the actual host below. - const runtime = { - 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' } }) + 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 }) - } as unknown as OrcaRuntimeService - let pending = observeAutomationChatRun(runtime, run, controller.signal) - void pending.catch(() => {}) - await eventually(() => expect(subscribe).toHaveBeenCalledOnce()) - await rig.host.flushStreamedEvents(HOST_TEST_SESSION) - await eventually(() => expect(full.mock.calls.length).toBeGreaterThan(0)) - const beforeTokens = full.mock.calls.length - const projectionTokens = [projections, projectedRows, scannedRows] - const tokenDeltas = [deltas.mock.calls.length, deltaRows] - const readsBeforeTokens = observerReads.mock.calls.length - const visitedBeforeTokens = visited - await tokenBurst() - expect(observerReads.mock.calls.length).toBe(readsBeforeTokens) - expect(full.mock.calls.length - beforeTokens).toBeLessThanOrEqual(baselineSnapshots) - expect(visited - visitedBeforeTokens).toBeLessThanOrEqual(baselineVisited) - expect( - [projections, projectedRows, scannedRows].map((v, i) => v - projectionTokens[i]) - ).toEqual(baselineProjection) - // One row per token in ordinary catch-up and one in prompt-cache invalidation. - expect([deltas.mock.calls.length - tokenDeltas[0], deltaRows - tokenDeltas[1]]).toEqual([ - baselineDeltas[0] + 50, - baselineDeltas[1] + 50 - ]) - controller.abort() - await expect(pending).rejects.toThrow('request_aborted') - expect(releases[0]).toHaveBeenCalledOnce() - pending = observeAutomationChatRun(runtime, run, new AbortController().signal) - await eventually(() => expect(subscribe).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) - await eventually(async () => expect(await rig.handoff(q)).toBeDefined()) - const sent = await rig.handoffId(q) - expect(sent).not.toBe(q) - await eventually(() => expect(journal.submission(sent)?.handedOverAt).toBeDefined()) - await rig.settleAccepted(sent, 'automation') - const accepted = await rig.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.publish({ lifecycle: true }) - expect(await sink.written?.()).toEqual({ ok: true }) - await rig.host.flushStreamedEvents(HOST_TEST_SESSION) - expect(await pending).toMatchObject({ status: 'completed' }) - expect(rig.dispatch).toHaveBeenCalledTimes(2) - expect(releases).toHaveLength(2) - for (const release of releases) { - expect(release).toHaveBeenCalledOnce() - } - expect(latest).toContainEqual( - expect.objectContaining({ - turn: expect.objectContaining({ turnId: 'turn-automation', state: 'completed' }) + const timers = vi.spyOn(globalThis, 'setTimeout'), + cleared = vi.spyOn(globalThis, 'clearTimeout') + let visited = 0 + const realSnapshot = journal.snapshot.bind(journal) + const full = vi.spyOn(journal, 'snapshot').mockImplementation((...args) => { + const value = realSnapshot(...args) + visited += value.items.length + value.submissions.length + return value }) - ) - 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) + 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) + } } - } - // Fixed work includes both hydrations, canonical queue handoff and accepted root completion. - expect(full.mock.calls.length - 2 * baselineSnapshots).toBe(23) - expect(visited - 2 * baselineVisited).toBeLessThan((history + 30) * 23) - process.stdout.write( - `${JSON.stringify({ - history, - baselineSnapshots, - baselineVisited, - baselineProjection, - baselineDeltas, + const releases: ReturnType[] = [] + 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: { items: Map } = Reflect.get( + 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 + } + }) + const fullApis = [ + 'pendingSubmissions', + 'runningTurn', + 'newestTurn', + 'threadGoalSource', + 'contextUsage', + 'visitItemsWithLinkage' + ] as const + const calls = fullApis.map((name) => vi.spyOn(journal, name)) + const keys = [ + vi.spyOn(journal, 'item'), + vi.spyOn(journal, 'submission'), + vi.spyOn(journal.queuedMessages, 'get'), + vi.spyOn(journal, 'canonicalItemId') + ] + const observerReads = vi.spyOn(rig.host, 'journalSnapshot') + const realObserve = rig.host.observeJournalPublications.bind(rig.host) + const registration = vi + .spyOn(rig.host, 'observeJournalPublications') + .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, - deltaReads: deltas.mock.calls.length, - deltaRows, - observerReads: observerReads.mock.calls.length, - eventTypes, - fullSnapshots: full.mock.calls.length, - visited, - subscriptions: subscribe.mock.calls.length - })}\n` - ) - } finally { - controller.abort() - mocks.actualHost = null - await rig.dispose() + full.mock.calls.length, + ...calls.map((spy) => spy.mock.calls.length), + publicReads.mock.calls.length, + submissionCopies.mock.calls.length, + visits.mock.calls.length + ] + 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) + // SAFETY: only receipt acquisition is a transport stand-in; the observer uses the actual host below. + const runtime = { + 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' } + }) + }) + } 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.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' }) + 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) + expect(copied + iteratorYields + projectedRows + scannedRows).toBeLessThan( + (history + 30) * 4000 + ) + const sessions = rig.host.collaboratorsForTests().sessions + expect(Reflect.get(sessions, 'observers').size).toBe(0) + expect(Reflect.get(sessions, 'attachments').size).toBe(1) + totals.push(measure()) + process.stdout.write( + `${JSON.stringify({ history, mode, sourceAttachments: Reflect.get(sessions, 'attachments').size, logicalObservers: Reflect.get(sessions, 'observers').size, baselineWork, observerWork, keyedAdded, totals: measure(), callbacks, committedRows, deltaReads: deltas.mock.calls.length, deltaRows, 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.filter((_, i) => i !== 5 && i !== 12)).toEqual( + added.filter((_, i) => i !== 5 && i !== 12).map(() => 0) + ) + expect(added[5]).toBe(6) + expect(added[12]).toBe(6) + process.stdout.write( + `${JSON.stringify({ history, fullWorkloadBaseline: totals[0], fullWorkloadInternal: totals[1], added, displayControl: totals[2] })}\n` + ) } ) - it.each(['withdraw', 'return'] as const)( + it.each(['withdraw', 'return', 'missing', 'end'] as const)( 'settles a queue-only %s without resending', async (outcome) => { - const rig = await createQueuedMessageTestRig() + const rig = await createQueuedMessageTestRig({ + idleSweep: { idleMs: 0, intervalMs: 3600000 } + }) mocks.actualHost = rig.host try { - await rig.workingSend() - const queued = rig.send('queued', 'queue-if-active') - await queued.result - const q = queued.id + const working = await rig.workingSend() const run = { ...buildProfileStateCutoverFixture('/fixture').automationRuns[0], createdAt: Date.now(), + dispatchedAt: Date.now(), chatSessionId: HOST_TEST_SESSION } - // Exercise canonical queue answers directly as well as live publisher observation above. + 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' } }) + }) + } + // SAFETY: only receipt transport is scripted; all observation and queue lifecycle owners are real. + 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), @@ -506,6 +699,32 @@ describe('real host queue publication and operation bounds', () => { ) ).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), @@ -514,6 +733,17 @@ describe('real host queue publication and operation bounds', () => { 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(Reflect.get(sessions, 'observers').size).toBe(0) + return + } if (outcome === 'withdraw') { await rig.deleteQueued(q) } else { @@ -530,6 +760,7 @@ describe('real host queue publication and operation bounds', () => { 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 diff --git a/src/main/automations/runtime-chat-run-observer.ts b/src/main/automations/runtime-chat-run-observer.ts index 80520632cc53..6fd6c2a9fe1a 100644 --- a/src/main/automations/runtime-chat-run-observer.ts +++ b/src/main/automations/runtime-chat-run-observer.ts @@ -1,3 +1,4 @@ +import type { JournalPublication } from '../native-chat/agent-session-wire/structured-agent-session-conversations' import type { AutomationRun } from '../../shared/automations-types' import type { AgentJournalSnapshot } from '../../shared/agent-session-journal-types' import type { AgentSessionSendResult } from '../../shared/agent-session-wire' @@ -34,20 +35,7 @@ export function chatAutomationRunObservation( if (!submission) { return null } - const keys = new Set([ - agentJournalSubmissionKey(submission.clientMessageId), - ...(submission.providerItemId ? [submission.providerItemId] : []) - ]) - const turnItem = 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)) - ) - }) + const turnItem = submissionTurn(snapshot, submission) const turn = turnItem ? readAgentJournalTurn(turnItem.body) : null if (!turn || !turnItem) { return submission.dispatchState === 'rejected' || submission.dispatchState === 'unknown' @@ -90,6 +78,26 @@ export function chatAutomationRunObservation( } } +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)) + ) + }) +} + export async function observeAutomationChatRun( runtime: OrcaRuntimeService, run: AutomationRun, @@ -122,9 +130,11 @@ export async function observeAutomationChatRun( let settled = false let reading = false let dirty = false - let submissionSignature = '' - let turnSignature = '' - let queueSignature = '' + 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 @@ -133,6 +143,9 @@ export async function observeAutomationChatRun( return } settled = true + source = null + currentJournal = null + cursor = undefined clearTimeout(deadline) signal.removeEventListener('abort', abort) release?.() @@ -151,62 +164,56 @@ export async function observeAutomationChatRun( }), Math.max(1, (run.dispatchedAt ?? run.createdAt) + 6 * 60 * 60 * 1000 - Date.now()) ) - const rememberSubmission = (entry: AgentJournalSnapshot['submissions'][number]): boolean => { - const signature = JSON.stringify([ - entry.clientMessageId, - entry.dispatchState, - entry.providerItemId, - entry.answeredInTurn + 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 changed = signature !== submissionSignature - submissionSignature = signature - submissionId = entry.clientMessageId - providerItemId = entry.providerItemId - turnItemId = entry.answeredInTurn?.via === 'start' ? entry.answeredInTurn.turnItemId : null - return changed - } - const rememberTurn = (item: AgentJournalSnapshot['items'][number]): boolean => { - const turn = readAgentJournalTurn(item.body) - if ( - !turn || - item.agentId || - !( - item.itemId === turnItemId || - (providerItemId !== null && turn.userItemId === providerItemId) || - turn.userItemId === agentJournalSubmissionKey(submissionId) - ) - ) { - return false - } - const signature = JSON.stringify([item.itemId, turn.state, readAgentJournalTurnOutcome(turn)]) - const changed = signature !== turnSignature - turnSignature = signature - return changed } const read = async (): Promise => { if (settled) { return } if (reading) { - dirty = true 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 = queued && 'submission' in queued ? queued.submission : snapshot.submissions.find((entry) => entry.clientMessageId === messageId) if (submission) { - rememberSubmission(submission) - } - for (const item of snapshot.items) { - rememberTurn(item) + submissionId = submission.clientMessageId + providerItemId = submission.providerItemId + turnItemId = submissionTurn(snapshot, submission)?.itemId ?? null } + fingerprint = interest() const observation = chatAutomationRunObservation(snapshot, messageId, agent, queued) if (observation) { finish(observation) @@ -214,9 +221,14 @@ export async function observeAutomationChatRun( } } while (dirty && !settled) } catch (error) { - finish(undefined, error) + if (!dirty) { + finish(undefined, error) + } } finally { reading = false + if (dirty && !settled) { + queueMicrotask(() => void read()) + } } } signal.addEventListener('abort', abort, { once: true }) @@ -224,55 +236,64 @@ export async function observeAutomationChatRun( abort() return } - void host - .subscribe({ - id: `automation:${run.id}`, - sessionId, - emit: (event) => { - let changed = event.type !== 'batch' - const rows = - event.type === 'batch' ? event.batch : event.type === 'end' ? null : event.page - for (const entry of rows?.submissions ?? []) { - if (entry.clientMessageId !== messageId && entry.queuedMessageId !== messageId) { - continue - } - changed = rememberSubmission(entry) || changed - } - for (const item of rows?.items ?? []) { - changed = rememberTurn(item) || changed - } - if ( - event.type === 'batch' && - turnItemId && - event.batch.removedItemIds?.includes(turnItemId) - ) { - changed = true + release = host.observeJournalPublications(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 contiguous = + cursor && + hint.cursor?.epoch === cursor.epoch && + rows?.every( + (row, i) => row.epoch === cursor.epoch && row.seq === cursor.sequence + i + 1 + ) && + hint.cursor.sequence === cursor.sequence + rows.length + const linked = rows?.some((row) => { + if (row.kind === 'submission') { + return row.queuedMessageId === messageId && row.clientMessageId !== submissionId } - if (event.type !== 'end' && event.queuedMessages !== undefined) { - const card = event.queuedMessages?.find((entry) => entry.messageId === messageId) - const signature = JSON.stringify( - card ? [card.messageId, card.state, card.consumedAs] : null - ) - if (signature !== queueSignature) { - changed = true - queueSignature = signature + const mutations = row.kind === 'lifecycle-batch' ? row.mutations : [row] + return mutations.some((item) => { + if (item.kind !== 'item') { + return false } - } - if (changed) { - void read() - } + 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()) } - }) - .then( - (unsubscribe) => { - release = unsubscribe - if (settled) { - unsubscribe() - } else { - void read() - } - }, - (error) => finish(undefined, error) - ) + }, + error: (error) => finish(undefined, error) + }) + if (settled) { + release() + } }) } 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 0f113b7cdec3..2252e66dfb57 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, @@ -115,7 +115,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) => { @@ -176,8 +176,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 => ({ @@ -368,8 +374,4 @@ export class AgentSessionJournal { ): 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/structured-agent-session-client-delivery.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-client-delivery.ts index 8fd442fe040a..edbe2fdaa1c7 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,3 +1,4 @@ +import type { StructuredAgentSessionConversations } from './structured-agent-session-conversations' import { StructuredAgentSessionRequestFailures } from './structured-agent-session-request-failures' import { structuredAgentSessionFailureWordsContext } from './structured-agent-session-send-preparation' import { AT_REST_COMMANDS_READ_BUDGET_MS } from './at-rest-command-catalog' @@ -50,7 +51,11 @@ 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, @@ -156,6 +161,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) { @@ -182,6 +188,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) @@ -197,6 +204,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 }) } @@ -214,6 +222,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) { @@ -226,6 +235,7 @@ export class StructuredAgentSessionClientDelivery { } closeAll(): void { + this.publications?.endPublications() this.requestFailures.clear() this.stopAtRestCommandUpdates() this.sendSettlement.closeAll() 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..52daabd482ca 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,136 @@ 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.observeJournalPublications('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.observeJournalPublications('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 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.observeJournalPublications(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.at(-1)).toMatchObject({ + kind: 'commit', + 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.observeJournalPublications(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..60b49ffe2034 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 } + observeJournalPublications(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) + } + listeners.add(observer) + const release = () => { + listeners.delete(observer) + if (listeners.size === 0) { + this.observers.delete(sessionId) + } + } + 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 observer of observers) { + this.deliverHint(observer, hint, () => { + const listeners = this.observers.get(sessionId) + listeners?.delete(observer) + 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-host.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts index d650c9d4558f..42ebaa2375a8 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 @@ -26,7 +26,7 @@ import type * as HostTypes from './structured-agent-session-host-types' import { StructuredAgentSessionEventRecovery } from './structured-agent-session-event-recovery' import { StructuredAgentSessionBackgroundTaskChannel } 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' @@ -40,16 +40,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()) @@ -62,7 +57,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() @@ -255,7 +251,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() @@ -316,6 +315,8 @@ export class StructuredAgentSessionHost { history: StructuredAgentSessionBackgroundTaskChannel['history'] = (...args) => this.backgroundTasks.history(...args) + observeJournalPublications: typeof this.sessions.observeJournalPublications = (...args) => + this.sessions.observeJournalPublications(...args) journalSnapshot = (sessionId: string) => this.backgroundTasks.journalSnapshot(sessionId) queuedSendAnswer = (sessionId: string, messageId: string) => this.backgroundTasks.queuedSendAnswer(sessionId, messageId) 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/renderer/src/lib/automation-terminal-ownership-test-harness.ts b/src/renderer/src/lib/automation-terminal-ownership-test-harness.ts new file mode 100644 index 000000000000..a8f67b65d1ce --- /dev/null +++ b/src/renderer/src/lib/automation-terminal-ownership-test-harness.ts @@ -0,0 +1,292 @@ +import { EventEmitter } from 'node:events' +import type * as pty from 'node-pty' +import { expect, vi } from 'vitest' +import { buildProfileStateCutoverFixture } from '../../../main/persistence/profile-state-cutover-fixture' +import { + createTestStore, + makeTab, + makeWorktree, + seedStore +} from '@/store/slices/store-test-helpers' +import { createStoreSessionMockApi } from '@/store/slices/store-session-test-harness' +import type { OrcaRuntimeService } from '../../../main/runtime/orca-runtime' +import type { Store } from '../../../main/persistence' +import type { PtyShutdownOptions } from '../../../main/providers/pty-provider-contract' +import { OrcaRuntimeWithStopExactTerminalsForWorktree } from '../../../main/runtime/terminal/stop/worktree-terminal-stop-targets' +import { registerTerminalPresentationIpcBridge } from '@/hooks/ipc-events/terminal-presentation-ipc-bridge' +import { registerAgentLaunchTabIpcBridge } from '@/hooks/ipc-events/agent-launch-tab-ipc-bridge' +import { createDesktopRunTerminalLifecycle } from '../../../main/automations/desktop-run-terminal-lifecycle' +import { + shutdownLocalPty, + createPtyPhysicalExit +} from '../../../main/providers/local-pty-termination' +import { + ptyProcesses, + ptyIncarnations, + ptyPhysicalExits, + clearPtyState +} from '../../../main/providers/local-pty-provider-state' + +export const OWNERSHIP_WORKSPACE_ID = 'repo1::/repo1/main' +const WT = OWNERSHIP_WORKSPACE_ID +const state = buildProfileStateCutoverFixture('/fixture') +const noop = () => {} +export function createAutomationTerminalOwnershipFixture( + mocks: { + store: ReturnType | null + ipc: EventEmitter | null + prepare: () => Promise + }, + cleanups: (() => void)[] +) { + const store = createTestStore() + let subscribers = 0 + const subscribe = store.subscribe + vi.spyOn(store, 'subscribe').mockImplementation((listener) => { + const release = subscribe(listener) + subscribers++ + return () => { + subscribers-- + release() + } + }) + mocks.store = store + const api = createStoreSessionMockApi() + const listeners = new EventEmitter() + const events: string[] = [] + const web = Object.assign(new EventEmitter(), { + mainFrame: {}, + isDestroyed: () => false, + send: (channel: string, payload: unknown) => { + events.push( + channel === 'automations:terminalLifecycleRequest' && + typeof payload === 'object' && + payload !== null && + 'operation' in payload + ? `${payload.operation}:${'phase' in payload ? payload.phase : ''}` + : channel + ) + listeners.emit(channel, payload) + } + }) + const win = Object.assign(new EventEmitter(), { webContents: web, isDestroyed: () => false }) + const on = (channel: string) => (listener: (...payload: unknown[]) => void) => { + listeners.on(channel, listener) + return () => { + listeners.off(channel, listener) + } + } + const session = { + set: vi.fn(async () => { + events.push('session:set') + }), + flush: vi.fn(async () => { + events.push('session:flush') + }) + } + vi.stubGlobal('window', { + dispatchEvent: vi.fn(), + api: { + ...api, + session, + automations: { + onTerminalLifecycleRequest: on('automations:terminalLifecycleRequest'), + respondTerminalLifecycle: (reply: unknown) => + mocks.ipc!.emit( + 'automations:terminalLifecycleResponse', + { sender: web, senderFrame: web.mainFrame }, + reply + ) + }, + ui: { + onLaunchRecipe: on('recipe'), + onCreateTerminal: on('ui:createTerminal'), + onRequestTerminalTabMount: on('mount'), + onPublishAgentLaunchTab: on('ui:publishAgentLaunchTab'), + onAgentLaunchPaneVerdict: on('verdict'), + replyAgentLaunchTabPublish: vi.fn(), + replyTerminalCreate: vi.fn() + } + } + }) + seedStore(store, { + worktreesByRepo: { repo1: [makeWorktree({ id: WT, repoId: 'repo1', path: '/repo1/main' })] }, + activeWorktreeId: 'other', + activeTabId: 'other-tab', + activeTabType: 'terminal', + tabsByWorktree: { [WT]: [makeTab({ id: 'sibling', worktreeId: WT, ptyId: 'setup' })] }, + ptyIdsByTabId: { sibling: ['setup'] } + }) + const unsubs: (() => void)[] = [] + registerTerminalPresentationIpcBridge(unsubs) + registerAgentLaunchTabIpcBridge(unsubs) + cleanups.push(() => unsubs.forEach((release) => release())) + // SAFETY: the sibling has a fake physical process; every exercised stop owner must leave it live. + ptyProcesses.set('setup', { + pid: 4343, + kill: () => { + throw new Error('sibling stopped') + } + } as unknown as pty.IPty) + ptyIncarnations.set('setup', 'setup') + let expectedPty = '' + let expectedPane = '' + let provenance: string | undefined + let stopFailure: 'live' | 'unproven' | null = null + const runtime = { + getAuthoritativeWindow: () => win, + getTerminalPtyIdForHandle: () => expectedPty, + getTerminalHandleForPaneKey: () => 'term-current', + getPtyExecutionHostMetadata: () => ({ incarnationId: 'original', executionHostId: 'local' }), + terminalRunFacts: { readLastDrivingInputAt: () => null }, + stopExactTerminalsForWorktree: vi.fn( + async ( + _selector: string, + ids: string[], + opts: NonNullable[2]> + ) => { + if (stopFailure) { + expect(await opts.authorizeStop!()).toBe(true) + if (stopFailure === 'unproven') { + ptyProcesses.delete(expectedPty) + throw new Error('lost reply') + } + throw new Error('still alive') + } + // Actual exact-stop owner proves the target exited while retaining the live sibling. + const inventory = new Map([ + [ids[0], { worktreeId: WT, ptyId: ids[0], connected: true, incarnationId: 'original' }], + ['setup', { worktreeId: WT, ptyId: 'setup', connected: true, incarnationId: 'setup' }] + ]) + const exact = Object.assign( + Object.create(OrcaRuntimeWithStopExactTerminalsForWorktree.prototype), + { + captureReadyGraphEpoch: noop, + assertStableReadyGraph: noop, + resolveWorktreeSelector: async () => ({ id: WT }), + getResolvedWorktreeMap: async () => new Map(), + refreshPtyWorktreeRecordsFromController: async () => + new Set([...ptyProcesses.keys(), 'setup']), + leaves: new Map(), + ptysById: inventory, + intentionalPtyStops: { mark: () => noop }, + ptyController: { + stopAndWait: async (id: string, options: PtyShutdownOptions) => { + events.push('provider:prepare') + await shutdownLocalPty(id, { ...options, immediate: true }) + events.push('provider:stopped') + return true + } + } + } + ) + return exact.stopExactTerminalsForWorktree(_selector, ids, opts) + } + ), + listTerminals: async () => ({ + terminals: [...ptyProcesses.keys()].map((ptyId) => ({ + ptyId, + connected: true, + incarnationId: 'original' + })) + }) + } + // SAFETY: transport/window and OS doubles implement the exercised runtime/store boundaries; lifecycle and local stop are real. + const lifecycle = createDesktopRunTerminalLifecycle( + runtime as unknown as OrcaRuntimeService, + { + getWorktreeMeta: () => ({ automationProvenance: { automationRunId: provenance } }), + listAutomationRuns: () => [] + } as unknown as Store, + async (_id, operation) => operation() + ) + cleanups.push(lifecycle.stop) + function bindProcess(ptyId: string, paneKey: string) { + expectedPty = ptyId + expectedPane = paneKey + // SAFETY: node-pty's destructive OS boundary is a fake; exit and exact process maps are the real owner state. + ptyProcesses.set(expectedPty, { + pid: 4242, + kill: () => { + events.push('os:exit') + ptyPhysicalExits.get(ptyId)?.markExited() + clearPtyState(ptyId) + } + } as unknown as pty.IPty) + ptyIncarnations.set(expectedPty, 'original') + createPtyPhysicalExit(expectedPty) + } + function publish( + index = 1, + preserve = true, + early = true, + saved?: (typeof state.automationRuns)[number] + ) { + const run = { + ...state.automationRuns[0], + id: `run-${index}`, + ...saved, + workspaceId: WT, + terminalPtyId: `pty-${index}`, + status: 'completed' as const + } + provenance = preserve ? run.id : undefined + const owner = lifecycle.begin( + { ...state.automations[0], reuseSession: false }, + run, + `operation-${index}` + )! + expectedPty = run.terminalPtyId + expectedPane = owner.paneKey + const [tabId, leafId] = expectedPane.split(':') + if (early) { + owner.reserve(WT) + } else { + owner.policy.onWorkspaceCreated!(WT) + } + if (early) { + web.send('ui:publishAgentLaunchTab', { + requestId: 'publish', + worktreeId: WT, + tabId, + leafId, + viewer: 'background', + launchAgent: 'codex' + }) + } + bindProcess(expectedPty, expectedPane) + owner.policy.onSurfacePublished!({ + worktreeId: WT, + outcome: { kind: 'terminal', paneKey: expectedPane, handle: 'term-original' } + } as never) + store + .getState() + .setAgentStatus( + expectedPane, + { state: 'done', prompt: 'resume', agentType: 'codex' }, + 'Codex', + { updatedAt: 2000, stateStartedAt: 1000 }, + { tabId, worktreeId: WT }, + { providerSession: { key: 'session_id', id: `session-${index}` } } + ) + return { run, owner, tabId, leafId, paneKey: expectedPane } + } + return { + store, + bindProcess, + activeSubscribers: () => subscribers, + session, + runtime, + lifecycle, + publish, + events, + web, + listeners, + prepare: (fn: () => Promise) => { + mocks.prepare = fn + }, + failStop: (kind: typeof stopFailure) => { + stopFailure = kind + } + } +} diff --git a/src/renderer/src/lib/automation-terminal-ownership.test.ts b/src/renderer/src/lib/automation-terminal-ownership.test.ts index 8574b047f784..9f4797685f8b 100644 --- a/src/renderer/src/lib/automation-terminal-ownership.test.ts +++ b/src/renderer/src/lib/automation-terminal-ownership.test.ts @@ -1,8 +1,18 @@ +import { randomUUID } from 'node:crypto' +import { createRuntimeAutomationService } from '../../../main/automations/runtime-automation-service' +import { runtimeStub } from '../../../main/runtime/rpc/methods/agent-launch.test-fixture' +import { createQueuedMessageTestRig } from '../../../main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { hostTestAttachParams } from '../../../main/native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { setStructuredAgentSessionHost } from '../../../main/native-chat/agent-session-wire/structured-agent-session-registry' +import { readAutomationRunReceipt } from '../../../main/automations/automation-run-receipt' +import { hostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' +import { revealCreatedTerminal } from '../../../main/runtime/terminal/launch/terminal-create-reveal' +import { OrcaRuntimeWithPublishPtyBackedMobileSessionTerminal } from '../../../main/runtime/session-tabs/pty-backed-session-publication' +import { OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce } from '../../../main/runtime/session-tabs/structured-session-tab-restoration' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/runtime-types' import { stopRevokers } from '../../../main/automations/desktop-run-terminal-stop' -import type { PtyShutdownOptions } from '../../../main/providers/pty-provider-contract' import type * as ChildProcess from 'node:child_process' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeWithStopExactTerminalsForWorktree } from '../../../main/runtime/terminal/stop/worktree-terminal-stop-targets' import { AutomationService } from '../../../main/automations/service' import { createStore, @@ -13,39 +23,21 @@ import { import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { EventEmitter } from 'node:events' -import type * as pty from 'node-pty' +import type { EventEmitter } from 'node:events' import type { OrcaRuntimeService } from '../../../main/runtime/orca-runtime' -import type { Store } from '../../../main/persistence' import type { ConnectPanePtySession } from '@/components/terminal-pane/pty-connection/connect-pane-pty-session' import { buildProfileStateCutoverFixture } from '../../../main/persistence/profile-state-cutover-fixture' -import { - createTestStore, - makeTab, - makeWorktree, - seedStore -} from '@/store/slices/store-test-helpers' -import { createStoreSessionMockApi } from '@/store/slices/store-session-test-harness' +import type { createTestStore } from '@/store/slices/store-test-helpers' import { singlePaneLayoutSnapshot } from '@/store/slices/terminal-helpers' import { recordTerminalInputActivity, flushTerminalInputActivity } from './terminal-input-activity-coalescing' import { createAutomationTerminalOwnership } from './automation-terminal-ownership' -import { registerTerminalPresentationIpcBridge } from '@/hooks/ipc-events/terminal-presentation-ipc-bridge' -import { registerAgentLaunchTabIpcBridge } from '@/hooks/ipc-events/agent-launch-tab-ipc-bridge' -import { - createDesktopRunTerminalLifecycle, - cancelDesktopTerminalRetirement -} from '../../../main/automations/desktop-run-terminal-lifecycle' -import { - shutdownLocalPty, - createPtyPhysicalExit -} from '../../../main/providers/local-pty-termination' +import { cancelDesktopTerminalRetirement } from '../../../main/automations/desktop-run-terminal-lifecycle' import { ptyProcesses, ptyIncarnations, - ptyPhysicalExits, ptyShutdownOperations, clearPtyState } from '../../../main/providers/local-pty-provider-state' @@ -98,7 +90,10 @@ vi.mock('sonner', () => ({ vi.mock('@/lib/focus-terminal-tab-surface', () => ({ focusTerminalTabSurface: vi.fn() })) const state = buildProfileStateCutoverFixture('/fixture') -const WT = 'repo1::/repo1/main' +import { + createAutomationTerminalOwnershipFixture, + OWNERSHIP_WORKSPACE_ID as WT +} from './automation-terminal-ownership-test-harness' const noop = () => {} const cleanups: (() => void)[] = [] beforeEach(() => { @@ -118,250 +113,7 @@ afterEach(() => { }) function fixture() { - const store = createTestStore() - let subscribers = 0 - const subscribe = store.subscribe - vi.spyOn(store, 'subscribe').mockImplementation((listener) => { - const release = subscribe(listener) - subscribers++ - return () => { - subscribers-- - release() - } - }) - mocks.store = store - const api = createStoreSessionMockApi() - const listeners = new EventEmitter() - const events: string[] = [] - const web = Object.assign(new EventEmitter(), { - mainFrame: {}, - isDestroyed: () => false, - send: (channel: string, payload: unknown) => { - events.push( - channel === 'automations:terminalLifecycleRequest' && - typeof payload === 'object' && - payload !== null && - 'operation' in payload - ? `${payload.operation}:${'phase' in payload ? payload.phase : ''}` - : channel - ) - listeners.emit(channel, payload) - } - }) - const win = Object.assign(new EventEmitter(), { webContents: web, isDestroyed: () => false }) - const on = (channel: string) => (listener: (...payload: unknown[]) => void) => { - listeners.on(channel, listener) - return () => { - listeners.off(channel, listener) - } - } - const session = { - set: vi.fn(async () => { - events.push('session:set') - }), - flush: vi.fn(async () => { - events.push('session:flush') - }) - } - vi.stubGlobal('window', { - dispatchEvent: vi.fn(), - api: { - ...api, - session, - automations: { - onTerminalLifecycleRequest: on('automations:terminalLifecycleRequest'), - respondTerminalLifecycle: (reply: unknown) => - mocks.ipc!.emit( - 'automations:terminalLifecycleResponse', - { sender: web, senderFrame: web.mainFrame }, - reply - ) - }, - ui: { - onLaunchRecipe: on('recipe'), - onCreateTerminal: on('ui:createTerminal'), - onRequestTerminalTabMount: on('mount'), - onPublishAgentLaunchTab: on('ui:publishAgentLaunchTab'), - onAgentLaunchPaneVerdict: on('verdict'), - replyAgentLaunchTabPublish: vi.fn(), - replyTerminalCreate: vi.fn() - } - } - }) - seedStore(store, { - worktreesByRepo: { repo1: [makeWorktree({ id: WT, repoId: 'repo1', path: '/repo1/main' })] }, - activeWorktreeId: 'other', - activeTabId: 'other-tab', - activeTabType: 'terminal', - tabsByWorktree: { [WT]: [makeTab({ id: 'sibling', worktreeId: WT, ptyId: 'setup' })] }, - ptyIdsByTabId: { sibling: ['setup'] } - }) - const unsubs: (() => void)[] = [] - registerTerminalPresentationIpcBridge(unsubs) - registerAgentLaunchTabIpcBridge(unsubs) - cleanups.push(() => unsubs.forEach((release) => release())) - // SAFETY: the sibling has a fake physical process; every exercised stop owner must leave it live. - ptyProcesses.set('setup', { - pid: 4343, - kill: () => { - throw new Error('sibling stopped') - } - } as unknown as pty.IPty) - ptyIncarnations.set('setup', 'setup') - let expectedPty = '' - let expectedPane = '' - let provenance: string | undefined - let stopFailure: 'live' | 'unproven' | null = null - const runtime = { - getAuthoritativeWindow: () => win, - getTerminalPtyIdForHandle: () => expectedPty, - getTerminalHandleForPaneKey: () => 'term-current', - getPtyExecutionHostMetadata: () => ({ incarnationId: 'original', executionHostId: 'local' }), - terminalRunFacts: { readLastDrivingInputAt: () => null }, - stopExactTerminalsForWorktree: vi.fn( - async ( - _selector: string, - ids: string[], - opts: NonNullable[2]> - ) => { - if (stopFailure) { - expect(await opts.authorizeStop!()).toBe(true) - if (stopFailure === 'unproven') { - ptyProcesses.delete(expectedPty) - throw new Error('lost reply') - } - throw new Error('still alive') - } - // Actual exact-stop owner proves the target exited while retaining the live sibling. - const inventory = new Map([ - [ids[0], { worktreeId: WT, ptyId: ids[0], connected: true, incarnationId: 'original' }], - ['setup', { worktreeId: WT, ptyId: 'setup', connected: true, incarnationId: 'setup' }] - ]) - const exact = Object.assign( - Object.create(OrcaRuntimeWithStopExactTerminalsForWorktree.prototype), - { - captureReadyGraphEpoch: noop, - assertStableReadyGraph: noop, - resolveWorktreeSelector: async () => ({ id: WT }), - getResolvedWorktreeMap: async () => new Map(), - refreshPtyWorktreeRecordsFromController: async () => - new Set([...ptyProcesses.keys(), 'setup']), - leaves: new Map(), - ptysById: inventory, - intentionalPtyStops: { mark: () => noop }, - ptyController: { - stopAndWait: async (id: string, options: PtyShutdownOptions) => { - events.push('provider:prepare') - await shutdownLocalPty(id, { ...options, immediate: true }) - events.push('provider:stopped') - return true - } - } - } - ) - return exact.stopExactTerminalsForWorktree(_selector, ids, opts) - } - ), - listTerminals: async () => ({ - terminals: [...ptyProcesses.keys()].map((ptyId) => ({ - ptyId, - connected: true, - incarnationId: 'original' - })) - }) - } - // SAFETY: transport/window and OS doubles implement the exercised runtime/store boundaries; lifecycle and local stop are real. - const lifecycle = createDesktopRunTerminalLifecycle( - runtime as unknown as OrcaRuntimeService, - { - getWorktreeMeta: () => ({ automationProvenance: { automationRunId: provenance } }), - listAutomationRuns: () => [] - } as unknown as Store, - async (_id, operation) => operation() - ) - cleanups.push(lifecycle.stop) - function publish( - index = 1, - preserve = true, - early = true, - saved?: (typeof state.automationRuns)[number] - ) { - const run = { - ...state.automationRuns[0], - id: `run-${index}`, - ...saved, - workspaceId: WT, - terminalPtyId: `pty-${index}`, - status: 'completed' as const - } - provenance = preserve ? run.id : undefined - const owner = lifecycle.begin( - { ...state.automations[0], reuseSession: false }, - run, - `operation-${index}` - )! - expectedPty = run.terminalPtyId - expectedPane = owner.paneKey - const [tabId, leafId] = expectedPane.split(':') - if (early) { - owner.reserve(WT) - } else { - owner.policy.onWorkspaceCreated!(WT) - } - if (early) { - web.send('ui:publishAgentLaunchTab', { - requestId: 'publish', - worktreeId: WT, - tabId, - leafId, - viewer: 'background', - launchAgent: 'codex' - }) - } - // SAFETY: node-pty's destructive OS boundary is a fake; exit and exact process maps are the real owner state. - ptyProcesses.set(expectedPty, { - pid: 4242, - kill: () => { - events.push('os:exit') - ptyPhysicalExits.get(run.terminalPtyId)?.markExited() - clearPtyState(run.terminalPtyId) - } - } as unknown as pty.IPty) - ptyIncarnations.set(expectedPty, 'original') - createPtyPhysicalExit(expectedPty) - owner.policy.onSurfacePublished!({ - worktreeId: WT, - outcome: { kind: 'terminal', paneKey: expectedPane, handle: 'term-original' } - } as never) - store - .getState() - .setAgentStatus( - expectedPane, - { state: 'done', prompt: 'resume', agentType: 'codex' }, - 'Codex', - { updatedAt: 2000, stateStartedAt: 1000 }, - { tabId, worktreeId: WT }, - { providerSession: { key: 'session_id', id: `session-${index}` } } - ) - return { run, owner, tabId, leafId, paneKey: expectedPane } - } - return { - store, - activeSubscribers: () => subscribers, - session, - runtime, - lifecycle, - publish, - events, - web, - listeners, - prepare: (fn: () => Promise) => { - mocks.prepare = fn - }, - failStop: (kind: typeof stopFailure) => { - stopFailure = kind - } - } + return createAutomationTerminalOwnershipFixture(mocks, cleanups) } describe('desktop completion through local publication and process owner', () => { @@ -702,45 +454,247 @@ describe('desktop completion through local publication and process owner', () => f.lifecycle.begin({ ...state.automations[0], reuseSession: true }, t.run, 'reuse') ).toBeNull() }) - it.each([5, 50])('bounds repeated cleanup resources at N=%i', async (count) => { - const timers = vi.spyOn(globalThis, 'setTimeout') - const cleared = vi.spyOn(globalThis, 'clearTimeout') - const f = fixture() - for (let n = 1; n <= count; n++) { - const t = f.publish(n, n % 2 === 0, n % 3 === 0) - expect(await f.lifecycle.finalize(t.run)).toMatchObject({ terminalPtyId: null }) - expect([...ptyProcesses.keys()]).toEqual(['setup']) - expect(ptyShutdownOperations.size).toBe(0) +}) + +it.each([5, 50])('bounds actual desktop fallback/Chat/Reuse owners at N=%i', async (count) => { + vi.spyOn(Date, 'now').mockReturnValue(1_800_000_000_000) + const root = mkdtempSync(join(tmpdir(), 'orca-34332-fallback-')) + testState.dir = root + const disk = createStore(), + f = fixture() + const rig = await createQueuedMessageTestRig({ restartable: true }) + setStructuredAgentSessionHost(rig.host) + const timers = vi.spyOn(globalThis, 'setTimeout'), + cleared = vi.spyOn(globalThis, 'clearTimeout') + const tabs = new Map() + const bindings = new Map() + const publisher = Object.assign( + Object.create(OrcaRuntimeWithPublishPtyBackedMobileSessionTerminal.prototype), + { + mobileSessionTabsByWorktree: tabs, + isMobileSessionSurfaceMembershipAllowed: () => true, + getPtyDisplayRecord: (record: unknown) => record, + getPtyManualTitle: () => null, + storeMobileSessionSnapshot: (id: string, snapshot: RuntimeMobileSessionTabsSnapshot) => { + tabs.set(id, snapshot) + return snapshot + }, + notifyMobileSessionTabsChanged: vi.fn() + } + ) + const chatPublisher = Object.assign( + Object.create(OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce.prototype), + { + mobileSessionTabsByWorktree: tabs, + saveWindowlessAgentSessionTab: vi.fn(), + storeMobileSessionSnapshot: publisher.storeMobileSessionSnapshot, + emitMobileSessionTabsSnapshot: vi.fn() + } + ) + let mode = 'unavailable', + currentRun = '', + service: ReturnType | undefined + const trace: string[] = [] + const runtime = { + ...runtimeStub(), + ...f.runtime, + requireStore: () => disk, + setAutomationService: vi.fn(), + notifyAutomationsChanged: vi.fn(), + openAgentSessionRecordStore: async () => rig.store, + showRepo: async () => disk.getRepo('repo1'), + showAutomation: (id: string) => disk.listAutomations().find((a) => a.id === id), + listAutomationRuns: (id: string) => disk.listAutomationRuns(id), + getAgentStatusRowsForPane: () => [], + getTerminalPtyIdForHandle: (handle: string) => bindings.get(handle)?.ptyId ?? null, + getTerminalPaneKey: (handle: string) => bindings.get(handle)?.paneKey ?? null, + getTerminalHandleForPaneKey: (paneKey: string) => + [...bindings].find(([, b]) => b.paneKey === paneKey && ptyProcesses.has(b.ptyId))?.[0] ?? + null, + showManagedWorktree: async () => ({ displayName: 'Fallback' }), + getStructuredAgentSessionCreateSupport: async () => { + trace.push('support') + if (mode === 'unknown') { + throw new Error('support unavailable') + } + return { supported: mode === 'refused' || mode === 'chat', reason: 'chat-program' as const } + }, + resolveStructuredAgentSessionCreateIntent: async () => { + if (mode === 'refused') { + throw new Error('structured_agent_session_unsupported') + } + const { envelope: _, ...params } = hostTestAttachParams(null) + return { ...params, location: { ...params.location, workspaceId: WT } } + }, + publishStructuredAgentSessionTab: + chatPublisher.publishStructuredAgentSessionTab.bind(chatPublisher), + createManagedWorktree: async ( + args: Parameters[0] + ) => { + trace.push('create') + currentRun = args.automationProvenance!.automationRunId + disk.setWorktreeMeta(hostWorktreeTarget({ id: WT, hostId: 'local' }), { + automationProvenance: args.automationProvenance + }) + args.onWorkspaceCreated!(WT) + return { worktree: { id: WT, path: '/repo1/main' } } + }, + createTerminal: async ( + _selector: string, + options: NonNullable[1]> + ) => { + trace.push('terminal') + const tabId = options.tabId ?? randomUUID(), + leafId = options.leafId ?? randomUUID() + const paneKey = `${tabId}:${leafId}` + const ptyId = `actual-${bindings.size}`, + handle = `term-${bindings.size}` + bindings.set(handle, { paneKey, ptyId }) + f.bindProcess(ptyId, paneKey) + publisher.publishPtyBackedMobileSessionTerminal( + WT, + { ptyId, incarnationId: 'original', launchAgent: 'codex' }, + { tabId, leafId, title: 'Codex', activate: false, selectIfNoActiveTab: false } + ) + await revealCreatedTerminal({ + notifier: null, + workspace: { id: WT, path: '/repo1/main' }, + ptyId, + handle, + cwd: '/repo1/main', + launchOpts: options, + opts: options, + tabId, + leafId, + presentation: options.presentation, + adoptedStablePane: false, + effectiveLaunchConfig: undefined, + launchToken: undefined + }) + options.onPtySpawnDispatched?.() + options.onStartupPromptCarry?.(true) + return { handle, paneKey } + }, + deliverStartupFollowup: async () => true, + waitForTerminal: async (_handle: string, options: { signal: AbortSignal }) => + new Promise((_resolve, reject) => { + if (options.signal.aborted) { + reject(new Error('aborted')) + } else { + options.signal.addEventListener('abort', () => reject(new Error('aborted')), { + once: true + }) + } + }), + readTerminal: async () => ({ tail: [] }) + } + try { + disk.addRepo({ ...state.repos[0], id: 'repo1', path: '/repo1/main', connectionId: null }) + // SAFETY: only runtime OS/transport boundaries are scripted; service, common executor, receipt, lifecycle, renderer transaction and stop owner are real. + service = createRuntimeAutomationService({ + store: disk, + runtime: runtime as unknown as OrcaRuntimeService, + headless: false + }) + service.setWebContents(f.web) + service.setRendererReady() + let eligible = 0, + retained = 0, + chats = 0 + for (let n = 0; n < count; n++) { + mode = ['unavailable', 'unknown', 'refused', 'chat', 'unavailable'][n % 5] + const reuseSession = n % 5 === 4 + const automation = disk.createAutomation({ + name: 'Fallback', + prompt: 'check', + agentId: 'codex', + projectId: 'repo1', + workspaceMode: reuseSession ? 'existing' : 'new_per_run', + workspaceId: reuseSession ? WT : null, + surface: reuseSession ? 'terminal' : 'chat', + reuseSession, + timezone: 'UTC', + rrule: 'FREQ=DAILY', + dtstart: Date.now() + 86400000, + setupDecision: 'skip' + }) + const start = f.events.length + const run = await service.runNow(automation.id) + expect(run.status).toBe('dispatched') + expect(readAutomationRunReceipt(rig.store, run)?.accepted).toBe(true) + expect(trace.splice(0)).toEqual( + reuseSession + ? ['terminal'] + : mode === 'chat' + ? ['create', 'support'] + : ['create', 'support', 'terminal'] + ) + if (mode === 'chat') { + chats++ + expect(run.sessionKind).toBe('chat') + expect(f.events.slice(start)).toContain('arm:') + expect(f.events.slice(start)).not.toContain('ui:createTerminal') + expect(tabs.get(WT)!.tabs.filter((t) => t.type === 'agent-session')).toHaveLength(chats) + expect(chatPublisher.saveWindowlessAgentSessionTab.mock.lastCall[1].activate).toBe(false) + } else if (reuseSession) { + retained++ + expect(f.events.slice(start).some((e) => e.startsWith('arm:'))).toBe(false) + } else { + eligible++ + expect(f.events.slice(start).filter((e) => e.startsWith('arm:'))).toHaveLength(1) + expect(f.events.slice(start).filter((e) => e.startsWith('bind:'))).toHaveLength(1) + expect(f.events.indexOf('arm:', start)).toBeLessThan( + f.events.indexOf('ui:createTerminal', start) + ) + f.store + .getState() + .setAgentStatus( + run.terminalPaneKey!, + { state: 'done', prompt: 'resume', agentType: 'codex' }, + 'Codex', + { updatedAt: 2000, stateStartedAt: 1000 }, + { tabId: run.terminalSessionId!, worktreeId: WT }, + { providerSession: { key: 'session_id', id: currentRun } } + ) + } + const finalized = await service.markDispatchResult({ runId: run.id, status: 'completed' }) + expect(finalized.terminalPtyId).toBe(reuseSession ? run.terminalPtyId : null) expect(stopRevokers.size).toBe(0) expect(f.activeSubscribers()).toBe(0) + expect(ptyShutdownOperations.size).toBe(0) expect(f.web.eventNames()).toEqual([]) expect(mocks.ipc!.eventNames()).toEqual([]) - expect(isPtyDataHandlerShutdownPending(t.run.terminalPtyId)).toBe(false) + expect(ptyProcesses.size).toBe(1 + retained) + expect(ptyProcesses.has('setup')).toBe(true) + const persisted = JSON.parse(readPersistedStateJson(join(root, 'orca-data.json'))) + expect( + persisted.automationRuns.find((row: { id: string }) => row.id === run.id) + ).toMatchObject({ + status: 'completed', + chatSessionId: run.chatSessionId, + terminalPtyId: finalized.terminalPtyId + }) } - expect(f.store.getState().tabsByWorktree[WT]).toHaveLength(1 + Math.floor(count / 2)) - expect( - Object.values(f.store.getState().sleepingAgentSessionsByPaneKey).filter( - (r) => r.origin === 'worktree-sleep' - ) - ).toHaveLength(Math.floor(count / 2)) - const protocolTimers = timers.mock.calls.flatMap((args, index) => - args[1] === 20_000 ? [timers.mock.results[index].value] : [] + const sessions = rig.host.collaboratorsForTests().sessions + expect(Reflect.get(sessions, 'observers').size).toBe(0) + expect(Reflect.get(sessions, 'attachments').size).toBe(chats + 1) + const protocol = timers.mock.calls.flatMap((args, i) => + args[1] === 20_000 ? [timers.mock.results[i].value] : [] ) - expect(protocolTimers.length).toBeGreaterThan(0) - expect(protocolTimers.length).toBeLessThanOrEqual(5 * count) - for (const timer of protocolTimers) { + for (const timer of protocol) { expect(cleared).toHaveBeenCalledWith(timer) } + const sleepers = Object.keys(f.store.getState().sleepingAgentSessionsByPaneKey).length + expect(sleepers).toBe(eligible) + expect(f.store.getState().tabsByWorktree[WT]).toHaveLength(1 + eligible) process.stdout.write( - `${JSON.stringify({ - desktopRuns: count, - livePtys: ptyProcesses.size, - shutdowns: ptyShutdownOperations.size, - registrations: stopRevokers.size, - subscribers: f.activeSubscribers(), - relayListeners: mocks.ipc!.eventNames().length, - protocolTimers: protocolTimers.length - })}\n` + `${JSON.stringify({ desktopRuns: count, canonicalSources: Reflect.get(sessions, 'attachments').size, logicalObservers: Reflect.get(sessions, 'observers').size, eligible, retainedReuse: retained, chats, ptys: ptyProcesses.size, desktopTabs: f.store.getState().tabsByWorktree[WT].length, runtimeTabs: tabs.get(WT)!.tabs.length, sleepers, registrations: stopRevokers.size, subscribers: f.activeSubscribers(), timersCreated: protocol.length, timersCleared: protocol.filter((timer) => cleared.mock.calls.some(([clearedTimer]) => timer === clearedTimer)).length })}\n` ) - }) + } finally { + service?.stop() + setStructuredAgentSessionHost(null) + await rig.dispose() + await closeTestStores() + rmSync(root, { recursive: true, force: true }) + } }) From 161d88e81f967e21801fb30fb381e33b644ae100 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 27 Oct 2026 11:40:34 -0700 Subject: [PATCH 06/23] Scope automation observation and reconciliation work to each operation --- ...ation-chat-run-measurement-test-harness.ts | 210 ++++++++++++++++++ .../automation-chat-run-observation.ts | 116 ++++++++++ .../desktop-run-terminal-lifecycle.ts | 10 +- .../desktop-run-terminal-reconciliation.ts | 22 ++ .../runtime-chat-run-observer.test.ts | 195 ++++++---------- .../automations/runtime-chat-run-observer.ts | 102 +-------- ...ctured-agent-session-conversations.test.ts | 33 +++ .../structured-agent-session-conversations.ts | 32 +-- ...omation-terminal-inventory-test-harness.ts | 117 ++++++++++ .../lib/automation-terminal-ownership.test.ts | 95 +++++++- 10 files changed, 682 insertions(+), 250 deletions(-) create mode 100644 src/main/automations/automation-chat-run-measurement-test-harness.ts create mode 100644 src/main/automations/automation-chat-run-observation.ts create mode 100644 src/main/automations/desktop-run-terminal-reconciliation.ts create mode 100644 src/renderer/src/lib/automation-terminal-inventory-test-harness.ts 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..b6a6f1af674e --- /dev/null +++ b/src/main/automations/automation-chat-run-measurement-test-harness.ts @@ -0,0 +1,210 @@ +import { vi } from 'vitest' +import type { + AgentJournalSnapshot, + AgentJournalRenderItem +} 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 function measureAutomationChatRun( + journal: AgentSessionJournal, + host: StructuredAgentSessionHost +) { + 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] + } + } + } + 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: ReturnType[] = [] + 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: { items: Map } = Reflect.get(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 + } + }) + const fullApis = [ + 'pendingSubmissions', + 'runningTurn', + 'newestTurn', + 'threadGoalSource', + 'contextUsage', + 'visitItemsWithLinkage' + ] as const + const calls = fullApis.map((name) => vi.spyOn(journal, name)) + const 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.observeJournalPublications.bind(host) + const registration = vi + .spyOn(host, 'observeJournalPublications') + .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/desktop-run-terminal-lifecycle.ts b/src/main/automations/desktop-run-terminal-lifecycle.ts index 27b4fd3a828a..0da5fb35e7bc 100644 --- a/src/main/automations/desktop-run-terminal-lifecycle.ts +++ b/src/main/automations/desktop-run-terminal-lifecycle.ts @@ -1,3 +1,4 @@ +import { reconcileDesktopRunTerminals } from './desktop-run-terminal-reconciliation' import { stopDesktopRunTerminal, watchDesktopTerminalStop, @@ -286,14 +287,7 @@ export function createDesktopRunTerminalLifecycle( }, finalize: (run: AutomationRun) => registrations.get(run.id)?.finalize(run) ?? Promise.resolve(null), - reconcile: () => { - for (const [id, owner] of registrations) { - const run = store.listAutomationRuns().find((entry) => entry.id === id) - if (!run || !['dispatching', 'dispatched', 'completed'].includes(run.status)) { - owner.release() - } - } - }, + reconcile: () => reconcileDesktopRunTerminals(registrations, () => store.listAutomationRuns()), stop: () => { for (const owner of registrations.values()) { owner.release() diff --git a/src/main/automations/desktop-run-terminal-reconciliation.ts b/src/main/automations/desktop-run-terminal-reconciliation.ts new file mode 100644 index 000000000000..7b2198e7666f --- /dev/null +++ b/src/main/automations/desktop-run-terminal-reconciliation.ts @@ -0,0 +1,22 @@ +import type { AutomationRun } from '../../shared/automations-types' + +export function reconcileDesktopRunTerminals( + registrations: ReadonlyMap void }>, + listRuns: () => readonly AutomationRun[] +): void { + if (registrations.size === 0) { + return + } + const statuses = new Map() + for (const run of listRuns()) { + if (!statuses.has(run.id)) { + statuses.set(run.id, run.status) + } + } + for (const [id, owner] of registrations) { + const status = statuses.get(id) + if (!status || !['dispatching', 'dispatched', 'completed'].includes(status)) { + owner.release() + } + } +} diff --git a/src/main/automations/runtime-chat-run-observer.test.ts b/src/main/automations/runtime-chat-run-observer.test.ts index 6e886042968e..2e095947d264 100644 --- a/src/main/automations/runtime-chat-run-observer.test.ts +++ b/src/main/automations/runtime-chat-run-observer.test.ts @@ -1,10 +1,14 @@ +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 } from '../../shared/agent-session-journal-item-key' +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' @@ -97,21 +101,32 @@ describe('exact automation chat turn', () => { 'Claude' ) ).toBeNull() - expect( - chatAutomationRunObservation(snapshot([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 result = chatAutomationRunObservation( - snapshot([ - turn('own', agentJournalSubmissionKey('prompt')), - answer('a', 'own', 'Automation output'), - answer('b', 'human', 'Private later output'), - { ...answer('c', 'own', 'Child output'), agentId: 'child' } - ]), - 'prompt', - 'Codex' - ) + 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 + } + }) + const result = chatAutomationRunObservation(view, 'prompt', 'Codex') + expect(outputRows).toBe(4) expect(result).toMatchObject({ status: 'completed', error: null, @@ -352,53 +367,9 @@ describe('real host queue publication and operation bounds', () => { } ) ).toMatchObject({ ok: true, value: { queued: { messageId: q, state: 'waiting' } } }) - 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 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') - let visited = 0 - const realSnapshot = journal.snapshot.bind(journal) - const full = vi.spyOn(journal, 'snapshot').mockImplementation((...args) => { - const value = realSnapshot(...args) - visited += value.items.length + value.submissions.length - return value - }) + 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( @@ -415,73 +386,6 @@ describe('real host queue publication and operation bounds', () => { await rig.host.flushStreamedEvents(HOST_TEST_SESSION) } } - const releases: ReturnType[] = [] - 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: { items: Map } = Reflect.get( - 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 - } - }) - const fullApis = [ - 'pendingSubmissions', - 'runningTurn', - 'newestTurn', - 'threadGoalSource', - 'contextUsage', - 'visitItemsWithLinkage' - ] as const - const calls = fullApis.map((name) => vi.spyOn(journal, name)) - const keys = [ - vi.spyOn(journal, 'item'), - vi.spyOn(journal, 'submission'), - vi.spyOn(journal.queuedMessages, 'get'), - vi.spyOn(journal, 'canonicalItemId') - ] - const observerReads = vi.spyOn(rig.host, 'journalSnapshot') - const realObserve = rig.host.observeJournalPublications.bind(rig.host) - const registration = vi - .spyOn(rig.host, 'observeJournalPublications') - .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 - ] const difference = (before: number[]) => measure().map((value, index) => value - before[index]) const displayRelease = @@ -595,6 +499,15 @@ describe('real host queue publication and operation bounds', () => { }, { 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) @@ -607,7 +520,10 @@ describe('real host queue publication and operation bounds', () => { 'Codex', await rig.host.queuedSendAnswer(HOST_TEST_SESSION, q) ) - ).toMatchObject({ status: 'completed' }) + ).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) { @@ -621,6 +537,7 @@ describe('real host queue publication and operation bounds', () => { 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 ) @@ -629,7 +546,7 @@ describe('real host queue publication and operation bounds', () => { expect(Reflect.get(sessions, 'attachments').size).toBe(1) totals.push(measure()) process.stdout.write( - `${JSON.stringify({ history, mode, sourceAttachments: Reflect.get(sessions, 'attachments').size, logicalObservers: Reflect.get(sessions, 'observers').size, baselineWork, observerWork, keyedAdded, totals: measure(), callbacks, committedRows, deltaReads: deltas.mock.calls.length, deltaRows, reconciliations: observerReads.mock.calls.length, registrations: registration.mock.calls.length, releases: releases.filter((r) => r.mock.calls.length === 1).length })}\n` + `${JSON.stringify({ history, mode, sourceAttachments: Reflect.get(sessions, 'attachments').size, logicalObservers: Reflect.get(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() @@ -639,11 +556,25 @@ describe('real host queue publication and operation bounds', () => { } } const added = totals[1].map((value, i) => value - totals[0][i]) - expect(added.filter((_, i) => i !== 5 && i !== 12)).toEqual( - added.filter((_, i) => i !== 5 && i !== 12).map(() => 0) + 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` ) diff --git a/src/main/automations/runtime-chat-run-observer.ts b/src/main/automations/runtime-chat-run-observer.ts index 6fd6c2a9fe1a..177e3b660908 100644 --- a/src/main/automations/runtime-chat-run-observer.ts +++ b/src/main/automations/runtime-chat-run-observer.ts @@ -1,7 +1,7 @@ +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 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, @@ -10,94 +10,9 @@ import { 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 { createHeadlessAutomationOutputSnapshotBuffer } from './headless-dispatch' import type { AutomationRunCompletionObservation } from './run-completion-watcher' import { tuiAgentDisplayName } from '../../shared/tui-agent-display-names' -export function chatAutomationRunObservation( - snapshot: AgentJournalSnapshot, - messageId: string, - 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 - } - const submission = - queued && 'submission' in queued - ? queued.submission - : snapshot.submissions.find((entry) => entry.clientMessageId === messageId) - if (!submission) { - return null - } - const turnItem = submissionTurn(snapshot, submission) - 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)) - ) - }) -} - export async function observeAutomationChatRun( runtime: OrcaRuntimeService, run: AutomationRun, @@ -204,17 +119,18 @@ export async function observeAutomationChatRun( if (!current()) { continue } - const submission = - queued && 'submission' in queued - ? queued.submission - : snapshot.submissions.find((entry) => entry.clientMessageId === messageId) + const { submission, turnItem, observation } = resolveChatAutomationRun( + snapshot, + messageId, + agent, + queued + ) if (submission) { submissionId = submission.clientMessageId providerItemId = submission.providerItemId - turnItemId = submissionTurn(snapshot, submission)?.itemId ?? null + turnItemId = turnItem?.itemId ?? null } fingerprint = interest() - const observation = chatAutomationRunObservation(snapshot, messageId, agent, queued) if (observation) { finish(observation) return 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 52daabd482ca..4860f6ab7e3e 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 @@ -212,6 +212,39 @@ describe('internal publication lifetime, independently of presentation', () => { release() release() fail() + const successor = { next: vi.fn(), error: vi.fn() } + const releaseB = conversations.observeJournalPublications('session-1', successor) + release() + conversations.publish('session-1', 'operational') + expect(successor.next.mock.lastCall![0].kind).toBe('operational') + const releaseC = conversations.observeJournalPublications('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.observeJournalPublications('session-1', { + next: () => { + throw new Error('initial reader') + }, + error: () => { + reentrantRelease = conversations.observeJournalPublications('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(Reflect.get(conversations, 'observers').size).toBe(0) const listener = vi.fn() const before = old.observeCommits(listener) const after = old.observeCommits(listener) 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 60b49ffe2034..9139cfc6aca9 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 @@ -22,7 +22,7 @@ export class StructuredAgentSessionConversations extends Map< string, StructuredAgentSessionHostSession > { - private readonly observers = new Map>() + private readonly observers = new Map>() private readonly attachments = new Map< string, { journal: AgentSessionJournal; release: () => void } @@ -141,13 +141,9 @@ export class StructuredAgentSessionConversations extends Map< listeners = new Set() this.observers.set(sessionId, listeners) } - listeners.add(observer) - const release = () => { - listeners.delete(observer) - if (listeners.size === 0) { - this.observers.delete(sessionId) - } - } + const registration = { observer } + listeners.add(registration) + const release = () => this.removeObserver(sessionId, registration) this.deliverHint(observer, this.hint(sessionId, 'reset'), release) return release } @@ -173,14 +169,18 @@ export class StructuredAgentSessionConversations extends Map< return } const hint = this.hint(sessionId, kind, rows) - for (const observer of observers) { - this.deliverHint(observer, hint, () => { - const listeners = this.observers.get(sessionId) - listeners?.delete(observer) - if (listeners?.size === 0) { - this.observers.delete(sessionId) - } - }) + 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) } } diff --git a/src/renderer/src/lib/automation-terminal-inventory-test-harness.ts b/src/renderer/src/lib/automation-terminal-inventory-test-harness.ts new file mode 100644 index 000000000000..29fbd4e9dbfe --- /dev/null +++ b/src/renderer/src/lib/automation-terminal-inventory-test-harness.ts @@ -0,0 +1,117 @@ +import type { AutomationRun } from '../../../shared/automations-types' +import { reconcileDesktopRunTerminals } from '../../../main/automations/desktop-run-terminal-reconciliation' +import { expect, vi } from 'vitest' +import type { Store } from '../../../main/persistence' +import type { createDesktopRunTerminalLifecycle } from '../../../main/automations/desktop-run-terminal-lifecycle' +import * as runNormalization from '../../../main/persistence/scheduling-automations/automation-context-migration' +import { compareAutomationRunsNewestFirst } from '../../../shared/automation-run-cursor' + +export function measureTerminalInventory( + disk: Store, + lifecycle: ReturnType, + registered: ReadonlySet +) { + const list = disk.listAutomationRuns.bind(disk) + let rows = 0, + statusVisits = 0, + linearFinds = 0, + measuring = false + const lists = vi.spyOn(disk, 'listAutomationRuns').mockImplementation((...args) => { + const result = list(...args) + if (!measuring) { + return result + } + return new Proxy(result, { + get(target, key, receiver) { + if (key === 'find') { + linearFinds++ + } + const value = Reflect.get(target, key, receiver) + if (typeof key !== 'string' || !/^(0|[1-9][0-9]*)$/.test(key)) { + return value + } + rows++ + return new Proxy(value, { + get(run, field, rowReceiver) { + if (field === 'status') { + statusVisits++ + } + return Reflect.get(run, field, rowReceiver) + } + }) + } + }) + }) + const normalized = vi.spyOn(runNormalization, 'normalizeAutomationPrecheckResult') + const sorts = vi.spyOn(Array.prototype, 'sort') + const lookups = vi.spyOn(Map.prototype, 'get') + let inventories = 0, + normalizations = 0, + fullSorts = 0, + selectedLookups = 0 + const reconcile = lifecycle.reconcile + vi.spyOn(lifecycle, 'reconcile').mockImplementation(() => { + const before = [ + lists.mock.calls.length, + normalized.mock.calls.length, + sorts.mock.calls.length, + lookups.mock.calls.length + ] + measuring = true + try { + reconcile() + } finally { + measuring = false + } + inventories += lists.mock.calls.length - before[0] + normalizations += normalized.mock.calls.length - before[1] + fullSorts += sorts.mock.calls + .slice(before[2]) + .filter(([compare]) => compare === compareAutomationRunsNewestFirst).length + selectedLookups += lookups.mock.calls + .slice(before[3]) + .filter( + ([key], i) => + typeof key === 'string' && + registered.has(key) && + typeof lookups.mock.results[before[3] + i].value === 'string' + ).length + }) + return { + lists, + counts: () => ({ + inventories, + normalizations, + sorts: fullSorts, + rows, + statusVisits, + linearFinds, + selectedLookups + }) + } +} + +export function assertTerminalInventorySelection(run: AutomationRun): void { + const released = vi.fn(), + kept = vi.fn() + const registrations = new Map([ + ['missing', { release: released }], + ['failed', { release: released }], + ['duplicate', { release: kept }], + ...(['dispatching', 'dispatched', 'completed'] as const).map( + (status) => [status, { release: kept }] as const + ) + ]) + reconcileDesktopRunTerminals(registrations, () => [ + { ...run, id: 'duplicate', status: 'completed' }, + { ...run, id: 'duplicate', status: 'dispatch_failed' }, + { ...run, id: 'failed', status: 'dispatch_failed' }, + ...(['dispatching', 'dispatched', 'completed'] as const).map((status) => ({ + ...run, + id: status, + status + })) + ]) + expect(released).toHaveBeenCalledTimes(2) + expect(kept).not.toHaveBeenCalled() +} diff --git a/src/renderer/src/lib/automation-terminal-ownership.test.ts b/src/renderer/src/lib/automation-terminal-ownership.test.ts index 9f4797685f8b..bedb3589d0c4 100644 --- a/src/renderer/src/lib/automation-terminal-ownership.test.ts +++ b/src/renderer/src/lib/automation-terminal-ownership.test.ts @@ -1,3 +1,8 @@ +import { + measureTerminalInventory, + assertTerminalInventorySelection +} from './automation-terminal-inventory-test-harness' +import * as desktopLifecycle from '../../../main/automations/desktop-run-terminal-lifecycle' import { randomUUID } from 'node:crypto' import { createRuntimeAutomationService } from '../../../main/automations/runtime-automation-service' import { runtimeStub } from '../../../main/runtime/rpc/methods/agent-launch.test-fixture' @@ -18,7 +23,8 @@ import { createStore, closeTestStores, testState, - readPersistedStateJson + readPersistedStateJson, + writeDataFile } from '../../../main/persistence/persistence-test-harness' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' @@ -698,3 +704,90 @@ it.each([5, 50])('bounds actual desktop fallback/Chat/Reuse owners at N=%i', asy rmSync(root, { recursive: true, force: true }) } }) + +it.each([ + [5, 100], + [50, 1000] +])('shares one current inventory for %i owners and %i retained rows', async (owners, history) => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-34332-inventory-')) + const seeded = buildProfileStateCutoverFixture('/fixture') + seeded.automations = Array.from({ length: history / 100 }, (_, i) => ({ + ...seeded.automations[0], + id: `inventory-${i}` + })) + seeded.automationRuns = Array.from({ length: history }, (_, i) => ({ + ...seeded.automationRuns[0], + id: `inventory-run-${i}`, + automationId: seeded.automations[Math.floor(i / 100)].id, + status: i < owners ? (['dispatching', 'dispatched', 'completed'] as const)[i % 3] : 'completed', + createdAt: i + })) + writeDataFile(seeded) + const disk = createStore(), + f = fixture() + const create = vi.spyOn(desktopLifecycle, 'createDesktopRunTerminalLifecycle') + const runtime = { + ...runtimeStub(), + ...f.runtime, + setAutomationService: vi.fn(), + notifyAutomationsChanged: vi.fn() + } + // SAFETY: only the OS/window transport is scripted; actual runtime/service/writer/persistence/lifecycle owners execute. + const service = createRuntimeAutomationService({ + store: disk, + runtime: runtime as unknown as OrcaRuntimeService, + headless: false + }) + const lifecycle = create.mock.results[0].value! + try { + const runs = disk.listAutomationRuns(), + registered = new Set( + runs.filter((r) => Number(r.id.split('-').at(-1)) < owners).map((r) => r.id) + ) + await service.markDispatchResult({ runId: runs[0].id, status: 'completed' }) + const inventory = measureTerminalInventory(disk, lifecycle, registered) + const { lists } = inventory + lifecycle.reconcile() + expect(lists).not.toHaveBeenCalled() + for (const run of runs.filter((r) => registered.has(r.id))) { + expect( + lifecycle.begin({ ...seeded.automations[0], reuseSession: false }, run, run.id) + ).not.toBeNull() + } + await service.markDispatchResult({ + runId: runs[0].id, + status: 'completed' + }) + expect(inventory.counts()).toEqual({ + inventories: 1, + normalizations: history, + sorts: 1, + rows: history, + statusVisits: history, + linearFinds: 0, + selectedLookups: owners + }) + expect(f.web.listenerCount('render-process-gone')).toBe(1) + process.stdout.write(`${JSON.stringify({ owners, history, ...inventory.counts() })}\n`) + lifecycle.begin( + { ...seeded.automations[0], reuseSession: false }, + { ...runs[0], id: 'missing' }, + 'missing' + ) + lifecycle.reconcile() + expect(stopRevokers.size).toBe(owners) + const failed = runs.find((run) => registered.has(run.id))! + await service.markDispatchResult({ runId: failed.id, status: 'dispatch_failed' }) + expect(stopRevokers.size).toBe(owners - 1) + lifecycle.stop() + lists.mockClear() + lifecycle.reconcile() + expect(lists).not.toHaveBeenCalled() + assertTerminalInventorySelection(runs[0]) + expect(f.web.eventNames()).toEqual([]) + } finally { + service.stop() + await closeTestStores() + rmSync(testState.dir, { recursive: true, force: true }) + } +}) From e1a175ddb9a9941866d079fecff624dd6ff1eee7 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:52:35 -0700 Subject: [PATCH 07/23] Restore automation server composition and process import boundaries --- config/flaky-test-pattern-baseline.txt | 1 - config/scripts/orcad-entry-build.test.mjs | 12 +- ...ntime-automation-service-retention.test.ts | 5 +- .../runtime-automation-service.test.ts | 7 +- .../automations/runtime-automation-service.ts | 17 +- .../structured-agent-session-host.ts | 27 ++- ...tructured-agent-session-workspace-sleep.ts | 34 ++++ src/main/pty-descendant-snapshot.ts | 147 +++++++++++++--- src/main/pty-descendant-termination.ts | 159 +++++------------- src/main/startup/main-process-automations.ts | 5 +- .../lib/automation-terminal-ownership.test.ts | 6 +- 11 files changed, 241 insertions(+), 179 deletions(-) diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index b2d5e1756260..f1a738bb646f 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -1156,7 +1156,6 @@ 1 test-no-wall-clock:src/renderer/src/components/WorktreeJumpPalette.test.tsx 2 test-no-wall-clock:src/renderer/src/hooks/ipc-events/agent-status-terminal-title-tab-write.test.ts 1 test-no-wall-clock:src/renderer/src/hooks/ipc-events/worktree-event-lineage-refresh.test.ts -3 test-no-wall-clock:src/renderer/src/hooks/useAutomationDispatchEvents.test.ts 1 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-agent-status-hook-titles.test.ts 1 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-browser-tab-create.test.ts 2 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts 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/src/main/automations/runtime-automation-service-retention.test.ts b/src/main/automations/runtime-automation-service-retention.test.ts index 2b21371513fb..25936bfc5cd7 100644 --- a/src/main/automations/runtime-automation-service-retention.test.ts +++ b/src/main/automations/runtime-automation-service-retention.test.ts @@ -1,3 +1,4 @@ +import { createDesktopRunTerminalLifecycle } from './desktop-run-terminal-lifecycle' import { afterEach, describe, expect, it, vi } from 'vitest' import type { AutomationRun } from '../../shared/automations-types' import { RUN_TERMINAL_GRACE_MS } from './headless-run-terminal-retention' @@ -71,7 +72,9 @@ function build(headless: boolean) { store: store as never, // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: retention reads only the members faked above. runtime: runtime as never, - headless + ...(headless + ? { headless: true as const } + : { headless: false as const, createDesktopLifecycle: createDesktopRunTerminalLifecycle }) }) return { runtime, service, store } } diff --git a/src/main/automations/runtime-automation-service.test.ts b/src/main/automations/runtime-automation-service.test.ts index a7863c73f651..b286cc7cf78b 100644 --- a/src/main/automations/runtime-automation-service.test.ts +++ b/src/main/automations/runtime-automation-service.test.ts @@ -1,3 +1,4 @@ +import { createDesktopRunTerminalLifecycle } from './desktop-run-terminal-lifecycle' import { beforeEach, describe, expect, it, vi } from 'vitest' import type * as AgentLauncher from './headless-automation-agent-launch' import type { HeadlessAutomationDispatcher } from './headless-dispatch' @@ -39,7 +40,7 @@ import { createRuntimeAutomationService } from './runtime-automation-service' const state = buildProfileStateCutoverFixture('/fixture') const run = { ...state.automationRuns[0], - createdAt: Date.now(), + createdAt: 1_700_000_000_000, status: 'dispatching' as const, chatSessionId: null } @@ -72,7 +73,9 @@ function fixture(headless: boolean) { } 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 + ...(headless + ? { headless: true as const } + : { headless: false as const, createDesktopLifecycle: createDesktopRunTerminalLifecycle }) }) return { runtime, rows } } diff --git a/src/main/automations/runtime-automation-service.ts b/src/main/automations/runtime-automation-service.ts index 4dfd7dd49014..f4071ab32d3c 100644 --- a/src/main/automations/runtime-automation-service.ts +++ b/src/main/automations/runtime-automation-service.ts @@ -1,4 +1,4 @@ -import { createDesktopRunTerminalLifecycle } from './desktop-run-terminal-lifecycle' +import type { createDesktopRunTerminalLifecycle } from './desktop-run-terminal-lifecycle' import { automationRunOperationId } from './automation-run-operation' import { observeAutomationChatRun } from './runtime-chat-run-observer' import { readAutomationRunReceipt } from './automation-run-receipt' @@ -28,14 +28,19 @@ import { closeEarlierHookReviewRunTerminals } from './hook-review-blocked-run-te const MAX_REMEMBERED_LAUNCHES = 256 -export function createRuntimeAutomationService(input: { +type RuntimeAutomationServiceInput = { store: Store runtime: OrcaRuntimeService claudeUsage?: ClaudeUsageStore codexUsage?: CodexUsageStore - /** Execute remote_host_service schedules through the headless dispatcher. */ - headless: boolean -}): AutomationService { +} & ( + | { headless: true } + | { headless: false; createDesktopLifecycle: typeof createDesktopRunTerminalLifecycle } +) + +export function createRuntimeAutomationService( + input: RuntimeAutomationServiceInput +): AutomationService { const { store, runtime, claudeUsage, codexUsage } = input // Launch handles remain usable before pane-key lookup resolves. const launchedHandles = new Map() @@ -200,7 +205,7 @@ export function createRuntimeAutomationService(input: { if (input.headless) { bindHeadlessRunTerminalRetention(service, store, runtime) } else { - desktop = createDesktopRunTerminalLifecycle(runtime, store, (id, operation) => + desktop = input.createDesktopLifecycle(runtime, store, (id, operation) => service.runInAutomationLane(id, operation) ) const stop = service.stop.bind(service) 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 42ebaa2375a8..0e924ce03fa3 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 @@ -32,7 +32,7 @@ import { structuredAgentSessionRestartResumeSurfaces } from './structured-agent- 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 { @@ -198,22 +198,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) 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/pty-descendant-snapshot.ts b/src/main/pty-descendant-snapshot.ts index 65ba1dc85524..a70c449eb35d 100644 --- a/src/main/pty-descendant-snapshot.ts +++ b/src/main/pty-descendant-snapshot.ts @@ -1,9 +1,6 @@ -import { execFile } from 'node:child_process' -import { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' +import type { ProcessTableRow } from './pty-process-table-parser' export const DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000 -// Busy hosts can exceed execFile’s 1MB default; truncated output would omit descendants. -const PS_MAX_BUFFER_BYTES = 32 * 1024 * 1024 export type ProcessTableCapture = { rows: ProcessTableRow[] @@ -12,29 +9,125 @@ export type ProcessTableCapture = { } export type ProcessTableReader = (timeoutMs?: number) => Promise -export function readFreshProcessTable( - timeoutMs = DESCENDANT_SNAPSHOT_TIMEOUT_MS -): Promise { - // Stamp before ps starts so a capture-second PID cannot appear older after a clock rollover. - const capturedAtMs = Date.now() - return new Promise((resolve, reject) => { - execFile( - 'ps', - ['-axo', 'pid=,ppid=,pgid=,tpgid=,lstart='], - { - maxBuffer: PS_MAX_BUFFER_BYTES, - timeout: timeoutMs, - killSignal: 'SIGKILL', - // Pin lstart’s locale so delayed identity checks parse it consistently. - env: { ...process.env, LANG: 'C', LC_ALL: 'C' } - }, - (error, stdout) => { - if (error) { - reject(error) - return - } - resolve({ rows: parseProcessTable(stdout), capturedAtMs }) + +export type PosixProcessIdentity = Pick + +export type DescendantSnapshot = { + root?: PosixProcessIdentity + rootPgid: number | null + descendants: ProcessTableRow[] + /** Wall-clock boundary for an unmerged snapshot (or legacy callers). */ + capturedAtMs: number + /** Per-PID identity boundaries for merged captures. */ + capturedAtMsByPid?: Readonly> + /** Fresh ancestry proves ownership despite lstart’s second-resolution timestamps; retained merge rows do not. */ + reDerivedPids?: ReadonlySet +} + +/** Share only scans not yet started; later requests need fresh identities before signalling. */ +export function createProcessTableSnapshotReader( + readFresh: ProcessTableReader +): ProcessTableReader { + let queued: { promise: Promise; started: boolean } | null = null + + return (timeoutMs) => { + if (queued && !queued.started) { + return queued.promise + } + + const entry: { promise: Promise; started: boolean } = { + promise: Promise.resolve(undefined as never), + started: false + } + entry.promise = Promise.resolve().then(() => { + // Start each later request’s scan within its own deadline, without queuing behind an older one. + entry.started = true + return readFresh(timeoutMs) + }) + queued = entry + const clearQueued = (): void => { + if (queued === entry) { + queued = null } - ) + } + void entry.promise.then(clearQueued, clearQueued) + return entry.promise + } +} + +export function readProcessTableBeforeDeadline( + readTable: ProcessTableReader, + timeoutMs: number +): Promise { + return new Promise((resolve) => { + let settled = false + const finish = (capture: ProcessTableCapture | null): void => { + if (settled) { + return + } + settled = true + clearTimeout(timer) + resolve(capture) + } + const timer = setTimeout(() => finish(null), timeoutMs) + timer.unref?.() + try { + void readTable(timeoutMs).then( + (rows) => finish(rows), + () => finish(null) + ) + } catch { + finish(null) + } }) } + +export function collectDescendantRows( + rootPid: number, + table: ProcessTableRow[], + capturedAtMs = Date.now() +): DescendantSnapshot { + const childrenByPpid = new Map() + let rootRow: ProcessTableRow | null = null + let duplicateRoot = false + for (const row of table) { + if (row.pid === rootPid) { + // Duplicate root rows from a non-atomic read leave its identity ambiguous. + duplicateRoot = rootRow !== null + rootRow ??= row + continue + } + const siblings = childrenByPpid.get(row.ppid) + if (siblings) { + siblings.push(row) + } else { + childrenByPpid.set(row.ppid, [row]) + } + } + // After root exit, descendants reparent; remaining rows with its old PID as parent may reflect PID reuse. + if (!rootRow || duplicateRoot) { + return { rootPgid: null, descendants: [], capturedAtMs } + } + const descendants: ProcessTableRow[] = [] + const queue = [rootPid] + const visited = new Set(queue) + for (let nextIndex = 0; nextIndex < queue.length; nextIndex += 1) { + const pid = queue[nextIndex] + for (const child of childrenByPpid.get(pid) ?? []) { + // Non-atomic ps output can contain duplicate or cyclic rows; never loop on them. + if (visited.has(child.pid)) { + continue + } + visited.add(child.pid) + descendants.push(child) + queue.push(child.pid) + } + } + return { + root: { pid: rootRow.pid, startedAt: rootRow.startedAt }, + rootPgid: rootRow.pgid, + descendants, + capturedAtMs, + reDerivedPids: new Set(descendants.map((row) => row.pid)) + } +} diff --git a/src/main/pty-descendant-termination.ts b/src/main/pty-descendant-termination.ts index 5b55a7dbb33a..4f616448dfe5 100644 --- a/src/main/pty-descendant-termination.ts +++ b/src/main/pty-descendant-termination.ts @@ -1,12 +1,16 @@ +import { execFile } from 'node:child_process' import type { JobTerminationOutcome } from './windows/windows-pty-job' import { terminateWindowsProcessTree, type WindowsTreeKiller } from './windows-process-tree-kill' import { verifyWindowsTreeKillTarget, type WindowsTreeKillTarget } from './windows-pty-root-identity' -import type { ProcessTableRow } from './pty-process-table-parser' +import { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' import { - readFreshProcessTable, + createProcessTableSnapshotReader, + readProcessTableBeforeDeadline, + collectDescendantRows, + type DescendantSnapshot, DESCENDANT_SNAPSHOT_TIMEOUT_MS, type ProcessTableCapture, type ProcessTableReader @@ -14,6 +18,11 @@ import { export { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' export { + createProcessTableSnapshotReader, + readProcessTableBeforeDeadline, + collectDescendantRows, + type PosixProcessIdentity, + type DescendantSnapshot, DESCENDANT_SNAPSHOT_TIMEOUT_MS, type ProcessTableCapture, type ProcessTableReader @@ -21,138 +30,46 @@ export { export const DESCENDANT_KILL_GRACE_MS = 2_000 -export type PosixProcessIdentity = Pick - -export type DescendantSnapshot = { - root?: PosixProcessIdentity - rootPgid: number | null - descendants: ProcessTableRow[] - /** Wall-clock boundary for an unmerged snapshot (or legacy callers). */ - capturedAtMs: number - /** Per-PID identity boundaries for merged captures. */ - capturedAtMsByPid?: Readonly> - /** Fresh ancestry proves ownership despite lstart’s second-resolution timestamps; retained merge rows do not. */ - reDerivedPids?: ReadonlySet -} - export type SignalSender = (pid: number, signal: NodeJS.Signals) => void -/** Share only scans not yet started; later requests need fresh identities before signalling. */ -export function createProcessTableSnapshotReader( - readFresh: ProcessTableReader -): ProcessTableReader { - let queued: { promise: Promise; started: boolean } | null = null - - return (timeoutMs) => { - if (queued && !queued.started) { - return queued.promise - } - - const entry: { promise: Promise; started: boolean } = { - promise: Promise.resolve(undefined as never), - started: false - } - entry.promise = Promise.resolve().then(() => { - // Start each later request’s scan within its own deadline, without queuing behind an older one. - entry.started = true - return readFresh(timeoutMs) - }) - queued = entry - const clearQueued = (): void => { - if (queued === entry) { - queued = null +// Busy hosts can exceed execFile’s 1MB default; truncated output would omit descendants. +const PS_MAX_BUFFER_BYTES = 32 * 1024 * 1024 + +function readFreshProcessTable( + timeoutMs = DESCENDANT_SNAPSHOT_TIMEOUT_MS +): Promise { + // Stamp before ps starts so a capture-second PID cannot appear older after a clock rollover. + const capturedAtMs = Date.now() + return new Promise((resolve, reject) => { + execFile( + 'ps', + ['-axo', 'pid=,ppid=,pgid=,tpgid=,lstart='], + { + maxBuffer: PS_MAX_BUFFER_BYTES, + timeout: timeoutMs, + killSignal: 'SIGKILL', + // Pin lstart’s locale so delayed identity checks parse it consistently. + env: { ...process.env, LANG: 'C', LC_ALL: 'C' } + }, + (error, stdout) => { + if (error) { + reject(error) + return + } + resolve({ rows: parseProcessTable(stdout), capturedAtMs }) } - } - void entry.promise.then(clearQueued, clearQueued) - return entry.promise - } + ) + }) } export const readProcessTable = createProcessTableSnapshotReader(readFreshProcessTable) -export function readProcessTableBeforeDeadline( - readTable: ProcessTableReader, - timeoutMs: number -): Promise { - return new Promise((resolve) => { - let settled = false - const finish = (capture: ProcessTableCapture | null): void => { - if (settled) { - return - } - settled = true - clearTimeout(timer) - resolve(capture) - } - const timer = setTimeout(() => finish(null), timeoutMs) - timer.unref?.() - try { - void readTable(timeoutMs).then( - (rows) => finish(rows), - () => finish(null) - ) - } catch { - finish(null) - } - }) -} - type SnapshotDeps = { readTable?: ProcessTableReader platform?: NodeJS.Platform timeoutMs?: number } -export function collectDescendantRows( - rootPid: number, - table: ProcessTableRow[], - capturedAtMs = Date.now() -): DescendantSnapshot { - const childrenByPpid = new Map() - let rootRow: ProcessTableRow | null = null - let duplicateRoot = false - for (const row of table) { - if (row.pid === rootPid) { - // Duplicate root rows from a non-atomic read leave its identity ambiguous. - duplicateRoot = rootRow !== null - rootRow ??= row - continue - } - const siblings = childrenByPpid.get(row.ppid) - if (siblings) { - siblings.push(row) - } else { - childrenByPpid.set(row.ppid, [row]) - } - } - // After root exit, descendants reparent; remaining rows with its old PID as parent may reflect PID reuse. - if (!rootRow || duplicateRoot) { - return { rootPgid: null, descendants: [], capturedAtMs } - } - const descendants: ProcessTableRow[] = [] - const queue = [rootPid] - const visited = new Set(queue) - for (let nextIndex = 0; nextIndex < queue.length; nextIndex += 1) { - const pid = queue[nextIndex] - for (const child of childrenByPpid.get(pid) ?? []) { - // Non-atomic ps output can contain duplicate or cyclic rows; never loop on them. - if (visited.has(child.pid)) { - continue - } - visited.add(child.pid) - descendants.push(child) - queue.push(child.pid) - } - } - return { - root: { pid: rootRow.pid, startedAt: rootRow.startedAt }, - rootPgid: rootRow.pgid, - descendants, - capturedAtMs, - reDerivedPids: new Set(descendants.map((row) => row.pid)) - } -} - /** Capture before signalling the root: exited parents’ descendants reparent and become unfindable; failure returns null. */ export async function captureDescendantSnapshot( rootPid: number, diff --git a/src/main/startup/main-process-automations.ts b/src/main/startup/main-process-automations.ts index aea94b954fa3..24b5875d1cae 100644 --- a/src/main/startup/main-process-automations.ts +++ b/src/main/startup/main-process-automations.ts @@ -1,3 +1,4 @@ +import { createDesktopRunTerminalLifecycle } from '../automations/desktop-run-terminal-lifecycle' import type { AutomationService } from '../automations/service' import { createRuntimeAutomationService } from '../automations/runtime-automation-service' import { mainProcessState as state } from './main-process-state' @@ -16,7 +17,9 @@ export function initializeMainProcessAutomations(): AutomationService { claudeUsage, codexUsage, // Remote clients mirror schedules; only server processes execute remote_host_service ownership. - headless: state.isServeMode + ...(state.isServeMode + ? { headless: true as const } + : { headless: false as const, createDesktopLifecycle: createDesktopRunTerminalLifecycle }) }) state.automations = service return service diff --git a/src/renderer/src/lib/automation-terminal-ownership.test.ts b/src/renderer/src/lib/automation-terminal-ownership.test.ts index bedb3589d0c4..9290f8894180 100644 --- a/src/renderer/src/lib/automation-terminal-ownership.test.ts +++ b/src/renderer/src/lib/automation-terminal-ownership.test.ts @@ -600,7 +600,8 @@ it.each([5, 50])('bounds actual desktop fallback/Chat/Reuse owners at N=%i', asy service = createRuntimeAutomationService({ store: disk, runtime: runtime as unknown as OrcaRuntimeService, - headless: false + headless: false, + createDesktopLifecycle: desktopLifecycle.createDesktopRunTerminalLifecycle }) service.setWebContents(f.web) service.setRendererReady() @@ -736,7 +737,8 @@ it.each([ const service = createRuntimeAutomationService({ store: disk, runtime: runtime as unknown as OrcaRuntimeService, - headless: false + headless: false, + createDesktopLifecycle: desktopLifecycle.createDesktopRunTerminalLifecycle }) const lifecycle = create.mock.results[0].value! try { From 008d6613ef9bb4109fa2ca8d62bdd869540b7052 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:48:23 -0700 Subject: [PATCH 08/23] fix(automations): preserve busy chat reuse and runtime boundaries --- config/scripts/ci-shard-timings.json | 4 +- config/tsconfig.tc.web.json | 1 + ...ation-chat-run-measurement-test-harness.ts | 9 +- .../automation-chat-session-reuse.ts | 83 ++-- .../desktop-run-terminal-lifecycle.ts | 9 +- .../automations/runtime-automation-service.ts | 7 +- .../runtime-chat-run-observer.test.ts | 9 +- .../automations/runtime-chat-run-observer.ts | 10 +- src/main/automations/service.test.ts | 20 +- src/main/daemon/daemon-pty-session-control.ts | 27 +- src/main/ipc/pty/provider/shutdown-detect.ts | 2 +- src/main/ipc/pty/renderer-fenced-kill.test.ts | 126 +++++ ...ctured-agent-session-conversations.test.ts | 2 +- ...session-queued-message-rig.test-fixture.ts | 21 +- .../automations/automation-launch-surface.ts | 4 +- ...omation-terminal-bind-layout-owner.test.ts | 114 ++++- ...automation-terminal-ownership.unit.test.ts | 57 +-- ...dless-automation-agent-launch.unit.test.ts | 457 ++++++++++-------- .../automation-chat-reuse-test-harness.ts | 275 +++++++++++ ...omation-terminal-inventory-test-harness.ts | 14 +- ...omation-terminal-ownership-test-harness.ts | 16 +- 21 files changed, 912 insertions(+), 355 deletions(-) rename src/renderer/src/lib/automation-terminal-ownership.test.ts => tests/e2e/automation-terminal-ownership.unit.test.ts (91%) rename src/main/automations/headless-automation-agent-launch.test.ts => tests/e2e/headless-automation-agent-launch.unit.test.ts (58%) create mode 100644 tests/e2e/helpers/automation-chat-reuse-test-harness.ts rename {src/renderer/src/lib => tests/e2e/helpers}/automation-terminal-inventory-test-harness.ts (80%) rename {src/renderer/src/lib => tests/e2e/helpers}/automation-terminal-ownership-test-harness.ts (93%) diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index 08aec15e1534..760e286c8654 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -1167,7 +1167,7 @@ "src/main/automations/external-automation-probe-scheduler.test.ts": 86, "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, @@ -10480,7 +10480,7 @@ "src/renderer/src/lib/automation-session-observer.test.ts": 55, "src/renderer/src/lib/automation-session-reuse.test.ts": 65, "src/renderer/src/lib/automation-terminal-bind-layout-owner.test.ts": 1382, - "src/renderer/src/lib/automation-terminal-ownership.test.ts": 1491, + "tests/e2e/automation-terminal-ownership.unit.test.ts": 1491, "src/renderer/src/lib/base64-bytes.test.ts": 65, "src/renderer/src/lib/bounded-generation-map.test.ts": 23, "src/renderer/src/lib/browser-cookie-import-toast.test.ts": 172, diff --git a/config/tsconfig.tc.web.json b/config/tsconfig.tc.web.json index b1f956552a00..5332999f8d3b 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-chat-run-measurement-test-harness.ts b/src/main/automations/automation-chat-run-measurement-test-harness.ts index a23c225707e1..5f3d223cd320 100644 --- a/src/main/automations/automation-chat-run-measurement-test-harness.ts +++ b/src/main/automations/automation-chat-run-measurement-test-harness.ts @@ -1,8 +1,5 @@ import { vi } from 'vitest' -import type { - AgentJournalSnapshot, - AgentJournalRenderItem -} from '../../shared/agent-session-journal-types' +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' @@ -58,6 +55,7 @@ export function measureAutomationChatRun( } } } + // 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) } }) @@ -127,13 +125,14 @@ export function measureAutomationChatRun( return rows }) // Count actual folded history iterators, without replacing their algorithms. - const folded: { items: Map } = Reflect.get(journal, 'state') + 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', diff --git a/src/main/automations/automation-chat-session-reuse.ts b/src/main/automations/automation-chat-session-reuse.ts index c5a505c67b30..00a0a7f981f5 100644 --- a/src/main/automations/automation-chat-session-reuse.ts +++ b/src/main/automations/automation-chat-session-reuse.ts @@ -17,44 +17,29 @@ export async function reuseAutomationChat( runtime: OrcaRuntimeService, { automation, run, runs }: AutomationAgentLaunchRequest ): Promise { - await runtime.ensureStructuredAgentSessionHost() - const host = getStructuredAgentSessionHost() - if (!host) { + 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 store = await runtime.openAgentSessionRecordStore() + 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 (!id || seen.has(id)) { + if (previous.sessionKind !== 'chat' || !id || seen.has(id)) { continue } seen.add(id) - if ( - previous.sessionKind !== 'chat' || - previous.status !== 'completed' || - previous.workspaceId !== automation.workspaceId - ) { - continue - } - const record = store.getConversation(id) - if ( - !record || - record.provider !== automation.agentId || - record.location.workspaceId !== automation.workspaceId - ) { - continue - } - await host.journalSnapshot(id) - const current = store.getConversation(id) - const work = host.currentWork(id) - if (!current || !work || work.working()) { - continue - } const target: HeadlessAutomationAgentLaunch = { - workspaceId: record.location.workspaceId, + // The caller only attempts Chat reuse for a stable workspace. + workspaceId: automation.workspaceId!, workspaceDisplayName: null, sessionKind: 'chat', chatSessionId: id, @@ -64,11 +49,37 @@ export async function reuseAutomationChat( 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: rpcCallerOperationKey(AUTOMATION_AGENT_CALLER) }, + { callerKey }, structuredAgentSessionMessageSendMutation({ sessionId: id, - clientOperationId: automationRunOperationId(run, 'reuse-send'), + clientOperationId: operationId, expectedRuntimeFence: current.currentFence, delivery: 'queue-if-active', body: structuredAgentSessionSendBody(automation.prompt, []) @@ -77,11 +88,15 @@ export async function reuseAutomationChat( if (sent.ok) { return target } - const row = store.getOperationRow( - rpcCallerOperationKey(AUTOMATION_AGENT_CALLER), - automationRunOperationId(run, 'reuse-send') - ) - if (sent.refusal.code === 'agent_session_conflict' || row?.outcome.status === 'failed') { + 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( diff --git a/src/main/automations/desktop-run-terminal-lifecycle.ts b/src/main/automations/desktop-run-terminal-lifecycle.ts index 0da5fb35e7bc..33dacf2015fa 100644 --- a/src/main/automations/desktop-run-terminal-lifecycle.ts +++ b/src/main/automations/desktop-run-terminal-lifecycle.ts @@ -24,8 +24,6 @@ import { requestAutomationTerminalLifecycle } from '../window/terminal-tab-close import { terminalPresentationRequest } from '../window/runtime-window-lifecycle' import type { AgentLaunchHostPolicy } from '../runtime/rpc/methods/agent-launch-surfaces' -export { cancelDesktopTerminalRetirement } from './desktop-run-terminal-stop' - export function createDesktopRunTerminalLifecycle( runtime: OrcaRuntimeService, store: Store, @@ -48,7 +46,7 @@ export function createDesktopRunTerminalLifecycle( let epoch: string | null = null let target: AutomationTerminalTarget | null = null let ptyId: string | null = null - let incarnationId: string | undefined + let incarnationId: string | null | undefined let finalizing = false let enrollment = Promise.resolve() const listeners: (() => void)[] = [] @@ -85,7 +83,10 @@ export function createDesktopRunTerminalLifecycle( (reply) => { if ( !valid() || - Object.entries(correlation).some(([key, value]) => Reflect.get(reply, key) !== value) || + reply.registrationId !== correlation.registrationId || + reply.runId !== correlation.runId || + reply.operationId !== correlation.operationId || + reply.serviceGeneration !== correlation.serviceGeneration || (epoch !== null && reply.documentEpoch !== epoch) ) { throw new Error('terminal_lifecycle_owner_lost') diff --git a/src/main/automations/runtime-automation-service.ts b/src/main/automations/runtime-automation-service.ts index f4071ab32d3c..e10877639e31 100644 --- a/src/main/automations/runtime-automation-service.ts +++ b/src/main/automations/runtime-automation-service.ts @@ -71,9 +71,10 @@ export function createRuntimeAutomationService( if (!run.chatSessionId) { const records = await runtime.openAgentSessionRecordStore() const receipt = readAutomationRunReceipt(records, run) + const automationId = run.automationId const agent = tuiAgentDisplayName( - store.listAutomations().find((entry) => entry.id === run.automationId)?.agentId ?? + store.listAutomations().find((entry) => entry.id === automationId)?.agentId ?? 'Agent' ) ?? 'Agent' if (!receipt) { @@ -129,10 +130,10 @@ export function createRuntimeAutomationService( throw error } console.error('[automations] chat run observation failed:', error) + const automationId = run.automationId const agent = tuiAgentDisplayName( - store.listAutomations().find((entry) => entry.id === run.automationId)?.agentId ?? - '' + store.listAutomations().find((entry) => entry.id === automationId)?.agentId ?? '' ) ?? 'The agent' return { status: 'dispatch_failed', diff --git a/src/main/automations/runtime-chat-run-observer.test.ts b/src/main/automations/runtime-chat-run-observer.test.ts index f007dd6cce4d..155522e94c6b 100644 --- a/src/main/automations/runtime-chat-run-observer.test.ts +++ b/src/main/automations/runtime-chat-run-observer.test.ts @@ -124,6 +124,7 @@ describe('exact automation chat turn', () => { outputRows++ yield item } + return undefined }) const result = chatAutomationRunObservation(view, 'prompt', 'Codex') expect(outputRows).toBe(4) @@ -542,11 +543,11 @@ describe('real host queue publication and operation bounds', () => { (history + 30) * 4000 ) const sessions = rig.host.collaboratorsForTests().sessions - expect(Reflect.get(sessions, 'observers').size).toBe(0) - expect(Reflect.get(sessions, 'attachments').size).toBe(1) + expect(sessions['observers'].size).toBe(0) + expect(sessions['attachments'].size).toBe(1) totals.push(measure()) process.stdout.write( - `${JSON.stringify({ history, mode, sourceAttachments: Reflect.get(sessions, 'attachments').size, logicalObservers: Reflect.get(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` + `${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() @@ -672,7 +673,7 @@ describe('real host queue publication and operation bounds', () => { rig.host.stopDelivery() } expect(await liveResult).toBeInstanceOf(Error) - expect(Reflect.get(sessions, 'observers').size).toBe(0) + expect(sessions['observers'].size).toBe(0) return } if (outcome === 'withdraw') { diff --git a/src/main/automations/runtime-chat-run-observer.ts b/src/main/automations/runtime-chat-run-observer.ts index 6403afb7c894..72f9c87490e7 100644 --- a/src/main/automations/runtime-chat-run-observer.ts +++ b/src/main/automations/runtime-chat-run-observer.ts @@ -164,13 +164,15 @@ export async function observeAutomationChatRun( currentJournal = hint.journal const semantic = interest() const rows = hint.rows + const currentCursor = cursor const contiguous = - cursor && - hint.cursor?.epoch === cursor.epoch && + currentCursor && + hint.cursor?.epoch === currentCursor.epoch && rows?.every( - (row, i) => row.epoch === cursor.epoch && row.seq === cursor.sequence + i + 1 + (row, i) => + row.epoch === currentCursor.epoch && row.seq === currentCursor.sequence + i + 1 ) && - hint.cursor.sequence === cursor.sequence + rows.length + hint.cursor.sequence === currentCursor.sequence + rows.length const linked = rows?.some((row) => { if (row.kind === 'submission') { return row.queuedMessageId === messageId && row.clientMessageId !== submissionId diff --git a/src/main/automations/service.test.ts b/src/main/automations/service.test.ts index 31f697ff0767..1efc2f34e743 100644 --- a/src/main/automations/service.test.ts +++ b/src/main/automations/service.test.ts @@ -12,6 +12,7 @@ import { tmpdir } from 'node:os' import type { Repo } from '../../shared/repo-types' import { toRuntimeExecutionHostId } from '../../shared/execution-host' import { AutomationService } from './service' +import type { HeadlessAutomationDispatcher } from './headless-dispatch' vi.mock('electron', () => ({ app: { @@ -70,7 +71,10 @@ describe('AutomationService', () => { }) vi.setSystemTime(new Date('2026-05-13T09:01:00')) - const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) + const send = vi.fn(async (_request) => ({ + workspaceId: 'wt1', + terminalSessionId: 'tab-1' + })) const service = new AutomationService(store, { headlessDispatcher: send, tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, @@ -682,9 +686,12 @@ describe('AutomationService', () => { const logged = vi.spyOn(console, 'error').mockImplementation(() => {}) vi.setSystemTime(new Date('2026-05-13T09:01:00')) - const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) + const send = vi.fn(async (_request) => ({ + workspaceId: 'wt1', + terminalSessionId: 'tab-1' + })) const service = new AutomationService(reloaded, { headlessDispatcher: send, tickMs: 60_000 }) - service.setWebContents({ isDestroyed: () => false, send }) + service.setWebContents({ isDestroyed: () => false, send: vi.fn() }) service.start() service.setRendererReady() @@ -742,9 +749,12 @@ describe('AutomationService', () => { const logged = vi.spyOn(console, 'error').mockImplementation(() => {}) vi.setSystemTime(new Date('2026-05-13T09:01:00')) - const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) + const send = vi.fn(async (_request) => ({ + workspaceId: 'wt1', + terminalSessionId: 'tab-1' + })) const service = new AutomationService(reloaded, { headlessDispatcher: send, tickMs: 60_000 }) - service.setWebContents({ isDestroyed: () => false, send }) + service.setWebContents({ isDestroyed: () => false, send: vi.fn() }) service.start() service.setRendererReady() diff --git a/src/main/daemon/daemon-pty-session-control.ts b/src/main/daemon/daemon-pty-session-control.ts index 5c3a50124f84..55ec181e57ca 100644 --- a/src/main/daemon/daemon-pty-session-control.ts +++ b/src/main/daemon/daemon-pty-session-control.ts @@ -188,23 +188,24 @@ export abstract class DaemonPtySessionControl extends DaemonPtySessionLiveness { opts.authorizeStop && (await this.probePtyLiveness(id)) === true && this.sessionIncarnations.get(id) === original && - endpoint && - this.client.getDaemonIdentity() && - sameEndpointIdentity(this.client.getDaemonIdentity(), endpoint) + endpoint ) { - if (installedRestore && this.coldRestoreCache.get(id) === installedRestore) { - if (previousRestore) { - this.coldRestoreCache.set(id, previousRestore) - } else { - this.coldRestoreCache.delete(id) + const currentEndpoint = this.client.getDaemonIdentity() + if (currentEndpoint && sameEndpointIdentity(currentEndpoint, endpoint)) { + if (installedRestore && this.coldRestoreCache.get(id) === installedRestore) { + if (previousRestore) { + this.coldRestoreCache.set(id, previousRestore) + } else { + this.coldRestoreCache.delete(id) + } + if (!previouslySlept) { + this.sleepRestoreSessionIds.delete(id) + } } - if (!previouslySlept) { - this.sleepRestoreSessionIds.delete(id) + if (hadWriter) { + this.historyManager?.registerWriter(id) } } - if (hadWriter) { - this.historyManager?.registerWriter(id) - } } // Gone is known for a session this adapter lost, or (after a relaunch forgot that) one whose // history is unended and that no daemon sharing the history dir may still run. diff --git a/src/main/ipc/pty/provider/shutdown-detect.ts b/src/main/ipc/pty/provider/shutdown-detect.ts index ccb16b1e0216..c8dddbd08c14 100644 --- a/src/main/ipc/pty/provider/shutdown-detect.ts +++ b/src/main/ipc/pty/provider/shutdown-detect.ts @@ -1,4 +1,4 @@ -import { cancelDesktopTerminalRetirement } from '../../../automations/desktop-run-terminal-lifecycle' +import { cancelDesktopTerminalRetirement } from '../../../automations/desktop-run-terminal-stop' import type { IPtyProvider } from '../../../providers/pty-provider-contract' import { ptyIncarnationById } from './ownership-state' diff --git a/src/main/ipc/pty/renderer-fenced-kill.test.ts b/src/main/ipc/pty/renderer-fenced-kill.test.ts index e03ea9580bc1..9d75d673dff5 100644 --- a/src/main/ipc/pty/renderer-fenced-kill.test.ts +++ b/src/main/ipc/pty/renderer-fenced-kill.test.ts @@ -5,6 +5,7 @@ import { startLateExitHarness } from './daemon-late-exit-test-fixture' import { ptyIncarnationById } from './provider/ownership-state' import { installPtyKillIpcHandler } from './ipc/renderer-kill' import { shutdownProviderAndDetectExit } from './provider/shutdown-detect' +import { stopRevokers } from '../../automations/desktop-run-terminal-stop' const request = (id: string, expectedIncarnationId: string) => ({ id, @@ -14,6 +15,131 @@ const request = (id: string, expectedIncarnationId: string) => ({ }) describe('checked renderer stop route', () => { + it('revokes only the matching retirement before ordinary IPC Stop subscribes or shuts down', async () => { + const harness = await startLateExitHarness() + const matchingKey = 'renderer-stop-matching' + const unrelatedKey = 'renderer-stop-unrelated' + const release = vi.fn(() => { + stopRevokers.delete(matchingKey) + }) + const unrelated = vi.fn() + stopRevokers.set(matchingKey, { ptyId: harness.id, release }) + stopRevokers.set(unrelatedKey, { ptyId: 'other-pty', release: unrelated }) + const onExit = harness.adapter.onExit.bind(harness.adapter) + const shutdown = harness.adapter.shutdown.bind(harness.adapter) + const subscriptions: ReturnType[] = [] + const subscription = vi.spyOn(harness.adapter, 'onExit').mockImplementation((listener) => { + expect(release).toHaveBeenCalledOnce() + expect(stopRevokers.has(matchingKey)).toBe(false) + expect(unrelated).not.toHaveBeenCalled() + const unsubscribe = vi.fn(onExit(listener)) + subscriptions.push(unsubscribe) + return unsubscribe + }) + const stop = vi.spyOn(harness.adapter, 'shutdown').mockImplementation(async (id, opts) => { + expect(release).toHaveBeenCalledOnce() + expect(stopRevokers.has(matchingKey)).toBe(false) + expect(id).toBe(harness.id) + expect(ptyIncarnationById.get(id)).toBe(harness.result.incarnationId) + expect(opts).toEqual({ immediate: true, keepHistory: false }) + await shutdown(id, opts) + await harness.waitForExit() + }) + const physicalExit = vi.spyOn(harness.subprocess, 'forceKill').mockImplementation(() => { + harness.subprocess._simulateExit(137) + }) + try { + await harness.kill() + expect(stop).toHaveBeenCalledOnce() + expect(physicalExit).toHaveBeenCalledOnce() + expect(subscriptions).toHaveLength(1) + expect(subscriptions[0]).toHaveBeenCalledOnce() + expect(unrelated).not.toHaveBeenCalled() + expect(stopRevokers.has(unrelatedKey)).toBe(true) + expect(harness.providerExits).toEqual([ + { + id: harness.id, + code: 137, + incarnationId: harness.result.incarnationId, + cause: { kind: 'operator_close' } + } + ]) + expect(harness.rendererExits).toHaveLength(1) + expect(harness.runtime.captureState().connected).toBe(false) + expect((await harness.capture()).exitListenerCalls).toBe(1) + } finally { + subscription.mockRestore() + stop.mockRestore() + physicalExit.mockRestore() + stopRevokers.delete(matchingKey) + stopRevokers.delete(unrelatedKey) + await harness.dispose() + } + }) + + it('keeps retirement authorization and requires an observed matching exit, not just a shutdown ACK', async () => { + const harness = await startLateExitHarness() + const matchingKey = 'authorized-stop-matching' + const unrelatedKey = 'authorized-stop-unrelated' + const release = vi.fn() + const unrelated = vi.fn() + stopRevokers.set(matchingKey, { ptyId: harness.id, release }) + stopRevokers.set(unrelatedKey, { ptyId: 'other-pty', release: unrelated }) + const onExit = harness.adapter.onExit.bind(harness.adapter) + const subscriptions: ReturnType[] = [] + const subscription = vi.spyOn(harness.adapter, 'onExit').mockImplementation((listener) => { + expect(release).not.toHaveBeenCalled() + const unsubscribe = vi.fn(onExit(listener)) + subscriptions.push(unsubscribe) + return unsubscribe + }) + const authorizeStop = vi.fn(async () => true) + const opts = { + immediate: true, + keepHistory: false, + expectedIncarnationId: harness.result.incarnationId, + authorizeStop + } + const stop = vi.spyOn(harness.adapter, 'shutdown') + const physicalExit = vi.spyOn(harness.subprocess, 'forceKill').mockImplementation(() => { + harness.subprocess._simulateExit(137) + }) + try { + harness.pauseStream() + await expect(shutdownProviderAndDetectExit(harness.adapter, harness.id, opts)).resolves.toBe( + false + ) + expect(stop).toHaveBeenCalledExactlyOnceWith(harness.id, opts) + expect(authorizeStop).toHaveBeenCalledOnce() + expect(physicalExit).toHaveBeenCalledOnce() + expect(subscriptions).toHaveLength(1) + expect(subscriptions[0]).toHaveBeenCalledOnce() + expect(release).not.toHaveBeenCalled() + expect(unrelated).not.toHaveBeenCalled() + expect(stopRevokers.has(matchingKey)).toBe(true) + expect(stopRevokers.has(unrelatedKey)).toBe(true) + expect(harness.providerExits).toHaveLength(0) + harness.resumeStream() + await harness.waitForExit() + expect(harness.providerExits).toEqual([ + { + id: harness.id, + code: 137, + incarnationId: harness.result.incarnationId, + cause: { kind: 'operator_close' } + } + ]) + expect(harness.rendererExits).toHaveLength(1) + } finally { + subscription.mockRestore() + stop.mockRestore() + physicalExit.mockRestore() + stopRevokers.delete(matchingKey) + stopRevokers.delete(unrelatedKey) + await harness.dispose() + } + }) + it('refuses missing identity without falling through to the unfenced stop', async () => { const harness = await startLateExitHarness() try { 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 45461cc91026..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 @@ -244,7 +244,7 @@ describe('internal publication lifetime, independently of presentation', () => { expect(reentrant.mock.lastCall![0].kind).toBe('end') releaseC() reentrantRelease() - expect(Reflect.get(conversations, 'observers').size).toBe(0) + expect(conversations['observers'].size).toBe(0) const listener = vi.fn() const before = old.observeCommits(listener) const after = old.observeCommits(listener) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts index c631f4477dae..8cd115e3f329 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts @@ -19,7 +19,7 @@ import { } from './structured-agent-session-host' import { HOST_TEST_NOW as NOW, - HOST_TEST_SESSION as SESSION, + HOST_TEST_SESSION as DEFAULT_SESSION, HOST_TEST_THREAD as THREAD, hostTestAttachParams, hostTestMessage, @@ -56,11 +56,13 @@ export async function createQueuedMessageTestRig( now?: () => number /** Teardown records its restart offers, which `restartOffers` lists. */ recoveryCapsule?: true + sessionId?: string location?: AgentSessionExecutionLocation /** Defaults to indeterminate. */ probeOwner?: StructuredAgentSessionHostDeps['probeOwner'] } = {} ) { + const SESSION = options.sessionId ?? DEFAULT_SESSION const root = await mkdtemp(join(tmpdir(), 'orca-queued-messages-')) resetHostTestOperationIds() const store = await openTestAgentSessionRecordStore(root) @@ -81,10 +83,19 @@ export async function createQueuedMessageTestRig( ...(options.recoveryCapsule ? { recoveryCapsule: new AgentSessionRecoveryCapsule(root) } : {}) }) let host = makeHost() - const firstAttach = hostTestAttachParams( - null, - options.location ? { location: options.location } : {} - ) + const firstAttach = hostTestAttachParams(null, { + ...(options.location ? { location: options.location } : {}), + ...(options.sessionId + ? { + envelope: { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: null, + payloadFingerprint: '0'.repeat(64) + } + } + : {}) + }) expect(await host.attach(QUEUED_RIG_CALLER, firstAttach)).toMatchObject({ ok: true }) function envelope( diff --git a/src/renderer/src/components/automations/automation-launch-surface.ts b/src/renderer/src/components/automations/automation-launch-surface.ts index c2fc5dd4f4bf..6c5f356889b8 100644 --- a/src/renderer/src/components/automations/automation-launch-surface.ts +++ b/src/renderer/src/components/automations/automation-launch-surface.ts @@ -24,8 +24,8 @@ export function automationLaunchWorkspace( ...(ready ? { executionHostId: - ready.entry.owner.selector.kind === 'ssh' - ? `ssh:${ready.entry.owner.selector.targetId}` + ready.destination.selector.kind === 'ssh' + ? `ssh:${ready.destination.selector.targetId}` : ready.authority.kind === 'runtime' ? `runtime:${ready.authority.environmentId}` : 'local' diff --git a/src/renderer/src/lib/automation-terminal-bind-layout-owner.test.ts b/src/renderer/src/lib/automation-terminal-bind-layout-owner.test.ts index 3f2d7fd2865e..5c6bb14499ed 100644 --- a/src/renderer/src/lib/automation-terminal-bind-layout-owner.test.ts +++ b/src/renderer/src/lib/automation-terminal-bind-layout-owner.test.ts @@ -4,7 +4,8 @@ import { createTestStore, makeWorktree, seedStore } from '@/store/slices/store-t import { createStoreCascadesMockApi } from '@/store/slices/store-cascades-test-harness' import { makePaneKey } from '../../../shared/stable-pane-id' import { LayoutApplyParams } from '../../../shared/rpc-contract/workspace-layout-params' -import { bindAutomationTerminal } from './automation-terminal-ownership' +import { publishAgentLaunchTab } from './agent-launch-tab-publication' +import { registerTerminalPresentationIpcBridge } from '@/hooks/ipc-events/terminal-presentation-ipc-bridge' const mocks = vi.hoisted(() => { const storeRef: { current: unknown } = { current: null } @@ -50,27 +51,98 @@ beforeEach(() => { }) describe('a background agent tab in a layout-owner build', () => { - it('binds the one-pane tree main made the tab with, so the bind changes no pane tree', () => { - // As adoptAgentBackgroundSessionTab: the tab is made under its terminal's pane id. - const tab = store.getState().createTab(WT, undefined, undefined, { - id: 'tab-run', - initialLeafId: LEAF, - initialPtyId: 'pty-run', - activate: false, - recordInteraction: false - }) - const [create] = mocks.callRuntimeRpc.mock.calls.map( - ([, , params]) => LayoutApplyParams.parse(params).command + it('binds the published reserved pane without another layout RPC', () => { + const onLifecycle = vi.fn( + () => () => {} ) - - bindAutomationTerminal(tab, makePaneKey(tab.id, LEAF), 'pty-run', 'environment') - - expect(create).toEqual(expect.objectContaining({ type: 'createTerminalTab', leafId: LEAF })) - expect(store.getState().terminalLayoutsByTabId[tab.id]?.root).toEqual({ - type: 'leaf', - leafId: LEAF + const respond = vi.fn() + const onCreate = vi.fn(() => () => {}) + vi.stubGlobal('window', { + dispatchEvent: vi.fn(), + api: { + ...window.api, + automations: { onTerminalLifecycleRequest: onLifecycle, respondTerminalLifecycle: respond }, + ui: { + onLaunchRecipe: () => () => {}, + onCreateTerminal: onCreate, + onRequestTerminalTabMount: () => () => {}, + replyTerminalCreate: vi.fn() + } + } }) - // The bind sends nothing more: main already holds this tree. - expect(mocks.callRuntimeRpc).toHaveBeenCalledTimes(1) + const unsubs: (() => void)[] = [] + registerTerminalPresentationIpcBridge(unsubs) + try { + const lifecycle = onLifecycle.mock.calls[0][0] + const correlation = { + requestId: 'arm', + registrationId: 'registration', + runId: 'run', + operationId: 'operation', + serviceGeneration: 'generation', + documentEpoch: null + } + const target = { + worktreeId: WT, + tabId: 'tab-run', + leafId: LEAF, + paneKey: makePaneKey('tab-run', LEAF) + } + lifecycle({ ...correlation, operation: 'arm', target }) + expect(respond).toHaveBeenLastCalledWith(expect.objectContaining({ disposition: 'armed' })) + const epoch = respond.mock.calls[0][0].documentEpoch + const published = publishAgentLaunchTab({ + requestId: 'publish', + worktreeId: WT, + tabId: target.tabId, + leafId: LEAF, + launchAgent: 'codex', + viewMode: 'terminal', + viewer: 'none' + }) + expect(published).toMatchObject({ tabId: target.tabId, created: true }) + onCreate.mock.calls[0][0]({ + requestId: 'materialize', + worktreeId: WT, + tabId: target.tabId, + leafId: LEAF, + ptyId: 'pty-run', + presentation: 'background', + surfaceOwner: false, + agentLaunchViewer: 'none' + }) + lifecycle({ + ...correlation, + requestId: 'bind', + documentEpoch: epoch, + operation: 'bind', + ptyId: 'pty-run', + incarnationId: 'original', + hostId: 'local' + }) + expect(respond).toHaveBeenLastCalledWith( + expect.objectContaining({ + ...correlation, + requestId: 'bind', + documentEpoch: epoch, + disposition: 'bound' + }) + ) + expect( + store.getState().tabsByWorktree[WT].find((tab) => tab.id === target.tabId)?.ptyId + ).toBe('pty-run') + const layout = store.getState().terminalLayoutsByTabId[target.tabId] + expect(layout?.root).toEqual({ type: 'leaf', leafId: LEAF }) + expect(layout?.ptyIdsByLeafId).toEqual({ [LEAF]: 'pty-run' }) + expect(store.getState().ptyIdsByTabId[target.tabId]).toEqual(['pty-run']) + expect(store.getState().tabsByWorktree[WT]).toHaveLength(1) + expect(mocks.callRuntimeRpc).toHaveBeenCalledTimes(1) + expect(LayoutApplyParams.parse(mocks.callRuntimeRpc.mock.calls[0][2]).command).toEqual( + expect.objectContaining({ type: 'createTerminalTab', leafId: LEAF }) + ) + } finally { + unsubs.forEach((release) => release()) + vi.unstubAllGlobals() + } }) }) diff --git a/src/renderer/src/lib/automation-terminal-ownership.test.ts b/tests/e2e/automation-terminal-ownership.unit.test.ts similarity index 91% rename from src/renderer/src/lib/automation-terminal-ownership.test.ts rename to tests/e2e/automation-terminal-ownership.unit.test.ts index 9290f8894180..39fa6ac2f90b 100644 --- a/src/renderer/src/lib/automation-terminal-ownership.test.ts +++ b/tests/e2e/automation-terminal-ownership.unit.test.ts @@ -1,52 +1,52 @@ import { measureTerminalInventory, assertTerminalInventorySelection -} from './automation-terminal-inventory-test-harness' -import * as desktopLifecycle from '../../../main/automations/desktop-run-terminal-lifecycle' +} from './helpers/automation-terminal-inventory-test-harness' +import * as desktopLifecycle from '../../src/main/automations/desktop-run-terminal-lifecycle' import { randomUUID } from 'node:crypto' -import { createRuntimeAutomationService } from '../../../main/automations/runtime-automation-service' -import { runtimeStub } from '../../../main/runtime/rpc/methods/agent-launch.test-fixture' -import { createQueuedMessageTestRig } from '../../../main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' -import { hostTestAttachParams } from '../../../main/native-chat/agent-session-wire/structured-agent-session-host-test-data' -import { setStructuredAgentSessionHost } from '../../../main/native-chat/agent-session-wire/structured-agent-session-registry' -import { readAutomationRunReceipt } from '../../../main/automations/automation-run-receipt' -import { hostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' -import { revealCreatedTerminal } from '../../../main/runtime/terminal/launch/terminal-create-reveal' -import { OrcaRuntimeWithPublishPtyBackedMobileSessionTerminal } from '../../../main/runtime/session-tabs/pty-backed-session-publication' -import { OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce } from '../../../main/runtime/session-tabs/structured-session-tab-restoration' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/runtime-types' -import { stopRevokers } from '../../../main/automations/desktop-run-terminal-stop' +import { createRuntimeAutomationService } from '../../src/main/automations/runtime-automation-service' +import { runtimeStub } from '../../src/main/runtime/rpc/methods/agent-launch.test-fixture' +import { createQueuedMessageTestRig } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { hostTestAttachParams } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { setStructuredAgentSessionHost } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-registry' +import { readAutomationRunReceipt } from '../../src/main/automations/automation-run-receipt' +import { hostWorktreeTarget } from '../../src/shared/worktree/host-qualified-identity' +import { revealCreatedTerminal } from '../../src/main/runtime/terminal/launch/terminal-create-reveal' +import { OrcaRuntimeWithPublishPtyBackedMobileSessionTerminal } from '../../src/main/runtime/session-tabs/pty-backed-session-publication' +import { OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce } from '../../src/main/runtime/session-tabs/structured-session-tab-restoration' +import type { RuntimeMobileSessionTabsSnapshot } from '../../src/shared/runtime-types' +import { stopRevokers } from '../../src/main/automations/desktop-run-terminal-stop' import type * as ChildProcess from 'node:child_process' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AutomationService } from '../../../main/automations/service' +import { AutomationService } from '../../src/main/automations/service' import { createStore, closeTestStores, testState, readPersistedStateJson, writeDataFile -} from '../../../main/persistence/persistence-test-harness' +} from '../../src/main/persistence/persistence-test-harness' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import type { EventEmitter } from 'node:events' -import type { OrcaRuntimeService } from '../../../main/runtime/orca-runtime' +import type { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' import type { ConnectPanePtySession } from '@/components/terminal-pane/pty-connection/connect-pane-pty-session' -import { buildProfileStateCutoverFixture } from '../../../main/persistence/profile-state-cutover-fixture' +import { buildProfileStateCutoverFixture } from '../../src/main/persistence/profile-state-cutover-fixture' import type { createTestStore } from '@/store/slices/store-test-helpers' import { singlePaneLayoutSnapshot } from '@/store/slices/terminal-helpers' import { recordTerminalInputActivity, flushTerminalInputActivity -} from './terminal-input-activity-coalescing' -import { createAutomationTerminalOwnership } from './automation-terminal-ownership' -import { cancelDesktopTerminalRetirement } from '../../../main/automations/desktop-run-terminal-lifecycle' +} from '../../src/renderer/src/lib/terminal-input-activity-coalescing' +import { createAutomationTerminalOwnership } from '../../src/renderer/src/lib/automation-terminal-ownership' +import { cancelDesktopTerminalRetirement } from '../../src/main/automations/desktop-run-terminal-stop' import { ptyProcesses, ptyIncarnations, ptyShutdownOperations, clearPtyState -} from '../../../main/providers/local-pty-provider-state' +} from '../../src/main/providers/local-pty-provider-state' import { isPtyDataHandlerShutdownPending } from '@/components/terminal-pane/pty-shutdown-data-suspension' import { installPtyExitHibernate } from '@/components/terminal-pane/pty-connection/pty-exit-hibernate' import { installSleepingRecordAccess } from '@/components/terminal-pane/pty-connection/sleeping-record-access' @@ -99,7 +99,7 @@ const state = buildProfileStateCutoverFixture('/fixture') import { createAutomationTerminalOwnershipFixture, OWNERSHIP_WORKSPACE_ID as WT -} from './automation-terminal-ownership-test-harness' +} from './helpers/automation-terminal-ownership-test-harness' const noop = () => {} const cleanups: (() => void)[] = [] beforeEach(() => { @@ -422,7 +422,7 @@ describe('desktop completion through local publication and process owner', () => const respond = window.api.automations.respondTerminalLifecycle let late: Parameters[0] | undefined window.api.automations.respondTerminalLifecycle = (reply) => { - if (reply.operation !== 'arm') { + if (reply.disposition !== 'armed') { return respond(reply) } late = reply @@ -618,13 +618,14 @@ it.each([5, 50])('bounds actual desktop fallback/Chat/Reuse owners at N=%i', asy projectId: 'repo1', workspaceMode: reuseSession ? 'existing' : 'new_per_run', workspaceId: reuseSession ? WT : null, - surface: reuseSession ? 'terminal' : 'chat', + launchSetupPatch: { surface: reuseSession ? 'terminal' : 'chat' }, reuseSession, timezone: 'UTC', rrule: 'FREQ=DAILY', dtstart: Date.now() + 86400000, setupDecision: 'skip' }) + expect(automation.surface).toBe(reuseSession ? 'terminal' : 'chat') const start = f.events.length const run = await service.runNow(automation.id) expect(run.status).toBe('dispatched') @@ -683,8 +684,8 @@ it.each([5, 50])('bounds actual desktop fallback/Chat/Reuse owners at N=%i', asy }) } const sessions = rig.host.collaboratorsForTests().sessions - expect(Reflect.get(sessions, 'observers').size).toBe(0) - expect(Reflect.get(sessions, 'attachments').size).toBe(chats + 1) + expect(sessions['observers'].size).toBe(0) + expect(sessions['attachments'].size).toBe(chats + 1) const protocol = timers.mock.calls.flatMap((args, i) => args[1] === 20_000 ? [timers.mock.results[i].value] : [] ) @@ -695,7 +696,7 @@ it.each([5, 50])('bounds actual desktop fallback/Chat/Reuse owners at N=%i', asy expect(sleepers).toBe(eligible) expect(f.store.getState().tabsByWorktree[WT]).toHaveLength(1 + eligible) process.stdout.write( - `${JSON.stringify({ desktopRuns: count, canonicalSources: Reflect.get(sessions, 'attachments').size, logicalObservers: Reflect.get(sessions, 'observers').size, eligible, retainedReuse: retained, chats, ptys: ptyProcesses.size, desktopTabs: f.store.getState().tabsByWorktree[WT].length, runtimeTabs: tabs.get(WT)!.tabs.length, sleepers, registrations: stopRevokers.size, subscribers: f.activeSubscribers(), timersCreated: protocol.length, timersCleared: protocol.filter((timer) => cleared.mock.calls.some(([clearedTimer]) => timer === clearedTimer)).length })}\n` + `${JSON.stringify({ desktopRuns: count, canonicalSources: sessions['attachments'].size, logicalObservers: sessions['observers'].size, eligible, retainedReuse: retained, chats, ptys: ptyProcesses.size, desktopTabs: f.store.getState().tabsByWorktree[WT].length, runtimeTabs: tabs.get(WT)!.tabs.length, sleepers, registrations: stopRevokers.size, subscribers: f.activeSubscribers(), timersCreated: protocol.length, timersCleared: protocol.filter((timer) => cleared.mock.calls.some(([clearedTimer]) => timer === clearedTimer)).length })}\n` ) } finally { service?.stop() diff --git a/src/main/automations/headless-automation-agent-launch.test.ts b/tests/e2e/headless-automation-agent-launch.unit.test.ts similarity index 58% rename from src/main/automations/headless-automation-agent-launch.test.ts rename to tests/e2e/headless-automation-agent-launch.unit.test.ts index fda3edb49839..5520d0880150 100644 --- a/src/main/automations/headless-automation-agent-launch.test.ts +++ b/tests/e2e/headless-automation-agent-launch.unit.test.ts @@ -1,45 +1,40 @@ -import { agentJournalSubmissionKey } from '../../shared/agent-session-journal-item-key' -import type { StructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-host' +import { exerciseBusyChatReuse } from './helpers/automation-chat-reuse-test-harness' +import { readAutomationRunReceipt } from '../../src/main/automations/automation-run-receipt' +import { AUTOMATION_AGENT_CALLER } from '../../src/main/automations/automation-run-operation' +import { rpcCallerOperationKey } from '../../src/main/runtime/rpc/rpc-caller-identity' import { - createQueuedMessageTestRig, - eventually -} from '../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' -import { hostTestAttachParams } from '../native-chat/agent-session-wire/structured-agent-session-host-test-data' -import { runHeadlessAutomationDispatch } from './headless-dispatch-runner' -import { observeAutomationChatRun } from './runtime-chat-run-observer' -import { createAutomationRunWriter } from './automation-run-writer' -import { - createStore, - closeTestStores, - testState, - readPersistedStateJson -} from '../persistence/persistence-test-harness' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { createAutomationRunWorkspaceAction } from '../../renderer/src/components/automations/automation-run-workspace-action' -import type { AutomationsPageActionContext } from '../../renderer/src/components/automations/automations-page-action-context' + 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 '../runtime/orca-runtime' -import type { AgentLaunchResult } from '../../shared/agent-launch-intent' -import { buildProfileStateCutoverFixture } from '../persistence/profile-state-cutover-fixture' -import { automationRunOperationId } from './automation-run-operation' -import { tokenizeStartupCommand } from '../../shared/tui-agent-startup-shell' -import { launchHeadlessAutomationAgent } from './headless-automation-agent-launch' +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 { automationRunOperationId } from '../../src/main/automations/automation-run-operation' +import { tokenizeStartupCommand } from '../../src/shared/tui-agent-startup-shell' +import { launchHeadlessAutomationAgent } from '../../src/main/automations/headless-automation-agent-launch' const mocks = vi.hoisted(() => ({ actualHost: null as StructuredAgentSessionHost | null, + hostAvailable: true, openChat: vi.fn(), - readChat: vi.fn(async () => ({})), + readChat: vi.fn().mockResolvedValue({}), launch: vi.fn(), host: { journalSnapshot: vi.fn(), currentWork: vi.fn(), send: vi.fn() } })) -vi.mock('../runtime/rpc/methods/agent-launch', () => ({ launchAgentOnHost: mocks.launch })) -vi.mock('../native-chat/agent-session-wire/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => mocks.actualHost ?? mocks.host +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: unknown[]) => mocks.readChat(...args) + callStructuredAgentSession: (...args: Parameters) => + mocks.readChat(...args) })) vi.mock('@/lib/structured-agent-session-launch-surface', () => ({ openStructuredAgentSessionProvisionalTab: (...args: unknown[]) => mocks.openChat(...args) @@ -82,14 +77,21 @@ const chat: AgentLaunchResult = { 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(() => ({ - sessionId: 'claude_prev', - provider: 'claude', - location: { workspaceId: 'wt-1' }, - currentFence: 2 - })) + getConversation: vi.fn<(id: string) => ReturnType | null>(conversation) } const runtime = { requireStore: () => ({ @@ -120,6 +122,7 @@ function fixture() { 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 }) @@ -307,13 +310,15 @@ describe('automations through agent.launch', () => { ).rejects.toMatchObject({ target: { workspaceId: 'wt-1', sessionKind: 'terminal' } }) expect(mocks.launch).toHaveBeenCalledTimes(1) }) - it('reuses only a completed compatible idle chat and derives a separate send identity', async () => { - const { runtime } = fixture() + 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: 'old', - status: 'completed' as const, - workspaceId: 'wt-1', + id: 'newest', + createdAt: run.createdAt + 10, + status: 'dispatched' as const, + workspaceId: 'stale-workspace', sessionKind: 'chat' as const, chatSessionId: 'claude_prev' } @@ -321,12 +326,32 @@ describe('automations through agent.launch', () => { automation: { ...automation, surface: 'chat', reuseSession: true }, run, target, - runs: [previous] + 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(mocks.launch).not.toHaveBeenCalled() - expect(mocks.host.send).toHaveBeenCalledWith( + 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'), @@ -334,29 +359,48 @@ describe('automations through agent.launch', () => { }) }) ) - expect(result.chatSessionId).toBe('claude_prev') + expect(mocks.host.currentWork).not.toHaveBeenCalled() + expect(mocks.host.journalSnapshot).not.toHaveBeenCalled() + expect(mocks.launch).not.toHaveBeenCalled() }) - it('does not reuse a chat whose newest run or current human turn is unfinished', async () => { - const { runtime } = fixture() - mocks.launch.mockResolvedValue(chat) - mocks.host.currentWork.mockReturnValue({ working: () => true }) - await launchHeadlessAutomationAgent(runtime, { - automation: { ...automation, surface: 'chat', reuseSession: true }, + 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: [ - { - ...run, - id: 'old', - status: 'completed', - workspaceId: 'wt-1', - sessionKind: 'chat', - chatSessionId: 'claude_prev' - } - ] - }) + runs + } + expect((await launchHeadlessAutomationAgent(runtime, request)).chatSessionId).toBe( + 'claude_prev' + ) + expect(mocks.launch).not.toHaveBeenCalled() + mocks.host.send.mockClear() + mocks.launch.mockResolvedValue(chat) + await launchHeadlessAutomationAgent(runtime, { ...request, runs: runs.slice(0, 2) }) expect(mocks.host.send).not.toHaveBeenCalled() - expect(mocks.launch).toHaveBeenCalledTimes(1) + expect(mocks.launch).toHaveBeenCalledOnce() + expect(mocks.launch.mock.calls[0][0].operationId).toBe( + automationRunOperationId(run, 'fresh-launch') + ) }) }) @@ -431,162 +475,149 @@ it.each(['terminal', 'chat', 'reuse-terminal'] as const)( } ) -it('keeps accepted reused Chat through throwing metadata/reply, real runner persistence, observation and normal Details', async () => { - vi.spyOn(Date, 'now').mockReturnValue(1_800_000_000_000) - const rig = await createQueuedMessageTestRig({ restartable: true }) - mocks.actualHost = rig.host - const root = mkdtempSync(join(tmpdir(), 'orca-34332-accepted-')) - testState.dir = root - const disk = createStore() - const id = 'codex_reused' - const initial = hostTestAttachParams(null) - const controller = new AbortController() - try { - expect( - await rig.host.create( - { callerKey: 'initial' }, - hostTestAttachParams(null, { - envelope: { ...initial.envelope, sessionId: id }, - location: { ...initial.location, workspaceId: 'wt-1' } - }) - ) - ).toMatchObject({ ok: true }) - disk.addRepo(state.repos[0]) - const saved = disk.createAutomation({ - ...automation, - agentId: 'codex', - surface: 'chat', - reuseSession: true, - projectId: state.repos[0].id +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 + }, + openChat: mocks.openChat, + launch: mocks.launch }) - const writer = createAutomationRunWriter(disk, null) - const sent = rig.host.send.bind(rig.host) - for (const lostReply of [false, true]) { - const current = await writer.createRun(saved, Date.now(), 'manual') - const previous = { - ...current, - id: 'previous', - status: 'completed' as const, - workspaceId: 'wt-1', - sessionKind: 'chat' as const, - chatSessionId: id - } - const send = vi.spyOn(rig.host, 'send').mockImplementationOnce(async (...args) => { - const answer = await sent(...args) - expect(answer.ok).toBe(true) - if (lostReply) { - throw new Error('accepted reply lost') - } - return answer +) + +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') }) - // SAFETY: runtime transport/metadata only; send, receipt, result, runner, writer and observer use their actual owners. - const runtime = { - ensureStructuredAgentSessionHost: async () => {}, - openAgentSessionRecordStore: async () => rig.store, - showManagedWorktree: async () => { - throw new Error('optional display unavailable') - } - } as unknown as OrcaRuntimeService - const dispatched = await runHeadlessAutomationDispatch({ - automation: saved, - run: current, + } + 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( + launchHeadlessAutomationAgent(runtime, { + automation: { ...automation, surface: 'chat', reuseSession: true }, + run, target, - runs: writer, - dispatcher: () => - launchHeadlessAutomationAgent(runtime, { - automation: saved, - run: current, - target, - runs: [previous] - }), - runPrecheck: async () => null, - markDispatchResult: writer.updateRun, - watchRun: () => {} + runs: [{ ...run, id: 'old', sessionKind: 'chat', chatSessionId: 'claude_prev' }] }) - expect(send).toHaveBeenCalledOnce() - expect(dispatched).toMatchObject({ - status: 'dispatched', - sessionKind: 'chat', - chatSessionId: id + ).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) }) - const pending = observeAutomationChatRun(runtime, dispatched, controller.signal) - const journal = rig.host.collaboratorsForTests().sessions.get(id)!.journal - const message = automationRunOperationId(current, 'reuse-send') - await eventually(() => expect(journal.submission(message)).toBeDefined()) - const item = await journal.appendItem( - { provider: 'orca', clientMessageId: `turn-${current.id}` }, - { - kind: 'turn', - turnId: current.id, - userItemId: agentJournalSubmissionKey(message), - state: 'running' - }, - { fence: 1, turnScope: { kind: 'thread' } } - ) - await journal.resolveDispatch({ - clientMessageId: message, - state: 'accepted', - providerIdentity: { provider: 'orca', clientMessageId: message }, - fence: 1 + 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 }) - await journal.appendItem( - { provider: 'orca', clientMessageId: `answer-${current.id}` }, - { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: 'Exact automation output' }] - }, - { fence: 1, turnScope: { kind: 'turn', turnItemId: item.itemId } } - ) - await journal.appendItem( - { provider: 'orca', clientMessageId: `turn-${current.id}` }, - { - kind: 'turn', - turnId: current.id, - userItemId: agentJournalSubmissionKey(message), - state: 'completed', - outcome: 'success' + mocks.launch.mockResolvedValue(chat) + const attempt = launchHeadlessAutomationAgent(runtime, { + automation: { + ...automation, + agentId: 'codex', + workspaceId: HOST_TEST_LOCATION.workspaceId, + surface: 'chat', + reuseSession: true }, - { fence: 1, turnScope: { kind: 'thread' } } - ) - const observation = await pending - const completed = await writer.updateRun({ runId: current.id, ...observation }) - expect(completed).toMatchObject({ - status: 'completed', - chatSessionId: id, - outputSnapshot: { content: 'Exact automation output' } + run: current, + target, + runs: [{ ...run, id: 'old', sessionKind: 'chat', chatSessionId: HOST_TEST_SESSION }] }) - const persisted = JSON.parse(readPersistedStateJson(join(root, 'orca-data.json'))) + 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( - persisted.automationRuns.find((row: { id: string }) => row.id === current.id) - ).toMatchObject({ chatSessionId: id, status: 'completed' }) - // SAFETY: normal action's surrounding page context is scripted; actual Details action executes. - const context = { - store: { - repoForRow: () => undefined, - worktreeForRow: () => ({ id: 'wt-1', hostId: 'local' }) - }, - list: { selectedRow: { key: 'row' } } - } as unknown as AutomationsPageActionContext - createAutomationRunWorkspaceAction(context)(completed) - await eventually(() => - expect(mocks.openChat).toHaveBeenCalledWith( - expect.objectContaining({ sessionId: id, agent: 'codex' }) + 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') ) - ) - send.mockRestore() - mocks.openChat.mockClear() + } + } 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() } - } finally { - controller.abort() - mocks.actualHost = null - await rig.dispose() - await closeTestStores() - rmSync(root, { recursive: true, force: true }) } -}) +) -it.each(['unknown', 'refused'] as const)( +it.each(['unknown', 'refused', 'conflict', 'failed-row'] as const)( 'retains known reused Chat on %s acceptance without resending', async (acceptance) => { const { runtime, records } = fixture() @@ -594,9 +625,17 @@ it.each(['unknown', 'refused'] as const)( if (acceptance === 'unknown') { throw new Error('transport lost') } - return { ok: false, refusal: { code: 'agent_session_operation_unknown' } } + return { + ok: false, + refusal: { + code: + acceptance === 'conflict' ? 'agent_session_conflict' : 'agent_session_operation_unknown' + } + } }) - records.getOperationRow.mockReturnValue(undefined) + records.getOperationRow.mockReturnValue( + acceptance === 'failed-row' ? { outcome: { status: 'failed' } } : undefined + ) await expect( launchHeadlessAutomationAgent(runtime, { automation: { ...automation, surface: 'chat', reuseSession: true }, 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..465091e74d15 --- /dev/null +++ b/tests/e2e/helpers/automation-chat-reuse-test-harness.ts @@ -0,0 +1,275 @@ +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 { runHeadlessAutomationDispatch } from '../../../src/main/automations/headless-dispatch-runner' +import { + launchHeadlessAutomationAgent, + type AutomationAgentLaunchRequest +} from '../../../src/main/automations/headless-automation-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' +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' + +export type ChatReuseMode = 'normal' | 'lost-reply' | 'restart' + +export async function exerciseBusyChatReuse( + mode: ChatReuseMode, + automation: AutomationAgentLaunchRequest['automation'], + target: AutomationAgentLaunchRequest['target'], + controls: { + setHost: (host: StructuredAgentSessionHost | null) => void + openChat: Mock + 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: { + content: 'Prior automation output', + truncated: false, + capturedAt: Date.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 + }) + // SAFETY: only runtime transport/metadata is scripted; service, send, receipts, queue, writer and observer are real. + const runtime = { + ensureStructuredAgentSessionHost: async () => {}, + openAgentSessionRecordStore: async () => rig.store, + setAutomationService: vi.fn(), + notifyAutomationsChanged: vi.fn(), + showManagedWorktree: async () => { + throw new Error('optional display unavailable') + } + } as unknown as OrcaRuntimeService + const dispatched = await runHeadlessAutomationDispatch({ + automation: saved, + run: current, + target, + runs: writer, + dispatcher: () => + launchHeadlessAutomationAgent(runtime, { + automation: saved, + run: current, + target, + runs: disk.listAutomationRuns(saved.id) + }), + runPrecheck: async () => null, + markDispatchResult: writer.updateRun, + watchRun: () => {} + }) + 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 = createRuntimeAutomationService({ store: disk, runtime, headless: true }) + 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' } + }) + // SAFETY: page context alone is scripted; the ordinary Details action executes. + const context = { + store: { + repoForRow: () => undefined, + worktreeForRow: () => ({ id: saved.workspaceId, hostId: 'local' }) + }, + list: { selectedRow: { key: 'row' } } + } as unknown as AutomationsPageActionContext + createAutomationRunWorkspaceAction(context)(readCurrent()) + await eventually(() => + expect(controls.openChat).toHaveBeenCalledWith( + expect.objectContaining({ sessionId: sessionId, agent: 'codex' }) + ) + ) + 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) + } + } +} diff --git a/src/renderer/src/lib/automation-terminal-inventory-test-harness.ts b/tests/e2e/helpers/automation-terminal-inventory-test-harness.ts similarity index 80% rename from src/renderer/src/lib/automation-terminal-inventory-test-harness.ts rename to tests/e2e/helpers/automation-terminal-inventory-test-harness.ts index 29fbd4e9dbfe..b1c157755258 100644 --- a/src/renderer/src/lib/automation-terminal-inventory-test-harness.ts +++ b/tests/e2e/helpers/automation-terminal-inventory-test-harness.ts @@ -1,10 +1,10 @@ -import type { AutomationRun } from '../../../shared/automations-types' -import { reconcileDesktopRunTerminals } from '../../../main/automations/desktop-run-terminal-reconciliation' +import type { AutomationRun } from '../../../src/shared/automations-types' +import { reconcileDesktopRunTerminals } from '../../../src/main/automations/desktop-run-terminal-reconciliation' import { expect, vi } from 'vitest' -import type { Store } from '../../../main/persistence' -import type { createDesktopRunTerminalLifecycle } from '../../../main/automations/desktop-run-terminal-lifecycle' -import * as runNormalization from '../../../main/persistence/scheduling-automations/automation-context-migration' -import { compareAutomationRunsNewestFirst } from '../../../shared/automation-run-cursor' +import type { Store } from '../../../src/main/persistence' +import type { createDesktopRunTerminalLifecycle } from '../../../src/main/automations/desktop-run-terminal-lifecycle' +import * as runNormalization from '../../../src/main/persistence/scheduling-automations/automation-context-migration' +import { compareAutomationRunsNewestFirst } from '../../../src/shared/automation-run-cursor' export function measureTerminalInventory( disk: Store, @@ -26,6 +26,7 @@ export function measureTerminalInventory( if (key === 'find') { linearFinds++ } + // 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. const value = Reflect.get(target, key, receiver) if (typeof key !== 'string' || !/^(0|[1-9][0-9]*)$/.test(key)) { return value @@ -36,6 +37,7 @@ export function measureTerminalInventory( if (field === 'status') { statusVisits++ } + // 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(run, field, rowReceiver) } }) diff --git a/src/renderer/src/lib/automation-terminal-ownership-test-harness.ts b/tests/e2e/helpers/automation-terminal-ownership-test-harness.ts similarity index 93% rename from src/renderer/src/lib/automation-terminal-ownership-test-harness.ts rename to tests/e2e/helpers/automation-terminal-ownership-test-harness.ts index a8f67b65d1ce..31ff67366d39 100644 --- a/src/renderer/src/lib/automation-terminal-ownership-test-harness.ts +++ b/tests/e2e/helpers/automation-terminal-ownership-test-harness.ts @@ -1,7 +1,7 @@ import { EventEmitter } from 'node:events' import type * as pty from 'node-pty' import { expect, vi } from 'vitest' -import { buildProfileStateCutoverFixture } from '../../../main/persistence/profile-state-cutover-fixture' +import { buildProfileStateCutoverFixture } from '../../../src/main/persistence/profile-state-cutover-fixture' import { createTestStore, makeTab, @@ -9,23 +9,23 @@ import { seedStore } from '@/store/slices/store-test-helpers' import { createStoreSessionMockApi } from '@/store/slices/store-session-test-harness' -import type { OrcaRuntimeService } from '../../../main/runtime/orca-runtime' -import type { Store } from '../../../main/persistence' -import type { PtyShutdownOptions } from '../../../main/providers/pty-provider-contract' -import { OrcaRuntimeWithStopExactTerminalsForWorktree } from '../../../main/runtime/terminal/stop/worktree-terminal-stop-targets' +import type { OrcaRuntimeService } from '../../../src/main/runtime/orca-runtime' +import type { Store } from '../../../src/main/persistence' +import type { PtyShutdownOptions } from '../../../src/main/providers/pty-provider-contract' +import { OrcaRuntimeWithStopExactTerminalsForWorktree } from '../../../src/main/runtime/terminal/stop/worktree-terminal-stop-targets' import { registerTerminalPresentationIpcBridge } from '@/hooks/ipc-events/terminal-presentation-ipc-bridge' import { registerAgentLaunchTabIpcBridge } from '@/hooks/ipc-events/agent-launch-tab-ipc-bridge' -import { createDesktopRunTerminalLifecycle } from '../../../main/automations/desktop-run-terminal-lifecycle' +import { createDesktopRunTerminalLifecycle } from '../../../src/main/automations/desktop-run-terminal-lifecycle' import { shutdownLocalPty, createPtyPhysicalExit -} from '../../../main/providers/local-pty-termination' +} from '../../../src/main/providers/local-pty-termination' import { ptyProcesses, ptyIncarnations, ptyPhysicalExits, clearPtyState -} from '../../../main/providers/local-pty-provider-state' +} from '../../../src/main/providers/local-pty-provider-state' export const OWNERSHIP_WORKSPACE_ID = 'repo1::/repo1/main' const WT = OWNERSHIP_WORKSPACE_ID From e5112e63de646f4e7fe9bc5e37761b37d9c9d7d3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 00:38:16 -0700 Subject: [PATCH 09/23] Correct shutdown test acquisition and exported measurement types --- ...ation-chat-run-measurement-test-harness.ts | 35 ++++++++++++++++--- .../local-pty-provider-shutdown.test.ts | 5 ++- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/src/main/automations/automation-chat-run-measurement-test-harness.ts b/src/main/automations/automation-chat-run-measurement-test-harness.ts index 5f3d223cd320..32c27c51886d 100644 --- a/src/main/automations/automation-chat-run-measurement-test-harness.ts +++ b/src/main/automations/automation-chat-run-measurement-test-harness.ts @@ -1,12 +1,39 @@ -import { vi } from 'vitest' +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, @@ -113,7 +140,7 @@ export function measureAutomationChatRun( const value = realSnapshot(...args) return value }) - const releases: ReturnType[] = [] + const releases: Mock<() => void>[] = [] let callbacks = 0, committedRows = 0, copied = 0, @@ -143,7 +170,7 @@ export function measureAutomationChatRun( 'visitItemsWithLinkage' ] as const const calls = fullApis.map((name) => vi.spyOn(journal, name)) - const keys = [ + const keys: AutomationChatRunMeasurement['keys'] = [ vi.spyOn(journal, 'item'), vi.spyOn(journal, 'submission'), vi.spyOn(journal.queuedMessages, 'get'), diff --git a/src/main/providers/local-pty-provider-shutdown.test.ts b/src/main/providers/local-pty-provider-shutdown.test.ts index 58ed5bf8d5ae..5277ee1576ca 100644 --- a/src/main/providers/local-pty-provider-shutdown.test.ts +++ b/src/main/providers/local-pty-provider-shutdown.test.ts @@ -134,10 +134,9 @@ import { type LocalPtyMockProcess } from './local-pty-provider-test-harness' +const actual = await vi.importActual('../pty-descendant-termination') + async function installActualShutdownSweep() { - const actual = await vi.importActual( - '../pty-descendant-termination' - ) const capture = { capturedAtMs: Date.parse('Tue Jul 14 12:01:00 2026'), rows: [ From f4cec2b3fd6907c79caedd62f2f78888c0f1447f Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 01:07:47 -0700 Subject: [PATCH 10/23] Correct automation fixture contracts and duplicate imports --- src/main/automations/precheck-runner.ts | 7 ++-- ...automation-terminal-ownership.unit.test.ts | 33 +++++++++++------- ...dless-automation-agent-launch.unit.test.ts | 6 ++-- ...omation-terminal-ownership-test-harness.ts | 34 +++++++++++++------ 4 files changed, 53 insertions(+), 27 deletions(-) diff --git a/src/main/automations/precheck-runner.ts b/src/main/automations/precheck-runner.ts index 31cf40d1113e..4b6257c6f051 100644 --- a/src/main/automations/precheck-runner.ts +++ b/src/main/automations/precheck-runner.ts @@ -1,9 +1,12 @@ import type { Store } from '../persistence' -import type { Automation } from '../../shared/automations-types' +import type { + Automation, + AutomationPrecheck, + AutomationPrecheckResult +} from '../../shared/automations-types' import type { AutomationRunTargetResult } from './run-target-resolution' import { spawn, type ChildProcess } from 'node:child_process' import type { ClientChannel } from 'ssh2' -import type { AutomationPrecheck, AutomationPrecheckResult } from '../../shared/automations-types' import { MAX_AUTOMATION_PRECHECK_OUTPUT_CHARS } from '../../shared/automation-precheck' import { getSshConnectionManager } from '../ssh/targets/ssh-target-registry' import { quotePosixShell } from '../../shared/shell-argument-quoting' diff --git a/tests/e2e/automation-terminal-ownership.unit.test.ts b/tests/e2e/automation-terminal-ownership.unit.test.ts index 39fa6ac2f90b..2e01dd983e79 100644 --- a/tests/e2e/automation-terminal-ownership.unit.test.ts +++ b/tests/e2e/automation-terminal-ownership.unit.test.ts @@ -15,9 +15,12 @@ import { revealCreatedTerminal } from '../../src/main/runtime/terminal/launch/te import { OrcaRuntimeWithPublishPtyBackedMobileSessionTerminal } from '../../src/main/runtime/session-tabs/pty-backed-session-publication' import { OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce } from '../../src/main/runtime/session-tabs/structured-session-tab-restoration' import type { RuntimeMobileSessionTabsSnapshot } from '../../src/shared/runtime-types' -import { stopRevokers } from '../../src/main/automations/desktop-run-terminal-stop' +import { + stopRevokers, + cancelDesktopTerminalRetirement +} from '../../src/main/automations/desktop-run-terminal-stop' import type * as ChildProcess from 'node:child_process' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' import { AutomationService } from '../../src/main/automations/service' import { createStore, @@ -33,14 +36,13 @@ import type { EventEmitter } from 'node:events' import type { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' import type { ConnectPanePtySession } from '@/components/terminal-pane/pty-connection/connect-pane-pty-session' import { buildProfileStateCutoverFixture } from '../../src/main/persistence/profile-state-cutover-fixture' -import type { createTestStore } from '@/store/slices/store-test-helpers' +import type { OwnershipTestStore } from './helpers/automation-terminal-ownership-test-harness' import { singlePaneLayoutSnapshot } from '@/store/slices/terminal-helpers' import { recordTerminalInputActivity, flushTerminalInputActivity } from '../../src/renderer/src/lib/terminal-input-activity-coalescing' import { createAutomationTerminalOwnership } from '../../src/renderer/src/lib/automation-terminal-ownership' -import { cancelDesktopTerminalRetirement } from '../../src/main/automations/desktop-run-terminal-stop' import { ptyProcesses, ptyIncarnations, @@ -51,12 +53,19 @@ import { isPtyDataHandlerShutdownPending } from '@/components/terminal-pane/pty- import { installPtyExitHibernate } from '@/components/terminal-pane/pty-connection/pty-exit-hibernate' import { installSleepingRecordAccess } from '@/components/terminal-pane/pty-connection/sleeping-record-access' -const mocks = vi.hoisted(() => ({ - store: null as ReturnType | null, - ipc: null as EventEmitter | null, - capture: vi.fn(), - prepare: async () => {} -})) +const mocks = vi.hoisted( + (): { + store: OwnershipTestStore | null + ipc: EventEmitter | null + capture: Mock + prepare: () => Promise + } => ({ + store: null, + ipc: null, + capture: vi.fn(), + prepare: async () => {} + }) +) vi.mock('electron', async () => { const { EventEmitter } = await import('node:events') mocks.ipc = new EventEmitter() @@ -73,9 +82,9 @@ vi.mock('electron', async () => { vi.mock('@/store', () => ({ useAppStore: { getState: () => mocks.store!.getState(), - setState: (...args: Parameters['setState']>) => + setState: (...args: Parameters) => mocks.store!.setState(...args), - subscribe: (...args: Parameters['subscribe']>) => + subscribe: (...args: Parameters) => mocks.store!.subscribe(...args) } })) diff --git a/tests/e2e/headless-automation-agent-launch.unit.test.ts b/tests/e2e/headless-automation-agent-launch.unit.test.ts index 5520d0880150..e83c324e3e6b 100644 --- a/tests/e2e/headless-automation-agent-launch.unit.test.ts +++ b/tests/e2e/headless-automation-agent-launch.unit.test.ts @@ -1,6 +1,9 @@ import { exerciseBusyChatReuse } from './helpers/automation-chat-reuse-test-harness' import { readAutomationRunReceipt } from '../../src/main/automations/automation-run-receipt' -import { AUTOMATION_AGENT_CALLER } from '../../src/main/automations/automation-run-operation' +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, @@ -14,7 +17,6 @@ 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 { automationRunOperationId } from '../../src/main/automations/automation-run-operation' import { tokenizeStartupCommand } from '../../src/shared/tui-agent-startup-shell' import { launchHeadlessAutomationAgent } from '../../src/main/automations/headless-automation-agent-launch' diff --git a/tests/e2e/helpers/automation-terminal-ownership-test-harness.ts b/tests/e2e/helpers/automation-terminal-ownership-test-harness.ts index 31ff67366d39..6424ed0e6c77 100644 --- a/tests/e2e/helpers/automation-terminal-ownership-test-harness.ts +++ b/tests/e2e/helpers/automation-terminal-ownership-test-harness.ts @@ -1,13 +1,15 @@ import { EventEmitter } from 'node:events' import type * as pty from 'node-pty' import { expect, vi } from 'vitest' +import type { StoreApi, UseBoundStore } from 'zustand' +import type { AppState } from '../../../src/renderer/src/store/types' import { buildProfileStateCutoverFixture } from '../../../src/main/persistence/profile-state-cutover-fixture' import { createTestStore, makeTab, makeWorktree, seedStore -} from '@/store/slices/store-test-helpers' +} from '../../../src/renderer/src/store/slices/store-test-helpers' import { createStoreSessionMockApi } from '@/store/slices/store-session-test-harness' import type { OrcaRuntimeService } from '../../../src/main/runtime/orca-runtime' import type { Store } from '../../../src/main/persistence' @@ -27,19 +29,21 @@ import { clearPtyState } from '../../../src/main/providers/local-pty-provider-state' +export type OwnershipTestStore = UseBoundStore> + export const OWNERSHIP_WORKSPACE_ID = 'repo1::/repo1/main' const WT = OWNERSHIP_WORKSPACE_ID const state = buildProfileStateCutoverFixture('/fixture') const noop = () => {} export function createAutomationTerminalOwnershipFixture( mocks: { - store: ReturnType | null + store: OwnershipTestStore | null ipc: EventEmitter | null prepare: () => Promise }, cleanups: (() => void)[] ) { - const store = createTestStore() + const store: OwnershipTestStore = createTestStore() let subscribers = 0 const subscribe = store.subscribe vi.spyOn(store, 'subscribe').mockImplementation((listener) => { @@ -58,14 +62,22 @@ export function createAutomationTerminalOwnershipFixture( mainFrame: {}, isDestroyed: () => false, send: (channel: string, payload: unknown) => { - events.push( - channel === 'automations:terminalLifecycleRequest' && - typeof payload === 'object' && - payload !== null && - 'operation' in payload - ? `${payload.operation}:${'phase' in payload ? payload.phase : ''}` - : channel - ) + let label = channel + if (channel === 'automations:terminalLifecycleRequest') { + if ( + typeof payload !== 'object' || + payload === null || + !('operation' in payload) || + typeof payload.operation !== 'string' + ) { + throw new Error('Lifecycle test transport requires a string operation') + } + if ('phase' in payload && typeof payload.phase !== 'string') { + throw new Error('Lifecycle test transport requires a string phase when present') + } + label = `${payload.operation}:${'phase' in payload ? payload.phase : ''}` + } + events.push(label) listeners.emit(channel, payload) } }) From 50a73188b8845a98f9344ee8fa989fb1a5cae588 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:54:31 -0700 Subject: [PATCH 11/23] Keep Chat automations separate from Terminal execution --- config/flaky-test-pattern-baseline.txt | 34 +- config/scripts/ci-shard-timings.json | 20 +- config/tsconfig.tc.web.json | 4 + .../automation-agent-run-result.ts | 12 +- .../automation-chat-agent-launch.ts | 116 ++ .../automation-chat-session-reuse.ts | 12 +- .../automation-dispatch-host-fence.test.ts | 31 +- .../automation-dispatch-request.ts | 66 +- .../automations/automation-run-operation.ts | 2 +- .../automations/automation-run-receipt.ts | 5 +- .../automation-worker-durability.test.ts | 40 +- .../desktop-run-terminal-lifecycle.ts | 298 ---- .../desktop-run-terminal-reconciliation.ts | 22 - .../automations/desktop-run-terminal-stop.ts | 87 -- src/main/automations/dispatch-refusal.ts | 26 +- .../headless-automation-agent-launch.test.ts | 256 +++ .../headless-automation-agent-launch.ts | 393 +++-- .../automations/headless-dispatch-runner.ts | 3 +- .../headless-workspace-create.test.ts | 101 +- .../automations/headless-workspace-create.ts | 35 + src/main/automations/precheck-runner.ts | 39 +- ...ntime-automation-service-retention.test.ts | 5 +- .../runtime-automation-service.test.ts | 204 +-- .../automations/runtime-automation-service.ts | 183 +-- .../automations/service-lifecycle.test.ts | 3 +- src/main/automations/service.test.ts | 168 +- src/main/automations/service.ts | 44 +- ...adapter-history-shutdown-admission.test.ts | 85 - src/main/daemon/daemon-pty-session-control.ts | 219 +-- .../daemon/daemon-pty-session-liveness.ts | 106 -- src/main/ipc/pty/provider/shutdown-detect.ts | 8 +- src/main/ipc/pty/renderer-fenced-kill.test.ts | 126 -- src/main/ipc/pty/runtime/controller-deps.ts | 5 +- src/main/ipc/pty/runtime/kill.ts | 24 +- ...session-queued-message-rig.test-fixture.ts | 8 + ...stence-legacy-automation-twin-host.test.ts | 10 +- .../local-pty-provider-shutdown.test.ts | 184 +-- .../providers/local-pty-provider-state.ts | 3 +- src/main/providers/local-pty-provider.ts | 2 +- src/main/providers/local-pty-termination.ts | 55 +- src/main/providers/pty-provider-contract.ts | 25 +- src/main/pty-descendant-snapshot.ts | 133 -- .../pty-descendant-stop-authorization.test.ts | 45 - src/main/pty-descendant-termination.ts | 168 +- .../construction/runtime-host-services.ts | 2 +- .../rpc/methods/agent-launch-replay.ts | 2 +- .../rpc/methods/agent-launch-surfaces.ts | 20 +- .../methods/agent-launch-worktree-creation.ts | 14 +- .../runtime/rpc/methods/agent-launch.test.ts | 113 +- src/main/runtime/rpc/methods/agent-launch.ts | 13 +- .../runtime-pty-controller-contract.ts | 11 +- .../stop/worktree-terminal-stop-targets.ts | 13 +- .../terminal/stop/worktree-terminal-stop.ts | 6 +- src/main/startup/main-process-automations.ts | 5 +- src/main/window/runtime-window-lifecycle.ts | 66 +- .../terminal-tab-close-request-relay.ts | 73 +- src/preload/api/automation-api.ts | 8 - src/preload/api/automations-bridge.ts | 17 - .../automations/AutomationEditorDialog.tsx | 2 +- ...utomationsPage.create-destination.test.tsx | 4 +- .../automation-capability-probe.ts | 6 +- .../automations/automation-edit-draft.ts | 6 +- .../automations/automation-launch-surface.ts | 23 + .../automations/automation-orca-save.ts | 13 +- .../automations/automation-run-view-state.ts | 57 +- .../automations/automation-save-action.ts | 2 +- .../hooks/automation-dispatch-completion.ts | 276 ++++ .../src/hooks/automation-dispatch-handler.ts | 241 +++ ...automation-dispatch-observer-test-probe.ts | 30 + ...omation-dispatch-unverifiable-loss.test.ts | 102 ++ .../hooks/automation-dispatch-workspace.ts | 258 ++++ .../terminal-presentation-ipc-bridge.ts | 46 +- .../terminal-presentation-pane-title.test.ts | 10 +- .../terminal-tab-mount-ipc-bridge.ts | 28 - .../hooks/useAutomationDispatchEvents.test.ts | 885 ++++++++++- .../src/hooks/useAutomationDispatchEvents.ts | 3 + src/renderer/src/i18n/locales/en.json | 1373 ++++++++++++++--- src/renderer/src/i18n/locales/es.json | 1321 +++++++++++++--- src/renderer/src/i18n/locales/fr.json | 1321 +++++++++++++--- src/renderer/src/i18n/locales/ja.json | 1230 ++++++++++++--- src/renderer/src/i18n/locales/ko.json | 1230 ++++++++++++--- src/renderer/src/i18n/locales/pt.json | 1314 +++++++++++++--- src/renderer/src/i18n/locales/zh.json | 1233 ++++++++++++--- .../lib/adopt-agent-background-session-tab.ts | 114 ++ .../lib/agent-background-session-contract.ts | 28 + ...omation-terminal-bind-layout-owner.test.ts | 114 +- .../lib/automation-terminal-ownership.test.ts | 273 ++++ .../src/lib/automation-terminal-ownership.ts | 368 ++--- ...gent-background-session-extra-args.test.ts | 131 ++ ...t-background-session-launch-parity.test.ts | 121 ++ ...ch-agent-background-session-remote.test.ts | 487 ++++++ .../launch-agent-background-session.test.ts | 642 ++++++++ .../lib/launch-agent-background-session.ts | 310 ++++ .../src/store/terminals/terminal-actions.ts | 7 - .../terminal-pane-hibernation-commit.ts | 92 -- .../terminals/terminal-pane-hibernation.ts | 149 +- src/shared/automation-terminal-lifecycle.ts | 78 - ...automation-terminal-ownership.unit.test.ts | 805 ---------- ...dless-automation-agent-launch.unit.test.ts | 155 +- .../automation-chat-reuse-test-harness.ts | 30 +- ...omation-terminal-inventory-test-harness.ts | 119 -- ...omation-terminal-ownership-test-harness.ts | 304 ---- 102 files changed, 13074 insertions(+), 6045 deletions(-) create mode 100644 src/main/automations/automation-chat-agent-launch.ts delete mode 100644 src/main/automations/desktop-run-terminal-lifecycle.ts delete mode 100644 src/main/automations/desktop-run-terminal-reconciliation.ts delete mode 100644 src/main/automations/desktop-run-terminal-stop.ts create mode 100644 src/main/automations/headless-automation-agent-launch.test.ts delete mode 100644 src/main/daemon/daemon-pty-session-liveness.ts delete mode 100644 src/main/pty-descendant-snapshot.ts delete mode 100644 src/main/pty-descendant-stop-authorization.test.ts create mode 100644 src/renderer/src/hooks/automation-dispatch-completion.ts create mode 100644 src/renderer/src/hooks/automation-dispatch-handler.ts create mode 100644 src/renderer/src/hooks/automation-dispatch-observer-test-probe.ts create mode 100644 src/renderer/src/hooks/automation-dispatch-unverifiable-loss.test.ts create mode 100644 src/renderer/src/hooks/automation-dispatch-workspace.ts delete mode 100644 src/renderer/src/hooks/ipc-events/terminal-tab-mount-ipc-bridge.ts create mode 100644 src/renderer/src/lib/adopt-agent-background-session-tab.ts create mode 100644 src/renderer/src/lib/agent-background-session-contract.ts create mode 100644 src/renderer/src/lib/automation-terminal-ownership.test.ts create mode 100644 src/renderer/src/lib/launch-agent-background-session-extra-args.test.ts create mode 100644 src/renderer/src/lib/launch-agent-background-session-launch-parity.test.ts create mode 100644 src/renderer/src/lib/launch-agent-background-session-remote.test.ts create mode 100644 src/renderer/src/lib/launch-agent-background-session.test.ts create mode 100644 src/renderer/src/lib/launch-agent-background-session.ts delete mode 100644 src/renderer/src/store/terminals/terminal-pane-hibernation-commit.ts delete mode 100644 src/shared/automation-terminal-lifecycle.ts delete mode 100644 tests/e2e/automation-terminal-ownership.unit.test.ts delete mode 100644 tests/e2e/helpers/automation-terminal-inventory-test-harness.ts delete mode 100644 tests/e2e/helpers/automation-terminal-ownership-test-harness.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 5d86a9669384..85b0299f1ffe 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -337,11 +337,11 @@ 2 test-no-real-time-wait:src/main/ipc/folder-repo-git-upgrade.test.ts 2 test-no-real-time-wait:src/main/ipc/native-chat.test.ts 1 test-no-real-time-wait:src/main/ipc/parcel-watcher-shallow-file-subscription.test.ts +1 test-no-real-time-wait:src/main/ipc/pty/host-env/spawn-cwd-hung-folder.test.ts 1 test-no-real-time-wait:src/main/ipc/pty/pty-agent-launch-pane-attach.test.ts 1 test-no-real-time-wait:src/main/ipc/pty/pty-daemon-controller-teardown.test.ts 1 test-no-real-time-wait:src/main/ipc/pty/pty-launch-parity.test.ts 2 test-no-real-time-wait:src/main/ipc/pty/pty-spawn-cwd-fallback-hung-folder.test.ts -1 test-no-real-time-wait:src/main/ipc/pty/host-env/spawn-cwd-hung-folder.test.ts 1 test-no-real-time-wait:src/main/ipc/rebinding-file-watch-noise.test.ts 1 test-no-real-time-wait:src/main/ipc/rebinding-file-watch.test.ts 3 test-no-real-time-wait:src/main/ipc/runtime-environments/runtime-environment-preference.test.ts @@ -485,19 +485,20 @@ 2 test-no-real-time-wait:src/main/wsl/wsl-orcad-real-distro-lane.test.ts 1 test-no-real-time-wait:src/main/wsl/wsl-orcad-stdio-bridge.test.ts 3 test-no-real-time-wait:src/main/wsl/wsl-orcad-watch.test.ts +1 test-no-real-time-wait:src/renderer/src/components/UpdateCard.error-card.test.tsx 4 test-no-real-time-wait:src/renderer/src/components/activity/activity-auto-mark-read-loop.react185.test.tsx 1 test-no-real-time-wait:src/renderer/src/components/activity/activity-portal-readiness-loop.react185.test.tsx 1 test-no-real-time-wait:src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx -9 test-no-real-time-wait:src/renderer/src/components/contextual-tours/contextual-tour-floating-position.test.ts 1 test-no-real-time-wait:src/renderer/src/components/contextual-tours/ContextualTourOverlay.remeasure.test.tsx +9 test-no-real-time-wait:src/renderer/src/components/contextual-tours/contextual-tour-floating-position.test.ts 1 test-no-real-time-wait:src/renderer/src/components/dashboard-popout/useDashboardSnapshot.test.tsx -1 test-no-real-time-wait:src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-stale-analysis-work-budget.test.tsx 1 test-no-real-time-wait:src/renderer/src/components/editor/DiagramViewerModal.test.tsx -1 test-no-real-time-wait:src/renderer/src/components/native-chat/native-chat-composer-draft-lifecycle.test.tsx -6 test-no-real-time-wait:src/renderer/src/components/native-chat/native-chat-composer-draft-store.test.ts +1 test-no-real-time-wait:src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-stale-analysis-work-budget.test.tsx 1 test-no-real-time-wait:src/renderer/src/components/native-chat/NativeChatModelCombobox.test.tsx 1 test-no-real-time-wait:src/renderer/src/components/native-chat/NativeChatResolvedView.prompt-card-composer.test.tsx 1 test-no-real-time-wait:src/renderer/src/components/native-chat/NativeChatSessionOptionPickers.focus-return.test.tsx +1 test-no-real-time-wait:src/renderer/src/components/native-chat/native-chat-composer-draft-lifecycle.test.tsx +6 test-no-real-time-wait:src/renderer/src/components/native-chat/native-chat-composer-draft-store.test.ts 1 test-no-real-time-wait:src/renderer/src/components/native-chat/structured-chat-menu-lifetime.test.tsx 2 test-no-real-time-wait:src/renderer/src/components/native-chat/use-native-chat-find.test.tsx 1 test-no-real-time-wait:src/renderer/src/components/native-chat/use-structured-agent-session-legacy-recovery.test.tsx @@ -522,7 +523,6 @@ 1 test-no-real-time-wait:src/renderer/src/components/terminal-pane/terminal-fit-restore.test.ts 1 test-no-real-time-wait:src/renderer/src/components/terminal-pane/terminal-ime-xterm-preedit-cell-grid.test.ts 1 test-no-real-time-wait:src/renderer/src/components/terminal-search-decoration-leak.test.ts -1 test-no-real-time-wait:src/renderer/src/components/UpdateCard.error-card.test.tsx 2 test-no-real-time-wait:src/renderer/src/hooks/runtime-project-refresh-scheduler.test.ts 1 test-no-real-time-wait:src/renderer/src/lib/agent-hibernation-coordinator.test.ts 1 test-no-real-time-wait:src/renderer/src/lib/agent-paste-draft-readiness-budget.test.ts @@ -544,9 +544,9 @@ 1 test-no-real-time-wait:src/shared/git-branch-line-total-soft-deadline.test.ts 1 test-no-real-time-wait:src/shared/osc52-clipboard.test.ts 4 test-no-real-time-wait:src/shared/pty-reply-echo-shapes.node-pty.test.ts -1 test-no-real-time-wait:src/shared/remote-runtime/remote-runtime-outbound-admission.test.ts 2 test-no-real-time-wait:src/shared/remote-runtime/control/remote-runtime-shared-control-auth-refusal.test.ts 1 test-no-real-time-wait:src/shared/remote-runtime/control/remote-runtime-shared-control-standing-intent.test.ts +1 test-no-real-time-wait:src/shared/remote-runtime/remote-runtime-outbound-admission.test.ts 1 test-no-real-time-wait:src/shared/secure-file-windows.test.ts 1 test-no-real-time-wait:src/shared/secure-path-windows-acl.win32.test.ts 1 test-no-real-time-wait:src/shared/setup-agent-sequencing-codex-no-daemon.test.ts @@ -953,7 +953,6 @@ 2 test-no-wall-clock:src/main/persistence/tracking-repos/persistence-workspace-session-scrollback.test.ts 1 test-no-wall-clock:src/main/persistence/tracking-repos/worktree-metadata-normalization.test.ts 1 test-no-wall-clock:src/main/plugins/plugin-host-methods.test.ts -1 test-no-wall-clock:src/main/plugins/plugin-worker-controller.test.ts 2 test-no-wall-clock:src/main/provider-process/provider-group-orphan-guard.integration.test.ts 1 test-no-wall-clock:src/main/provider-process/provider-group-orphan-guard.test.ts 18 test-no-wall-clock:src/main/provider-process/provider-process-supervisor.integration.test.ts @@ -1088,9 +1087,12 @@ 3 test-no-wall-clock:src/main/wsl/wsl-orcad-real-distro-lane.test.ts 4 test-no-wall-clock:src/main/wsl/wsl-runner.wsl.test.ts 1 test-no-wall-clock:src/renderer/src/app-shell/visible-review-reporting.test.ts +7 test-no-wall-clock:src/renderer/src/components/WorktreeJumpPalette.recent-tabs.behavior.test.tsx +15 test-no-wall-clock:src/renderer/src/components/WorktreeJumpPalette.recent-tabs.test.tsx +1 test-no-wall-clock:src/renderer/src/components/WorktreeJumpPalette.test.tsx 3 test-no-wall-clock:src/renderer/src/components/activity/activity-auto-mark-read-loop.react185.test.tsx -2 test-no-wall-clock:src/renderer/src/components/artifacts/artifact-list-windowing.test.tsx 2 test-no-wall-clock:src/renderer/src/components/artifacts/ArtifactCollection.test.tsx +2 test-no-wall-clock:src/renderer/src/components/artifacts/artifact-list-windowing.test.tsx 7 test-no-wall-clock:src/renderer/src/components/automations/AutomationListLocalRows.test.tsx 1 test-no-wall-clock:src/renderer/src/components/automations/use-automation-list-search.test.tsx 1 test-no-wall-clock:src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx @@ -1112,24 +1114,24 @@ 1 test-no-wall-clock:src/renderer/src/components/settings/GrokAccountsSection.test.tsx 3 test-no-wall-clock:src/renderer/src/components/settings/ZcodePlanAccountsSection.test.tsx 1 test-no-wall-clock:src/renderer/src/components/sidebar/SidebarToolbar.test.tsx -5 test-no-wall-clock:src/renderer/src/components/sidebar/use-workspace-reference-details.test.tsx -3 test-no-wall-clock:src/renderer/src/components/sidebar/worktree-agent-rows-subscriptions.bench.test.tsx 4 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeCard.compact-hover.test.tsx 13 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeCard.pr-display.test.tsx 2 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeCard.single-reference-details.test.tsx 3 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeCardAgents.send-target.test.tsx 1 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeList.lineage-agent-expansion-coupling.test.tsx 1 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeList.lineage-child-real-card.test.tsx +5 test-no-wall-clock:src/renderer/src/components/sidebar/use-workspace-reference-details.test.tsx +3 test-no-wall-clock:src/renderer/src/components/sidebar/worktree-agent-rows-subscriptions.bench.test.tsx +1 test-no-wall-clock:src/renderer/src/components/status-bar/RuntimeHostStatusRow.test.tsx 5 test-no-wall-clock:src/renderer/src/components/status-bar/inline-usage-bars.test.tsx 4 test-no-wall-clock:src/renderer/src/components/status-bar/provider-segment-balance.test.tsx -1 test-no-wall-clock:src/renderer/src/components/status-bar/RuntimeHostStatusRow.test.tsx 2 test-no-wall-clock:src/renderer/src/components/status-bar/status-bar-antigravity-segment.test.tsx 1 test-no-wall-clock:src/renderer/src/components/status-bar/status-bar-cursor-segment.test.tsx 3 test-no-wall-clock:src/renderer/src/components/status-bar/status-bar-provider-menu-focus.test.tsx 1 test-no-wall-clock:src/renderer/src/components/status-bar/workspace-space-worktree-row.test.tsx +1 test-no-wall-clock:src/renderer/src/components/tab-bar/TabBarCreateEntry.history.test.tsx 2 test-no-wall-clock:src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts 1 test-no-wall-clock:src/renderer/src/components/tab-bar/open-tab-search.test.ts -1 test-no-wall-clock:src/renderer/src/components/tab-bar/TabBarCreateEntry.history.test.tsx 4 test-no-wall-clock:src/renderer/src/components/task-page-jira-cache-selectors.test.ts 1 test-no-wall-clock:src/renderer/src/components/task-page-jira-saved-filter-load-failure.test.tsx 1 test-no-wall-clock:src/renderer/src/components/terminal-pane/cache-timer-seeding.test.ts @@ -1144,20 +1146,18 @@ 2 test-no-wall-clock:src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-removal.agent-stop.test.tsx 6 test-no-wall-clock:src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.test.tsx 2 test-no-wall-clock:src/renderer/src/components/worktree-creation/WorktreeCreationPanel.test.tsx -7 test-no-wall-clock:src/renderer/src/components/WorktreeJumpPalette.recent-tabs.behavior.test.tsx -15 test-no-wall-clock:src/renderer/src/components/WorktreeJumpPalette.recent-tabs.test.tsx -1 test-no-wall-clock:src/renderer/src/components/WorktreeJumpPalette.test.tsx 2 test-no-wall-clock:src/renderer/src/hooks/ipc-events/agent-status-terminal-title-tab-write.test.ts 1 test-no-wall-clock:src/renderer/src/hooks/ipc-events/worktree-event-lineage-refresh.test.ts +3 test-no-wall-clock:src/renderer/src/hooks/useAutomationDispatchEvents.test.ts 1 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-agent-status-hook-titles.test.ts 1 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-browser-tab-create.test.ts 2 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts 3 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts 1 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts 2 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-updater-status.test.ts +2 test-no-wall-clock:src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.test.ts 1 test-no-wall-clock:src/renderer/src/lib/paired-runtime-closed-tab-resume.test.ts 2 test-no-wall-clock:src/renderer/src/lib/settled-worker-wake-policy.test.ts -2 test-no-wall-clock:src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.test.ts 2 test-no-wall-clock:src/renderer/src/lib/use-tab-agent-observed-signal-dispatch.test.tsx 2 test-no-wall-clock:src/renderer/src/lib/wake-sleeping-agents-live-unmounted-pane.test.ts 1 test-no-wall-clock:src/renderer/src/lib/workspace-activation-path-gate.test.ts diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index 085b6634c752..0ec8c09d7a2d 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -1167,6 +1167,7 @@ "src/main/automations/external-automation-probe-scheduler.test.ts": 86, "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, @@ -5773,7 +5774,7 @@ "src/main/runtime/runtime-rpc-device-key-dispatch.test.ts": 3022, "src/main/runtime/runtime-rpc-device-revocation.test.ts": 4229, "src/main/runtime/runtime-rpc-dispatch-inject-long-poll.test.ts": 2899, - "src/main/runtime/runtime-rpc-linear-comment-cancellation.test.ts": 2559, + "src/main/runtime/runtime-rpc-local-disconnect-forwarding.test.ts": 2559, "src/main/runtime/runtime-rpc-long-poll-transport.test.ts": 23796, "src/main/runtime/runtime-rpc-metadata-lifecycle.test.ts": 2618, "src/main/runtime/runtime-rpc-mobile-legacy-socket-relay-refusal.test.ts": 2701, @@ -6213,7 +6214,6 @@ "src/main/skills/skill-remote-install-service.test.ts": 120, "src/main/skills/skill-remove-transaction.test.ts": 439, "src/main/skills/skill-root-file-walk.test.ts": 46, - "src/main/skills/skill-runtime-capability.test.ts": 76, "src/main/skills/skill-scan-coalescer.test.ts": 58, "src/main/skills/skill-share-package-name.test.ts": 358, "src/main/skills/skill-share-preparation-service.test.ts": 343, @@ -9828,7 +9828,6 @@ "src/renderer/src/components/terminal-pane/terminal-drop-write-failure.test.ts": 47, "src/renderer/src/components/terminal-pane/terminal-error-accumulation.test.ts": 198, "src/renderer/src/components/terminal-pane/terminal-error-remote-closed-localization.test.ts": 96, - "src/renderer/src/components/terminal-pane/terminal-eviction-exempt-tabs.test.ts": 884, "src/renderer/src/components/terminal-pane/terminal-file-link-actions.test.ts": 250, "src/renderer/src/components/terminal-pane/terminal-file-link-target.test.ts": 1741, "src/renderer/src/components/terminal-pane/terminal-fit-restore.test.ts": 43, @@ -9948,7 +9947,6 @@ "src/renderer/src/components/terminal-pane/terminal-pane-recovery.test.ts": 676, "src/renderer/src/components/terminal-pane/terminal-pane-set-title-event.test.ts": 1546, "src/renderer/src/components/terminal-pane/terminal-pane-spawn-placement.test.ts": 473, - "src/renderer/src/components/terminal-pane/terminal-pane-split-completion.test.ts": 29, "src/renderer/src/components/terminal-pane/terminal-pane-split-in-main.test.ts": 367, "src/renderer/src/components/terminal-pane/terminal-pane-split-request-routing.test.ts": 1631, "src/renderer/src/components/terminal-pane/terminal-pane-split-with-inherited-cwd.test.ts": 1817, @@ -10251,7 +10249,6 @@ "src/renderer/src/hooks/ipc-events/terminal-presentation-pane-title.test.ts": 1399, "src/renderer/src/hooks/ipc-events/terminal-request-ipc-bridge-placement.test.ts": 1252, "src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge-split.test.ts": 998, - "src/renderer/src/hooks/ipc-events/updater-status-ipc-bridge.test.ts": 50, "src/renderer/src/hooks/ipc-events/worktree-event-lineage-refresh.test.ts": 1702, "src/renderer/src/hooks/ipc-events/worktree-event-runtime-activation.test.ts": 1375, "src/renderer/src/hooks/ipc-events/wsl-host-ipc-bridge.test.ts": 1381, @@ -10467,7 +10464,7 @@ "src/renderer/src/lib/automation-session-observer.test.ts": 55, "src/renderer/src/lib/automation-session-reuse.test.ts": 65, "src/renderer/src/lib/automation-terminal-bind-layout-owner.test.ts": 1382, - "tests/e2e/automation-terminal-ownership.unit.test.ts": 1491, + "src/renderer/src/lib/automation-terminal-ownership.test.ts": 1491, "src/renderer/src/lib/base64-bytes.test.ts": 65, "src/renderer/src/lib/bounded-generation-map.test.ts": 23, "src/renderer/src/lib/browser-cookie-import-toast.test.ts": 172, @@ -10658,7 +10655,7 @@ "src/renderer/src/lib/monaco-languages/zig-highlighting.test.ts": 4871, "src/renderer/src/lib/monaco-setup-steps.test.ts": 48, "src/renderer/src/lib/native-chat-cli-fork-preparation.test.ts": 2392, - "src/renderer/src/lib/native-chat-transcript-readability.test.ts": 35, + "src/shared/native-chat/transcript/native-chat-transcript-readability.test.ts": 35, "src/renderer/src/lib/nested-repo-selected-paths.test.ts": 24, "src/renderer/src/lib/new-agent-prompt-outcome.test.ts": 744, "src/renderer/src/lib/new-tab-agent-menu-rows.test.ts": 362, @@ -12485,7 +12482,7 @@ "src/shared/native-chat/native-chat-context-usage.test.ts": 28, "src/shared/native-chat-cut-turn-notice.test.ts": 217, "src/shared/native-chat-href-routing.test.ts": 36, - "src/shared/native-chat-image-transcript-markers.test.ts": 51, + "src/shared/native-chat/transcript/native-chat-image-transcript-markers.test.ts": 51, "src/shared/native-chat-paste-bytes.test.ts": 35, "src/shared/native-chat/native-chat-scope-cache.test.ts": 28, "src/shared/native-chat/input/native-chat-session-option-commands.test.ts": 114, @@ -12496,20 +12493,19 @@ "src/shared/native-chat/input/native-chat-slash-commands.omp.test.ts": 54, "src/shared/native-chat/input/native-chat-slash-commands.test.ts": 52, "src/shared/native-chat-stopped-send-turn.test.ts": 278, - "src/shared/native-chat-subagent-items.test.ts": 167, - "src/shared/native-chat-subagent-summary.test.ts": 45, + "src/shared/native-chat/transcript/native-chat-subagent-items.test.ts": 167, + "src/shared/native-chat/transcript/native-chat-subagent-summary.test.ts": 45, "src/shared/native-chat/input/native-chat-task-list-history.test.ts": 58, "src/shared/native-chat/input/native-chat-task-list.test.ts": 41, "src/shared/native-chat/transcript/native-chat-text-reveal.test.ts": 27, "src/shared/native-chat-transcript-contracts.test.ts": 591, "src/shared/native-chat-transcript-projection.test.ts": 134, - "src/shared/native-chat-transcript-retention.test.ts": 55, + "src/shared/native-chat/transcript/native-chat-transcript-retention.test.ts": 55, "src/shared/native-chat/transcript/native-chat-turn-activity.test.ts": 137, "src/shared/native-chat/transcript/native-chat-turn-fold.test.ts": 120, "src/shared/native-chat-turn-membership.test.ts": 174, "src/shared/native-chat-turn-status.test.ts": 52, "src/shared/native-chat-unverifiable-turn-status.test.ts": 111, - "src/shared/native-chat/native-chat-upgrade-tip-audience.test.ts": 41, "src/shared/native-chat/native-chat-visual-directive.test.ts": 45, "src/shared/native-chat/native-chat-visual-height-governor.test.ts": 141, "src/shared/native-chat/native-chat-visual-shell.reader-scroll.test.ts": 188, diff --git a/config/tsconfig.tc.web.json b/config/tsconfig.tc.web.json index 5332999f8d3b..7ad94dda9ec8 100644 --- a/config/tsconfig.tc.web.json +++ b/config/tsconfig.tc.web.json @@ -38,6 +38,10 @@ "../src/main/jira/adf-markdown.ts", "../src/main/jira/adf-text-marks.ts", "../src/main/jira/adf-media-destination.ts", + "../src/main/ipc/dashboard-payload-validation.ts", + "../src/main/ipc/dashboard-agent-launch-validation.ts", + "../src/main/ipc/dashboard-workspace-payload-validation.ts", + "../src/main/ipc/dashboard-filter-payload-validation.ts", "../src/main/ipc/deferred-emoji-shortcode-dataset.ts", "../src/main/ipc/worktree-branch-name.ts", "../src/main/ipc/worktree-logic.ts", diff --git a/src/main/automations/automation-agent-run-result.ts b/src/main/automations/automation-agent-run-result.ts index 9c2cb976a5aa..e2042d8e0565 100644 --- a/src/main/automations/automation-agent-run-result.ts +++ b/src/main/automations/automation-agent-run-result.ts @@ -1,7 +1,7 @@ import type { AgentLaunchResult } from '../../shared/agent-launch-intent' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { AutomationRun } from '../../shared/automations-types' -import type { HeadlessAutomationAgentLaunch } from './headless-automation-agent-launch' +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' @@ -10,7 +10,7 @@ import { AutomationRunLaunchError } from './headless-dispatch' export function publishedLaunchTarget( runtime: Pick, result: Pick -): HeadlessAutomationAgentLaunch { +): AutomationChatAgentLaunch { let paneKey = result.outcome.kind === 'terminal' ? (result.outcome.paneKey ?? null) : null let ptyId: string | null = null if (result.outcome.kind === 'terminal') { @@ -39,8 +39,8 @@ export function publishedLaunchTarget( export async function enrichAutomationRunTarget( runtime: OrcaRuntimeService, - target: HeadlessAutomationAgentLaunch -): Promise { + target: AutomationChatAgentLaunch +): Promise { try { const shown = await runtime.showManagedWorktree(`id:${target.workspaceId}`) target.workspaceDisplayName = shown.displayName ?? null @@ -61,10 +61,10 @@ export async function enrichAutomationRunTarget( export async function automationRunAcceptedTarget( runtime: OrcaRuntimeService, run: Pick, - target: HeadlessAutomationAgentLaunch | undefined, + target: AutomationChatAgentLaunch | undefined, error: unknown, agent: string -): Promise { +): Promise { const receipt = await runtime .openAgentSessionRecordStore() .then((store) => readAutomationRunReceipt(store, run)) 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-session-reuse.ts b/src/main/automations/automation-chat-session-reuse.ts index 00a0a7f981f5..6f13d8534304 100644 --- a/src/main/automations/automation-chat-session-reuse.ts +++ b/src/main/automations/automation-chat-session-reuse.ts @@ -1,8 +1,8 @@ import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { - AutomationAgentLaunchRequest, - HeadlessAutomationAgentLaunch -} from './headless-automation-agent-launch' + 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' @@ -15,8 +15,8 @@ import { automationRunAcceptedTarget } from './automation-agent-run-result' export async function reuseAutomationChat( runtime: OrcaRuntimeService, - { automation, run, runs }: AutomationAgentLaunchRequest -): Promise { + { automation, run, runs }: AutomationChatLaunchRequest +): Promise { let preparationError: { error: unknown } | undefined const store = await runtime.openAgentSessionRecordStore().catch((error: unknown) => { preparationError = { error } @@ -37,7 +37,7 @@ export async function reuseAutomationChat( continue } seen.add(id) - const target: HeadlessAutomationAgentLaunch = { + const target: AutomationChatAgentLaunch = { // The caller only attempts Chat reuse for a stable workspace. workspaceId: automation.workspaceId!, workspaceDisplayName: null, diff --git a/src/main/automations/automation-dispatch-host-fence.test.ts b/src/main/automations/automation-dispatch-host-fence.test.ts index 1a540eaaadbc..b31d31b48da4 100644 --- a/src/main/automations/automation-dispatch-host-fence.test.ts +++ b/src/main/automations/automation-dispatch-host-fence.test.ts @@ -129,8 +129,8 @@ function attachedService(store: Store): { service: AutomationService send: ReturnType } { - const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) - const service = new AutomationService(store, { headlessDispatcher: send, tickMs: 60_000 }) + const send = vi.fn() + const service = new AutomationService(store, { tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, send } as never) return { service, send } } @@ -197,9 +197,8 @@ describe('scheduled dispatch fenced on the host the record captured', () => { vi.setSystemTime(new Date('2026-05-13T08:00:00')) const store = await createStore() const automation = seedRemoteScheduledAutomation(store) - const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) + const send = vi.fn() const service = new AutomationService(store, { - headlessDispatcher: send, tickMs: 60_000, allowRemoteHostScheduling: true }) @@ -213,9 +212,7 @@ describe('scheduled dispatch fenced on the host the record captured', () => { await evaluateAt(store, service, automation.id, '2026-05-13T09:01:00') - expect(send).toHaveBeenCalledWith( - expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) - ) + expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.anything()) }) it('dispatches while the registration the record captured is still the live one', async () => { @@ -226,12 +223,8 @@ describe('scheduled dispatch fenced on the host the record captured', () => { await evaluateAt(store, service, automation.id, '2026-05-13T09:01:00') - expect(send).toHaveBeenCalledWith( - expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) - ) - await vi.waitFor(() => - expect(store.listAutomationRuns(automation.id)[0]?.status).toBe('dispatched') - ) + expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.anything()) + expect(store.listAutomationRuns(automation.id)[0]?.status).toBe('dispatching') }) it('dispatches a record that captured no generation at all', async () => { @@ -244,9 +237,7 @@ describe('scheduled dispatch fenced on the host the record captured', () => { expect(automation.executionTargetGeneration).toBeUndefined() await evaluateAt(store, service, automation.id, '2026-05-13T09:01:00') - expect(send).toHaveBeenCalledWith( - expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) - ) + expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.anything()) }) it('refuses a legacy record with no run context once its host was replaced', async () => { @@ -331,9 +322,7 @@ describe('scheduled dispatch fenced on the host the record captured', () => { store.updateSshTarget(TARGET_ID, { orcadFence: undefined }) await evaluateAt(store, service, automation.id, '2026-05-13T09:02:00') - expect(send).toHaveBeenCalledWith( - expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) - ) + expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.anything()) }) it('still runs an automation Move anyway left on this desktop', async () => { @@ -349,8 +338,6 @@ describe('scheduled dispatch fenced on the host the record captured', () => { await evaluateAt(store, service, automation.id, '2026-05-13T09:01:00') - expect(send).toHaveBeenCalledWith( - expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) - ) + expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.anything()) }) }) diff --git a/src/main/automations/automation-dispatch-request.ts b/src/main/automations/automation-dispatch-request.ts index 817921433630..5d0fbf0ef3fe 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' @@ -11,7 +16,12 @@ import { runHeadlessAutomationDispatch } from './headless-dispatch-runner' import type { AutomationRunTargetResult } from './run-target-resolution' -import { NO_DISPATCH_HOST, describeScheduledRefusal } from './dispatch-refusal' +import { createAutomationDispatchToken } from './dispatch-tokens' +import { + NO_DISPATCH_HOST, + describeScheduledRefusal, + sendRendererDispatch +} from './dispatch-refusal' import { isOrcadFencedAutomation, ORCAD_FENCED_AUTOMATION } from './orcad-fenced-automation' import { AutomationDispatchCancelledError } from './automation-dispatch-cancelled-error' @@ -26,7 +36,9 @@ type DispatchContext = Pick< store: Store runs: AutomationRunWriter isActive(): boolean + getRenderer(): AutomationRendererChannel | null headlessDispatcher: HeadlessAutomationDispatcher | null + chatDispatcher?: HeadlessAutomationDispatcher | null resolveTarget(automation: Automation): AutomationRunTargetResult } @@ -109,7 +121,10 @@ export async function requestAutomationDispatch( let target = resolveCurrentTarget() const refusal = describeScheduledRefusal({ target, - canDispatch: Boolean(ctx.headlessDispatcher) + canDispatch: + automation.surface === 'chat' + ? Boolean(ctx.chatDispatcher) + : Boolean(ctx.getRenderer() || ctx.headlessDispatcher) }) if (refusal || !target.ok) { return refuse(refusal ?? NO_DISPATCH_HOST) @@ -131,7 +146,20 @@ export async function requestAutomationDispatch( if (lateRefusal || !target.ok) { return refuse(lateRefusal ?? NO_DISPATCH_HOST) } - const dispatcher = ctx.headlessDispatcher + const renderer = automation.surface === 'chat' ? null : ctx.getRenderer() + if (renderer) { + return sendRendererDispatch( + renderer, + { + automation, + run, + dispatchToken: createAutomationDispatchToken(automation.id, run.id) + }, + ctx.runs, + run + ) + } + const dispatcher = automation.surface === 'chat' ? ctx.chatDispatcher : ctx.headlessDispatcher if (!dispatcher) { return refuse(NO_DISPATCH_HOST) } @@ -160,3 +188,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 index cacf935aa850..4d73a7d9e960 100644 --- a/src/main/automations/automation-run-operation.ts +++ b/src/main/automations/automation-run-operation.ts @@ -5,7 +5,7 @@ export const AUTOMATION_AGENT_CALLER = { kind: 'local-cli' } as const export function automationRunOperationId( run: Pick, - purpose: 'fresh-launch' | 'reuse-send' | 'reuse-terminal-launch' + purpose: 'fresh-launch' | 'reuse-send' ): string { const entropy = canonicalAgentSessionDigest({ domain: `automation:${purpose}`, diff --git a/src/main/automations/automation-run-receipt.ts b/src/main/automations/automation-run-receipt.ts index 02b1070cf741..7f5a5c9963b5 100644 --- a/src/main/automations/automation-run-receipt.ts +++ b/src/main/automations/automation-run-receipt.ts @@ -26,7 +26,7 @@ export function readAutomationRunReceipt( run: Pick ): AutomationRunReceipt | null { const callerKey = rpcCallerOperationKey(AUTOMATION_AGENT_CALLER) - for (const purpose of ['fresh-launch', 'reuse-terminal-launch'] as const) { + for (const purpose of ['fresh-launch'] as const) { const row = store.getOperationRow(callerKey, automationRunOperationId(run, purpose)) if (!row) { continue @@ -35,6 +35,9 @@ export function readAutomationRunReceipt( return null } const launch = row.outcome.launch + if (launch.receipt.preferred !== 'structured') { + return null + } if (launch.outcome.kind === 'structured') { return { kind: 'chat', diff --git a/src/main/automations/automation-worker-durability.test.ts b/src/main/automations/automation-worker-durability.test.ts index 44bc2a3103a2..1bf497a71a4e 100644 --- a/src/main/automations/automation-worker-durability.test.ts +++ b/src/main/automations/automation-worker-durability.test.ts @@ -58,10 +58,7 @@ describe('automation background writer durability', () => { vi.spyOn(Date, 'now').mockReturnValue(1_800_000_000_000) const { store, automation } = await fixture() const dispatcher = vi.fn(async () => launch) - const service = new AutomationService(store, { - allowRemoteHostScheduling: true, - headlessDispatcher: dispatcher - }) + const service = new AutomationService(store, { headlessDispatcher: dispatcher }) try { const runs = await Promise.all([service.runNow(automation.id), service.runNow(automation.id)]) expect(new Set(runs.map((run) => run.id)).size).toBe(1) @@ -85,10 +82,7 @@ describe('automation background writer durability', () => { ) return launch }) - const service = new AutomationService(store, { - allowRemoteHostScheduling: true, - headlessDispatcher: dispatcher - }) + const service = new AutomationService(store, { headlessDispatcher: dispatcher }) try { const run = service.runNow(automation.id) await Promise.resolve() @@ -105,10 +99,7 @@ describe('automation background writer durability', () => { const { store, automation } = await fixture() vi.spyOn(store, 'flushPendingOrThrowAsync').mockRejectedValueOnce(new Error('disk full')) const dispatcher = vi.fn(async () => launch) - const service = new AutomationService(store, { - allowRemoteHostScheduling: true, - headlessDispatcher: dispatcher - }) + const service = new AutomationService(store, { headlessDispatcher: dispatcher }) try { await expect(service.runNow(automation.id)).rejects.toThrow('disk full') expect(dispatcher).not.toHaveBeenCalled() @@ -136,10 +127,7 @@ describe('automation background writer durability', () => { await store.flushPendingOrThrowAsync() clock.mockReturnValue(dueAt + lateness) const dispatcher = vi.fn(async () => launch) - const service = new AutomationService(store, { - allowRemoteHostScheduling: true, - headlessDispatcher: dispatcher - }) + const service = new AutomationService(store, { headlessDispatcher: dispatcher }) try { service.start() await vi.waitFor(() => { @@ -161,10 +149,7 @@ describe('automation background writer durability', () => { const { store, automation } = await fixture() const acknowledgement = blockAcknowledgement(store, index) const dispatcher = vi.fn(async () => launch) - const service = new AutomationService(store, { - allowRemoteHostScheduling: true, - headlessDispatcher: dispatcher - }) + const service = new AutomationService(store, { headlessDispatcher: dispatcher }) const pending = service.runNow(automation.id) const rejected = expect(pending).rejects.toThrow('stopped before') await acknowledgement.blocked @@ -178,10 +163,7 @@ describe('automation background writer durability', () => { const { store, automation, readState } = await fixture() const acknowledgement = blockAcknowledgement(store, 2) const dispatcher = vi.fn(async () => launch) - const service = new AutomationService(store, { - allowRemoteHostScheduling: true, - headlessDispatcher: dispatcher - }) + const service = new AutomationService(store, { headlessDispatcher: dispatcher }) try { const pending = service.runNow(automation.id) const rejected = expect(pending).rejects.toThrow('removed before') @@ -204,10 +186,7 @@ describe('automation background writer durability', () => { const { store, automation } = await fixture() const acknowledgement = blockAcknowledgement(store, index) const dispatcher = vi.fn(async () => launch) - const service = new AutomationService(store, { - allowRemoteHostScheduling: true, - headlessDispatcher: dispatcher - }) + const service = new AutomationService(store, { headlessDispatcher: dispatcher }) try { const pending = service.runNow(automation.id) await acknowledgement.blocked @@ -227,10 +206,7 @@ describe('automation background writer durability', () => { const { store, automation } = await fixture() const acknowledgement = blockAcknowledgement(store, index) const dispatcher = vi.fn(async () => launch) - const service = new AutomationService(store, { - allowRemoteHostScheduling: true, - headlessDispatcher: dispatcher - }) + const service = new AutomationService(store, { headlessDispatcher: dispatcher }) try { const pending = service.runNow(automation.id) await acknowledgement.blocked diff --git a/src/main/automations/desktop-run-terminal-lifecycle.ts b/src/main/automations/desktop-run-terminal-lifecycle.ts deleted file mode 100644 index 33dacf2015fa..000000000000 --- a/src/main/automations/desktop-run-terminal-lifecycle.ts +++ /dev/null @@ -1,298 +0,0 @@ -import { reconcileDesktopRunTerminals } from './desktop-run-terminal-reconciliation' -import { - stopDesktopRunTerminal, - watchDesktopTerminalStop, - stopRevokers -} from './desktop-run-terminal-stop' -import { randomUUID } from 'node:crypto' -import type { - Automation, - AutomationDispatchResult, - AutomationRun -} from '../../shared/automations-types' -import type { - AutomationTerminalCorrelation, - AutomationTerminalLifecycleRequest, - AutomationTerminalLifecycleResponse, - AutomationTerminalTarget -} from '../../shared/automation-terminal-lifecycle' -import { makePaneKey, parsePaneKey } from '../../shared/stable-pane-id' -import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import type { Store } from '../persistence' -import { requestAutomationTerminalLifecycle } from '../window/terminal-tab-close-request-relay' -import { terminalPresentationRequest } from '../window/runtime-window-lifecycle' -import type { AgentLaunchHostPolicy } from '../runtime/rpc/methods/agent-launch-surfaces' - -export function createDesktopRunTerminalLifecycle( - runtime: OrcaRuntimeService, - store: Store, - inLane: (automationId: string, operation: () => Promise) => Promise -) { - const generation = randomUUID() - const registrations = new Map>() - function register( - automation: Automation, - run: Pick, - operationId: string - ) { - const window = runtime.getAuthoritativeWindow() - const web = window.webContents - const frame = web.mainFrame - const abort = new AbortController() - const registrationId = randomUUID() - const paneKey = makePaneKey(randomUUID(), randomUUID()) - const pane = parsePaneKey(paneKey)! - let epoch: string | null = null - let target: AutomationTerminalTarget | null = null - let ptyId: string | null = null - let incarnationId: string | null | undefined - let finalizing = false - let enrollment = Promise.resolve() - const listeners: (() => void)[] = [] - const valid = (): boolean => { - try { - return ( - !abort.signal.aborted && - !window.isDestroyed() && - !web.isDestroyed() && - web.mainFrame === frame && - runtime.getAuthoritativeWindow() === window - ) - } catch { - return false - } - } - type Operation = R extends AutomationTerminalCorrelation - ? Omit - : never - const correlation = { - registrationId, - runId: run.id, - operationId, - serviceGeneration: generation - } - const envelope = (operation: Operation): AutomationTerminalLifecycleRequest => ({ - ...correlation, - requestId: randomUUID(), - documentEpoch: epoch, - ...operation - }) - const request = (operation: Operation): Promise => - requestAutomationTerminalLifecycle(window, envelope(operation), abort.signal, valid).then( - (reply) => { - if ( - !valid() || - reply.registrationId !== correlation.registrationId || - reply.runId !== correlation.runId || - reply.operationId !== correlation.operationId || - reply.serviceGeneration !== correlation.serviceGeneration || - (epoch !== null && reply.documentEpoch !== epoch) - ) { - throw new Error('terminal_lifecycle_owner_lost') - } - return reply - } - ) - const release = (): void => { - if (abort.signal.aborted) { - return - } - // Enqueue release to this document only; cancellation cannot retarget a new window. - try { - if (valid()) { - web.send('automations:terminalLifecycleRequest', envelope({ operation: 'release' })) - } - } catch { - /* The document is already unreachable. */ - } - abort.abort() - for (const dispose of listeners) { - dispose() - } - stopRevokers.delete(registrationId) - registrations.delete(run.id) - } - listeners.push(...watchDesktopTerminalStop(window, web, release)) - const revoker: { ptyId: string | null; release: () => void } = { ptyId, release } - stopRevokers.set(registrationId, revoker) - const reserve = (worktreeId: string): void => { - if (target || !valid()) { - return - } - target = { worktreeId, tabId: pane.tabId, leafId: pane.leafId, paneKey } - try { - enrollment = request({ operation: 'arm', target }).then((reply) => { - if (reply.disposition !== 'armed' || !reply.documentEpoch) { - throw new Error('terminal_lifecycle_not_armed') - } - epoch = reply.documentEpoch - }) - void enrollment.catch(release) - } catch { - release() - } - } - const policy: AgentLaunchHostPolicy = { - onWorkspaceCreated: reserve, - onSurfacePublished: (surface) => { - if ( - surface.outcome.kind !== 'terminal' || - !target || - surface.worktreeId !== target.worktreeId || - surface.outcome.paneKey !== paneKey || - ptyId - ) { - release() - return - } - ptyId = runtime.getTerminalPtyIdForHandle(surface.outcome.handle) - if (!ptyId) { - release() - return - } - const metadata = runtime.getPtyExecutionHostMetadata(ptyId) - incarnationId = metadata.incarnationId - if (!incarnationId || metadata.executionHostId !== LOCAL_EXECUTION_HOST_ID) { - release() - return - } - revoker.ptyId = ptyId - web.send( - 'ui:createTerminal', - terminalPresentationRequest(target.worktreeId, { - ptyId, - tabId: pane.tabId, - leafId: pane.leafId, - presentation: 'background', - surfaceOwner: false, - activate: false, - expectedProcessIdentity: { terminalHandle: surface.outcome.handle, incarnationId } - }) - ) - enrollment = enrollment.then(async () => { - const reply = await request({ - operation: 'bind', - ptyId: ptyId!, - incarnationId: incarnationId!, - hostId: LOCAL_EXECUTION_HOST_ID - }) - if (reply.disposition !== 'bound') { - release() - } - }) - void enrollment.catch(release) - } - } - return { - paneKey, - policy, - reserve, - release, - finalize: async (completed: AutomationRun): Promise => { - if (finalizing) { - return null - } - finalizing = true - try { - await enrollment - if ( - !valid() || - completed.status !== 'completed' || - completed.terminalPtyId !== ptyId || - !target || - !ptyId || - !incarnationId - ) { - return null - } - const { worktreeId } = target - const expectedPtyId = ptyId - const expectedIncarnationId = incarnationId - return await inLane(automation.id, async () => { - const eligible = (): boolean => - valid() && - runtime.getTerminalPtyIdForHandle( - runtime.getTerminalHandleForPaneKey(paneKey) ?? '' - ) === expectedPtyId && - runtime.getPtyExecutionHostMetadata(expectedPtyId).incarnationId === - expectedIncarnationId && - runtime.terminalRunFacts.readLastDrivingInputAt(expectedPtyId) === null - if (!eligible()) { - return null - } - const prepared = await request({ - operation: 'finalize', - phase: 'prepare', - preservePane: - store.getWorktreeMeta(worktreeId)?.automationProvenance?.automationRunId === run.id - }) - if (prepared.disposition !== 'prepared') { - return null - } - const proof = await stopDesktopRunTerminal( - runtime, - worktreeId, - expectedPtyId, - expectedIncarnationId, - async () => { - if (!eligible()) { - return false - } - const answer = await request({ operation: 'finalize', phase: 'authorize' }) - return answer.disposition === 'authorized' && eligible() - } - ) - let disposition: AutomationTerminalLifecycleResponse['disposition'] = 'unproven' - try { - disposition = (await request({ operation: 'finalize', phase: 'stop-settled', proof })) - .disposition - } catch { - /* Keep recovery identity when acknowledgement is lost. */ - } - return proof === 'stopped' - ? { - runId: run.id, - status: completed.status, - terminalPtyId: null, - ...(disposition === 'closed' - ? { terminalPaneKey: null, terminalSessionId: null } - : {}) - } - : null - }) - } catch { - return null - } finally { - release() - } - } - } - } - return { - begin: ( - automation: Automation, - run: Pick, - operationId: string - ) => { - if (automation.reuseSession) { - return null - } - try { - const registration = register(automation, run, operationId) - registrations.set(run.id, registration) - return registration - } catch { - return null - } - }, - finalize: (run: AutomationRun) => - registrations.get(run.id)?.finalize(run) ?? Promise.resolve(null), - reconcile: () => reconcileDesktopRunTerminals(registrations, () => store.listAutomationRuns()), - stop: () => { - for (const owner of registrations.values()) { - owner.release() - } - } - } -} diff --git a/src/main/automations/desktop-run-terminal-reconciliation.ts b/src/main/automations/desktop-run-terminal-reconciliation.ts deleted file mode 100644 index 7b2198e7666f..000000000000 --- a/src/main/automations/desktop-run-terminal-reconciliation.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { AutomationRun } from '../../shared/automations-types' - -export function reconcileDesktopRunTerminals( - registrations: ReadonlyMap void }>, - listRuns: () => readonly AutomationRun[] -): void { - if (registrations.size === 0) { - return - } - const statuses = new Map() - for (const run of listRuns()) { - if (!statuses.has(run.id)) { - statuses.set(run.id, run.status) - } - } - for (const [id, owner] of registrations) { - const status = statuses.get(id) - if (!status || !['dispatching', 'dispatched', 'completed'].includes(status)) { - owner.release() - } - } -} diff --git a/src/main/automations/desktop-run-terminal-stop.ts b/src/main/automations/desktop-run-terminal-stop.ts deleted file mode 100644 index 858e523b3ebe..000000000000 --- a/src/main/automations/desktop-run-terminal-stop.ts +++ /dev/null @@ -1,87 +0,0 @@ -import type { BrowserWindow, WebContents } from 'electron' -import { addFanoutListener, addFanoutListeners } from '../event-listener-fanout' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' - -// Ordinary Stop revokes the same registration, including a pending provider authorization. -export const stopRevokers = new Map void }>() -export function cancelDesktopTerminalRetirement(ptyId: string): void { - for (const owner of stopRevokers.values()) { - if (owner.ptyId === ptyId) { - owner.release() - } - } -} - -export async function stopDesktopRunTerminal( - runtime: OrcaRuntimeService, - worktreeId: string, - expectedPtyId: string, - expectedIncarnationId: string, - authorizeStop: () => Promise -): Promise<'stopped' | 'live' | 'unproven'> { - let dispatched = false - let proof: 'stopped' | 'live' | 'unproven' = 'live' - try { - const stopped = await runtime.stopExactTerminalsForWorktree( - `id:${worktreeId}`, - [expectedPtyId], - { - keepHistory: true, - targetOnly: true, - expectedIncarnationId, - authorizeStop: async () => { - dispatched = await authorizeStop() - return dispatched - } - } - ) - proof = - stopped.postStopVerified && stopped.stoppedPtyIds.includes(expectedPtyId) - ? 'stopped' - : 'unproven' - } catch { - proof = 'live' - if (dispatched) { - proof = 'unproven' - try { - const inventory = await runtime.listTerminals(`id:${worktreeId}`, 1000, { - requireFreshPtyLiveness: true - }) - if ( - inventory.terminals.some( - (entry) => - entry.ptyId === expectedPtyId && - entry.incarnationId === expectedIncarnationId && - entry.connected - ) - ) { - proof = 'live' - } - } catch { - /* Unavailable inventory cannot prove a live rollback. */ - } - } - } - - return proof -} - -export function watchDesktopTerminalStop( - window: BrowserWindow, - web: WebContents, - release: () => void -): (() => void)[] { - return [ - addFanoutListener(window, 'closed', release), - addFanoutListeners(web, ['destroyed', 'render-process-gone'], release), - addFanoutListener( - web, - 'did-start-navigation', - (_event: unknown, _url: string, sameDocument: boolean, mainFrame: boolean) => { - if (mainFrame && !sameDocument) { - release() - } - } - ) - ] -} diff --git a/src/main/automations/dispatch-refusal.ts b/src/main/automations/dispatch-refusal.ts index 26a93fd17e04..cac3c1cebf1e 100644 --- a/src/main/automations/dispatch-refusal.ts +++ b/src/main/automations/dispatch-refusal.ts @@ -1,6 +1,11 @@ // Skip coalescing requires a fixed, byte-identical sentence for each refusal reason. +import type { WebContents } from 'electron' import type { Store } from '../persistence' -import type { Automation } from '../../shared/automations-types' +import type { + Automation, + AutomationDispatchRequest, + AutomationRun +} from '../../shared/automations-types' import { resolveAutomationRunTarget, type AutomationRunTargetResult } from './run-target-resolution' import type { AutomationRunWriter } from './automation-run-writer' import { wslMoveRepoBackoff } from '../persistence/moving-wsl-projects/wsl-move-background-backoff' @@ -89,6 +94,25 @@ export async function recordUnevaluableAutomation(input: { } } +export async function sendRendererDispatch( + channel: Pick | null, + payload: AutomationDispatchRequest, + runs: AutomationRunWriter, + run: AutomationRun +): Promise { + try { + channel?.send('automations:dispatchRequested', payload) + return run + } catch (error) { + return runs.updateRun({ + runId: run.id, + status: 'dispatch_failed', + workspaceId: run.workspaceId, + error: error instanceof Error ? error.message : String(error) + }) + } +} + /** Allow tick jitter beyond downtime grace; elapsed time still catches system sleep. * Short outages inside the tolerance are accepted; long inline dispatches may still exceed it. */ export function missedBeyondGrace(input: { diff --git a/src/main/automations/headless-automation-agent-launch.test.ts b/src/main/automations/headless-automation-agent-launch.test.ts new file mode 100644 index 000000000000..2776dfa0292a --- /dev/null +++ b/src/main/automations/headless-automation-agent-launch.test.ts @@ -0,0 +1,256 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { AutomationRun } from '../../shared/automations-types' +import { launchHeadlessAutomationAgent } from './headless-automation-agent-launch' + +const { deliverTerminalAgentLaunchPrompt } = vi.hoisted(() => ({ + deliverTerminalAgentLaunchPrompt: vi.fn(async (_args: Record) => true) +})) +vi.mock('../runtime/rpc/methods/agent-launch-terminal-prompt', () => ({ + deliverTerminalAgentLaunchPrompt +})) + +beforeEach(() => { + deliverTerminalAgentLaunchPrompt.mockClear() + deliverTerminalAgentLaunchPrompt.mockResolvedValue(true) +}) + +const CHAT_DEFAULT_ON = { experimentalNativeChat: true } + +function harness(options: { startupTerminal?: Record | null } = {}) { + const runtime = { + requireStore: () => ({ getSettings: () => CHAT_DEFAULT_ON }), + getStructuredAgentSessionCreateSupport: vi.fn(async () => ({ supported: true })), + createManagedWorktree: vi.fn(async (_args: Record) => ({ + worktree: { id: 'repo-1::/wt/auto', displayName: 'auto-nightly' }, + ...(options.startupTerminal === null + ? { warning: 'Startup terminal failed.' } + : { + startupTerminal: options.startupTerminal ?? { + handle: 'term_new', + tabId: 'tab-new', + paneKey: 'tab-new:leaf-1', + ptyId: 'pty-new' + } + }) + })), + launchAgentTerminal: vi.fn(async (_selector: string, _opts: Record) => ({ + handle: 'term_existing', + tabId: 'tab-1', + paneKey: 'tab-1:leaf-1', + ptyId: 'pty-1', + worktreeId: 'wt-1', + title: 'Nightly', + suppressStartupUpdatePrompt: true + })), + showManagedWorktree: vi.fn(async () => ({ displayName: 'repo' })), + getAgentStatusRowsForPane: vi.fn((_paneKey: string) => [ + { state: 'done', agentType: 'claude', receivedAt: 2 } + ]), + getTerminalHandleForPaneKey: vi.fn((paneKey: string) => + paneKey === 'tab-prev:leaf-1' ? 'term_prev' : null + ), + getTerminalPtyIdForHandle: vi.fn((_handle: string) => 'pty-prev'), + deliverStartupFollowup: vi.fn( + async (_handle: string, _followup: { agent: string; prompt: string }) => true + ) + } + return runtime +} + +function automation(overrides: Record) { + return { + id: 'auto-1', + agentId: 'claude', + prompt: ' fix the flaky test ', + workspaceMode: 'existing', + workspaceId: 'wt-1', + ...overrides + } +} + +const RUN = { id: 'run-1', title: 'Nightly', scheduledFor: Date.UTC(2026, 9, 9, 3) } +const TARGET = { ok: true, repo: { id: 'repo-1', path: '/repo', displayName: 'repo' } } + +function previousRun(overrides: Partial = {}): AutomationRun { + return { + id: 'run-0', + automationId: 'auto-1', + title: 'Nightly', + scheduledFor: 1, + status: 'completed', + trigger: 'scheduled', + workspaceId: 'wt-1', + workspaceDisplayName: 'repo', + sessionKind: 'terminal', + chatSessionId: null, + terminalSessionId: 'tab-prev', + terminalPaneKey: 'tab-prev:leaf-1', + terminalPtyId: 'pty-prev', + outputSnapshot: null, + precheckResult: null, + usage: null, + error: null, + startedAt: 1, + dispatchedAt: 1, + createdAt: 1, + ...overrides + } +} + +function launch( + runtime: ReturnType, + overrides: Record, + runs: AutomationRun[] = [] +) { + return launchHeadlessAutomationAgent( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the launch reads only the members faked in harness(). + runtime as never, + { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only these automation fields are read. + automation: automation(overrides) as never, + run: RUN, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the repo is read. + target: TARGET as never, + runs + } + ) +} + +describe('headless automation agent launch', () => { + it('starts a post-start agent bare and delivers its prompt once, after the terminal is recorded', async () => { + const runtime = harness() + let finishDelivery: (delivered: boolean) => void = () => {} + runtime.deliverStartupFollowup.mockImplementation( + () => new Promise((resolve) => (finishDelivery = resolve)) + ) + + const launched = await launch(runtime, { agentId: 'aider' }) + + expect(launched.terminalPaneKey).toBe('tab-1:leaf-1') + expect(runtime.launchAgentTerminal).toHaveBeenCalledWith( + 'id:wt-1', + expect.objectContaining({ agent: 'aider', prompt: '' }) + ) + expect(runtime.deliverStartupFollowup).toHaveBeenCalledTimes(1) + expect(runtime.deliverStartupFollowup).toHaveBeenCalledWith('term_existing', { + agent: 'aider', + prompt: 'fix the flaky test' + }) + finishDelivery(true) + }) + + it('fails the run with the create warning when no agent terminal started, without a second one', async () => { + const runtime = harness({ startupTerminal: null }) + + await expect( + launch(runtime, { workspaceMode: 'new_per_run', workspaceId: null }) + ).rejects.toThrow('Startup terminal failed.') + expect(runtime.launchAgentTerminal).not.toHaveBeenCalled() + }) + + it('logs a failure after the terminal was recorded instead of dropping it', async () => { + const runtime = harness() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + runtime.deliverStartupFollowup.mockRejectedValue(new Error('writer broke')) + + const launched = await launch(runtime, { agentId: 'aider' }) + await vi.waitFor(() => + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('after its terminal was published'), + expect.objectContaining({ message: 'writer broke' }) + ) + ) + + expect(launched.terminalHandle).toBe('term_existing') + warn.mockRestore() + }) + + it('refuses an existing-workspace run whose workspace is gone', async () => { + const runtime = harness() + + await expect(launch(runtime, { workspaceId: null })).rejects.toThrow( + 'The target workspace is no longer available.' + ) + expect(runtime.launchAgentTerminal).not.toHaveBeenCalled() + }) + + it('sends a reuse-session prompt into the idle agent its previous run left', async () => { + const runtime = harness() + + const launched = await launch(runtime, { reuseSession: true }, [previousRun()]) + + expect(deliverTerminalAgentLaunchPrompt).toHaveBeenCalledWith({ + runtime, + handle: 'term_prev', + agent: 'claude', + freshLaunch: false, + text: 'fix the flaky test', + unprovableHost: 'write-unless-shell' + }) + expect(runtime.launchAgentTerminal).not.toHaveBeenCalled() + expect(launched).toEqual({ + workspaceId: 'wt-1', + workspaceDisplayName: 'repo', + terminalHandle: 'term_prev', + terminalSessionId: 'tab-prev', + terminalPaneKey: 'tab-prev:leaf-1', + terminalPtyId: 'pty-prev' + }) + }) + + it('launches fresh when the idle agent did not take the prompt', async () => { + const runtime = harness() + deliverTerminalAgentLaunchPrompt.mockResolvedValue(false) + + const launched = await launch(runtime, { reuseSession: true }, [previousRun()]) + + expect(deliverTerminalAgentLaunchPrompt).toHaveBeenCalledTimes(1) + expect(runtime.launchAgentTerminal).toHaveBeenCalledTimes(1) + expect(launched.terminalHandle).toBe('term_existing') + }) + + it.each([ + ['its pane now holds another PTY', { ptyId: 'pty-restarted' }], + ['its agent is working', { row: { state: 'working', agentType: 'claude', receivedAt: 2 } }], + ['another agent is in it', { row: { state: 'done', agentType: 'codex', receivedAt: 2 } }], + ['the previous run did not complete', { run: { status: 'dispatch_failed' as const } }], + ['reuse is off', { reuseSession: false }] + ])('launches fresh without sending when %s', async (_label, setup) => { + const runtime = harness() + if ('ptyId' in setup) { + runtime.getTerminalPtyIdForHandle.mockReturnValue(setup.ptyId) + } + if ('row' in setup) { + runtime.getAgentStatusRowsForPane.mockReturnValue([setup.row]) + } + + await launch(runtime, { reuseSession: 'reuseSession' in setup ? setup.reuseSession : true }, [ + previousRun('run' in setup ? setup.run : {}) + ]) + + expect(deliverTerminalAgentLaunchPrompt).not.toHaveBeenCalled() + expect(runtime.launchAgentTerminal).toHaveBeenCalledTimes(1) + }) + + it('launches fresh while the previous run is still working in the reused agent', async () => { + const runtime = harness() + const inFlight = previousRun({ id: 'run-scheduled', status: 'dispatched', dispatchedAt: 2 }) + + await launch(runtime, { reuseSession: true }, [previousRun(), inFlight]) + + expect(deliverTerminalAgentLaunchPrompt).not.toHaveBeenCalled() + expect(runtime.launchAgentTerminal).toHaveBeenCalledTimes(1) + }) + + it("reads the pane's newest status row, not a stale done", async () => { + const runtime = harness() + runtime.getAgentStatusRowsForPane.mockReturnValue([ + { state: 'done', agentType: 'claude', receivedAt: 1 }, + { state: 'working', agentType: 'claude', receivedAt: 3 } + ]) + + await launch(runtime, { reuseSession: true }, [previousRun()]) + + expect(deliverTerminalAgentLaunchPrompt).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/automations/headless-automation-agent-launch.ts b/src/main/automations/headless-automation-agent-launch.ts index e5c4a56e506f..ac006a38ff81 100644 --- a/src/main/automations/headless-automation-agent-launch.ts +++ b/src/main/automations/headless-automation-agent-launch.ts @@ -1,234 +1,190 @@ +// Automations observe PTYs, so launch terminal agents regardless of the chat default. + +import type { + AgentLaunchPublishedSurface, + AgentLaunchSurfaceExecution +} from '../agent-launch/agent-launch-execution' +import { executeAgentLaunch } from '../agent-launch/agent-launch-executor' import type { Automation, AutomationRun } from '../../shared/automations-types' -import type { AgentLaunchResult } from '../../shared/agent-launch-intent' -import type { createDesktopRunTerminalLifecycle } from './desktop-run-terminal-lifecycle' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import { launchAgentOnHost } from '../runtime/rpc/methods/agent-launch' import { findReusableAutomationRun } from '../../shared/automation-session-reuse' -import { reuseAutomationChat } from './automation-chat-session-reuse' -import { buildHeadlessAutomationWorkspaceName } from './headless-workspace-create' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import { deliverTerminalAgentLaunchPrompt } from '../runtime/rpc/methods/agent-launch-terminal-prompt' +import type { HeadlessAutomationDispatchLaunch } from './headless-dispatch' +import { buildHeadlessAutomationWorktreeCreateArgs } 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' -export { publishedLaunchTarget } from './automation-agent-run-result' -import { automationRunOperationId, AUTOMATION_AGENT_CALLER } from './automation-run-operation' -import { createAutomationDispatchToken } from './dispatch-tokens' -import { mergeExtraAgentArgs, hasExtraAgentArgs } from '../../shared/automation-extra-agent-args' -import { resolveTuiAgentLaunchArgs } from '../../shared/tui-agent-launch-defaults' -import { agentLaunchQuotingShell } from '../../shared/agent-launch-runtime' -import { - resolveAgentLaunchRuntime, - newWorktreeLaunchScope -} from '../runtime/agent-launch-scope-runtime' -import { rpcCallerOperationKey } from '../runtime/rpc/rpc-caller-identity' -import { tuiAgentDisplayName } from '../../shared/tui-agent-display-names' -export type HeadlessAutomationAgentLaunch = HeadlessAutomationDispatchLaunch & { - terminalHandle: string | null +const TERMINAL_ONLY_MESSAGE = 'An automation starts a terminal agent only.' + +type LaunchedTerminal = { + handle: string + tabId?: string | null + paneKey?: string | null + ptyId?: string | null } -export type AutomationAgentLaunchRequest = { - automation: Automation - run: Pick - target: Extract - runs: readonly AutomationRun[] +export type HeadlessAutomationAgentLaunch = Omit & { + terminalHandle: string } export async function launchHeadlessAutomationAgent( runtime: OrcaRuntimeService, - request: AutomationAgentLaunchRequest, - lifecycle?: ReturnType['begin']> -): Promise { - try { - return await enrichAutomationRunTarget( - runtime, - await launchAutomationAgent(runtime, request, lifecycle) - ) - } catch (error) { - lifecycle?.release() - if (error instanceof AutomationRunLaunchError) { - throw error - } - console.error('[automations] agent 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.` - ) + request: { + automation: Automation + run: Pick + target: Extract + runs: readonly AutomationRun[] } -} - -async function launchAutomationAgent( - runtime: OrcaRuntimeService, - request: AutomationAgentLaunchRequest, - lifecycle?: ReturnType['begin']> ): Promise { const { automation, run, target } = request - const surface = automation.surface ?? 'terminal' - const context = { runtime, caller: AUTOMATION_AGENT_CALLER } - let published: HeadlessAutomationAgentLaunch | undefined - const policy = { - ...lifecycle?.policy, - onSurfacePublished: (result: AgentLaunchResult) => { - published = publishedLaunchTarget(runtime, result) - lifecycle?.policy.onSurfacePublished?.(result) + const agent = automation.agentId + const text = automation.prompt?.trim() + if (automation.reuseSession && automation.workspaceMode === 'existing' && text) { + const reused = await sendToReusableSession(runtime, { ...request, text }) + if (reused) { + return reused + } + } + let workspace: { id: string; displayName: string | null } | undefined + let terminal: LaunchedTerminal | undefined + const execution: AgentLaunchSurfaceExecution = { + runtime, + intent: { + agent, + // The workspace factory supplies create arguments from the automation. + target: + automation.workspaceMode === 'new_per_run' + ? { kind: 'create-worktree', create: {} } + : { kind: 'existing', worktree: requireWorkspaceId(automation) }, + ...(text ? { prompt: { text, delivery: 'submit' as const } } : {}) }, - terminalTitle: run.title, - suppressStartupUpdatePrompt: true, - unprovableHost: 'write-unless-shell' - } as const - if ( - automation.reuseSession && - automation.workspaceId && - (surface === 'chat' || !hasExtraAgentArgs(automation.extraAgentArgs)) - ) { - if (surface === 'chat') { - const reused = await reuseAutomationChat(runtime, request) - if (reused) { - return reused - } - } else { - const reused = findReusableAutomationRun({ - automationId: automation.id, - agentId: automation.agentId, - worktreeId: automation.workspaceId, - currentRunId: run.id, - runs: request.runs.filter((entry) => entry.sessionKind === 'terminal'), - agentStatusForPane: (paneKey) => - runtime - .getAgentStatusRowsForPane(paneKey) - .filter((row) => !row.providerSessionOnly) - .toSorted((a, b) => b.receivedAt - a.receivedAt)[0], - liveSession: (previous) => runOwnHandle(runtime, previous) - }) - if (reused) { - published = publishedLaunchTarget(runtime, { - worktreeId: automation.workspaceId, - outcome: { kind: 'terminal', handle: reused } + terminalOnly: true, + workspaces: { + createWorktree: async ({ startupAgent, startupPrompt }) => { + if (startupAgent === undefined) { + throw new Error(TERMINAL_ONLY_MESSAGE) + } + const { startupPrompt: _prompt, ...create } = buildHeadlessAutomationWorktreeCreateArgs({ + automation, + run, + repo: target.repo }) - const operationId = automationRunOperationId(run, 'reuse-terminal-launch') - try { - const result = await launchAgentOnHost( - { - agent: automation.agentId, - operationId, - target: { kind: 'existing', worktree: `id:${automation.workspaceId}` }, - surface, - reuseTerminal: { handle: reused }, - prompt: { text: automation.prompt, delivery: 'submit' }, - presentation: 'background' - }, - context, - policy - ) - published ??= publishedLaunchTarget(runtime, result) - if (result.prompt?.outcome === 'handed-to-terminal') { - return publishedLaunchTarget(runtime, result) - } - throw new AutomationRunLaunchError( - `${tuiAgentDisplayName(automation.agentId)} could not confirm this run's prompt. Open the terminal before running again.`, - published - ) - } catch (error) { - const records = await runtime.openAgentSessionRecordStore() - const row = records.getOperationRow( - rpcCallerOperationKey(AUTOMATION_AGENT_CALLER), - operationId + const created = await runtime.createManagedWorktree({ + ...create, + startupAgent, + ...(startupPrompt ? { startupPrompt } : {}) + }) + workspace = { + id: created.worktree.id, + displayName: created.worktree.displayName ?? null + } + const startup = created.startupTerminal + if (!startup?.handle) { + throw new Error( + created.warning || 'Automation workspace was created, but no agent terminal started.' ) - // Only the launch owner's durable no-effect verdict permits a different launch. - if (row?.outcome.status !== 'failed') { - return automationRunAcceptedTarget(runtime, run, published, error, automation.agentId) - } - published = undefined + } + terminal = { ...startup, handle: startup.handle } + return { + worktreeId: created.worktree.id, + startupTerminalHandle: startup.handle, + ...(startup.paneKey ? { startupTerminalPaneKey: startup.paneKey } : {}), + // Creation stages long prompts while keeping them on the launch command. + ...(startupPrompt ? { promptRodeLaunchCommand: true } : {}) } } + }, + surfaces: { + createStructuredSession: () => { + throw new Error(TERMINAL_ONLY_MESSAGE) + }, + createTerminalAgent: async ({ worktreeId, startupPrompt }) => { + const launched = await runtime.launchAgentTerminal(`id:${worktreeId}`, { + agent, + prompt: startupPrompt ?? '', + title: run.title, + suppressStartupUpdatePrompt: true, + ...(automation.extraAgentArgs ? { extraAgentArgs: automation.extraAgentArgs } : {}) + }) + terminal = launched + const shown = await runtime.showManagedWorktree(`id:${launched.worktreeId}`) + workspace = { id: launched.worktreeId, displayName: shown.displayName ?? null } + return { + handle: launched.handle, + ...(launched.paneKey ? { paneKey: launched.paneKey } : {}), + ...(startupPrompt ? { promptRodeLaunchCommand: true } : {}) + } + }, + deliverTerminalPrompt: ({ handle, prompt }) => + runtime.deliverStartupFollowup(handle, { agent, prompt: prompt.text }) } } - const operationId = automationRunOperationId(run, 'fresh-launch') - const settings = runtime.requireStore().getSettings() - let merged: ReturnType | null = null - if (surface === 'terminal' && hasExtraAgentArgs(automation.extraAgentArgs)) { - const scope = - automation.workspaceMode === 'existing' && automation.workspaceId - ? await runtime.showTerminalWorkspaceLaunchScope(`id:${automation.workspaceId}`) - : newWorktreeLaunchScope(target.repo, settings) - merged = mergeExtraAgentArgs({ - agent: automation.agentId, - extraAgentArgs: automation.extraAgentArgs, - defaultArgs: resolveTuiAgentLaunchArgs(automation.agentId, settings), - shell: agentLaunchQuotingShell( - resolveAgentLaunchRuntime(runtime.requireStore(), scope, undefined, automation.agentId) - ) - }) + await launchUntilPublished(execution) + if (!workspace || !terminal) { + throw new Error('Automation agent launch did not report its terminal.') } - if (merged && !merged.ok) { - throw new AutomationRunLaunchError( - `${tuiAgentDisplayName(automation.agentId)} could not start. ${merged.error}` - ) + return { + workspaceId: workspace.id, + workspaceDisplayName: workspace.displayName, + terminalHandle: terminal.handle, + terminalSessionId: terminal.tabId ?? null, + terminalPaneKey: terminal.paneKey ?? null, + terminalPtyId: terminal.ptyId ?? null } - if (automation.workspaceMode === 'existing' && automation.workspaceId) { - lifecycle?.reserve(automation.workspaceId) +} + +async function sendToReusableSession( + runtime: OrcaRuntimeService, + request: { + automation: Automation + run: Pick + runs: readonly AutomationRun[] + text: string } - try { - const result = await launchAgentOnHost( - { - agent: automation.agentId, - operationId, - ...(lifecycle ? { paneKey: lifecycle.paneKey } : {}), - surface, - presentation: 'background', - prompt: { text: automation.prompt, delivery: 'submit' }, - ...(merged?.ok ? { agentArgs: merged.agentArgs } : {}), - 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 - } - } - } - }, - context, - policy - ) - 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) - ) +): Promise { + const { automation, text } = request + const worktreeId = requireWorkspaceId(automation) + const session = findReusableAutomationRun({ + automationId: automation.id, + agentId: automation.agentId, + worktreeId, + currentRunId: request.run.id, + runs: request.runs, + agentStatusForPane: (paneKey) => + runtime + .getAgentStatusRowsForPane(paneKey) + .filter((row) => !row.providerSessionOnly) + .toSorted((left, right) => right.receivedAt - left.receivedAt)[0], + liveSession: (previous) => { + const handle = runOwnHandle(runtime, previous) + return handle ? { handle, previous } : null } - 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) + }) + if ( + !session || + !(await deliverTerminalAgentLaunchPrompt({ + runtime, + handle: session.handle, + agent: automation.agentId, + freshLaunch: false, + text, + // Windows cannot prove which agent is foreground; refuse only a proven shell. + unprovableHost: 'write-unless-shell' + })) + ) { + return null + } + const shown = await runtime.showManagedWorktree(`id:${worktreeId}`) + return { + workspaceId: worktreeId, + workspaceDisplayName: shown.displayName ?? null, + terminalHandle: session.handle, + terminalSessionId: session.previous.terminalSessionId, + terminalPaneKey: session.previous.terminalPaneKey, + terminalPtyId: session.previous.terminalPtyId } } -/** A pane may have been reused by a later process. */ +/** Reject reused pane handles whose PTY no longer belongs to this run. */ export function runOwnHandle( runtime: Pick, run: AutomationRun @@ -242,3 +198,32 @@ export function runOwnHandle( ? handle : null } + +/** Return on terminal publication; post-start prompt delivery may still be pending. */ +function launchUntilPublished( + execution: AgentLaunchSurfaceExecution +): Promise { + return new Promise((resolve, reject) => { + let published = false + executeAgentLaunch({ + ...execution, + onSurfacePublished: (surface) => { + published = true + resolve(surface) + } + }).catch((error: unknown) => { + if (!published) { + reject(error) + return + } + console.warn('[automations] the agent launch failed after its terminal was published', error) + }) + }) +} + +function requireWorkspaceId(automation: Automation): string { + if (!automation.workspaceId) { + throw new Error('The target workspace is no longer available.') + } + return automation.workspaceId +} diff --git a/src/main/automations/headless-dispatch-runner.ts b/src/main/automations/headless-dispatch-runner.ts index 5c1ac50efe41..49e1eb483074 100644 --- a/src/main/automations/headless-dispatch-runner.ts +++ b/src/main/automations/headless-dispatch-runner.ts @@ -61,8 +61,7 @@ export async function runHeadlessAutomationDispatch( error instanceof AutomationDispatchRefusedError ? 'skipped_unavailable' : 'dispatch_failed', workspaceId: automation.workspaceId, ...(error instanceof AutomationRunLaunchError ? error.target : {}), - dispatchedAt, - precheckResult, + ...(automation.surface === 'chat' ? { dispatchedAt, precheckResult } : {}), error: describeDispatchError(error) }) } diff --git a/src/main/automations/headless-workspace-create.test.ts b/src/main/automations/headless-workspace-create.test.ts index 380bb82e92e3..8c2ffb3efe1d 100644 --- a/src/main/automations/headless-workspace-create.test.ts +++ b/src/main/automations/headless-workspace-create.test.ts @@ -1,11 +1,92 @@ -import { expect, it } from 'vitest' -import { buildHeadlessAutomationWorkspaceName } from './headless-workspace-create' - -it('bounds automation workspace names while retaining the scheduled timestamp', () => { - expect( - buildHeadlessAutomationWorkspaceName('Nightly review run', Date.UTC(2026, 0, 2, 3, 4, 5)) - ).toBe('auto-nightly-review-run-20260102T0304') - expect(buildHeadlessAutomationWorkspaceName('!', Date.UTC(2026, 0, 2))).toBe( - 'auto-run-20260102T0000' - ) +import path from 'node:path' +import { describe, expect, it } from 'vitest' +import type { Automation } from '../../shared/automations-types' +import type { Repo } from '../../shared/repo-types' +import { buildHeadlessAutomationWorktreeCreateArgs } from './headless-workspace-create' + +const repoPath = path.join('tmp', 'orca') + +const repo: Repo = { + id: 'repo-1', + path: repoPath, + displayName: 'orca', + badgeColor: '#000', + addedAt: 1, + kind: 'git', + executionHostId: 'ssh:ssh-target-1' +} + +const automation: Automation = { + id: 'automation-1', + name: 'Nightly review', + prompt: 'Review changes', + precheck: null, + agentId: 'codex', + runContext: { + kind: 'workspace-run', + projectId: 'project-1', + hostId: 'ssh:ssh-target-1', + projectHostSetupId: 'setup-1', + repoId: 'repo-1', + path: repoPath + }, + sourceContext: null, + projectId: 'legacy-repo-1', + executionTargetType: 'ssh', + executionTargetId: 'ssh-target-1', + schedulerOwner: 'remote_host_service', + workspaceMode: 'new_per_run', + workspaceId: null, + baseBranch: 'origin/main', + setupDecision: 'skip', + reuseSession: false, + timezone: 'UTC', + rrule: 'FREQ=DAILY', + dtstart: 1, + enabled: true, + nextRunAt: 2, + missedRunPolicy: 'run_once_within_grace', + missedRunGraceMinutes: 720, + createdAt: 1, + updatedAt: 1 +} + +describe('headless automation workspace create args', () => { + it('stamps automation provenance for serve-mode new-per-run workspaces', () => { + const args = buildHeadlessAutomationWorktreeCreateArgs({ + automation, + run: { + id: 'run-1', + title: 'Nightly review run', + scheduledFor: Date.UTC(2026, 0, 2, 3, 4, 5) + }, + repo, + createdAt: 123 + }) + + expect(args).toMatchObject({ + repoSelector: 'repo-1', + name: 'auto-nightly-review-run-20260102T0304', + baseBranch: 'origin/main', + setupDecision: 'skip', + activate: false, + createdWithAgent: 'codex', + startupAgent: 'codex', + startupPrompt: 'Review changes', + telemetrySource: 'unknown', + automationProvenance: { + kind: 'created-by-automation', + automationId: 'automation-1', + automationNameSnapshot: 'Nightly review', + automationRunId: 'run-1', + automationRunTitleSnapshot: 'Nightly review run', + createdAt: 123, + executionTargetType: 'ssh', + executionTargetId: 'ssh-target-1', + projectId: 'project-1', + repoId: 'repo-1', + hostId: 'ssh:ssh-target-1' + } + }) + }) }) diff --git a/src/main/automations/headless-workspace-create.ts b/src/main/automations/headless-workspace-create.ts index bcd17173113b..239d67db26fd 100644 --- a/src/main/automations/headless-workspace-create.ts +++ b/src/main/automations/headless-workspace-create.ts @@ -1,3 +1,11 @@ +import type { Automation, AutomationRun } from '../../shared/automations-types' +import { buildAutomationWorkspaceProvenance } from '../../shared/automation-workspace-provenance' +import type { Repo } from '../../shared/repo-types' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' + +type HeadlessAutomationRunForWorkspace = Pick +type RuntimeCreateManagedWorktreeArgs = Parameters[0] + export function buildHeadlessAutomationWorkspaceName( runTitle: string, scheduledFor: number @@ -11,3 +19,30 @@ export function buildHeadlessAutomationWorkspaceName( const stamp = new Date(scheduledFor).toISOString().replace(/[-:]/g, '').slice(0, 13) return `auto-${slug || 'run'}-${stamp}` } + +export function buildHeadlessAutomationWorktreeCreateArgs({ + automation, + run, + repo, + createdAt = Date.now() +}: { + automation: Automation + run: HeadlessAutomationRunForWorkspace + repo: Repo + createdAt?: number +}): RuntimeCreateManagedWorktreeArgs { + return { + repoSelector: repo.id, + name: buildHeadlessAutomationWorkspaceName(run.title, run.scheduledFor), + baseBranch: automation.baseBranch ?? undefined, + setupDecision: automation.setupDecision ?? 'skip', + activate: false, + createdWithAgent: automation.agentId, + startupAgent: automation.agentId, + startupPrompt: automation.prompt, + startupSuppressUpdatePrompt: true, + ...(automation.extraAgentArgs ? { startupExtraAgentArgs: automation.extraAgentArgs } : {}), + telemetrySource: 'unknown', + automationProvenance: buildAutomationWorkspaceProvenance(automation, run, repo, createdAt) + } +} diff --git a/src/main/automations/precheck-runner.ts b/src/main/automations/precheck-runner.ts index 4b6257c6f051..099362756418 100644 --- a/src/main/automations/precheck-runner.ts +++ b/src/main/automations/precheck-runner.ts @@ -1,12 +1,6 @@ -import type { Store } from '../persistence' -import type { - Automation, - AutomationPrecheck, - AutomationPrecheckResult -} from '../../shared/automations-types' -import type { AutomationRunTargetResult } from './run-target-resolution' import { spawn, type ChildProcess } from 'node:child_process' import type { ClientChannel } from 'ssh2' +import type { AutomationPrecheck, AutomationPrecheckResult } from '../../shared/automations-types' import { MAX_AUTOMATION_PRECHECK_OUTPUT_CHARS } from '../../shared/automation-precheck' import { getSshConnectionManager } from '../ssh/targets/ssh-target-registry' import { quotePosixShell } from '../../shared/shell-argument-quoting' @@ -283,34 +277,3 @@ export async function runAutomationPrecheck(args: { } return await runLocalPrecheck(args.precheck, args.target) } - -export async function runAutomationRunPrecheck( - store: Store, - automationId: string, - runId: string, - resolveTarget: (automation: Automation) => AutomationRunTargetResult, - executePrecheck: typeof runAutomationPrecheck -): 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 executePrecheck({ - 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/runtime-automation-service-retention.test.ts b/src/main/automations/runtime-automation-service-retention.test.ts index 25936bfc5cd7..2b21371513fb 100644 --- a/src/main/automations/runtime-automation-service-retention.test.ts +++ b/src/main/automations/runtime-automation-service-retention.test.ts @@ -1,4 +1,3 @@ -import { createDesktopRunTerminalLifecycle } from './desktop-run-terminal-lifecycle' import { afterEach, describe, expect, it, vi } from 'vitest' import type { AutomationRun } from '../../shared/automations-types' import { RUN_TERMINAL_GRACE_MS } from './headless-run-terminal-retention' @@ -72,9 +71,7 @@ function build(headless: boolean) { store: store as never, // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: retention reads only the members faked above. runtime: runtime as never, - ...(headless - ? { headless: true as const } - : { headless: false as const, createDesktopLifecycle: createDesktopRunTerminalLifecycle }) + headless }) return { runtime, service, store } } diff --git a/src/main/automations/runtime-automation-service.test.ts b/src/main/automations/runtime-automation-service.test.ts index b286cc7cf78b..d7b8ed610e88 100644 --- a/src/main/automations/runtime-automation-service.test.ts +++ b/src/main/automations/runtime-automation-service.test.ts @@ -1,6 +1,5 @@ -import { createDesktopRunTerminalLifecycle } from './desktop-run-terminal-lifecycle' import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as AgentLauncher from './headless-automation-agent-launch' +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' @@ -10,6 +9,7 @@ import { automationRunOperationId } from './automation-run-operation' type Options = { headlessDispatcher?: HeadlessAutomationDispatcher + chatDispatcher?: HeadlessAutomationDispatcher terminalObserver?: AutomationRunTerminalObserver } const captured = vi.hoisted(() => { @@ -21,6 +21,13 @@ const captured = vi.hoisted(() => { markDispatchResult: vi.fn() } }) +const { deliverTerminalAgentLaunchPrompt } = vi.hoisted(() => ({ + deliverTerminalAgentLaunchPrompt: vi.fn(async () => true) +})) +vi.mock('../runtime/rpc/methods/agent-launch-terminal-prompt', () => ({ + deliverTerminalAgentLaunchPrompt +})) + vi.mock('./service', () => ({ AutomationService: class { start(): void {} @@ -31,9 +38,9 @@ vi.mock('./service', () => ({ } } })) -vi.mock('./headless-automation-agent-launch', async (original) => ({ +vi.mock('./automation-chat-agent-launch', async (original) => ({ ...(await original()), - launchHeadlessAutomationAgent: captured.launch + launchAutomationChatAgent: captured.launch })) vi.mock('./runtime-chat-run-observer', () => ({ observeAutomationChatRun: captured.observeChat })) import { createRuntimeAutomationService } from './runtime-automation-service' @@ -44,19 +51,21 @@ const run = { status: 'dispatching' as const, chatSessionId: null } -function fixture(headless: boolean) { +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 () => ({ - getOperationRow: (_caller: string, id: string) => rows.get(id), - getConversation: () => ({ - sessionId: 'claude_chat', - provider: 'claude', - location: { workspaceId: 'wt-1' } - }) - }), + 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( @@ -69,13 +78,13 @@ function fixture(headless: boolean) { // 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' }] + 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 - ? { headless: true as const } - : { headless: false as const, createDesktopLifecycle: createDesktopRunTerminalLifecycle }) + headless }) return { runtime, rows } } @@ -86,7 +95,7 @@ beforeEach(() => { }) describe('host-owned automation execution', () => { it.each([false, true])( - 'uses the same dispatcher on desktop/headless=%s and immediately hands completion to the watcher', + 'uses the same Chat dispatcher on desktop/headless=%s without supplying a desktop Terminal dispatcher', async (headless) => { fixture(headless) captured.launch.mockResolvedValue({ @@ -96,9 +105,10 @@ describe('host-owned automation execution', () => { '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d:3f2504e0-4f89-41d3-9a0c-0305e82c3301', terminalHandle: 'term-1' }) - const dispatcher = captured.options.headlessDispatcher! + expect(Boolean(captured.options.headlessDispatcher)).toBe(headless) + const dispatcher = captured.options.chatDispatcher! const result = await dispatcher({ - automation: state.automations[0], + automation: { ...state.automations[0], surface: 'chat' }, run, target: { ok: true, cwd: '/fixture', repo: state.repos[0] } }) @@ -117,7 +127,7 @@ describe('host-owned automation execution', () => { 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) + const { rows } = fixture(false, purpose === 'fresh-launch' ? 'terminal' : 'chat') rows.set(automationRunOperationId(run, purpose), { outcome: { status: 'succeeded', @@ -157,98 +167,47 @@ describe('host-owned automation execution', () => { expect(captured.launch).not.toHaveBeenCalled() } ) - it('recovers a terminal reuse receipt without a pane key and never launches again', async () => { - const { rows, runtime } = fixture(false) - const originalRun = { ...run, terminalPtyId: 'pty-1' } - rows.set(automationRunOperationId(run, 'reuse-terminal-launch'), { + 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-reused' }, + outcome: { + kind: 'terminal', + handle: 'term-fallback', + paneKey: 'tab:11111111-1111-4111-8111-111111111111' + }, receipt: { mode: 'terminal', - preferred: 'terminal', - reason: 'requested', - detail: 'Terminal' + preferred: 'structured', + reason: 'unsupported', + detail: 'Fallback' }, prompt: { delivery: 'submit', outcome: 'handed-to-terminal' } } } }) - runtime.waitForTerminal.mockRejectedValueOnce(new Error('test-stop')) + runtime.waitForTerminal.mockRejectedValueOnce(new Error('ordinary-terminal-observer')) const observer = captured.options.terminalObserver! await expect( - observer.observeCompletion(observer.resolveRunTerminal(originalRun)!, { - run: originalRun, + observer.observeCompletion(observer.resolveRunTerminal(run)!, { + run, signal: new AbortController().signal }) - ).rejects.toThrow('test-stop') + ).rejects.toThrow('ordinary-terminal-observer') expect(captured.markDispatchResult).toHaveBeenCalledWith( expect.objectContaining({ + status: 'dispatched', sessionKind: 'terminal', - terminalPaneKey: - '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d:3f2504e0-4f89-41d3-9a0c-0305e82c3301', - terminalSessionId: '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d', terminalPtyId: 'pty-1' }) ) + expect(runtime.waitForTerminal).toHaveBeenCalledWith('term-fallback', expect.anything()) + expect(captured.observeChat).not.toHaveBeenCalled() expect(captured.launch).not.toHaveBeenCalled() }) - it.each(['same-process', 'replacement', 'unknown', 'same-id-replacement'] as const)( - 'projects an adopted live handle with independent %s evidence', - async (proof) => { - const { rows, runtime } = fixture(false) - runtime.getTerminalHandleForPaneKey.mockReturnValue('term-adopted') - runtime.getTerminalPtyIdForHandle.mockImplementation((handle) => - handle === 'term-adopted' - ? proof === 'same-process' || proof === 'same-id-replacement' - ? 'original-pty' - : proof === 'replacement' - ? 'replacement-pty' - : null - : proof === 'same-id-replacement' - ? null - : 'original-pty' - ) - const ownRun = { - ...run, - status: 'dispatched' as const, - sessionKind: 'terminal' as const, - terminalPaneKey: 'tab:leaf', - terminalPtyId: 'original-pty' - } - rows.set(automationRunOperationId(run, 'fresh-launch'), { - outcome: { - status: 'succeeded', - launch: { - worktreeId: 'wt-1', - outcome: { kind: 'terminal', handle: 'term-old', paneKey: 'tab:leaf' }, - receipt: { - mode: 'terminal', - preferred: 'terminal', - reason: 'requested', - detail: 'Terminal' - }, - prompt: { delivery: 'submit', outcome: 'handed-to-terminal' } - } - } - }) - const observer = captured.options.terminalObserver! - runtime.waitForTerminal.mockRejectedValueOnce(new Error('observed-current-handle')) - const pending = observer.observeCompletion(observer.resolveRunTerminal(ownRun)!, { - run: ownRun, - signal: new AbortController().signal - }) - if (proof === 'same-process') { - await expect(pending).rejects.toThrow('observed-current-handle') - } else { - expect(await pending).toMatchObject({ status: 'dispatch_failed' }) - expect(runtime.waitForTerminal).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) => { @@ -268,7 +227,7 @@ describe('host-owned automation execution', () => { }, receipt: { mode: kind === 'chat' ? 'structured' : 'terminal', - preferred: kind === 'chat' ? 'structured' : 'terminal', + preferred: 'structured', reason: 'requested', detail: 'Published' }, @@ -314,3 +273,66 @@ describe('host-owned automation execution', () => { expect(captured.launch).not.toHaveBeenCalled() }) }) + +function capturedOption(key: K): NonNullable { + const value = captured.options[key] + if (value === undefined) { + throw new Error(`the service was constructed without ${key}`) + } + return value +} + +describe('headless automation dispatch', () => { + it('hands the launched run to its watcher instead of awaiting one tui-idle wait itself', async () => { + const runtime = { + setAutomationService: vi.fn(), + notifyAutomationsChanged: vi.fn(), + launchAgentTerminal: vi.fn(async () => ({ + handle: 'terminal-1', + tabId: 'tab-1', + paneKey: 'tab-1:pane-1', + ptyId: 'pty-1', + worktreeId: 'wt-1' + })), + showManagedWorktree: vi.fn(async () => ({ displayName: 'repo' })), + waitForTerminal: vi.fn(), + getTerminalHandleForPaneKey: vi.fn(() => null), + getAgentStatusRowsForPane: vi.fn(() => []) + } + createRuntimeAutomationService({ + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the mocked service never reads the store; the dispatcher reads only past runs. + store: { listAutomationRuns: () => [] } as never, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the dispatcher reads only the members faked above. + runtime: runtime as never, + headless: true + }) + const dispatcher = capturedOption('headlessDispatcher') + const launch = await dispatcher({ + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a reuse-workspace automation; only these fields are read. + automation: { + workspaceMode: 'existing', + workspaceId: 'wt-1', + agentId: 'goose' + } as never, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the title is read. + run: { title: 'Nightly' } as never, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: unused for an existing workspace. + target: {} as never + }) + + expect(launch.completion).toBeUndefined() + expect(launch.terminalPaneKey).toBe('tab-1:pane-1') + expect(runtime.launchAgentTerminal).toHaveBeenCalledWith('id:wt-1', { + agent: 'goose', + prompt: '', + title: 'Nightly', + suppressStartupUpdatePrompt: true + }) + expect(runtime.waitForTerminal).not.toHaveBeenCalled() + const observer = capturedOption('terminalObserver') + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: resolution reads only the pane key. + expect(observer.resolveRunTerminal({ terminalPaneKey: 'tab-1:pane-1' } as never)).toBe( + 'terminal-1' + ) + }) +}) diff --git a/src/main/automations/runtime-automation-service.ts b/src/main/automations/runtime-automation-service.ts index e10877639e31..db77eee8168b 100644 --- a/src/main/automations/runtime-automation-service.ts +++ b/src/main/automations/runtime-automation-service.ts @@ -1,8 +1,7 @@ -import type { createDesktopRunTerminalLifecycle } from './desktop-run-terminal-lifecycle' -import { automationRunOperationId } from './automation-run-operation' import { observeAutomationChatRun } from './runtime-chat-run-observer' import { readAutomationRunReceipt } from './automation-run-receipt' -import { withLiveTerminalHandle } from '../runtime/rpc/methods/agent-launch-replay' +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' @@ -15,11 +14,7 @@ import { isTuiAgent, TUI_AGENT_CONFIG } from '../../shared/tui-agent-config' -import { - launchHeadlessAutomationAgent, - publishedLaunchTarget, - runOwnHandle -} from './headless-automation-agent-launch' +import { launchHeadlessAutomationAgent, runOwnHandle } from './headless-automation-agent-launch' import { AGENT_HOOKS_REVIEW_BLOCKED_ERROR, createRuntimeAutomationRunTerminalObserver @@ -28,19 +23,14 @@ import { closeEarlierHookReviewRunTerminals } from './hook-review-blocked-run-te const MAX_REMEMBERED_LAUNCHES = 256 -type RuntimeAutomationServiceInput = { +export function createRuntimeAutomationService(input: { store: Store runtime: OrcaRuntimeService claudeUsage?: ClaudeUsageStore codexUsage?: CodexUsageStore -} & ( - | { headless: true } - | { headless: false; createDesktopLifecycle: typeof createDesktopRunTerminalLifecycle } -) - -export function createRuntimeAutomationService( - input: RuntimeAutomationServiceInput -): AutomationService { + /** Execute remote_host_service schedules through the headless dispatcher. */ + headless: boolean +}): AutomationService { const { store, runtime, claudeUsage, codexUsage } = input // Launch handles remain usable before pane-key lookup resolves. const launchedHandles = new Map() @@ -51,30 +41,44 @@ export function createRuntimeAutomationService( store.listAutomations().find((entry) => entry.id === run.automationId)?.agentId ) }) - let desktop: ReturnType | undefined const service = new AutomationService(store, { claudeUsage, codexUsage, - onRunFinalized: (run) => desktop?.finalize(run) ?? Promise.resolve(null), terminalObserver: { ...observer, - resolveRunTerminal: (run) => - run.sessionKind === 'chat' || run.status === 'dispatching' - ? `automation:${run.id}` - : (runOwnHandle(runtime, 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) => { let run = options.run - let originalHandle: string | undefined - if (run && (handle.startsWith('automation:') || run.sessionKind !== 'chat')) { + if (run && handle.startsWith('automation:')) { if (!run.chatSessionId) { const records = await runtime.openAgentSessionRecordStore() const receipt = readAutomationRunReceipt(records, run) - const automationId = run.automationId const agent = tuiAgentDisplayName( - store.listAutomations().find((entry) => entry.id === automationId)?.agentId ?? + store.listAutomations().find((entry) => entry.id === run?.automationId)?.agentId ?? 'Agent' ) ?? 'Agent' if (!receipt) { @@ -83,43 +87,30 @@ export function createRuntimeAutomationService( error: `${agent} could not confirm this run after Orca restarted. Open its workspace before running again.` } } - const originalPtyId = + const target = receipt.kind === 'terminal' - ? runtime.getTerminalPtyIdForHandle(receipt.launch.outcome.handle) - : null - const projected = - receipt.kind === 'terminal' ? withLiveTerminalHandle(receipt.launch, runtime) : null - const terminal = projected?.outcome.kind === 'terminal' ? projected.outcome : null - const observable = - receipt.accepted && - (!terminal || - (originalPtyId !== null && - (!run.terminalPtyId || run.terminalPtyId === originalPtyId) && - runtime.getTerminalPtyIdForHandle(terminal.handle) === originalPtyId)) - const target = projected - ? publishedLaunchTarget(runtime, projected) - : { - workspaceId: receipt.kind === 'chat' ? receipt.workspaceId : null, - sessionKind: 'chat' as const, - chatSessionId: receipt.kind === 'chat' ? receipt.sessionId : null, - terminalPaneKey: null, - terminalSessionId: null - } + ? 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: observable ? 'dispatched' : 'dispatch_failed', - error: observable + status: receipt.accepted ? 'dispatched' : 'dispatch_failed', + error: receipt.accepted ? null - : `${agent} could not confirm this run's prompt or original process. Open the run before trying again.`, - terminalPtyId: originalPtyId + : `${agent} could not confirm this run's prompt. Open the run before trying again.` }) - if (!observable) { + if (!receipt.accepted) { return { status: 'dispatch_failed', error: run.error } } - if (terminal && receipt.kind === 'terminal') { - originalHandle = receipt.launch.outcome.handle - handle = terminal.handle + if (receipt.kind === 'terminal') { + handle = receipt.launch.outcome.handle } } if (run.sessionKind === 'chat') { @@ -130,11 +121,11 @@ export function createRuntimeAutomationService( throw error } console.error('[automations] chat run observation failed:', error) - const automationId = run.automationId const agent = tuiAgentDisplayName( - store.listAutomations().find((entry) => entry.id === automationId)?.agentId ?? '' - ) ?? 'The agent' + 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.` @@ -142,25 +133,7 @@ export function createRuntimeAutomationService( } } } - const originalProcessMissing = (): boolean => - Boolean( - run?.terminalPtyId && - (runtime.getTerminalPtyIdForHandle(handle) !== run.terminalPtyId || - (originalHandle !== undefined && - runtime.getTerminalPtyIdForHandle(originalHandle) !== run.terminalPtyId)) - ) - const processLost = { - status: 'dispatch_failed' as const, - error: - 'The agent’s original process is no longer available. Open the run before trying again.' - } - if (originalProcessMissing()) { - return processLost - } const observation = await observer.observeCompletion(handle, { ...options, run }) - if (originalProcessMissing()) { - return processLost - } if (options.run && observation.error === AGENT_HOOKS_REVIEW_BLOCKED_ERROR) { const markDispatchResult = service.markDispatchResult.bind(service) void closeEarlierHookReviewRunTerminals( @@ -173,47 +146,41 @@ export function createRuntimeAutomationService( return observation } }, - onAutomationsChanged: (payload) => { - desktop?.reconcile() - runtime.notifyAutomationsChanged(payload) - }, + onAutomationsChanged: (payload) => runtime.notifyAutomationsChanged(payload), allowRemoteHostScheduling: input.headless, - headlessDispatcher: async (request) => { - const lifecycle = desktop?.begin( - request.automation, - request.run, - automationRunOperationId(request.run, 'fresh-launch') - ) - const { terminalHandle, ...launch } = await launchHeadlessAutomationAgent( - runtime, - { - ...request, - runs: store.listAutomationRuns(request.automation.id) - }, - lifecycle - ) + 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 ?? '') } } - // Let the watcher retry wait timeouts until completion or its observation deadline. return launch - } + }, + headlessDispatcher: input.headless + ? async (request) => { + const { terminalHandle, ...launch } = await launchHeadlessAutomationAgent(runtime, { + ...request, + runs: store.listAutomationRuns(request.automation.id) + }) + if (launch.terminalPaneKey) { + launchedHandles.set(launch.terminalPaneKey, terminalHandle) + if (launchedHandles.size > MAX_REMEMBERED_LAUNCHES) { + launchedHandles.delete(launchedHandles.keys().next().value ?? '') + } + } + // Let the watcher retry wait timeouts until completion or its observation deadline. + return launch + } + : undefined }) runtime.setAutomationService(service) if (input.headless) { bindHeadlessRunTerminalRetention(service, store, runtime) - } else { - desktop = input.createDesktopLifecycle(runtime, store, (id, operation) => - service.runInAutomationLane(id, operation) - ) - const stop = service.stop.bind(service) - service.stop = () => { - desktop?.stop() - stop() - } } return service } diff --git a/src/main/automations/service-lifecycle.test.ts b/src/main/automations/service-lifecycle.test.ts index e470a3ff67b1..2f8494833703 100644 --- a/src/main/automations/service-lifecycle.test.ts +++ b/src/main/automations/service-lifecycle.test.ts @@ -31,6 +31,7 @@ it.each(['chat', 'terminal'] as const)( name: 'Failed delivery', prompt: 'check', agentId: 'claude', + launchSetupPatch: { surface: 'chat' }, projectId: 'r1', workspaceMode: 'existing', workspaceId: 'r1::/repo', @@ -53,7 +54,7 @@ it.each(['chat', 'terminal'] as const)( published ) }) - const service = new AutomationService(store, { headlessDispatcher: dispatch }) + const service = new AutomationService(store, { chatDispatcher: dispatch }) service.setWebContents({ isDestroyed: () => false, send: vi.fn() }) service.setRendererReady() const failed = await service.runNow(automation.id) diff --git a/src/main/automations/service.test.ts b/src/main/automations/service.test.ts index 1efc2f34e743..05f7475005d4 100644 --- a/src/main/automations/service.test.ts +++ b/src/main/automations/service.test.ts @@ -12,7 +12,6 @@ import { tmpdir } from 'node:os' import type { Repo } from '../../shared/repo-types' import { toRuntimeExecutionHostId } from '../../shared/execution-host' import { AutomationService } from './service' -import type { HeadlessAutomationDispatcher } from './headless-dispatch' vi.mock('electron', () => ({ app: { @@ -71,11 +70,8 @@ describe('AutomationService', () => { }) vi.setSystemTime(new Date('2026-05-13T09:01:00')) - const send = vi.fn(async (_request) => ({ - workspaceId: 'wt1', - terminalSessionId: 'tab-1' - })) - const service = new AutomationService(store, { headlessDispatcher: send, tickMs: 60_000 }) + const send = vi.fn() + const service = new AutomationService(store, { tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, send @@ -84,18 +80,14 @@ describe('AutomationService', () => { service.start() service.setRendererReady() await vi.waitFor(() => - expect(send).toHaveBeenCalledWith( - expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) - ) + expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.any(Object)) ) service.stop() - const [payload] = send.mock.calls[0] + const [, payload] = send.mock.calls[0] expect(payload.automation.id).toBe(automation.id) expect(payload.run.scheduledFor).toBe(new Date('2026-05-13T09:00:00').getTime()) - await vi.waitFor(() => - expect(store.listAutomationRuns(automation.id)[0]?.status).toBe('dispatched') - ) + expect(store.listAutomationRuns(automation.id)[0]?.status).toBe('dispatching') expect(store.listAutomations().find((entry) => entry.id === automation.id)?.nextRunAt).toBe( new Date('2026-05-14T09:00:00').getTime() ) @@ -116,8 +108,8 @@ describe('AutomationService', () => { rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', dtstart: new Date('2026-05-14T00:00:00Z').getTime() }) - const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) - const service = new AutomationService(store, { headlessDispatcher: send, tickMs: 60_000 }) + const send = vi.fn() + const service = new AutomationService(store, { tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, send @@ -126,17 +118,89 @@ describe('AutomationService', () => { const run = await service.runNow(automation.id) - expect(run.status).toBe('dispatched') - await vi.waitFor(() => - expect(store.listAutomationRuns(automation.id)[0]?.status).toBe('dispatched') - ) + expect(run.status).toBe('dispatching') + expect(store.listAutomationRuns(automation.id)[0]?.status).toBe('dispatching') expect(send).toHaveBeenCalledWith( + 'automations:dispatchRequested', expect.objectContaining({ run: expect.objectContaining({ id: run.id, status: 'dispatching' }) }) ) }) + 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() + } + } + ) + it('skips dispatch when the selected project host setup is gone', async () => { vi.setSystemTime(new Date('2026-05-13T08:00:00Z')) const store = await createStore() @@ -162,8 +226,8 @@ describe('AutomationService', () => { } }) const reloaded = await createStore() - const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) - const service = new AutomationService(reloaded, { headlessDispatcher: send, tickMs: 60_000 }) + const send = vi.fn() + const service = new AutomationService(reloaded, { tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, send @@ -203,8 +267,8 @@ describe('AutomationService', () => { } }) const reloaded = await createStore() - const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) - const service = new AutomationService(reloaded, { headlessDispatcher: send, tickMs: 60_000 }) + const send = vi.fn() + const service = new AutomationService(reloaded, { tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, send @@ -242,8 +306,8 @@ describe('AutomationService', () => { rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', dtstart: new Date('2026-05-14T00:00:00Z').getTime() }) - const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) - const service = new AutomationService(store, { headlessDispatcher: send, tickMs: 60_000 }) + const send = vi.fn() + const service = new AutomationService(store, { tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, send @@ -281,9 +345,8 @@ describe('AutomationService', () => { rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', dtstart: new Date('2026-05-14T00:00:00Z').getTime() }) - const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) + const send = vi.fn() const service = new AutomationService(store, { - headlessDispatcher: send, tickMs: 60_000, allowRemoteHostScheduling: true }) @@ -295,8 +358,9 @@ describe('AutomationService', () => { const run = await service.runNow(automation.id) - expect(run.status).toBe('dispatched') + expect(run.status).toBe('dispatching') expect(send).toHaveBeenCalledWith( + 'automations:dispatchRequested', expect.objectContaining({ automation: expect.objectContaining({ schedulerOwner: 'remote_host_service' }), run: expect.objectContaining({ id: run.id, status: 'dispatching' }) @@ -686,27 +750,20 @@ describe('AutomationService', () => { const logged = vi.spyOn(console, 'error').mockImplementation(() => {}) vi.setSystemTime(new Date('2026-05-13T09:01:00')) - const send = vi.fn(async (_request) => ({ - workspaceId: 'wt1', - terminalSessionId: 'tab-1' - })) - const service = new AutomationService(reloaded, { headlessDispatcher: send, tickMs: 60_000 }) - service.setWebContents({ isDestroyed: () => false, send: vi.fn() }) + const send = vi.fn() + const service = new AutomationService(reloaded, { tickMs: 60_000 }) + service.setWebContents({ isDestroyed: () => false, send }) service.start() service.setRendererReady() await vi.waitFor(() => - expect(send).toHaveBeenCalledWith( - expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) - ) + expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.any(Object)) ) service.stop() - const [payload] = send.mock.calls[0] + const [, payload] = send.mock.calls[0] expect(payload.automation.id).toBe(healthy.id) - await vi.waitFor(() => - expect(reloaded.listAutomationRuns(healthy.id)[0]?.status).toBe('dispatched') - ) + expect(reloaded.listAutomationRuns(healthy.id)[0]?.status).toBe('dispatching') const poisonRun = reloaded.listAutomationRuns(poison.id)[0] expect(poisonRun?.status).toBe('skipped_unavailable') expect(poisonRun?.error).toBe( @@ -749,34 +806,27 @@ describe('AutomationService', () => { const logged = vi.spyOn(console, 'error').mockImplementation(() => {}) vi.setSystemTime(new Date('2026-05-13T09:01:00')) - const send = vi.fn(async (_request) => ({ - workspaceId: 'wt1', - terminalSessionId: 'tab-1' - })) - const service = new AutomationService(reloaded, { headlessDispatcher: send, tickMs: 60_000 }) - service.setWebContents({ isDestroyed: () => false, send: vi.fn() }) + const send = vi.fn() + const service = new AutomationService(reloaded, { tickMs: 60_000 }) + service.setWebContents({ isDestroyed: () => false, send }) service.start() service.setRendererReady() await vi.waitFor(() => - expect(send).toHaveBeenCalledWith( - expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) - ) + expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.any(Object)) ) service.stop() - const [payload] = send.mock.calls[0] + const [, payload] = send.mock.calls[0] expect(payload.automation.id).toBe(healthy.id) - await vi.waitFor(() => - expect(reloaded.listAutomationRuns(healthy.id)[0]?.status).toBe('dispatched') - ) + expect(reloaded.listAutomationRuns(healthy.id)[0]?.status).toBe('dispatching') expect(reloaded.listAutomationRuns(poison.id)[0]?.error).toBe( 'Orca could not evaluate this automation and skipped the occurrence.' ) expect(logged).toHaveBeenCalled() }) - it('marks the run dispatch_failed when the host launch throws', async () => { + it('marks the run dispatch_failed when the renderer send throws', async () => { vi.setSystemTime(new Date('2026-05-13T08:59:00')) const store = await createStore() store.addRepo(makeRepo()) @@ -795,10 +845,10 @@ describe('AutomationService', () => { logged.mockClear() vi.setSystemTime(new Date('2026-05-13T09:01:00')) - const send = vi.fn(async () => { - throw new Error('host launch failed') + const send = vi.fn(() => { + throw new Error('renderer is gone') }) - const service = new AutomationService(store, { tickMs: 60_000, headlessDispatcher: send }) + const service = new AutomationService(store, { tickMs: 60_000 }) service.setWebContents({ isDestroyed: () => false, send }) service.start() @@ -809,7 +859,7 @@ describe('AutomationService', () => { const runs = store.listAutomationRuns(automation.id) expect(runs).toHaveLength(1) expect(runs[0]?.status).toBe('dispatch_failed') - expect(runs[0]?.error).toBe('host launch failed') + expect(runs[0]?.error).toBe('renderer is gone') expect(logged).not.toHaveBeenCalled() }) }) diff --git a/src/main/automations/service.ts b/src/main/automations/service.ts index d4be95f615d7..94d68c734eac 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 { runAutomationRunPrecheck, runAutomationPrecheck } from './precheck-runner' import { captureLegacyRunTarget, resolveAutomationRunTarget, @@ -43,7 +43,10 @@ import type { PublishAutomationsChanged } from '../../shared/runtime-client-events' +const DEFAULT_TICK_MS = 60 * 1000 + export class AutomationService { + private readonly store: Store private readonly tickMs: number private timer: ReturnType | null = null private webContents: AutomationRendererChannel | null = null @@ -55,12 +58,10 @@ 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 - private readonly onRunFinalized: - | ((run: AutomationRun) => Promise) - | undefined private readonly publish: PublishAutomationsChanged | null private readonly runs: AutomationRunWriter private readonly completionWatcher: AutomationRunCompletionWatcher | null @@ -68,24 +69,25 @@ export class AutomationService { externalProbePriority: ((run: () => T) => T) | null = null constructor( - private readonly store: Store, + store: Store, opts: { - onRunFinalized?: (run: AutomationRun) => Promise tickMs?: number claudeUsage?: ClaudeUsageStore codexUsage?: CodexUsageStore allowRemoteHostScheduling?: boolean headlessDispatcher?: HeadlessAutomationDispatcher + chatDispatcher?: HeadlessAutomationDispatcher terminalObserver?: AutomationRunTerminalObserver onAutomationsChanged?: PublishAutomationsChanged } = {} ) { - this.onRunFinalized = opts.onRunFinalized - this.tickMs = opts.tickMs ?? 60_000 + this.store = store + this.tickMs = opts.tickMs ?? DEFAULT_TICK_MS this.claudeUsage = opts.claudeUsage ?? null 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 @@ -125,7 +127,7 @@ export class AutomationService { this.completionWatcher?.reconcileRetainedRuns(this.store.listAutomationRuns()) reportAutomationScheduleDrift(this.store.listAutomations()) // Headless hosts need startup catch-up without a renderer-ready notification. - if (this.rendererReady || (this.allowRemoteHostScheduling && this.headlessDispatcher)) { + if (this.rendererReady || this.headlessDispatcher) { // Serve adopts PTYs and publishes its graph before start(). this.completionWatcher?.markTerminalSurfaceReady() void this.evaluateDueRuns() @@ -168,17 +170,13 @@ export class AutomationService { } async runPrecheck(automationId: string, runId: string): Promise { - return runAutomationRunPrecheck( - this.store, - automationId, - runId, - (automation) => this.resolveTarget(automation), - runAutomationPrecheck + return runAutomationRequestPrecheck(this.store, automationId, runId, (automation) => + this.resolveTarget(automation) ) } async markDispatchResult(result: AutomationDispatchResult): Promise { - let run = await this.runs.updateRun(result) + const run = await this.runs.updateRun(result) clearAutomationDispatchTokens(run.automationId, run.id) if (!isFinalAutomationRunStatus(run.status)) { if (run.status === 'dispatched') { @@ -186,10 +184,6 @@ export class AutomationService { } return run } - const retirement = await this.onRunFinalized?.(run) - if (retirement) { - run = await this.runs.updateRun(retirement) - } this.completionWatcher?.forget(run.id) // Duplicate completion effects must not recalculate usage with a later attribution window. if (run.usage) { @@ -254,9 +248,7 @@ export class AutomationService { // Fold recurring refusals before creating rows so they do not evict real run history. const target = this.resolveTarget(automation) - const canDispatch = - this.canDispatchToRenderer() || - Boolean(this.allowRemoteHostScheduling && this.headlessDispatcher) + const canDispatch = this.canDispatchToRenderer() || Boolean(this.headlessDispatcher) const refusal = describeScheduledRefusal({ target, canDispatch }) // Once WSL owns the schedule, avoid churning skips on the retained local copy. if (refusal === WSL_MOVE_OWNED_BY_HOST) { @@ -305,9 +297,11 @@ export class AutomationService { store: this.store, runs: this.runs, isActive: () => !this.stopped && generation === this.dispatchGeneration, - headlessDispatcher: + getRenderer: () => (this.canDispatchToRenderer() ? this.webContents : null), + headlessDispatcher: this.headlessDispatcher, + chatDispatcher: this.allowRemoteHostScheduling || this.canDispatchToRenderer() - ? this.headlessDispatcher + ? this.chatDispatcher : null, resolveTarget: (current) => this.resolveTarget(current), runPrecheck: () => this.runPrecheck(automation.id, run.id), diff --git a/src/main/daemon/daemon-pty-adapter-history-shutdown-admission.test.ts b/src/main/daemon/daemon-pty-adapter-history-shutdown-admission.test.ts index 3720bb24d256..6df79da759a8 100644 --- a/src/main/daemon/daemon-pty-adapter-history-shutdown-admission.test.ts +++ b/src/main/daemon/daemon-pty-adapter-history-shutdown-admission.test.ts @@ -77,88 +77,3 @@ it('drains keepHistory shutdowns admitted before connection preparation complete rmSync(harness.dir, { recursive: true, force: true }) } }) - -it.each(['cwd', 'checkpoint', 'lock'] as const)( - 'authorizes only after real daemon %s preparation and preserves live history on veto', - async (pause) => { - const subprocess = createMockSubprocess() - const harness = await startDaemonAdapterHarness(() => subprocess) - const adapter = new DaemonPtyAdapter({ - socketPath: harness.socketPath, - tokenPath: harness.tokenPath, - historyPath: join(harness.dir, 'history') - }) - try { - const { id, incarnationId } = await adapter.spawn({ - cols: 80, - rows: 24, - sessionId: `veto-${pause}` - }) - subprocess._simulateData('keep this live history\r\n') - // SAFETY: protected adapter owners are exposed only to pause their real preparation, not replace stop dispatch. - const inside = adapter as unknown as { - readLiveSleepCwd(id: string, deadline?: number): Promise - checkpointSessions( - ids: string[], - opts: { final: boolean; teardown: boolean } - ): Promise - withHistorySpawnLock(id: string, operation: () => Promise): Promise - coldRestoreCache: Map - sleepRestoreSessionIds: Set - sessionIncarnations: Map - historyManager: { hasWriter(id: string): boolean } - } - const entered = Promise.withResolvers() - const resume = Promise.withResolvers() - if (pause === 'cwd') { - const actual = inside.readLiveSleepCwd.bind(adapter) - vi.spyOn(inside, 'readLiveSleepCwd').mockImplementationOnce(async (...args) => { - entered.resolve() - await resume.promise - return actual(...args) - }) - } else if (pause === 'checkpoint') { - const actual = inside.checkpointSessions.bind(adapter) - vi.spyOn(inside, 'checkpointSessions').mockImplementationOnce(async (...args) => { - entered.resolve() - await resume.promise - return actual(...args) - }) - } else { - const actual = inside.withHistorySpawnLock.bind(adapter) - vi.spyOn(inside, 'withHistorySpawnLock').mockImplementationOnce(async (key, operation) => { - entered.resolve() - await resume.promise - return actual(key, operation) - }) - } - let untouched = true - const authorizeStop = vi.fn(async () => untouched) - const shutdown = adapter.shutdown(id, { - immediate: true, - keepHistory: true, - expectedIncarnationId: incarnationId, - authorizeStop - }) - const denied = expect(shutdown).rejects.toThrow('terminal_stop_declined') - await entered.promise - expect(authorizeStop).not.toHaveBeenCalled() - untouched = false - resume.resolve() - await denied - expect(subprocess.kill).not.toHaveBeenCalled() - expect(adapter.getActiveSessionIds()).toContain(id) - expect(inside.coldRestoreCache.has(id)).toBe(false) - expect(inside.sleepRestoreSessionIds.has(id)).toBe(false) - expect(inside.historyManager.hasWriter(id)).toBe(true) - // An ordinary Stop does not require the rejected automatic authority. - await adapter.shutdown(id, { immediate: true, keepHistory: true }) - expect(subprocess.forceKill).toHaveBeenCalledOnce() - } finally { - adapter.dispose() - harness.adapter.dispose() - await harness.server.shutdown() - rmSync(harness.dir, { recursive: true, force: true }) - } - } -) diff --git a/src/main/daemon/daemon-pty-session-control.ts b/src/main/daemon/daemon-pty-session-control.ts index 55ec181e57ca..d6970fbac0eb 100644 --- a/src/main/daemon/daemon-pty-session-control.ts +++ b/src/main/daemon/daemon-pty-session-control.ts @@ -1,30 +1,104 @@ import { coldRestorePayloadFromInfo, type ColdRestorePayload } from './cold-restore-payload-cache' -import { isPtyFencedTerminationOutcome } from '../../shared/pty-fenced-termination' -import type { DaemonEndpointIdentity } from './daemon-hello-protocol' -import { sameEndpointIdentity } from './daemon-endpoint-incarnation' -import { FENCED_TERMINATION_PROTOCOL_VERSION } from './daemon-protocol-version' +import { isUnknownRequestTypeError } from './daemon-endpoint-errors' +import { GET_SIZE_PROTOCOL_VERSION } from './daemon-protocol-version' +import { readDaemonAppliedPtySize, type DaemonAppliedPtySize } from './daemon-pty-applied-size' import { FinalCheckpointWaitExpiredError } from './daemon-pty-lifecycle-errors' -import { DaemonPtySessionLiveness } from './daemon-pty-session-liveness' -export { LIVENESS_PROBE_TIMEOUT_MS } from './daemon-pty-session-liveness' +import { DaemonPtySessionInput } from './daemon-pty-session-input' import { remainingDaemonRequestTimeoutMs, teardownReadBudgetMs } from './daemon-request-deadline' import type { ColdRestoreInfo } from './history-reader' import { normalizeWslColdRestoreCwd } from './wsl-cold-restore-cwd' import { readDaemonWslSleepCwd } from './daemon-wsl-sleep-cwd' import * as unlistedSession from './daemon-unlisted-session' -import { SessionNotFoundError } from './types' +import { SessionNotFoundError, type ListSessionsResult } from './types' import { resolveSafePtyDefaultCwd } from '../providers/pty-default-cwd' -import type { PtyShutdownOptions } from '../providers/pty-provider-contract' +import type { PtySpawnResult } from '../providers/pty-provider-contract' + +export const LIVENESS_PROBE_TIMEOUT_MS = 2_000 const MAX_TOMBSTONES = 1000 // A busy daemon must not eat the final checkpoint's share of the Sleep deadline. const LIVE_SLEEP_CWD_BUDGET_MS = 1_500 -export abstract class DaemonPtySessionControl extends DaemonPtySessionLiveness { +export abstract class DaemonPtySessionControl extends DaemonPtySessionInput { protected abstract adoptListedSessionForSleep( sessionId: string, deadlineMs?: number ): Promise + async attach(id: string): Promise | void> { + await this.ensureConnected() + if (!this.canDelegateBackgroundToDaemon) { + this.setPtyBackgrounded(id, false) + } + + // Attach at the proven live size; default geometry could resize an agent TUI or accidentally create a shell. + // Preserve transport errors: treating lost contact as absence could duplicate or retire a live owner. + const size = await this.readAppliedSize(id, 'preserve') + if (!size) { + throw new SessionNotFoundError(id) + } + const result = await this.spawn({ + sessionId: id, + cols: size.cols, + rows: size.rows, + attachOnly: true + }) + if (result.exitedBeforeSpawnReply) { + throw new SessionNotFoundError(id) + } + // A restarted runtime has never seen the surviving session's title. + return result.providerSequence || result.lastTitle + ? { + ...(result.providerSequence ? { providerSequence: result.providerSequence } : {}), + ...(result.lastTitle ? { lastTitle: result.lastTitle } : {}) + } + : undefined + } + + hasPty(id: string): boolean { + return this.activeSessionIds.has(id) + } + + /** Use the same saved-history probe as spawn. */ + hasRestorableHistory(id: string): boolean { + return this.historyReader?.hasRestorableHistory(id) ?? false + } + + async probePtyLiveness(id: string): Promise { + try { + if (!this.getSizeUnsupported && this.protocolVersion >= GET_SIZE_PROTOCOL_VERSION) { + try { + const result = await this.client.request<{ size: { cols: number; rows: number } | null }>( + 'getSize', + { sessionId: id }, + LIVENESS_PROBE_TIMEOUT_MS + ) + return result.size !== null + } catch (error) { + // getSize shipped without a protocol bump; remember rejection instead of trusting the version alone. + if (!isUnknownRequestTypeError(error)) { + throw error + } + this.getSizeUnsupported = true + } + } + // Legacy listSessions can prove absence; request it directly to avoid publishing inventory audit observations. + const { sessions } = await this.client.request( + 'listSessions', + undefined, + LIVENESS_PROBE_TIMEOUT_MS + ) + return sessions.some((session) => session.sessionId === id && session.isAlive) + } catch { + return null + } + } + + /** Whether this daemon lists the session at all, alive or not; null when it can't answer. */ + listsSession(id: string): Promise { + return unlistedSession.readDaemonSessionListing(this.client, id, LIVENESS_PROBE_TIMEOUT_MS) + } + /** The daemons that share this history dir and can answer for it; a router widens this. */ private listingDaemons: () => readonly unlistedSession.SessionListingDaemon[] = () => [this] @@ -34,21 +108,20 @@ export abstract class DaemonPtySessionControl extends DaemonPtySessionLiveness { async shutdown( id: string, - opts: PtyShutdownOptions, - endpoint: DaemonEndpointIdentity | null = this.client.getDaemonIdentity() + opts: { immediate?: boolean; keepHistory?: boolean; deadlineMs?: number } ): Promise { if (opts.keepHistory && this.disconnectOnlyPromise) { throw new Error('Cannot keep history after daemon disconnect has started') } if (!opts.keepHistory) { - await this.withHistorySpawnLock(id, () => this.shutdownWithHistoryLock(id, opts, endpoint)) + await this.withHistorySpawnLock(id, () => this.shutdownWithHistoryLock(id, opts)) return } const shutdown = Promise.resolve().then(async () => { // Outside the spawn lock, which adopting the session's history takes itself. await this.ensureConnected(opts.deadlineMs) await this.adoptListedSessionForSleep(id, opts.deadlineMs).catch(() => {}) - await this.withHistorySpawnLock(id, () => this.shutdownWithHistoryLock(id, opts, endpoint)) + await this.withHistorySpawnLock(id, () => this.shutdownWithHistoryLock(id, opts)) }) this.keepHistoryShutdowns.add(shutdown) try { @@ -60,24 +133,8 @@ export abstract class DaemonPtySessionControl extends DaemonPtySessionLiveness { protected async shutdownWithHistoryLock( id: string, - opts: PtyShutdownOptions, - endpoint: DaemonEndpointIdentity | null = this.client.getDaemonIdentity() + opts: { immediate?: boolean; keepHistory?: boolean; deadlineMs?: number } ): Promise { - const original = opts.expectedIncarnationId - if ( - opts.authorizeStop && - (!original || - !endpoint || - this.protocolVersion < FENCED_TERMINATION_PROTOCOL_VERSION || - this.sessionIncarnations.get(id) !== original) - ) { - throw new Error('terminal_stop_identity_unavailable') - } - const previousRestore = this.coldRestoreCache.get(id) - const previouslySlept = this.sleepRestoreSessionIds.has(id) - const hadWriter = this.historyManager?.hasWriter(id) - let installedRestore: ColdRestorePayload | null = null - let sleepCommit: (() => void) | undefined // Connect lazily, sharing one deadline with checkpoint waits and kill; durable writes themselves remain unbounded. await this.ensureConnected(opts.deadlineMs) // Sleep may precede the first periodic checkpoint; persist the screen before killing. @@ -129,84 +186,27 @@ export abstract class DaemonPtySessionControl extends DaemonPtySessionLiveness { } : null const coldRestore = restoreInfo ? this.buildColdRestorePayload(restoreInfo) : null - sleepCommit = () => { - if (coldRestore) { - installedRestore = coldRestore - this.coldRestoreCache.set(id, coldRestore) - if (this.coldRestoreCache.has(id)) { - this.sleepRestoreSessionIds.add(id) - } - // Intentional sleep keeps the final checkpoint authoritative; physical exit must not mark history clean. - this.historyManager?.suspendSession(id) - } else if ( - detection?.status === 'unreadable' || - (detection?.status === 'restored' && detection.hasUnreadableRecovery) - ) { - this.historyManager?.suspendSession(id) + if (coldRestore) { + this.coldRestoreCache.set(id, coldRestore) + if (this.coldRestoreCache.has(id)) { + this.sleepRestoreSessionIds.add(id) } - } - } - if (opts.authorizeStop) { - if (!(await opts.authorizeStop())) { - throw new Error('terminal_stop_declined') - } - const current = this.client.getDaemonIdentity() - if ( - !current || - !endpoint || - !sameEndpointIdentity(current, endpoint) || - this.sessionIncarnations.get(id) !== original + // Intentional sleep keeps the final checkpoint authoritative; physical exit must not mark history clean. + this.historyManager?.suspendSession(id) + } else if ( + detection?.status === 'unreadable' || + (detection?.status === 'restored' && detection.hasUnreadableRecovery) ) { - throw new Error('terminal_stop_identity_changed') + this.historyManager?.suspendSession(id) } } - sleepCommit?.() try { - const result = await this.client.request( + await this.client.request( 'kill', - { - sessionId: id, - immediate: opts.immediate ?? false, - ...(opts.authorizeStop - ? { - expectedIncarnationId: original, - requireNoAgentOwner: false, - requireUnattached: false - } - : {}) - }, + { sessionId: id, immediate: opts.immediate ?? false }, remainingDaemonRequestTimeoutMs(opts.deadlineMs) ) - if ( - opts.authorizeStop && - (!isPtyFencedTerminationOutcome(result) || result.outcome === 'refused') - ) { - throw new Error('terminal_stop_unproven') - } } catch (error) { - if ( - opts.authorizeStop && - (await this.probePtyLiveness(id)) === true && - this.sessionIncarnations.get(id) === original && - endpoint - ) { - const currentEndpoint = this.client.getDaemonIdentity() - if (currentEndpoint && sameEndpointIdentity(currentEndpoint, endpoint)) { - if (installedRestore && this.coldRestoreCache.get(id) === installedRestore) { - if (previousRestore) { - this.coldRestoreCache.set(id, previousRestore) - } else { - this.coldRestoreCache.delete(id) - } - if (!previouslySlept) { - this.sleepRestoreSessionIds.delete(id) - } - } - if (hadWriter) { - this.historyManager?.registerWriter(id) - } - } - } // Gone is known for a session this adapter lost, or (after a relaunch forgot that) one whose // history is unended and that no daemon sharing the history dir may still run. if ( @@ -327,4 +327,25 @@ export abstract class DaemonPtySessionControl extends DaemonPtySessionLiveness { async getInitialCwd(id: string): Promise { return this.initialCwds.get(id) ?? '' } + + // Resize notifications can be dropped; report applied dimensions so the renderer can repair drift. + async getAppliedSize(id: string): Promise<{ cols: number; rows: number } | null> { + return await this.readAppliedSize(id, 'suppress') + } + + private async readAppliedSize( + id: string, + failureMode: 'preserve' | 'suppress' + ): Promise { + return await readDaemonAppliedPtySize({ + client: this.client, + protocolVersion: this.protocolVersion, + sessionId: id, + failureMode, + getSizeUnsupported: this.getSizeUnsupported, + markGetSizeUnsupported: () => { + this.getSizeUnsupported = true + } + }) + } } diff --git a/src/main/daemon/daemon-pty-session-liveness.ts b/src/main/daemon/daemon-pty-session-liveness.ts deleted file mode 100644 index 87748d5e794f..000000000000 --- a/src/main/daemon/daemon-pty-session-liveness.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { DaemonPtySessionInput } from './daemon-pty-session-input' -import { isUnknownRequestTypeError } from './daemon-endpoint-errors' -import { GET_SIZE_PROTOCOL_VERSION } from './daemon-protocol-version' -import { readDaemonAppliedPtySize, type DaemonAppliedPtySize } from './daemon-pty-applied-size' -import { SessionNotFoundError, type ListSessionsResult } from './types' -import type { PtySpawnResult } from '../providers/pty-provider-contract' -import * as unlistedSession from './daemon-unlisted-session' - -export const LIVENESS_PROBE_TIMEOUT_MS = 2_000 - -export abstract class DaemonPtySessionLiveness extends DaemonPtySessionInput { - async attach(id: string): Promise | void> { - await this.ensureConnected() - if (!this.canDelegateBackgroundToDaemon) { - this.setPtyBackgrounded(id, false) - } - - // Attach at the proven live size; default geometry could resize an agent TUI or accidentally create a shell. - // Preserve transport errors: treating lost contact as absence could duplicate or retire a live owner. - const size = await this.readAppliedSize(id, 'preserve') - if (!size) { - throw new SessionNotFoundError(id) - } - const result = await this.spawn({ - sessionId: id, - cols: size.cols, - rows: size.rows, - attachOnly: true - }) - if (result.exitedBeforeSpawnReply) { - throw new SessionNotFoundError(id) - } - // A restarted runtime has never seen the surviving session's title. - return result.providerSequence || result.lastTitle - ? { - ...(result.providerSequence ? { providerSequence: result.providerSequence } : {}), - ...(result.lastTitle ? { lastTitle: result.lastTitle } : {}) - } - : undefined - } - - hasPty(id: string): boolean { - return this.activeSessionIds.has(id) - } - - /** Use the same saved-history probe as spawn. */ - hasRestorableHistory(id: string): boolean { - return this.historyReader?.hasRestorableHistory(id) ?? false - } - - async probePtyLiveness(id: string): Promise { - try { - if (!this.getSizeUnsupported && this.protocolVersion >= GET_SIZE_PROTOCOL_VERSION) { - try { - const result = await this.client.request<{ size: { cols: number; rows: number } | null }>( - 'getSize', - { sessionId: id }, - LIVENESS_PROBE_TIMEOUT_MS - ) - return result.size !== null - } catch (error) { - // getSize shipped without a protocol bump; remember rejection instead of trusting the version alone. - if (!isUnknownRequestTypeError(error)) { - throw error - } - this.getSizeUnsupported = true - } - } - // Legacy listSessions can prove absence; request it directly to avoid publishing inventory audit observations. - const { sessions } = await this.client.request( - 'listSessions', - undefined, - LIVENESS_PROBE_TIMEOUT_MS - ) - return sessions.some((session) => session.sessionId === id && session.isAlive) - } catch { - return null - } - } - - /** Whether this daemon lists the session at all, alive or not; null when it can't answer. */ - listsSession(id: string): Promise { - return unlistedSession.readDaemonSessionListing(this.client, id, LIVENESS_PROBE_TIMEOUT_MS) - } - - // Resize notifications can be dropped; report applied dimensions so the renderer can repair drift. - async getAppliedSize(id: string): Promise<{ cols: number; rows: number } | null> { - return await this.readAppliedSize(id, 'suppress') - } - - protected async readAppliedSize( - id: string, - failureMode: 'preserve' | 'suppress' - ): Promise { - return await readDaemonAppliedPtySize({ - client: this.client, - protocolVersion: this.protocolVersion, - sessionId: id, - failureMode, - getSizeUnsupported: this.getSizeUnsupported, - markGetSizeUnsupported: () => { - this.getSizeUnsupported = true - } - }) - } -} diff --git a/src/main/ipc/pty/provider/shutdown-detect.ts b/src/main/ipc/pty/provider/shutdown-detect.ts index c8dddbd08c14..b43928355aca 100644 --- a/src/main/ipc/pty/provider/shutdown-detect.ts +++ b/src/main/ipc/pty/provider/shutdown-detect.ts @@ -1,17 +1,13 @@ -import { cancelDesktopTerminalRetirement } from '../../../automations/desktop-run-terminal-stop' import type { IPtyProvider } from '../../../providers/pty-provider-contract' import { ptyIncarnationById } from './ownership-state' export async function shutdownProviderAndDetectExit( provider: IPtyProvider, id: string, - opts: Parameters[1] + opts: { immediate?: boolean; keepHistory?: boolean; deadlineMs?: number } ): Promise { - if (!opts.authorizeStop) { - cancelDesktopTerminalRetirement(id) - } let providerExitObserved = false - const expectedIncarnationId = opts.expectedIncarnationId ?? ptyIncarnationById.get(id) + const expectedIncarnationId = ptyIncarnationById.get(id) const unsubscribe = provider.onExit((payload) => { if ( payload.id === id && diff --git a/src/main/ipc/pty/renderer-fenced-kill.test.ts b/src/main/ipc/pty/renderer-fenced-kill.test.ts index 9d75d673dff5..e03ea9580bc1 100644 --- a/src/main/ipc/pty/renderer-fenced-kill.test.ts +++ b/src/main/ipc/pty/renderer-fenced-kill.test.ts @@ -5,7 +5,6 @@ import { startLateExitHarness } from './daemon-late-exit-test-fixture' import { ptyIncarnationById } from './provider/ownership-state' import { installPtyKillIpcHandler } from './ipc/renderer-kill' import { shutdownProviderAndDetectExit } from './provider/shutdown-detect' -import { stopRevokers } from '../../automations/desktop-run-terminal-stop' const request = (id: string, expectedIncarnationId: string) => ({ id, @@ -15,131 +14,6 @@ const request = (id: string, expectedIncarnationId: string) => ({ }) describe('checked renderer stop route', () => { - it('revokes only the matching retirement before ordinary IPC Stop subscribes or shuts down', async () => { - const harness = await startLateExitHarness() - const matchingKey = 'renderer-stop-matching' - const unrelatedKey = 'renderer-stop-unrelated' - const release = vi.fn(() => { - stopRevokers.delete(matchingKey) - }) - const unrelated = vi.fn() - stopRevokers.set(matchingKey, { ptyId: harness.id, release }) - stopRevokers.set(unrelatedKey, { ptyId: 'other-pty', release: unrelated }) - const onExit = harness.adapter.onExit.bind(harness.adapter) - const shutdown = harness.adapter.shutdown.bind(harness.adapter) - const subscriptions: ReturnType[] = [] - const subscription = vi.spyOn(harness.adapter, 'onExit').mockImplementation((listener) => { - expect(release).toHaveBeenCalledOnce() - expect(stopRevokers.has(matchingKey)).toBe(false) - expect(unrelated).not.toHaveBeenCalled() - const unsubscribe = vi.fn(onExit(listener)) - subscriptions.push(unsubscribe) - return unsubscribe - }) - const stop = vi.spyOn(harness.adapter, 'shutdown').mockImplementation(async (id, opts) => { - expect(release).toHaveBeenCalledOnce() - expect(stopRevokers.has(matchingKey)).toBe(false) - expect(id).toBe(harness.id) - expect(ptyIncarnationById.get(id)).toBe(harness.result.incarnationId) - expect(opts).toEqual({ immediate: true, keepHistory: false }) - await shutdown(id, opts) - await harness.waitForExit() - }) - const physicalExit = vi.spyOn(harness.subprocess, 'forceKill').mockImplementation(() => { - harness.subprocess._simulateExit(137) - }) - try { - await harness.kill() - expect(stop).toHaveBeenCalledOnce() - expect(physicalExit).toHaveBeenCalledOnce() - expect(subscriptions).toHaveLength(1) - expect(subscriptions[0]).toHaveBeenCalledOnce() - expect(unrelated).not.toHaveBeenCalled() - expect(stopRevokers.has(unrelatedKey)).toBe(true) - expect(harness.providerExits).toEqual([ - { - id: harness.id, - code: 137, - incarnationId: harness.result.incarnationId, - cause: { kind: 'operator_close' } - } - ]) - expect(harness.rendererExits).toHaveLength(1) - expect(harness.runtime.captureState().connected).toBe(false) - expect((await harness.capture()).exitListenerCalls).toBe(1) - } finally { - subscription.mockRestore() - stop.mockRestore() - physicalExit.mockRestore() - stopRevokers.delete(matchingKey) - stopRevokers.delete(unrelatedKey) - await harness.dispose() - } - }) - - it('keeps retirement authorization and requires an observed matching exit, not just a shutdown ACK', async () => { - const harness = await startLateExitHarness() - const matchingKey = 'authorized-stop-matching' - const unrelatedKey = 'authorized-stop-unrelated' - const release = vi.fn() - const unrelated = vi.fn() - stopRevokers.set(matchingKey, { ptyId: harness.id, release }) - stopRevokers.set(unrelatedKey, { ptyId: 'other-pty', release: unrelated }) - const onExit = harness.adapter.onExit.bind(harness.adapter) - const subscriptions: ReturnType[] = [] - const subscription = vi.spyOn(harness.adapter, 'onExit').mockImplementation((listener) => { - expect(release).not.toHaveBeenCalled() - const unsubscribe = vi.fn(onExit(listener)) - subscriptions.push(unsubscribe) - return unsubscribe - }) - const authorizeStop = vi.fn(async () => true) - const opts = { - immediate: true, - keepHistory: false, - expectedIncarnationId: harness.result.incarnationId, - authorizeStop - } - const stop = vi.spyOn(harness.adapter, 'shutdown') - const physicalExit = vi.spyOn(harness.subprocess, 'forceKill').mockImplementation(() => { - harness.subprocess._simulateExit(137) - }) - try { - harness.pauseStream() - await expect(shutdownProviderAndDetectExit(harness.adapter, harness.id, opts)).resolves.toBe( - false - ) - expect(stop).toHaveBeenCalledExactlyOnceWith(harness.id, opts) - expect(authorizeStop).toHaveBeenCalledOnce() - expect(physicalExit).toHaveBeenCalledOnce() - expect(subscriptions).toHaveLength(1) - expect(subscriptions[0]).toHaveBeenCalledOnce() - expect(release).not.toHaveBeenCalled() - expect(unrelated).not.toHaveBeenCalled() - expect(stopRevokers.has(matchingKey)).toBe(true) - expect(stopRevokers.has(unrelatedKey)).toBe(true) - expect(harness.providerExits).toHaveLength(0) - harness.resumeStream() - await harness.waitForExit() - expect(harness.providerExits).toEqual([ - { - id: harness.id, - code: 137, - incarnationId: harness.result.incarnationId, - cause: { kind: 'operator_close' } - } - ]) - expect(harness.rendererExits).toHaveLength(1) - } finally { - subscription.mockRestore() - stop.mockRestore() - physicalExit.mockRestore() - stopRevokers.delete(matchingKey) - stopRevokers.delete(unrelatedKey) - await harness.dispose() - } - }) - it('refuses missing identity without falling through to the unfenced stop', async () => { const harness = await startLateExitHarness() try { diff --git a/src/main/ipc/pty/runtime/controller-deps.ts b/src/main/ipc/pty/runtime/controller-deps.ts index 22aac962c711..42fd2697d861 100644 --- a/src/main/ipc/pty/runtime/controller-deps.ts +++ b/src/main/ipc/pty/runtime/controller-deps.ts @@ -24,7 +24,8 @@ export type PtyRuntimeControllerDeps = PtySpawnCodexResumeDeps & { getLocalPtyProviderStartupPromise: (hostId?: ResolvedPtyHost) => Promise | undefined assertWorkspaceAcceptsNewPty: ( worktreeId: string | undefined, - sessionId?: string + sessionId?: string, + cwd?: string ) => Promise | void resolvePtySpawnStartupCwd: ( worktreeId: string | undefined, @@ -45,7 +46,7 @@ export type PtyRuntimeControllerDeps = PtySpawnCodexResumeDeps & { shutdownProviderAndDetectExit: ( provider: IPtyProvider, id: string, - opts: Parameters[1] + opts: { immediate?: boolean; keepHistory?: boolean; deadlineMs?: number } ) => Promise rememberSyntheticKillExit: (id: string, incarnationId?: string) => void rememberRetiredRejectedPty: (id: string) => void diff --git a/src/main/ipc/pty/runtime/kill.ts b/src/main/ipc/pty/runtime/kill.ts index b3228cf1e44c..cc7c39c1f1bb 100644 --- a/src/main/ipc/pty/runtime/kill.ts +++ b/src/main/ipc/pty/runtime/kill.ts @@ -180,10 +180,7 @@ export function retireRejectedPtyFromRuntimeController( export async function stopAndWaitPtyFromRuntimeController( deps: PtyRuntimeControllerDeps, ptyId: string, - opts?: Pick< - Parameters[1], - 'keepHistory' | 'deadlineMs' | 'expectedIncarnationId' | 'authorizeStop' - > + opts?: { keepHistory?: boolean; deadlineMs?: number } ): Promise { // A final relay stop is owed until the relay proves it, so an unproven one still reads as closing. const relayOwesStop = @@ -203,10 +200,7 @@ export async function stopAndWaitPtyFromRuntimeController( async function stopAndWaitPty( deps: PtyRuntimeControllerDeps, ptyId: string, - opts?: Pick< - Parameters[1], - 'keepHistory' | 'deadlineMs' | 'expectedIncarnationId' | 'authorizeStop' - > + opts?: { keepHistory?: boolean; deadlineMs?: number } ): Promise { const { runtime, @@ -215,10 +209,7 @@ async function stopAndWaitPty( shutdownProviderAndDetectExit, finishPtyShutdown } = deps - if (!opts?.authorizeStop) { - runtime?.markPtyStopRequested?.(ptyId) - } - const expectedIncarnationId = opts?.expectedIncarnationId + runtime?.markPtyStopRequested?.(ptyId) const connectionId = getPtySshConnectionId(ptyId) if (connectionId && isLegacyRelayBridgedPty(ptyId)) { // A reversible stop must not leave the bridge's durable stop behind, so the pane stays live. @@ -273,18 +264,13 @@ async function stopAndWaitPty( } return false } - const stoppingIncarnationId = expectedIncarnationId ?? ptyIncarnationById.get(ptyId) - if (expectedIncarnationId && ptyIncarnationById.get(ptyId) !== expectedIncarnationId) { - return false - } + const stoppingIncarnationId = ptyIncarnationById.get(ptyId) let providerExitObserved = false try { providerExitObserved = await shutdownProviderAndDetectExit(provider, ptyId, { immediate: true, keepHistory: opts?.keepHistory ?? false, - deadlineMs, - expectedIncarnationId, - authorizeStop: opts?.authorizeStop + deadlineMs }) } catch (err) { if (!isPtyAlreadyGoneError(err)) { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts index 8cd115e3f329..fa9f4c2ec081 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts @@ -85,6 +85,14 @@ export async function createQueuedMessageTestRig( let host = makeHost() const firstAttach = hostTestAttachParams(null, { ...(options.location ? { location: options.location } : {}), + ...(options.agent === 'claude' + ? ({ + provider: 'claude', + agent: 'claude', + providerHandle: { kind: 'claude', sessionId: THREAD, leafUuid: null }, + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/private-fixture/claude' } + } as const) + : {}), ...(options.sessionId ? { envelope: { diff --git a/src/main/persistence/applying-settings/persistence-legacy-automation-twin-host.test.ts b/src/main/persistence/applying-settings/persistence-legacy-automation-twin-host.test.ts index 3dc6419fe6d1..0a163da988ec 100644 --- a/src/main/persistence/applying-settings/persistence-legacy-automation-twin-host.test.ts +++ b/src/main/persistence/applying-settings/persistence-legacy-automation-twin-host.test.ts @@ -116,18 +116,16 @@ describe('legacy automation on a repo id two hosts share', () => { it('captures the only host on its first run, which still launches, and keeps it', async () => { seed([localRow], legacyAutomation({ runContext: null })) const store = createStore() - const send = vi.fn(async () => ({ workspaceId: 'wt1', terminalSessionId: 'tab-1' })) - const service = new AutomationService(store, { headlessDispatcher: send, tickMs: 60_000 }) + const send = vi.fn() + const service = new AutomationService(store, { tickMs: 60_000 }) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: dispatch reads only isDestroyed and send. service.setWebContents({ isDestroyed: () => false, send } as never) service.setRendererReady() const run = await service.runNow('legacy-1') - expect(run.status).toBe('dispatched') - expect(send).toHaveBeenCalledWith( - expect.objectContaining({ automation: expect.any(Object), run: expect.any(Object) }) - ) + expect(run.status).toBe('dispatching') + expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.any(Object)) const stamped = storedAutomation(store).runContext expect(stamped).toMatchObject({ hostId: 'local', repoId: 'twin', path: '/laptop/twin' }) diff --git a/src/main/providers/local-pty-provider-shutdown.test.ts b/src/main/providers/local-pty-provider-shutdown.test.ts index 5277ee1576ca..70c037319ec9 100644 --- a/src/main/providers/local-pty-provider-shutdown.test.ts +++ b/src/main/providers/local-pty-provider-shutdown.test.ts @@ -1,7 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type * as MacosTccLoginShell from './macos-tcc-login-shell' import type * as PosixPtyProcessTable from '../pty/posix-pty-process-table' -import type * as DescendantTermination from '../pty-descendant-termination' const { existsSyncMock, @@ -134,30 +133,6 @@ import { type LocalPtyMockProcess } from './local-pty-provider-test-harness' -const actual = await vi.importActual('../pty-descendant-termination') - -async function installActualShutdownSweep() { - const capture = { - capturedAtMs: Date.parse('Tue Jul 14 12:01:00 2026'), - rows: [ - { pid: 12345, ppid: 1, pgid: 12345, startedAt: 'Tue Jul 14 12:00:00 2026' }, - { pid: 12346, ppid: 12345, pgid: 12346, startedAt: 'Tue Jul 14 12:00:00 2026' } - ] - } - const readTable = vi.fn(async () => capture) - const terminateDescendants = vi.fn( - async (_snapshot: DescendantTermination.DescendantSnapshot) => {} - ) - killWithDescendantSweepMock.mockImplementation( - ( - pid: number, - killRoot: () => void, - deps: Parameters[2] - ) => actual.killWithDescendantSweep(pid, killRoot, { ...deps, readTable, terminateDescendants }) - ) - return { capture, readTable, terminateDescendants } -} - describe('LocalPtyProvider', () => { let provider: LocalPtyProvider let mockProc: LocalPtyMockProcess @@ -521,143 +496,30 @@ describe('LocalPtyProvider', () => { expect(spawnMock).toHaveBeenCalledTimes(spawnCallsBefore + 2) }) - it.each(['synchronous', 'asynchronous'] as const)( - 'coalesces duplicate shutdown through detached descendants and %s physical exit', - async (exitTiming) => { - const sweep = await installActualShutdownSweep() - const table = Promise.withResolvers() - const descendants = Promise.withResolvers() - sweep.readTable.mockReturnValueOnce(table.promise) - sweep.terminateDescendants.mockReturnValueOnce(descendants.promise) - const killSpy = vi.fn(() => { - if (exitTiming === 'synchronous') { - exitCb?.({ exitCode: 137 }) - } - }) - mockProc.kill = killSpy - const { id } = await provider.spawn({ - cols: 80, - rows: 24, - launchAgent: 'claude' - }) + it('coalesces duplicate shutdown while descendant sweep is pending', async () => { + let releaseSweep!: () => void + killWithDescendantSweepMock.mockImplementation( + (_rootPid: number, killRoot: () => void) => + new Promise((resolve) => { + releaseSweep = () => { + killRoot() + resolve() + } + }) + ) + const { id } = await provider.spawn({ + cols: 80, + rows: 24, + launchAgent: 'claude' + }) - const first = provider.shutdown(id, { immediate: true }) - const second = provider.shutdown(id, { immediate: true }) - let settled = false - const completion = Promise.all([first, second]).then(() => { - settled = true - }) - expect(killWithDescendantSweepMock).toHaveBeenCalledOnce() - expect(killSpy).not.toHaveBeenCalled() - table.resolve(sweep.capture) - await vi.waitFor(() => expect(sweep.terminateDescendants).toHaveBeenCalledOnce()) - expect(sweep.terminateDescendants.mock.calls[0][0].descendants).toEqual([ - sweep.capture.rows[1] - ]) - expect(killSpy).not.toHaveBeenCalled() - expect(settled).toBe(false) - descendants.resolve() - await vi.waitFor(() => expect(killSpy).toHaveBeenCalledOnce()) - if (exitTiming === 'asynchronous') { - expect(settled).toBe(false) - expect(provider.hasPty(id)).toBe(true) - exitCb?.({ exitCode: 137 }) - } - await completion - expect(provider.hasPty(id)).toBe(false) - expect(killWithDescendantSweepMock).toHaveBeenCalledOnce() - } - ) - - it.each(['capture', 'callback', 'denied', 'accepted'] as const)( - 'ordinary Stop preserves full shutdown with an optional %s transaction', - async (stage) => { - const sweep = await installActualShutdownSweep() - const table = Promise.withResolvers() - const authority = Promise.withResolvers() - const entered = Promise.withResolvers() - const descendants = Promise.withResolvers() - const authorizeStop = vi.fn(() => { - entered.resolve() - return authority.promise - }) - if (stage === 'capture') { - sweep.readTable.mockReturnValueOnce(table.promise) - } - sweep.terminateDescendants.mockReturnValueOnce(descendants.promise) - const killSpy = vi.fn() - mockProc.kill = killSpy - const args = { - cols: 80, - rows: 24, - sessionId: 'optional-stop', - launchAgent: 'claude' as const - } - const { id, incarnationId } = await provider.spawn(args) - const optional = provider.shutdown(id, { - immediate: true, - expectedIncarnationId: incarnationId, - authorizeStop - }) - const optionalResult = - stage === 'accepted' - ? expect(optional).resolves.toBeUndefined() - : expect(optional).rejects.toThrow('terminal_stop_declined') - if (stage !== 'capture') { - await entered.promise - } - if (stage === 'denied') { - authority.resolve(false) - } else if (stage === 'accepted') { - authority.resolve(true) - await vi.waitFor(() => expect(sweep.terminateDescendants).toHaveBeenCalledOnce()) - } - const ordinary = provider.shutdown(id, { immediate: true }) - const duplicate = provider.shutdown(id, { immediate: true }) - await vi.waitFor(() => expect(sweep.terminateDescendants).toHaveBeenCalledOnce()) - expect(sweep.terminateDescendants.mock.calls[0][0].descendants).toEqual([ - sweep.capture.rows[1] - ]) - expect(killSpy).not.toHaveBeenCalled() - if (stage === 'denied') { - await optionalResult - } - const replacement = createLocalPtyMockProcess({ - get: () => exitCb, - set: (cb) => { - exitCb = cb - } - }) - spawnMock.mockReturnValueOnce(replacement) - const callsBefore = spawnMock.mock.calls.length - const respawn = provider.spawn(args) - await Promise.resolve() - expect(spawnMock).toHaveBeenCalledTimes(callsBefore) - descendants.resolve() - await vi.waitFor(() => expect(killSpy).toHaveBeenCalledOnce()) - let settled = false - void ordinary.then(() => { - settled = true - }) - await Promise.resolve() - expect(settled).toBe(false) - exitCb?.({ exitCode: 137 }) - await Promise.all([ordinary, duplicate]) - const restarted = await respawn - expect(restarted.incarnationId).not.toBe(incarnationId) - if (stage === 'capture') { - table.resolve(sweep.capture) - } else { - authority.resolve(true) - } - await optionalResult - expect(replacement.kill).not.toHaveBeenCalled() - expect(provider.hasPty(id)).toBe(true) - expect(sweep.terminateDescendants).toHaveBeenCalledOnce() - expect(killWithDescendantSweepMock).toHaveBeenCalledTimes(stage === 'accepted' ? 1 : 2) - expect(authorizeStop).toHaveBeenCalledTimes(stage === 'capture' ? 0 : 1) - } - ) + const first = provider.shutdown(id, { immediate: true }) + const second = provider.shutdown(id, { immediate: true }) + expect(killWithDescendantSweepMock).toHaveBeenCalledOnce() + releaseSweep() + await Promise.all([first, second]) + expect(killWithDescendantSweepMock).toHaveBeenCalledOnce() + }) it('does not terminate descendants after the tracked root exits mid-sweep', async () => { const terminateDescendants = vi.fn() diff --git a/src/main/providers/local-pty-provider-state.ts b/src/main/providers/local-pty-provider-state.ts index fe4730840a0e..956934904e4d 100644 --- a/src/main/providers/local-pty-provider-state.ts +++ b/src/main/providers/local-pty-provider-state.ts @@ -1,7 +1,7 @@ import type * as pty from 'node-pty' import type { PhysicalExitTracker } from '../../shared/physical-exit-tracker' import type { PtyStartupIngress } from '../../shared/pty-startup-ingress' -import type { IPtyProvider, PtyShutdownOptions } from './pty-provider-contract' +import type { IPtyProvider } from './pty-provider-contract' import type { PtyDataEvent } from './pty-provider-events' import { getSpawnedShellName, normalizeLocalCallerSessionId } from './local-pty-launch-helpers' @@ -10,7 +10,6 @@ export type PtyShutdownOperation = { immediate: boolean rootSignalled: boolean proc: pty.IPty - authorizeStop?: PtyShutdownOptions['authorizeStop'] } export type PendingLocalPtySpawn = { diff --git a/src/main/providers/local-pty-provider.ts b/src/main/providers/local-pty-provider.ts index 496238b572c7..e8b6c27ec88b 100644 --- a/src/main/providers/local-pty-provider.ts +++ b/src/main/providers/local-pty-provider.ts @@ -107,7 +107,7 @@ export class LocalPtyProvider implements IPtyProvider { return getLocalPtyAppliedSize(id) } - shutdown(id: string, opts: Parameters[1]): Promise { + shutdown(id: string, opts: { immediate?: boolean; keepHistory?: boolean }): Promise { return shutdownLocalPty(id, opts) } diff --git a/src/main/providers/local-pty-termination.ts b/src/main/providers/local-pty-termination.ts index 156b39a9e679..355a987e05fa 100644 --- a/src/main/providers/local-pty-termination.ts +++ b/src/main/providers/local-pty-termination.ts @@ -1,4 +1,3 @@ -import type { PtyShutdownOptions } from './pty-provider-contract' import type * as pty from 'node-pty' import { PhysicalExitTracker } from '../../shared/physical-exit-tracker' import { killWithDescendantSweep } from '../pty-descendant-termination' @@ -18,7 +17,6 @@ import { ptyForceKillTimers, ptyPhysicalExits, ptyProcesses, - ptyIncarnations, ptyShutdownOperations, ptyTerminationMode, ptyLoadGeneration, @@ -189,30 +187,12 @@ function requestTrackedPtyShutdown(id: string, proc: pty.IPty, immediate: boolea async function shutdownTrackedPty( id: string, proc: pty.IPty, - operation: PtyShutdownOperation, - opts: PtyShutdownOptions + operation: PtyShutdownOperation ): Promise { const physicalExit = ptyPhysicalExits.get(id) - const ownsOperation = (): boolean => - ptyProcesses.get(id) === proc && ptyShutdownOperations.get(id) === operation - const authorize = opts.authorizeStop - const authorizeStop = authorize - ? async (): Promise => { - if ( - !ownsOperation() || - !(await authorize()) || - !ownsOperation() || - ptyIncarnations.get(id) !== opts.expectedIncarnationId - ) { - return false - } - operation.authorizeStop = undefined - return true - } - : undefined const signalRoot = (): void => { // Natural exit can race descendant capture; never signal after losing this PTY handle. - if (!ownsOperation()) { + if (ptyProcesses.get(id) !== proc) { return } // Cancel startup delivery now, but keep the exit listener and ownership maps until node-pty reports physical exit. @@ -223,29 +203,22 @@ async function shutdownTrackedPty( if (ptyAgentSessionIds.has(id) || operation.immediate) { // Typed agents also detach tool process groups; immediate close must snapshot before root exit. await killWithDescendantSweep(proc.pid, signalRoot, { - ownsRoot: ownsOperation, - authorizeStop, + ownsRoot: () => ptyProcesses.get(id) === proc, terminateOwnedTree: () => terminatePtyJob(proc), terminateDescendants: terminateShutdownDescendants, // Group SIGKILL must wait out the SIGTERM grace so agents can run exit hooks (Claude SessionEnd). awaitEscalation: () => operation.immediate }) } else { - if (authorizeStop && !(await authorizeStop())) { - throw new Error('terminal_stop_declined') - } signalRoot() } await waitForPtyPhysicalExit(id, physicalExit) } -export async function shutdownLocalPty(id: string, opts: PtyShutdownOptions): Promise { - if ( - opts.authorizeStop && - (!opts.expectedIncarnationId || ptyIncarnations.get(id) !== opts.expectedIncarnationId) - ) { - throw new Error('terminal_stop_identity_changed') - } +export async function shutdownLocalPty( + id: string, + opts: { immediate?: boolean; keepHistory?: boolean } +): Promise { cancelPendingLocalPtySpawns(id) const pending = ptyShutdownOperations.get(id) if (pending) { @@ -255,25 +228,21 @@ export async function shutdownLocalPty(id: string, opts: PtyShutdownOptions): Pr requestTrackedPtyShutdown(id, pending.proc, true) } } - if (opts.authorizeStop || !pending.authorizeStop || pending.rootSignalled) { - await pending.promise - return - } + await pending.promise + return } const proc = ptyProcesses.get(id) if (!proc) { return } - const completion = Promise.withResolvers() const entry: PtyShutdownOperation = { - promise: completion.promise, + promise: Promise.resolve(), immediate: opts.immediate === true, rootSignalled: false, - proc, - authorizeStop: opts.authorizeStop + proc } + entry.promise = shutdownTrackedPty(id, proc, entry) ptyShutdownOperations.set(id, entry) - void shutdownTrackedPty(id, proc, entry, opts).then(completion.resolve, completion.reject) try { await entry.promise } finally { diff --git a/src/main/providers/pty-provider-contract.ts b/src/main/providers/pty-provider-contract.ts index 4e116093c91c..ebf8dd132370 100644 --- a/src/main/providers/pty-provider-contract.ts +++ b/src/main/providers/pty-provider-contract.ts @@ -167,7 +167,18 @@ export type IPtyProvider = { supportsForegroundProcessEvidence?(options?: { signal?: AbortSignal }): Promise // Absolute deadlines bound leaf RPCs within the destructive sweep budget; each leaf converts to a relative timeout. - shutdown(id: string, opts: PtyShutdownOptions): Promise + shutdown( + id: string, + opts: { + immediate?: boolean + keepHistory?: boolean + deadlineMs?: number + expectedIncarnationId?: PtyIncarnationId + /** Require the host-attested creator and current authenticated client to match before destructive ownership-based stops. + * Optional/ignored on older hosts; ordinary teardown and unattested revived PTYs may omit it. */ + expectedOwnerClientInstanceId?: string + } + ): Promise sendSignal(id: string, signal: string): Promise getCwd(id: string): Promise getInitialCwd(id: string): Promise @@ -217,15 +228,3 @@ export type IPtyProvider = { }) => void ): () => void } - -export type PtyShutdownOptions = { - immediate?: boolean - keepHistory?: boolean - deadlineMs?: number - expectedIncarnationId?: PtyIncarnationId - /** Require the host-attested creator and current authenticated client to match before destructive ownership-based stops. - * Optional/ignored on older hosts; ordinary teardown and unattested revived PTYs may omit it. */ - expectedOwnerClientInstanceId?: string - /** In-process final veto after provider preparation; never serialized. */ - authorizeStop?: () => Promise -} diff --git a/src/main/pty-descendant-snapshot.ts b/src/main/pty-descendant-snapshot.ts deleted file mode 100644 index a70c449eb35d..000000000000 --- a/src/main/pty-descendant-snapshot.ts +++ /dev/null @@ -1,133 +0,0 @@ -import type { ProcessTableRow } from './pty-process-table-parser' - -export const DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000 - -export type ProcessTableCapture = { - rows: ProcessTableRow[] - /** Start boundary of the scan that produced rows, never a later consumer's time. */ - capturedAtMs: number -} - -export type ProcessTableReader = (timeoutMs?: number) => Promise - -export type PosixProcessIdentity = Pick - -export type DescendantSnapshot = { - root?: PosixProcessIdentity - rootPgid: number | null - descendants: ProcessTableRow[] - /** Wall-clock boundary for an unmerged snapshot (or legacy callers). */ - capturedAtMs: number - /** Per-PID identity boundaries for merged captures. */ - capturedAtMsByPid?: Readonly> - /** Fresh ancestry proves ownership despite lstart’s second-resolution timestamps; retained merge rows do not. */ - reDerivedPids?: ReadonlySet -} - -/** Share only scans not yet started; later requests need fresh identities before signalling. */ -export function createProcessTableSnapshotReader( - readFresh: ProcessTableReader -): ProcessTableReader { - let queued: { promise: Promise; started: boolean } | null = null - - return (timeoutMs) => { - if (queued && !queued.started) { - return queued.promise - } - - const entry: { promise: Promise; started: boolean } = { - promise: Promise.resolve(undefined as never), - started: false - } - entry.promise = Promise.resolve().then(() => { - // Start each later request’s scan within its own deadline, without queuing behind an older one. - entry.started = true - return readFresh(timeoutMs) - }) - queued = entry - const clearQueued = (): void => { - if (queued === entry) { - queued = null - } - } - void entry.promise.then(clearQueued, clearQueued) - return entry.promise - } -} - -export function readProcessTableBeforeDeadline( - readTable: ProcessTableReader, - timeoutMs: number -): Promise { - return new Promise((resolve) => { - let settled = false - const finish = (capture: ProcessTableCapture | null): void => { - if (settled) { - return - } - settled = true - clearTimeout(timer) - resolve(capture) - } - const timer = setTimeout(() => finish(null), timeoutMs) - timer.unref?.() - try { - void readTable(timeoutMs).then( - (rows) => finish(rows), - () => finish(null) - ) - } catch { - finish(null) - } - }) -} - -export function collectDescendantRows( - rootPid: number, - table: ProcessTableRow[], - capturedAtMs = Date.now() -): DescendantSnapshot { - const childrenByPpid = new Map() - let rootRow: ProcessTableRow | null = null - let duplicateRoot = false - for (const row of table) { - if (row.pid === rootPid) { - // Duplicate root rows from a non-atomic read leave its identity ambiguous. - duplicateRoot = rootRow !== null - rootRow ??= row - continue - } - const siblings = childrenByPpid.get(row.ppid) - if (siblings) { - siblings.push(row) - } else { - childrenByPpid.set(row.ppid, [row]) - } - } - // After root exit, descendants reparent; remaining rows with its old PID as parent may reflect PID reuse. - if (!rootRow || duplicateRoot) { - return { rootPgid: null, descendants: [], capturedAtMs } - } - const descendants: ProcessTableRow[] = [] - const queue = [rootPid] - const visited = new Set(queue) - for (let nextIndex = 0; nextIndex < queue.length; nextIndex += 1) { - const pid = queue[nextIndex] - for (const child of childrenByPpid.get(pid) ?? []) { - // Non-atomic ps output can contain duplicate or cyclic rows; never loop on them. - if (visited.has(child.pid)) { - continue - } - visited.add(child.pid) - descendants.push(child) - queue.push(child.pid) - } - } - return { - root: { pid: rootRow.pid, startedAt: rootRow.startedAt }, - rootPgid: rootRow.pgid, - descendants, - capturedAtMs, - reDerivedPids: new Set(descendants.map((row) => row.pid)) - } -} diff --git a/src/main/pty-descendant-stop-authorization.test.ts b/src/main/pty-descendant-stop-authorization.test.ts deleted file mode 100644 index 191b2236ae64..000000000000 --- a/src/main/pty-descendant-stop-authorization.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { it, expect, vi } from 'vitest' -import { killWithDescendantSweep } from './pty-descendant-termination' - -it.each(['linux', 'win32'] as const)( - 'runs the last veto after %s process preparation and outside destructive finally', - async (platform) => { - const prepared = Promise.withResolvers() - const release = Promise.withResolvers() - const authorizeStop = vi.fn(async () => false) - const killRoot = vi.fn() - const terminateOwnedTree = vi.fn(() => 'terminated' as const) - const killWindowsTree = vi.fn(async () => {}) - const sendSignal = vi.fn() - const pending = killWithDescendantSweep(4242, killRoot, { - platform, - authorizeStop, - killWindowsTree, - terminateOwnedTree, - sendSignal, - readTable: async () => { - prepared.resolve() - await release.promise - return { - rows: [{ pid: 4242, ppid: 1, pgid: 4242, startedAt: 'Tue Jul 14 12:00:00 2026' }], - capturedAtMs: Date.parse('Tue Jul 14 12:01:00 2026') - } - }, - verifyTreeKillTarget: async () => { - prepared.resolve() - await release.promise - return 'own' - } - }) - const denied = expect(pending).rejects.toThrow('terminal_stop_declined') - await prepared.promise - expect(authorizeStop).not.toHaveBeenCalled() - release.resolve() - await denied - expect(authorizeStop).toHaveBeenCalledOnce() - expect(killRoot).not.toHaveBeenCalled() - expect(terminateOwnedTree).not.toHaveBeenCalled() - expect(killWindowsTree).not.toHaveBeenCalled() - expect(sendSignal).not.toHaveBeenCalled() - } -) diff --git a/src/main/pty-descendant-termination.ts b/src/main/pty-descendant-termination.ts index 4f616448dfe5..a46ca7d65894 100644 --- a/src/main/pty-descendant-termination.ts +++ b/src/main/pty-descendant-termination.ts @@ -6,35 +6,37 @@ import { type WindowsTreeKillTarget } from './windows-pty-root-identity' import { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' -import { - createProcessTableSnapshotReader, - readProcessTableBeforeDeadline, - collectDescendantRows, - type DescendantSnapshot, - DESCENDANT_SNAPSHOT_TIMEOUT_MS, - type ProcessTableCapture, - type ProcessTableReader -} from './pty-descendant-snapshot' export { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' -export { - createProcessTableSnapshotReader, - readProcessTableBeforeDeadline, - collectDescendantRows, - type PosixProcessIdentity, - type DescendantSnapshot, - DESCENDANT_SNAPSHOT_TIMEOUT_MS, - type ProcessTableCapture, - type ProcessTableReader -} from './pty-descendant-snapshot' export const DESCENDANT_KILL_GRACE_MS = 2_000 - -export type SignalSender = (pid: number, signal: NodeJS.Signals) => void - +export const DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000 // Busy hosts can exceed execFile’s 1MB default; truncated output would omit descendants. const PS_MAX_BUFFER_BYTES = 32 * 1024 * 1024 +export type PosixProcessIdentity = Pick + +export type DescendantSnapshot = { + root?: PosixProcessIdentity + rootPgid: number | null + descendants: ProcessTableRow[] + /** Wall-clock boundary for an unmerged snapshot (or legacy callers). */ + capturedAtMs: number + /** Per-PID identity boundaries for merged captures. */ + capturedAtMsByPid?: Readonly> + /** Fresh ancestry proves ownership despite lstart’s second-resolution timestamps; retained merge rows do not. */ + reDerivedPids?: ReadonlySet +} + +export type ProcessTableCapture = { + rows: ProcessTableRow[] + /** Start boundary of the scan that produced rows, never a later consumer's time. */ + capturedAtMs: number +} + +export type ProcessTableReader = (timeoutMs?: number) => Promise +export type SignalSender = (pid: number, signal: NodeJS.Signals) => void + function readFreshProcessTable( timeoutMs = DESCENDANT_SNAPSHOT_TIMEOUT_MS ): Promise { @@ -62,8 +64,116 @@ function readFreshProcessTable( }) } +/** Share only scans not yet started; later requests need fresh identities before signalling. */ +export function createProcessTableSnapshotReader( + readFresh: ProcessTableReader +): ProcessTableReader { + let queued: { promise: Promise; started: boolean } | null = null + + return (timeoutMs) => { + if (queued && !queued.started) { + return queued.promise + } + + const entry: { promise: Promise; started: boolean } = { + promise: Promise.resolve(undefined as never), + started: false + } + entry.promise = Promise.resolve().then(() => { + // Start each later request’s scan within its own deadline, without queuing behind an older one. + entry.started = true + return readFresh(timeoutMs) + }) + queued = entry + const clearQueued = (): void => { + if (queued === entry) { + queued = null + } + } + void entry.promise.then(clearQueued, clearQueued) + return entry.promise + } +} + export const readProcessTable = createProcessTableSnapshotReader(readFreshProcessTable) +export function readProcessTableBeforeDeadline( + readTable: ProcessTableReader, + timeoutMs: number +): Promise { + return new Promise((resolve) => { + let settled = false + const finish = (capture: ProcessTableCapture | null): void => { + if (settled) { + return + } + settled = true + clearTimeout(timer) + resolve(capture) + } + const timer = setTimeout(() => finish(null), timeoutMs) + timer.unref?.() + try { + void readTable(timeoutMs).then( + (rows) => finish(rows), + () => finish(null) + ) + } catch { + finish(null) + } + }) +} + +export function collectDescendantRows( + rootPid: number, + table: ProcessTableRow[], + capturedAtMs = Date.now() +): DescendantSnapshot { + const childrenByPpid = new Map() + let rootRow: ProcessTableRow | null = null + let duplicateRoot = false + for (const row of table) { + if (row.pid === rootPid) { + // Duplicate root rows from a non-atomic read leave its identity ambiguous. + duplicateRoot = rootRow !== null + rootRow ??= row + continue + } + const siblings = childrenByPpid.get(row.ppid) + if (siblings) { + siblings.push(row) + } else { + childrenByPpid.set(row.ppid, [row]) + } + } + // After root exit, descendants reparent; remaining rows with its old PID as parent may reflect PID reuse. + if (!rootRow || duplicateRoot) { + return { rootPgid: null, descendants: [], capturedAtMs } + } + const descendants: ProcessTableRow[] = [] + const queue = [rootPid] + const visited = new Set(queue) + for (let nextIndex = 0; nextIndex < queue.length; nextIndex += 1) { + const pid = queue[nextIndex] + for (const child of childrenByPpid.get(pid) ?? []) { + // Non-atomic ps output can contain duplicate or cyclic rows; never loop on them. + if (visited.has(child.pid)) { + continue + } + visited.add(child.pid) + descendants.push(child) + queue.push(child.pid) + } + } + return { + root: { pid: rootRow.pid, startedAt: rootRow.startedAt }, + rootPgid: rootRow.pgid, + descendants, + capturedAtMs, + reDerivedPids: new Set(descendants.map((row) => row.pid)) + } +} + type SnapshotDeps = { readTable?: ProcessTableReader platform?: NodeJS.Platform @@ -92,7 +202,6 @@ export async function captureDescendantSnapshot( type KillSweepDeps = SnapshotDeps & TerminateDeps & { ownsRoot?: () => boolean - authorizeStop?: () => Promise /** Shutdown can retain the owner until descendant escalation finishes. */ terminateDescendants?: (snapshot: DescendantSnapshot) => void | Promise awaitEscalation?: boolean | (() => boolean) @@ -110,13 +219,6 @@ export async function killWithDescendantSweep( ): Promise { const platform = deps.platform ?? process.platform if (platform === 'win32') { - const verify = deps.verifyTreeKillTarget ?? verifyWindowsTreeKillTarget - const preparedTarget = deps.authorizeStop - ? await verify(rootPid).catch((): WindowsTreeKillTarget => 'unknown') - : null - if (deps.authorizeStop && !(await deps.authorizeStop())) { - throw new Error('terminal_stop_declined') - } try { if ((deps.ownsRoot?.() ?? true) && Number.isInteger(rootPid) && rootPid > 0) { // Owned jobs survive PID reuse and include descendants reparented away from the shell. @@ -125,8 +227,7 @@ export async function killWithDescendantSweep( } // ConPTY closes the shell handle before JS sees exit; require OS identity to reject recycled PIDs. const verify = deps.verifyTreeKillTarget ?? verifyWindowsTreeKillTarget - const target = - preparedTarget ?? (await verify(rootPid).catch((): WindowsTreeKillTarget => 'unknown')) + const target = await verify(rootPid).catch((): WindowsTreeKillTarget => 'unknown') // Re-check ownership: the identity query awaits, so exit can land meanwhile. if (target === 'own' && (deps.ownsRoot?.() ?? true)) { const killTree = @@ -143,9 +244,6 @@ export async function killWithDescendantSweep( } const snapshot = await captureDescendantSnapshot(rootPid, deps) - if (deps.authorizeStop && !(await deps.authorizeStop())) { - throw new Error('terminal_stop_declined') - } let descendants: void | Promise = undefined const awaitEscalation = typeof deps.awaitEscalation === 'function' ? deps.awaitEscalation() : deps.awaitEscalation diff --git a/src/main/runtime/construction/runtime-host-services.ts b/src/main/runtime/construction/runtime-host-services.ts index d5d3463902fc..076a75c392f2 100644 --- a/src/main/runtime/construction/runtime-host-services.ts +++ b/src/main/runtime/construction/runtime-host-services.ts @@ -222,7 +222,7 @@ export abstract class OrcaRuntimeWithPreservedBranchCleanup extends OrcaRuntimeW const scope = await this.resolveTerminalWorkspaceLaunchScope(`id:${candidate.worktreeId}`) const resolved = scope.folderWorkspace ? this.folderWorkspaceToResolvedWorktree(scope.folderWorkspace) - : await this.resolveWorktreeSelector(`id:${scope.id}`) + : await this.resolveGitWorktreeSelector(`id:${scope.id}`) return { scope, resolved } }, refreshInventory: (worktrees, connectionId) => diff --git a/src/main/runtime/rpc/methods/agent-launch-replay.ts b/src/main/runtime/rpc/methods/agent-launch-replay.ts index 55db3e86f52f..ad576489731b 100644 --- a/src/main/runtime/rpc/methods/agent-launch-replay.ts +++ b/src/main/runtime/rpc/methods/agent-launch-replay.ts @@ -101,7 +101,7 @@ function readsUnconfirmedLaunchPrompt( /** Resolve the current handle by durable pane key when PTY incarnation or host re-adoption changed it. * Keep the recorded handle for an unknown pane: shipped clients require one, and an exited terminal is truthful. */ -export function withLiveTerminalHandle( +function withLiveTerminalHandle( recorded: AgentLaunchResult, runtime: Pick ): AgentLaunchResult { diff --git a/src/main/runtime/rpc/methods/agent-launch-surfaces.ts b/src/main/runtime/rpc/methods/agent-launch-surfaces.ts index f53b6ed14904..39a67f57c556 100644 --- a/src/main/runtime/rpc/methods/agent-launch-surfaces.ts +++ b/src/main/runtime/rpc/methods/agent-launch-surfaces.ts @@ -1,4 +1,3 @@ -import type { AgentLaunchResult } from '../../../../shared/agent-launch-intent' import { terminalImageViewerSupported } from '../../terminal-image-viewer-env' /** Use ordinary user-facing terminal/chat creation; worker factories add redrive, mailbox and background-tab behavior. * The executor selects surface and prompt delivery; this factory supplies the wire-shaped runtime calls. */ @@ -35,14 +34,6 @@ import { type AgentLaunchView } from './agent-launch-tab-publication' -export type AgentLaunchHostPolicy = { - terminalTitle?: string - suppressStartupUpdatePrompt?: true - unprovableHost?: 'write-unless-shell' - onWorkspaceCreated?: (worktreeId: string) => void - onSurfacePublished?: (result: AgentLaunchResult) => void -} - /** Replay-safe launches keep the nested attach in the same stable caller namespace as the launch. */ export function agentLaunchSurfaceFactory( context: RpcContext, @@ -52,8 +43,7 @@ export function agentLaunchSurfaceFactory( callerPresentsSurface = false, terminalSpawn: TerminalSpawnDispatch = trackTerminalSpawnDispatch(), // Read the early pane at spawn: publication and user close can finish after admission. - view: AgentLaunchView = { early: null, presentation: undefined }, - policy: AgentLaunchHostPolicy = {} + view: AgentLaunchView = { early: null, presentation: undefined } ): AgentLaunchSurfaceFactory { const movesHostWindow = agentLaunchMovesHostWindow(context) const { early: earlyTab, presentation } = view @@ -152,8 +142,6 @@ export function agentLaunchSurfaceFactory( const created = context.runtime.createTerminal(`id:${worktreeId}`, { // Let the runtime build the configured launcher: agent ids are not commands (cursor uses cursor-agent). startupAgent: agent, - ...(policy.terminalTitle ? { title: policy.terminalTitle } : {}), - ...(policy.suppressStartupUpdatePrompt ? { suppressStartupUpdatePrompt: true } : {}), terminalImageViewerSupported: terminalImageViewerSupported(context), // The runtime reports typed-line prompt carry; paste only when the command did not carry it. ...(startupPrompt @@ -212,10 +200,7 @@ export function agentLaunchSurfaceFactory( return runtime.deliverStartupFollowup( handle, { agent, prompt: prompt.text }, - { - agentLaunch: policy.unprovableHost !== 'write-unless-shell', - ...(signal ? { signal } : {}) - } + { agentLaunch: true, ...(signal ? { signal } : {}) } ) } return deliverTerminalAgentLaunchPrompt({ @@ -223,7 +208,6 @@ export function agentLaunchSurfaceFactory( handle, agent, freshLaunch, - ...(policy.unprovableHost ? { unprovableHost: policy.unprovableHost } : {}), text: prompt.text, ...(signal ? { signal } : {}) }) diff --git a/src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts b/src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts index 23a5432344fa..88317333bd22 100644 --- a/src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts +++ b/src/main/runtime/rpc/methods/agent-launch-worktree-creation.ts @@ -1,4 +1,3 @@ -import type { AgentLaunchHostPolicy } from './agent-launch-surfaces' /** Terminal launches create agent-first worktrees; structured launches create the workspace without an agent and add chat afterwards. * The executor chooses; setup, default tabs, provenance and lineage use the normal create path. */ @@ -29,8 +28,7 @@ const STRUCTURED_SETUP_WAIT_TIMEOUT_MS = 60_000 export function agentLaunchWorkspaceFactory( context: RpcContext, - agent: TuiAgent, - policy: AgentLaunchHostPolicy = {} + agent: TuiAgent ): AgentLaunchWorkspaceFactory { return { createFolderWorkspace: agentLaunchFolderWorkspaceCreator(context, agent), @@ -98,16 +96,8 @@ export function agentLaunchWorkspaceFactory( ...(accountEnv ? { startupAccountEnv: { ...accountEnv } } : {}), // Record the launch's agent on the workspace even when it has no startup terminal. createdWithAgent: agent, - ...(policy.suppressStartupUpdatePrompt ? { startupSuppressUpdatePrompt: true } : {}), ...(promisedAgentChat ? { promisedAgentChat } : {}), - onWorkspaceCreated: (id) => { - try { - policy.onWorkspaceCreated?.(id) - } catch (error) { - console.warn('[agent-launch] workspace bookkeeping failed', error) - } - onWorkspaceCreated?.(id) - }, + ...(onWorkspaceCreated ? { onWorkspaceCreated } : {}), // Chats have no startup command to sequence after setup; provision setup synchronously and return its completion token. awaitTerminalProvisioning: true, observeSetupCompletion: true diff --git a/src/main/runtime/rpc/methods/agent-launch.test.ts b/src/main/runtime/rpc/methods/agent-launch.test.ts index 1901690dfb60..d5abaeff03eb 100644 --- a/src/main/runtime/rpc/methods/agent-launch.test.ts +++ b/src/main/runtime/rpc/methods/agent-launch.test.ts @@ -1,7 +1,6 @@ /** Exercise RPC authorization, parsing and all surface factories; structured creates must omit startupAgent while legacy worktree.create retains its terminal contract. */ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { deliverStartupFollowupPrompt } from '../../runtime-worktree-startup-readiness' import { AGENT_LAUNCH_RUNTIME_CAPABILITY } from '../../../../shared/agent-launch-runtime-capability' import type { RpcContext } from '../core' import { @@ -29,7 +28,7 @@ vi.mock('./structured-agent-session-create', () => ({ createStructuredSession(args) })) -const { AGENT_LAUNCH_METHODS, launchAgentOnHost } = await import('./agent-launch') +const { AGENT_LAUNCH_METHODS } = await import('./agent-launch') const { WORKTREE_METHODS } = await import('./worktree') const AGENT_LAUNCH = methodNamed(AGENT_LAUNCH_METHODS, 'agent.launch') @@ -695,113 +694,3 @@ describe('launch inputs that cross the wire', () => { expect(result.receipt).toMatchObject({ mode: 'terminal', reason: 'tui_launch_command' }) }) }) - -describe('trusted unattended launch policy', () => { - it('uses the ordinary terminal factory while suppressing updates and retaining the run title', async () => { - const runtime = runtimeStub() - const result = await launchAgentOnHost( - AGENT_LAUNCH.params.parse({ - agent: 'claude', - surface: 'terminal', - presentation: 'background', - target: { kind: 'existing', worktree: 'id:wt-7' } - }), - rpcContext(runtime, {}), - { suppressStartupUpdatePrompt: true, terminalTitle: 'Nightly run 1' } - ) - expect(result.outcome.kind).toBe('terminal') - expect(runtime.createTerminal).toHaveBeenCalledWith( - 'id:wt-7', - expect.objectContaining({ - startupAgent: 'claude', - suppressStartupUpdatePrompt: true, - title: 'Nightly run 1', - presentation: 'background' - }) - ) - }) - it('forwards suppression through the ordinary new-workspace factory without exposing a wire option', async () => { - const runtime = runtimeStub() - const params = AGENT_LAUNCH.params.parse({ - ...CREATE_LAUNCH, - surface: 'terminal', - suppressStartupUpdatePrompt: true - }) - expect(params).not.toHaveProperty('suppressStartupUpdatePrompt') - await launchAgentOnHost(params, rpcContext(runtime, {}), { suppressStartupUpdatePrompt: true }) - expect(runtime.createManagedWorktree).toHaveBeenCalledWith( - expect.objectContaining({ - startupAgent: 'claude', - startupSuppressUpdatePrompt: true, - createdWithAgent: 'claude' - }) - ) - }) -}) - -it.each([ - ['fresh', true, false, true], - ['fresh', false, false, false], - ['fresh', true, true, false], - ['reuse', true, false, true], - ['reuse', false, false, false] -] as const)( - 'uses actual readiness for %s trusted=%s provenShell=%s', - async (mode, trusted, shell, delivered) => { - const runtime = runtimeStub() - const write = vi.fn() - const boundary = { - ...runtime, - waitForFreshWorkerComposer: async () => ({ satisfied: true, status: 'running' as const }), - waitForTerminal: async () => ({ satisfied: true, status: 'idle' as const }), - readLaunchedAgentForeground: async () => (shell ? ('shell' as const) : ('unknown' as const)), - subscribeToTerminalData: () => () => {}, - launchedAgentHostProvesAgent: () => false, - launchedAgentHostProvesShellAlone: () => shell, - sendTerminalAgentPrompt: async ( - _handle: string, - text: string, - opts: { beforeWrite?: (ptyId: string) => Promise } - ) => { - await opts.beforeWrite?.('pty-1') - write(text) - return { handle: 'term_1', accepted: true, bytesWritten: text.length } - } - } - const host = { - getPtyId: () => 'pty-1', - getForegroundProcess: async () => 'kimi', - subscribeToData: () => () => {}, - readRecentOutput: () => undefined, - write - } - // SAFETY: only the OS/read/write boundary is a stand-in; both launch and readiness/guard owners execute. - Object.assign(runtime, boundary, { - deliverStartupFollowup: ( - handle: string, - followup: { agent: 'kimi'; prompt: string }, - opts: { agentLaunch?: boolean } - ) => - deliverStartupFollowupPrompt( - boundary as unknown as Parameters[0], - host, - handle, - followup, - opts - ) - }) - const result = await launchAgentOnHost( - AGENT_LAUNCH.params.parse({ - agent: 'kimi', - surface: 'terminal', - prompt: { text: 'go', delivery: 'submit' }, - target: { kind: 'existing', worktree: 'id:wt-7' }, - ...(mode === 'reuse' ? { reuseTerminal: { handle: 'term_1' } } : {}) - }), - rpcContext(runtime, {}), - trusted ? { unprovableHost: 'write-unless-shell' } : {} - ) - expect(result.prompt?.outcome).toBe(delivered ? 'handed-to-terminal' : 'not-delivered') - expect(write).toHaveBeenCalledTimes(delivered ? 1 : 0) - } -) diff --git a/src/main/runtime/rpc/methods/agent-launch.ts b/src/main/runtime/rpc/methods/agent-launch.ts index f260f57f8dd7..37ad69775c58 100644 --- a/src/main/runtime/rpc/methods/agent-launch.ts +++ b/src/main/runtime/rpc/methods/agent-launch.ts @@ -31,7 +31,7 @@ import { AgentLaunchReplay, type AgentLaunchParams } from '../../../../shared/rpc-contract/agent-launch-params' -import { agentLaunchSurfaceFactory, type AgentLaunchHostPolicy } from './agent-launch-surfaces' +import { agentLaunchSurfaceFactory } from './agent-launch-surfaces' import { agentLaunchFailureCode, launchFailureWithoutEffectsCode @@ -55,7 +55,9 @@ import { export { supportsAgentLaunch } from './agent-launch-target-authorization' -type HostLaunchContext = RpcContext & { agentLaunchPolicy?: AgentLaunchHostPolicy } +type HostLaunchContext = RpcContext & { + agentLaunchPolicy?: { onSurfacePublished?: (surface: AgentLaunchResult) => void } +} /** What a launch admitted under an operation id carries into its execution. */ type ReplaySafeLaunch = { @@ -83,10 +85,9 @@ async function runAgentLaunch( replaySafe?.callerKey, callerNavigationId !== null, replaySafe?.terminalSpawn, - view, - context.agentLaunchPolicy + view ), - workspaces: agentLaunchWorkspaceFactory(context, intent.agent, context.agentLaunchPolicy), + 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 { @@ -308,7 +309,7 @@ export const AGENT_LAUNCH_METHODS = [ export async function launchAgentOnHost( { operationId, ...params }: AgentLaunchParams, context: RpcContext, - policy?: AgentLaunchHostPolicy + policy?: HostLaunchContext['agentLaunchPolicy'] ): Promise { const host = { ...context, agentLaunchPolicy: policy } if (!supportsAgentLaunch(host)) { diff --git a/src/main/runtime/runtime-pty-controller-contract.ts b/src/main/runtime/runtime-pty-controller-contract.ts index b842ab50cde9..b54afa32c6cb 100644 --- a/src/main/runtime/runtime-pty-controller-contract.ts +++ b/src/main/runtime/runtime-pty-controller-contract.ts @@ -1,3 +1,4 @@ +import type { TerminalViewAttributes } from '../../shared/terminal-view-attributes' import type { PtySpawnOutcome } from '../ipc/pty/spawn-outcome' import type { RuntimePaneCreateClaim } from '../ipc/pty/pane/spawn-reservation' import type { PaneSpawnOperation } from '../ipc/pty/pane/pane-spawn-operation' @@ -21,7 +22,6 @@ import type { ExecutionHostId } from '../../shared/execution-host' import type { PtyProviderBufferSnapshot, PtyProcessInfo, - PtyShutdownOptions, PtySpawnResult } from '../providers/pty-provider-contract' import type { PtyProcessInspection } from '../providers/pty-process-inspection' @@ -98,6 +98,10 @@ export type RuntimePtyController = { placement?: TerminalPanePlacement terminalKittyKeyboardProtocol?: boolean terminalColorQueryReplies?: { foreground?: string; background?: string } + /** A paired launcher's theme: its PTY answers OSC 10/11 with it over the host-wide theme. */ + launcherColorQueryReplies?: { foreground?: string; background?: string } + /** That launcher's palette and cursor, so its PTY's OSC 4/12 agree with its OSC 10/11. */ + launcherViewAttributes?: TerminalViewAttributes agentSessionEnsure?: { claim: AgentSessionExecutionClaim surface: AgentSessionSurfaceBinding @@ -145,10 +149,7 @@ export type RuntimePtyController = { retireRejectedPty?(ptyId: string, stopConfirmed: boolean, incarnationId: string | undefined): void stopAndWait?( ptyId: string, - opts?: Pick< - PtyShutdownOptions, - 'keepHistory' | 'deadlineMs' | 'expectedIncarnationId' | 'authorizeStop' - > + opts?: { keepHistory?: boolean; deadlineMs?: number } ): Promise getCwd?(ptyId: string): Promise getForegroundProcess(ptyId: string): Promise diff --git a/src/main/runtime/terminal/stop/worktree-terminal-stop-targets.ts b/src/main/runtime/terminal/stop/worktree-terminal-stop-targets.ts index ecbbb4a7eda3..8efc61667516 100644 --- a/src/main/runtime/terminal/stop/worktree-terminal-stop-targets.ts +++ b/src/main/runtime/terminal/stop/worktree-terminal-stop-targets.ts @@ -1,4 +1,3 @@ -import type { PtyShutdownOptions } from '../../../providers/pty-provider-contract' import { setTimeout as delay } from 'node:timers/promises' import { OrcaRuntimeWithSleepResolvedWorktreeTerminals } from './worktree-terminal-sleep' import { setsEqual } from '../../runtime-worktree-binding-index' @@ -20,9 +19,7 @@ export abstract class OrcaRuntimeWithStopExactTerminalsForWorktree extends OrcaR async stopExactTerminalsForWorktree( worktreeSelector: string, expectedPtyIds: readonly string[], - opts: Pick & { - targetOnly?: boolean - } = {} + opts: { keepHistory?: boolean; targetOnly?: boolean } = {} ): Promise<{ stopped: number stoppedPtyIds: string[] @@ -33,7 +30,7 @@ export abstract class OrcaRuntimeWithStopExactTerminalsForWorktree extends OrcaR }> { // Why: exact stop hibernates one known pane; worktree sleep discovers its complete host-owned set separately. const graphEpoch = this.captureReadyGraphEpoch() - const worktree = await this.resolveWorktreeSelector(worktreeSelector) + const worktree = await this.resolveWorkspaceSelector(worktreeSelector) this.assertStableReadyGraph(graphEpoch) const expected = new Set(expectedPtyIds.filter((ptyId) => ptyId.length > 0)) if (expected.size !== 1) { @@ -72,11 +69,7 @@ export abstract class OrcaRuntimeWithStopExactTerminalsForWorktree extends OrcaR : null let stopped = false try { - stopped = await this.ptyController.stopAndWait(ptyId, { - keepHistory: opts.keepHistory, - expectedIncarnationId: opts.expectedIncarnationId, - authorizeStop: opts.authorizeStop - }) + stopped = await this.ptyController.stopAndWait(ptyId, { keepHistory: opts.keepHistory }) } finally { settleStop?.(stopped) } diff --git a/src/main/runtime/terminal/stop/worktree-terminal-stop.ts b/src/main/runtime/terminal/stop/worktree-terminal-stop.ts index 967dac618a72..f58c72446dc7 100644 --- a/src/main/runtime/terminal/stop/worktree-terminal-stop.ts +++ b/src/main/runtime/terminal/stop/worktree-terminal-stop.ts @@ -50,7 +50,7 @@ export abstract class OrcaRuntimeWithStopTerminalsForWorktree extends OrcaRuntim worktreeSelector: string ): Promise { const graphEpoch = this.captureReadyGraphEpoch() - const worktree = await this.resolveWorktreeSelector(worktreeSelector) + const worktree = await this.resolveWorkspaceSelector(worktreeSelector) this.assertStableReadyGraph(graphEpoch) const hostFence = this.getWorktreeHostFence(worktree) @@ -175,7 +175,7 @@ export abstract class OrcaRuntimeWithStopTerminalsForWorktree extends OrcaRuntim const graphEpoch = this.captureReadyGraphEpoch() const worktree = options.resolvedWorktreeId ? { id: options.resolvedWorktreeId } - : await this.resolveWorktreeSelector(worktreeSelector) + : await this.resolveWorkspaceSelector(worktreeSelector) this.assertStableReadyGraph(graphEpoch) const pastDeadline = (): boolean => options.deadline !== undefined && Date.now() >= options.deadline @@ -255,7 +255,7 @@ export abstract class OrcaRuntimeWithStopTerminalsForWorktree extends OrcaRuntim worktreeSelector: string, options: { soleLivePtyId?: string } = {} ): Promise { - const worktree = await this.resolveWorktreeSelector(worktreeSelector) + const worktree = await this.resolveWorkspaceSelector(worktreeSelector) const scope = resolveSleepScope(this.store?.getRepos() ?? [], worktree) const existing = this.terminalSleepByHostWorktree.get(scope.key) if (existing) { diff --git a/src/main/startup/main-process-automations.ts b/src/main/startup/main-process-automations.ts index 24b5875d1cae..aea94b954fa3 100644 --- a/src/main/startup/main-process-automations.ts +++ b/src/main/startup/main-process-automations.ts @@ -1,4 +1,3 @@ -import { createDesktopRunTerminalLifecycle } from '../automations/desktop-run-terminal-lifecycle' import type { AutomationService } from '../automations/service' import { createRuntimeAutomationService } from '../automations/runtime-automation-service' import { mainProcessState as state } from './main-process-state' @@ -17,9 +16,7 @@ export function initializeMainProcessAutomations(): AutomationService { claudeUsage, codexUsage, // Remote clients mirror schedules; only server processes execute remote_host_service ownership. - ...(state.isServeMode - ? { headless: true as const } - : { headless: false as const, createDesktopLifecycle: createDesktopRunTerminalLifecycle }) + headless: state.isServeMode }) state.automations = service return service diff --git a/src/main/window/runtime-window-lifecycle.ts b/src/main/window/runtime-window-lifecycle.ts index 588538ca41cf..942fa1b64b3c 100644 --- a/src/main/window/runtime-window-lifecycle.ts +++ b/src/main/window/runtime-window-lifecycle.ts @@ -8,7 +8,6 @@ import type { RuntimeMobileSessionTabMove } from '../../shared/runtime-types' import type { TerminalTabCreateReply } from '../../shared/terminal-reveal-identity' import { runWorktreeChangeInvalidators } from '../ipc/worktree-change-invalidators' import { requestAgentLaunchTabPublishFromRenderer } from './agent-launch-tab-publish-relay' -import type { RuntimeNotifier } from '../runtime/runtime-notifier-contract' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { registerRendererDocumentNavigation } from './renderer-document-navigation' import { createRuntimeRendererNotificationSender } from './runtime-renderer-notification-sender' @@ -118,10 +117,33 @@ export function registerRuntimeWindowLifecycle( }) } ipcMain.on('terminal:tabCreateReply', handler) - const sent = send( - 'ui:createTerminal', - terminalPresentationRequest(worktreeId, opts, requestId) - ) + const sent = send('ui:createTerminal', { + requestId, + worktreeId, + ptyId: opts.ptyId, + title: opts.title ?? undefined, + ...(opts.cwd ? { cwd: opts.cwd } : {}), + ...(opts.launchConfig ? { launchConfig: opts.launchConfig } : {}), + ...(opts.launchToken ? { launchToken: opts.launchToken } : {}), + ...(opts.launchAgent ? { launchAgent: opts.launchAgent } : {}), + ...(opts.viewMode ? { viewMode: opts.viewMode } : {}), + ...(opts.targetGroupId ? { targetGroupId: opts.targetGroupId } : {}), + ...(opts.afterTabId ? { afterTabId: opts.afterTabId } : {}), + ...(opts.shellOverride ? { shellOverride: opts.shellOverride } : {}), + activate: opts.activate !== false, + ...(opts.presentation ? { presentation: opts.presentation } : {}), + ...(opts.surfaceOwner === false ? { surfaceOwner: false } : {}), + ...(opts.agentLaunchViewer ? { agentLaunchViewer: opts.agentLaunchViewer } : {}), + // Pre-mint tabId to match the PTY paneKey so hook events reach the correct tab. + ...(opts.tabId !== undefined ? { tabId: opts.tabId } : {}), + ...(opts.leafId !== undefined ? { leafId: opts.leafId } : {}), + ...(opts.splitFromLeafId !== undefined ? { splitFromLeafId: opts.splitFromLeafId } : {}), + ...(opts.splitDirection !== undefined ? { splitDirection: opts.splitDirection } : {}), + ...(opts.splitTelemetrySource !== undefined + ? { splitTelemetrySource: opts.splitTelemetrySource } + : {}), + ...(opts.focus !== undefined ? { focus: opts.focus } : {}) + }) if (!sent) { clearTimeout(timer) ipcMain.removeListener('terminal:tabCreateReply', handler) @@ -235,37 +257,3 @@ export function registerRuntimeWindowLifecycle( } }) } - -export function terminalPresentationRequest( - worktreeId: string, - opts: Parameters>[1], - requestId?: string -) { - return { - requestId, - worktreeId, - ptyId: opts.ptyId, - title: opts.title ?? undefined, - ...(opts.cwd ? { cwd: opts.cwd } : {}), - ...(opts.launchConfig ? { launchConfig: opts.launchConfig } : {}), - ...(opts.launchToken ? { launchToken: opts.launchToken } : {}), - ...(opts.launchAgent ? { launchAgent: opts.launchAgent } : {}), - ...(opts.viewMode ? { viewMode: opts.viewMode } : {}), - ...(opts.targetGroupId ? { targetGroupId: opts.targetGroupId } : {}), - ...(opts.afterTabId ? { afterTabId: opts.afterTabId } : {}), - ...(opts.shellOverride ? { shellOverride: opts.shellOverride } : {}), - activate: opts.activate !== false, - ...(opts.presentation ? { presentation: opts.presentation } : {}), - ...(opts.surfaceOwner === false ? { surfaceOwner: false } : {}), - ...(opts.agentLaunchViewer ? { agentLaunchViewer: opts.agentLaunchViewer } : {}), - // Pre-mint tabId to match the PTY paneKey so hook events reach the correct tab. - ...(opts.tabId !== undefined ? { tabId: opts.tabId } : {}), - ...(opts.leafId !== undefined ? { leafId: opts.leafId } : {}), - ...(opts.splitFromLeafId !== undefined ? { splitFromLeafId: opts.splitFromLeafId } : {}), - ...(opts.splitDirection !== undefined ? { splitDirection: opts.splitDirection } : {}), - ...(opts.splitTelemetrySource !== undefined - ? { splitTelemetrySource: opts.splitTelemetrySource } - : {}), - ...(opts.focus !== undefined ? { focus: opts.focus } : {}) - } -} diff --git a/src/main/window/terminal-tab-close-request-relay.ts b/src/main/window/terminal-tab-close-request-relay.ts index 0d652bbdba1b..b3b7d6d7a656 100644 --- a/src/main/window/terminal-tab-close-request-relay.ts +++ b/src/main/window/terminal-tab-close-request-relay.ts @@ -6,10 +6,6 @@ import type { TerminalTabCloseRequest, TerminalTabCloseResponse } from '../../shared/terminal-tab-close' -import type { - AutomationTerminalLifecycleRequest, - AutomationTerminalLifecycleResponse -} from '../../shared/automation-terminal-lifecycle' import { addFanoutListener, addFanoutListeners } from '../event-listener-fanout' const TERMINAL_TAB_CLOSE_TIMEOUT_MS = 20_000 @@ -19,41 +15,6 @@ export async function requestTerminalTabCloseFromRenderer( tabId: string, options: { localPtyTeardownOwnedExternally?: boolean; force?: boolean } = {} ): Promise { - const requestId = randomUUID() - const request: TerminalTabCloseRequest = { requestId, tabId, ...options } - const response = await requestWindowTransaction( - mainWindow, - 'ui:terminalTabCloseRequest', - 'ui:terminalTabCloseResponse', - request - ) - if (response.error) { - throw new Error(response.error) - } -} - -export function requestAutomationTerminalLifecycle( - window: BrowserWindow, - request: AutomationTerminalLifecycleRequest, - signal: AbortSignal, - valid: () => boolean -): Promise { - return requestWindowTransaction( - window, - 'automations:terminalLifecycleRequest', - 'automations:terminalLifecycleResponse', - request, - { signal, valid } - ) -} - -function requestWindowTransaction( - mainWindow: BrowserWindow, - requestChannel: string, - responseChannel: string, - request: { requestId: string }, - options: { signal?: AbortSignal; valid?: () => boolean } = {} -): Promise { if (mainWindow.isDestroyed()) { throw new Error('renderer_unavailable') } @@ -61,44 +22,42 @@ function requestWindowTransaction( if (webContents.isDestroyed()) { throw new Error('renderer_unavailable') } - return new Promise((resolve, reject) => { + const requestId = randomUUID() + await new Promise((resolve, reject) => { let settled = false const releaseListeners: (() => void)[] = [] const onRendererUnavailable = (): void => finish(new Error('renderer_unavailable')) - const finish = (error?: Error, response?: T): void => { + const finish = (error?: Error): void => { if (settled) { return } settled = true clearTimeout(timeout) - options.signal?.removeEventListener('abort', onRendererUnavailable) for (const release of releaseListeners) { release() } if (error) { reject(error) } else { - resolve(response!) + resolve() } } const timeout = setTimeout( () => finish(new Error('terminal_tab_close_timeout')), TERMINAL_TAB_CLOSE_TIMEOUT_MS ) - const onResponse = (event: Electron.IpcMainEvent, response: T): void => { + const onResponse = (event: Electron.IpcMainEvent, response: TerminalTabCloseResponse): void => { // Visible request IDs confer no authority; only the selected window may commit/reject its lifecycle transaction. - if ( - event.sender !== webContents || - !response || - response.requestId !== request.requestId || - (options.valid && (event.senderFrame !== webContents.mainFrame || !options.valid())) - ) { + if (event.sender !== webContents || response.requestId !== requestId) { return } - finish(undefined, response) + if (response.error) { + finish(new Error(response.error)) + } else { + finish() + } } - - releaseListeners.push(addFanoutListener(ipcMain, responseChannel, onResponse)) + releaseListeners.push(addFanoutListener(ipcMain, 'ui:terminalTabCloseResponse', onResponse)) // Lean test windows may lack event methods. if (typeof mainWindow.on === 'function') { releaseListeners.push(addFanoutListener(mainWindow, 'closed', onRendererUnavailable)) @@ -108,13 +67,9 @@ function requestWindowTransaction( addFanoutListeners(webContents, ['destroyed', 'render-process-gone'], onRendererUnavailable) ) } - options.signal?.addEventListener('abort', onRendererUnavailable, { once: true }) - if (options.signal?.aborted || options.valid?.() === false) { - onRendererUnavailable() - return - } + const request: TerminalTabCloseRequest = { requestId, tabId, ...options } try { - webContents.send(requestChannel, request) + webContents.send('ui:terminalTabCloseRequest', request) } catch { finish(new Error('renderer_unavailable')) } diff --git a/src/preload/api/automation-api.ts b/src/preload/api/automation-api.ts index 2a28f3626287..6d82279bfe22 100644 --- a/src/preload/api/automation-api.ts +++ b/src/preload/api/automation-api.ts @@ -1,8 +1,4 @@ import type { ExecutionHostId } from '../../shared/execution-host' -import type { - AutomationTerminalLifecycleRequest, - AutomationTerminalLifecycleResponse -} from '../../shared/automation-terminal-lifecycle' import type { AutomationDispatchRequest, AutomationDispatchResult, @@ -42,10 +38,6 @@ export type AutomationsApi = { displayName: string }) => Promise rendererReady: () => Promise - onTerminalLifecycleRequest: ( - callback: (request: AutomationTerminalLifecycleRequest) => void - ) => () => void - respondTerminalLifecycle: (response: AutomationTerminalLifecycleResponse) => void onDispatchRequested: (callback: (request: AutomationDispatchRequest) => void) => () => void onChanged: (callback: (payload: AutomationsChangedPayload) => void) => () => void } diff --git a/src/preload/api/automations-bridge.ts b/src/preload/api/automations-bridge.ts index 639a5e7cb9e9..51b90bedb63d 100644 --- a/src/preload/api/automations-bridge.ts +++ b/src/preload/api/automations-bridge.ts @@ -1,8 +1,4 @@ import type { ExecutionHostId } from '../../shared/execution-host' -import type { - AutomationTerminalLifecycleRequest, - AutomationTerminalLifecycleResponse -} from '../../shared/automation-terminal-lifecycle' import { ipcRenderer } from 'electron' import type { ExternalAutomationManagerResult, PreloadApi } from '../api-types' import type { @@ -40,19 +36,6 @@ export const automationsApi = { displayName: string }): Promise => ipcRenderer.invoke('automations:snapshotWorkspaceName', args), rendererReady: (): Promise => ipcRenderer.invoke('automations:rendererReady'), - onTerminalLifecycleRequest: ( - callback: (request: AutomationTerminalLifecycleRequest) => void - ): (() => void) => { - const listener = ( - _event: Electron.IpcRendererEvent, - request: AutomationTerminalLifecycleRequest - ) => callback(request) - ipcRenderer.on('automations:terminalLifecycleRequest', listener) - return () => ipcRenderer.removeListener('automations:terminalLifecycleRequest', listener) - }, - respondTerminalLifecycle: (response: AutomationTerminalLifecycleResponse): void => { - ipcRenderer.send('automations:terminalLifecycleResponse', response) - }, onDispatchRequested: (callback: (request: AutomationDispatchRequest) => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent, request: AutomationDispatchRequest) => callback(request) diff --git a/src/renderer/src/components/automations/AutomationEditorDialog.tsx b/src/renderer/src/components/automations/AutomationEditorDialog.tsx index 7e751ac9c093..1e8257342195 100644 --- a/src/renderer/src/components/automations/AutomationEditorDialog.tsx +++ b/src/renderer/src/components/automations/AutomationEditorDialog.tsx @@ -224,7 +224,7 @@ export function AutomationEditorDialog({ 0} onOpenChange={onOpenChange} onSave={onSave} 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 c3bc71f01e30..7a16d1ba1d0e 100644 --- a/src/renderer/src/components/automations/AutomationsPage.create-destination.test.tsx +++ b/src/renderer/src/components/automations/AutomationsPage.create-destination.test.tsx @@ -150,11 +150,12 @@ function createRpcCalls(): unknown[][] { } describe('AutomationsPage create destination', () => { - it('creates on the selected runtime rather than under the desktop authority', async () => { + it('creates Terminal on the selected runtime while Chat capability observation is unavailable', async () => { api.automations.list.mockResolvedValue([]) scopedList([]) runtimeHost([], []) runtimeCreateReturns(makeAutomation({ id: 'a-new', name: 'Sweep' })) + mocks.state.runtimeStatusByEnvironmentId = new Map() addRuntimeProject() mocks.state.automationHostFilter = RUNTIME_SELF_FILTER @@ -167,6 +168,7 @@ describe('AutomationsPage create destination', () => { 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}`, diff --git a/src/renderer/src/components/automations/automation-capability-probe.ts b/src/renderer/src/components/automations/automation-capability-probe.ts index fb33497630ed..fcbacb91f0a7 100644 --- a/src/renderer/src/components/automations/automation-capability-probe.ts +++ b/src/renderer/src/components/automations/automation-capability-probe.ts @@ -20,6 +20,7 @@ import { } from '../../../../shared/automation-extra-agent-args' import { automationAuthorityCatalogKey } from './automation-host-catalog-types' import { automationHostDiagnostics } from './automation-host-diagnostics' +import { translate } from '@/i18n/i18n' export const REQUEST_TIMEOUT_MS = 15_000 @@ -146,7 +147,10 @@ export async function assertAutomationCreateIdempotencySupported( await assertAuthorityCapability( authority, AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY, - 'Moving automations to this host requires a newer Orca server. Update the HUB and try again.' + translate( + 'auto.components.automations.capabilityProbe.createIdempotencyUpdateRequired', + 'Moving automations to this host requires a newer Orca server. Update the HUB and try again.' + ) ) } diff --git a/src/renderer/src/components/automations/automation-edit-draft.ts b/src/renderer/src/components/automations/automation-edit-draft.ts index 2a933f7a6f95..1aa82cbba4b6 100644 --- a/src/renderer/src/components/automations/automation-edit-draft.ts +++ b/src/renderer/src/components/automations/automation-edit-draft.ts @@ -1,4 +1,5 @@ import type { Automation } from '../../../../shared/automations-types' +import { translate } from '@/i18n/i18n' import { getAutomationRunRepoId } from '../../../../shared/automation-run-identity' import { isRunnableAutomationSchedule, @@ -37,6 +38,9 @@ export function buildAutomationEditDraft(automation: Automation): AutomationDraf scheduleWarning: schedule || hasCustomSchedule ? null - : 'This automation has an unsupported saved schedule. Pick a supported schedule before saving changes.' + : translate( + 'auto.components.automations.editDraft.unsupportedSchedule', + 'This automation has an unsupported saved schedule. Pick a supported schedule before saving changes.' + ) } } diff --git a/src/renderer/src/components/automations/automation-launch-surface.ts b/src/renderer/src/components/automations/automation-launch-surface.ts index 6c5f356889b8..8ba7753af7f7 100644 --- a/src/renderer/src/components/automations/automation-launch-surface.ts +++ b/src/renderer/src/components/automations/automation-launch-surface.ts @@ -1,3 +1,5 @@ +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 } from '../../../../shared/automation-runtime-capabilities' import { isNativeChatDefaultFor } from '../../../../shared/structured-native-chat-launch-route' @@ -59,3 +61,24 @@ export function automationDraftSurface( (chatSupported && 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 905b6382168f..27d822520d5d 100644 --- a/src/renderer/src/components/automations/automation-orca-save.ts +++ b/src/renderer/src/components/automations/automation-orca-save.ts @@ -1,5 +1,6 @@ import { automationChatSupport, + automationDraftLaunchSetup, automationDraftSurface, automationLaunchWorkspace } from './automation-launch-surface' @@ -20,7 +21,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 { @@ -166,18 +166,13 @@ export async function saveOrcaAutomation( automationLaunchWorkspace(draft, setupResolution ?? undefined) ) ) - const launchSetupPatch = { - surface, - ...(hasExtraAgentArgs(draft.extraAgentArgs) || currentAutomation?.extraAgentArgs - ? { arguments: { kind: 'legacy-extras' as const, value: draft.extraAgentArgs } } - : {}) - } + const launchSetup = automationDraftLaunchSetup(draft, surface, currentAutomation) const updates: AutomationUpdateInput = { name: draft.name, prompt: draft.prompt, precheck, agentId: draft.agentId, - launchSetupPatch, + ...launchSetup, runContext, projectId: draft.projectId, workspaceMode: draft.workspaceMode, @@ -197,7 +192,7 @@ export async function saveOrcaAutomation( prompt: draft.prompt, precheck, agentId: draft.agentId, - launchSetupPatch, + ...launchSetup, runContext, projectId: draft.projectId, workspaceMode: draft.workspaceMode, 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 c871919f172d..dfcc3d11f6e2 100644 --- a/src/renderer/src/components/automations/automation-run-view-state.ts +++ b/src/renderer/src/components/automations/automation-run-view-state.ts @@ -1,4 +1,5 @@ import type { Automation, AutomationRun } from '../../../../shared/automations-types' +import { translate } from '@/i18n/i18n' export type AutomationRunViewAvailability = | 'chat' @@ -79,8 +80,8 @@ export function getAutomationRunViewState({ if (run.workspaceId && workspaceExists && terminalTargetExists) { return { availability: 'terminal', - actionLabel: 'View run', - statusLabel: 'Run is open', + actionLabel: translate('auto.components.automations.runViewState.viewRun', 'View run'), + statusLabel: translate('auto.components.automations.runViewState.runOpen', 'Run is open'), canOpen: true } } @@ -88,8 +89,11 @@ export function getAutomationRunViewState({ if (run.workspaceId && workspaceExists && hasPaneIdentity && terminalOnPairedServer) { return { availability: 'terminal', - actionLabel: 'View run', - statusLabel: 'Run terminal is on the paired server.', + actionLabel: translate('auto.components.automations.runViewState.viewRun', 'View run'), + statusLabel: translate( + 'auto.components.automations.runViewState.terminalOnPairedServer', + 'Run terminal is on the paired server.' + ), canOpen: true } } @@ -97,8 +101,11 @@ export function getAutomationRunViewState({ if (run.workspaceId && workspaceExists && hasTerminalIdentity) { return { availability: 'terminal', - actionLabel: 'View run', - statusLabel: 'Run terminal is unavailable.', + actionLabel: translate('auto.components.automations.runViewState.viewRun', 'View run'), + statusLabel: translate( + 'auto.components.automations.runViewState.terminalUnavailable', + 'Run terminal is unavailable.' + ), canOpen: true } } @@ -107,8 +114,14 @@ export function getAutomationRunViewState({ if (run.workspaceId && workspaceExists && run.dispatchedAt !== null) { return { availability: 'workspace', - actionLabel: 'Open workspace', - statusLabel: 'Workspace is available.', + actionLabel: translate( + 'auto.components.automations.runViewState.openWorkspace', + 'Open workspace' + ), + statusLabel: translate( + 'auto.components.automations.runViewState.workspaceAvailable', + 'Workspace is available.' + ), canOpen: true } } @@ -116,20 +129,36 @@ export function getAutomationRunViewState({ if (run.outputSnapshot?.content.trim()) { return { availability: 'snapshot', - actionLabel: 'Snapshot saved', - statusLabel: 'Showing saved run snapshot.', + actionLabel: translate( + 'auto.components.automations.runViewState.snapshotSaved', + 'Snapshot saved' + ), + statusLabel: translate( + 'auto.components.automations.runViewState.showingSnapshot', + 'Showing saved run snapshot.' + ), canOpen: false } } return { availability: 'metadata', - actionLabel: 'View run', + actionLabel: translate('auto.components.automations.runViewState.viewRun', 'View run'), statusLabel: run.workspaceId ? run.workspaceDisplayName?.trim() - ? `${run.workspaceDisplayName.trim()} no longer available` - : 'Workspace no longer available' - : 'No workspace launched', + ? translate( + 'auto.components.automations.runViewState.namedWorkspaceGone', + '{{name}} no longer available', + { name: run.workspaceDisplayName.trim() } + ) + : translate( + 'auto.components.automations.runViewState.workspaceGone', + 'Workspace no longer available' + ) + : translate( + 'auto.components.automations.runViewState.noWorkspaceLaunched', + 'No workspace launched' + ), canOpen: false } } diff --git a/src/renderer/src/components/automations/automation-save-action.ts b/src/renderer/src/components/automations/automation-save-action.ts index 2d5d1b333aad..e7d07692977b 100644 --- a/src/renderer/src/components/automations/automation-save-action.ts +++ b/src/renderer/src/components/automations/automation-save-action.ts @@ -84,7 +84,7 @@ export function createAutomationSaveAction(context: AutomationSaveContext) { automationLaunchWorkspace(draft, resolution) ) const surface = automationDraftSurface(draft, settings, chatSupported) - if (chatSupported === null || (surface === 'chat' && !chatSupported)) { + if (surface === 'chat' && chatSupported !== true) { return } const effectiveDraft = { ...draft, surface } diff --git a/src/renderer/src/hooks/automation-dispatch-completion.ts b/src/renderer/src/hooks/automation-dispatch-completion.ts new file mode 100644 index 000000000000..c0c2b5dc1d04 --- /dev/null +++ b/src/renderer/src/hooks/automation-dispatch-completion.ts @@ -0,0 +1,276 @@ +import { + createAutomationRunOutputSnapshotBuffer, + selectAutomationRunOutputSnapshot +} from '@/components/automations/automation-run-output-snapshot' +import { useAppStore } from '@/store' +import type { + AutomationDispatchResult, + AutomationPrecheckResult, + AutomationRun +} from '../../../shared/automations-types' +import type { AgentStateHistoryEntry, AgentStatusEntry } from '../../../shared/agent-status-types' +import { + selectAutomationAgentStatusEntryChange, + UNCHANGED_AUTOMATION_AGENT_STATUS_ENTRY +} from './automation-agent-status-entry-change' +import type { Worktree } from '../../../shared/worktree/types' +import { isProvenProcessExit } from '../../../shared/terminal-exit-cause' +import type { AutomationTerminalOwnership } from '@/lib/automation-terminal-ownership' + +type MarkDispatchResult = (result: AutomationDispatchResult) => Promise + +export function createAutomationDispatchCompletion(args: { + run: AutomationRun + worktree: Worktree + precheckResult: AutomationPrecheckResult | null + markDispatchResult: MarkDispatchResult + releaseTerminalOwnership: () => void + finalizeTerminalOwnership: AutomationTerminalOwnership['finalize'] +}) { + const outputSnapshotBuffer = createAutomationRunOutputSnapshotBuffer() + let latestAssistantMessage: string | null = null + const getOutputSnapshot = () => + selectAutomationRunOutputSnapshot(latestAssistantMessage, outputSnapshotBuffer.snapshot()) + let dispatchMarked = false + let pendingExitCode: number | null = null + let pendingDone = false + let completionMarked = false + let contactLost = false + let unsubscribeAgentStatus = (): void => {} + let unsubscribeSessionObserver = (): void => {} + let releaseReuseDispatchTab = (): void => {} + const cleanupRunObservers = (): void => { + unsubscribeAgentStatus() + unsubscribeSessionObserver() + releaseReuseDispatchTab() + unsubscribeAgentStatus = (): void => {} + unsubscribeSessionObserver = (): void => {} + releaseReuseDispatchTab = (): void => {} + } + const markCompletionResult = async (): Promise => { + if (completionMarked) { + return + } + completionMarked = true + cleanupRunObservers() + try { + await args.markDispatchResult({ + runId: args.run.id, + status: 'completed', + workspaceId: args.worktree.id, + workspaceDisplayName: args.worktree.displayName, + outputSnapshot: getOutputSnapshot(), + precheckResult: args.precheckResult, + error: null + }) + } catch (error) { + args.releaseTerminalOwnership() + throw error + } + await retireRunTerminal() + } + const retireRunTerminal = async (): Promise => { + const retirement = await args.finalizeTerminalOwnership({ + // Why: only a workspace made for this run is its own; a shared one would gather a sleeping tab per run. + preservePane: args.worktree.automationProvenance?.automationRunId === args.run.id + }) + if (!retirement) { + return + } + // Clear stopped-process pointers best-effort; sleeping panes retain resumable tab/pane keys for View run. + try { + await args.markDispatchResult({ + runId: args.run.id, + status: 'completed', + ...(retirement === 'closed' ? { terminalSessionId: null, terminalPaneKey: null } : {}), + terminalPtyId: null + }) + } catch (error) { + console.error('[automations] Failed to clear retired terminal identity:', error) + } + } + /** Lost PTY contact proves no result: retain dispatched state and let main’s watcher report lost-terminal evidence. Never finalize or close unproven-dead work, which could orphan a live remote process. */ + const abandonUnverifiableRun = (code: number): void => { + if (completionMarked || contactLost) { + return + } + contactLost = true + cleanupRunObservers() + args.releaseTerminalOwnership() + console.warn( + `[automations] Lost contact with the process for run ${args.run.id} (code ${code}); leaving the run dispatched rather than reporting an exit.` + ) + } + const markExitResult = async (code: number): Promise => { + if (completionMarked) { + return + } + if (!isProvenProcessExit(code)) { + abandonUnverifiableRun(code) + return + } + completionMarked = true + cleanupRunObservers() + try { + await args.markDispatchResult({ + runId: args.run.id, + status: code === 0 ? 'completed' : 'dispatch_failed', + workspaceId: args.worktree.id, + workspaceDisplayName: args.worktree.displayName, + outputSnapshot: getOutputSnapshot(), + precheckResult: args.precheckResult, + error: code === 0 ? null : `Automation process exited with code ${code}.` + }) + } catch (error) { + args.releaseTerminalOwnership() + throw error + } + if (code === 0) { + await retireRunTerminal() + } else { + args.releaseTerminalOwnership() + } + } + const settleLateResult = (result: Promise): void => { + // Status/exit callbacks have no awaitable caller; release ownership before persistence failures propagate. + void result.catch((error) => { + console.error('[automations] Failed to persist late automation result:', error) + }) + } + const handleAgentDone = (): void => { + if (completionMarked) { + return + } + if (!dispatchMarked) { + pendingDone = true + return + } + settleLateResult(markCompletionResult()) + } + const handleExit = (code: number): void => { + if (completionMarked) { + return + } + if (!dispatchMarked) { + pendingExitCode = code + return + } + settleLateResult(markExitResult(code)) + } + const observeAgentStatus = ( + targetPaneKey: string, + startedAfter: number, + options?: { requireWorkingAfterStart?: boolean } + ): void => { + let sawWorkingAfterStart = false + let observedStateHistory: AgentStateHistoryEntry[] = [] + let observedEntry: AgentStatusEntry | undefined + const checkCurrentStatus = (): void => { + const entryChange = selectAutomationAgentStatusEntryChange( + useAppStore.getState().agentStatusByPaneKey, + targetPaneKey, + observedEntry + ) + if (entryChange === UNCHANGED_AUTOMATION_AGENT_STATUS_ENTRY) { + return + } + const entry = entryChange + observedEntry = entry + if (!entry || entry.updatedAt < startedAfter) { + return + } + const historyOverlap = getAgentStateHistoryOverlap(observedStateHistory, entry.stateHistory) + // Keep sawWorkingAfterStart monotonic: recreated entries lose history and cannot rederive the edge needed by reuseSession. + for (const historicalState of entry.stateHistory.slice(historyOverlap)) { + if (historicalState.startedAt < startedAfter) { + continue + } + if (historicalState.state === 'working') { + sawWorkingAfterStart = true + } + if ( + historicalState.state === 'done' && + (!options?.requireWorkingAfterStart || sawWorkingAfterStart) + ) { + // The done edge left live history; only the entry’s completed slot retains its output. + latestAssistantMessage = + entry.lastCompletedAssistantMessage?.trim() || latestAssistantMessage + handleAgentDone() + return + } + } + observedStateHistory = [...entry.stateHistory] + if (entry.state === 'working') { + sawWorkingAfterStart = true + } + if ( + entry.state === 'done' && + // SessionStart boundary-done means connection before prompt submission; finishing here would record empty output and close the new tab. + entry.sessionBoundary !== true && + (!options?.requireWorkingAfterStart || sawWorkingAfterStart) + ) { + latestAssistantMessage = entry.lastAssistantMessage?.trim() || latestAssistantMessage + handleAgentDone() + } + } + // Codex/Claude completion normally comes from global hook IPC rather than hidden PTY OSC. + unsubscribeAgentStatus = useAppStore.subscribe(checkCurrentStatus) + checkCurrentStatus() + } + + return { + appendOutput: (chunk: string) => outputSnapshotBuffer.append(chunk), + captureAssistantMessage: (message: string | null | undefined) => { + latestAssistantMessage = message?.trim() || latestAssistantMessage + }, + cleanupRunObservers, + handleAgentDone, + handleExit, + observeAgentStatus, + setReuseDispatchTabRelease: (release: () => void) => { + releaseReuseDispatchTab = release + }, + setSessionObserver: (unsubscribe: () => void) => { + unsubscribeSessionObserver = unsubscribe + }, + settlePendingAfterDispatch: async () => { + dispatchMarked = true + if (pendingDone) { + await markCompletionResult() + } else if (pendingExitCode !== null) { + await markExitResult(pendingExitCode) + } + } + } +} + +function agentStateHistoryEntriesEqual( + left: AgentStateHistoryEntry, + right: AgentStateHistoryEntry +): boolean { + return ( + left.state === right.state && + left.prompt === right.prompt && + left.startedAt === right.startedAt && + left.interrupted === right.interrupted + ) +} + +function getAgentStateHistoryOverlap( + previous: AgentStateHistoryEntry[], + current: AgentStateHistoryEntry[] +): number { + for (let overlap = Math.min(previous.length, current.length); overlap > 0; overlap -= 1) { + const previousOffset = previous.length - overlap + if ( + current + .slice(0, overlap) + .every((entry, index) => + agentStateHistoryEntriesEqual(entry, previous[previousOffset + index]) + ) + ) { + return overlap + } + } + return 0 +} diff --git a/src/renderer/src/hooks/automation-dispatch-handler.ts b/src/renderer/src/hooks/automation-dispatch-handler.ts new file mode 100644 index 000000000000..6f101bad103f --- /dev/null +++ b/src/renderer/src/hooks/automation-dispatch-handler.ts @@ -0,0 +1,241 @@ +import { listAutomationRunsForTarget } from '@/components/automations/automation-host-client' +import { translate } from '@/i18n/i18n' +import { submitPromptToAgentPty } from '@/lib/agent-paste-draft' +import { launchAgentBackgroundSession } from '@/lib/launch-agent-background-session' +import { observeExistingAutomationSession } from '@/lib/automation-session-observer' +import { findReusableAutomationSession } from '@/lib/automation-session-reuse' +import type { AutomationTerminalOwnership } from '@/lib/automation-terminal-ownership' +import { useAppStore } from '@/store' +import { captureWorkspaceSelection, restoreWorkspaceSelection } from '@/lib/active-workspace-host' +import type { + AutomationDispatchRequest, + AutomationDispatchResult +} from '../../../shared/automations-types' +import { createAutomationDispatchCompletion } from './automation-dispatch-completion' +import { + prepareAutomationDispatchWorkspace, + resolveAutomationDispatchWorkspace +} from './automation-dispatch-workspace' + +const activeReuseDispatchTabIds = new Set() + +function acquireReuseDispatchTab(tabId: string): (() => void) | null { + if (activeReuseDispatchTabIds.has(tabId)) { + return null + } + activeReuseDispatchTabIds.add(tabId) + return () => activeReuseDispatchTabIds.delete(tabId) +} + +export async function handleAutomationDispatchRequest({ + automation, + run, + dispatchToken +}: AutomationDispatchRequest): Promise { + const markDispatchResult = async (result: AutomationDispatchResult): Promise => { + // The writer publishes host-scoped change before reply; another unscoped emit would invalidate every host. + await window.api.automations.markDispatchResult(result) + } + const state = useAppStore.getState() + const focusBeforeDispatch = { + activeView: state.activeView, + activeWorktreeId: state.activeWorktreeId, + selection: captureWorkspaceSelection(state), + activeTabId: state.activeTabId, + activeTabType: state.activeTabType + } + const resolved = resolveAutomationDispatchWorkspace(state, automation, run) + let terminalOwnership: AutomationTerminalOwnership | null = null + const releaseTerminalOwnership = (): void => { + const ownership = terminalOwnership + terminalOwnership = null + ownership?.release() + } + const finalizeTerminalOwnership: AutomationTerminalOwnership['finalize'] = async (options) => { + const ownership = terminalOwnership + terminalOwnership = null + return (await ownership?.finalize(options)) ?? null + } + + if (!resolved.repo) { + await markDispatchResult({ + runId: run.id, + status: 'skipped_unavailable', + workspaceId: run.workspaceId, + workspaceDisplayName: run.workspaceDisplayName ?? null, + error: translate( + 'auto.hooks.useAutomationDispatchEvents.386db94f3e', + 'The target project is no longer available.' + ) + }) + return + } + + try { + const worktree = await prepareAutomationDispatchWorkspace({ + state, + automation, + run, + dispatchToken, + resolved: { ...resolved, repo: resolved.repo }, + markDispatchResult + }) + if (!worktree) { + return + } + const completion = createAutomationDispatchCompletion({ + run, + worktree, + precheckResult: resolved.context.precheckResult, + markDispatchResult, + releaseTerminalOwnership, + finalizeTerminalOwnership + }) + const dispatchStartedAt = Date.now() + if (automation.reuseSession) { + const reusableSession = findReusableAutomationSession({ + automationId: automation.id, + agentId: automation.agentId, + worktreeId: worktree.id, + currentRunId: run.id, + // Dispatch runs only on desktop authority, so history reads explicitly target the local runtime. + runs: await listAutomationRunsForTarget({ kind: 'local' }, automation.id), + state: useAppStore.getState() + }) + if (reusableSession) { + const releaseTab = acquireReuseDispatchTab(reusableSession.tabId) + if (releaseTab) { + completion.setReuseDispatchTabRelease(releaseTab) + try { + const submitted = await submitPromptToAgentPty({ + tabId: reusableSession.tabId, + ptyId: reusableSession.ptyId, + content: automation.prompt + }) + if (!submitted) { + completion.cleanupRunObservers() + } else { + let reuseSawWorking = false + const handleReusableAgentStatus = (payload: { state: string }): void => { + if (payload.state === 'working') { + reuseSawWorking = true + return + } + if (payload.state === 'done' && reuseSawWorking) { + completion.handleAgentDone() + } + } + const reuseCompletionStartedAt = Date.now() + completion.setSessionObserver( + await observeExistingAutomationSession({ + ptyId: reusableSession.ptyId, + paneKey: reusableSession.paneKey, + runId: run.id, + onData: completion.appendOutput, + onAgentStatus: (payload) => { + completion.captureAssistantMessage(payload.lastAssistantMessage) + handleReusableAgentStatus(payload) + }, + onExit: completion.handleExit + }) + ) + completion.observeAgentStatus(reusableSession.paneKey, reuseCompletionStartedAt, { + requireWorkingAfterStart: true + }) + await markDispatchResult({ + runId: run.id, + status: 'dispatched', + workspaceId: worktree.id, + workspaceDisplayName: worktree.displayName, + terminalSessionId: reusableSession.tabId, + terminalPaneKey: reusableSession.paneKey, + terminalPtyId: reusableSession.ptyId, + precheckResult: resolved.context.precheckResult, + error: null + }) + await completion.settlePendingAfterDispatch() + return + } + } catch (error) { + completion.cleanupRunObservers() + throw error + } + } + } + } + const result = await launchAgentBackgroundSession({ + agent: automation.agentId, + worktreeId: worktree.id, + prompt: automation.prompt, + ...(automation.extraAgentArgs ? { extraAgentArgs: automation.extraAgentArgs } : {}), + launchSource: 'unknown', + title: run.title, + onData: completion.appendOutput, + onAgentStatus: (payload) => { + completion.captureAssistantMessage(payload.lastAssistantMessage) + // Why: session-boundary done = launch connect, not run completion (see observeAgentStatus). + if (payload.state !== 'done' || payload.sessionBoundary === true) { + return + } + completion.handleAgentDone() + }, + onExit: (_ptyId, code) => { + completion.handleExit(code) + } + }) + if (!result) { + throw new Error('Unable to build an agent launch plan.') + } + terminalOwnership = result.terminalOwnership + completion.setSessionObserver(result.releaseRuntimeObservers) + if (automation.reuseSession) { + // Preserve the first fresh-launch seed under the same completion policy as reused tabs. + releaseTerminalOwnership() + } + const launchedTabId = result.tabId + completion.observeAgentStatus(result.paneKey, dispatchStartedAt) + try { + await markDispatchResult({ + runId: run.id, + status: 'dispatched', + workspaceId: worktree.id, + workspaceDisplayName: worktree.displayName, + terminalSessionId: launchedTabId, + terminalPaneKey: result.paneKey, + terminalPtyId: result.ptyId, + precheckResult: resolved.context.precheckResult, + error: null + }) + await completion.settlePendingAfterDispatch() + } catch (error) { + completion.cleanupRunObservers() + throw error + } + const currentState = useAppStore.getState() + // Scheduled/Run Now dispatch stays in background; explicit row clicks alone navigate. + if ( + focusBeforeDispatch.activeWorktreeId !== worktree.id && + currentState.activeWorktreeId === worktree.id + ) { + currentState.setActiveView(focusBeforeDispatch.activeView) + restoreWorkspaceSelection(currentState, focusBeforeDispatch.selection) + if (focusBeforeDispatch.activeTabId) { + currentState.setActiveTab(focusBeforeDispatch.activeTabId) + } + currentState.setActiveTabType( + focusBeforeDispatch.activeTabType, + focusBeforeDispatch.activeWorktreeId + ) + } + } catch (error) { + releaseTerminalOwnership() + await markDispatchResult({ + runId: run.id, + status: 'dispatch_failed', + workspaceId: resolved.context.workspaceId, + workspaceDisplayName: resolved.context.workspaceDisplayName, + precheckResult: resolved.context.precheckResult, + error: error instanceof Error ? error.message : String(error) + }) + } +} diff --git a/src/renderer/src/hooks/automation-dispatch-observer-test-probe.ts b/src/renderer/src/hooks/automation-dispatch-observer-test-probe.ts new file mode 100644 index 000000000000..302c052782c8 --- /dev/null +++ b/src/renderer/src/hooks/automation-dispatch-observer-test-probe.ts @@ -0,0 +1,30 @@ +import type { AgentStatusEntry } from '../../../shared/agent-status-types' + +const TARGET_PANE_KEY = 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d' + +export function countUnchangedObserverHistoryReads( + state: { agentStatusByPaneKey: Record }, + subscriber: (() => void) | null +): number { + if (!subscriber) { + throw new Error('agent status observer was not registered') + } + let historyReads = 0 + state.agentStatusByPaneKey = { + [TARGET_PANE_KEY]: { + paneKey: TARGET_PANE_KEY, + state: 'working', + prompt: 'turn', + updatedAt: Date.now() + 1, + stateStartedAt: Date.now() + 1, + get stateHistory() { + historyReads += 1 + return [] + } + } + } + subscriber() + historyReads = 0 + subscriber() + return historyReads +} diff --git a/src/renderer/src/hooks/automation-dispatch-unverifiable-loss.test.ts b/src/renderer/src/hooks/automation-dispatch-unverifiable-loss.test.ts new file mode 100644 index 000000000000..a8a525495b92 --- /dev/null +++ b/src/renderer/src/hooks/automation-dispatch-unverifiable-loss.test.ts @@ -0,0 +1,102 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { AutomationDispatchResult } from '../../../shared/automations-types' +import type { AutomationTerminalOwnership } from '@/lib/automation-terminal-ownership' + +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => ({ agentStatusByPaneKey: {} }), + subscribe: vi.fn(() => () => {}) + } +})) + +const markDispatchResult = vi.fn<(result: AutomationDispatchResult) => Promise>() +const releaseTerminalOwnership = vi.fn() +const finalizeTerminalOwnership = vi.fn(async () => null) + +async function createCompletion() { + const { createAutomationDispatchCompletion } = await import('./automation-dispatch-completion') + const completion = createAutomationDispatchCompletion({ + run: { id: 'run-1' } as never, + worktree: { id: 'wt-1', displayName: 'Automation worktree' } as never, + precheckResult: null, + markDispatchResult, + releaseTerminalOwnership, + finalizeTerminalOwnership + }) + await completion.settlePendingAfterDispatch() + markDispatchResult.mockClear() + return completion +} + +/** + * Loss of contact is never evidence of process death + * (docs/reference/ssh-execution-boundary.md). The exit sentinel these readers + * receive is the same one the terminal panes already classify as unverifiable. + */ +describe('automation dispatch completion on an unverifiable loss', () => { + beforeEach(() => { + vi.clearAllMocks() + markDispatchResult.mockResolvedValue(undefined) + finalizeTerminalOwnership.mockResolvedValue(null) + }) + + it('records no result, so the run keeps its non-final dispatched status', async () => { + // Exit -1 is unobserved relay/host loss, never a witnessed finish; SSH work may still run. + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const completion = await createCompletion() + + completion.handleExit(-1) + await vi.waitFor(() => expect(releaseTerminalOwnership).toHaveBeenCalledOnce()) + + expect(markDispatchResult).not.toHaveBeenCalled() + // Closing a terminal whose process cannot be proven dead orphans live work. + expect(finalizeTerminalOwnership).not.toHaveBeenCalled() + warnSpy.mockRestore() + }) + + it('still completes and finalizes a genuinely exited process', async () => { + const completion = await createCompletion() + finalizeTerminalOwnership.mockResolvedValue('closed') + + completion.handleExit(0) + await vi.waitFor(() => expect(finalizeTerminalOwnership).toHaveBeenCalledOnce()) + + expect(markDispatchResult).toHaveBeenCalledWith( + expect.objectContaining({ runId: 'run-1', status: 'completed', error: null }) + ) + expect(releaseTerminalOwnership).not.toHaveBeenCalled() + }) + + it('still reports a real automation failure as dispatch_failed', async () => { + const completion = await createCompletion() + + completion.handleExit(9) + await vi.waitFor(() => expect(releaseTerminalOwnership).toHaveBeenCalledOnce()) + + expect(markDispatchResult).toHaveBeenCalledWith( + expect.objectContaining({ + runId: 'run-1', + status: 'dispatch_failed', + error: 'Automation process exited with code 9.' + }) + ) + expect(finalizeTerminalOwnership).not.toHaveBeenCalled() + }) + + it('lets a later done still complete a run whose contact was lost', async () => { + // Loss withholds judgment; later positive evidence must still finish the run. + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const completion = await createCompletion() + + completion.handleExit(-1) + await vi.waitFor(() => expect(releaseTerminalOwnership).toHaveBeenCalledOnce()) + completion.handleAgentDone() + + await vi.waitFor(() => + expect(markDispatchResult).toHaveBeenCalledWith( + expect.objectContaining({ status: 'completed' }) + ) + ) + warnSpy.mockRestore() + }) +}) diff --git a/src/renderer/src/hooks/automation-dispatch-workspace.ts b/src/renderer/src/hooks/automation-dispatch-workspace.ts new file mode 100644 index 000000000000..dcb21ef597e5 --- /dev/null +++ b/src/renderer/src/hooks/automation-dispatch-workspace.ts @@ -0,0 +1,258 @@ +import { useAppStore } from '@/store' +import { translate } from '@/i18n/i18n' +import { createBrowserUuid } from '@/lib/browser-uuid' +import { getResolvedExecutionHostIdForWorktree } from '@/lib/resolved-worktree-execution-host' +import type { + Automation, + AutomationDispatchResult, + AutomationPrecheckResult, + AutomationRun +} from '../../../shared/automations-types' +import { getAutomationRunRepoId } from '../../../shared/automation-run-identity' +import { + didAutomationPrecheckPass, + formatAutomationPrecheckFailure +} from '../../../shared/automation-precheck' +import { + getRepoExecutionHostId, + parseExecutionHostId, + toSshExecutionHostId +} from '../../../shared/execution-host' +import { resolveFolderWorkspaceHost } from '../../../shared/folder-workspace-execution-host' +import type { Worktree } from '../../../shared/worktree/types' +import { parseWorkspaceKey } from '../../../shared/workspace-scope' + +type AutomationDispatchStoreState = ReturnType +type MarkDispatchResult = (result: AutomationDispatchResult) => Promise + +export type AutomationDispatchWorkspaceContext = { + workspaceId: string | null + workspaceDisplayName: string | null + precheckResult: AutomationPrecheckResult | null +} + +export function resolveAutomationDispatchWorkspace( + state: AutomationDispatchStoreState, + automation: Automation, + run: AutomationRun +) { + const runRepoId = getAutomationRunRepoId(automation) + const repo = state.repos.find((entry) => entry.id === runRepoId) + const automationWorkspaceScope = parseWorkspaceKey(automation.workspaceId ?? '') + const automationWorktree = automation.workspaceId + ? automationWorkspaceScope?.type === 'folder' + ? state.getKnownWorktreeById(automation.workspaceId) + : state.allWorktrees().find((entry) => entry.id === automation.workspaceId) + : null + const context: AutomationDispatchWorkspaceContext = { + workspaceId: automation.workspaceId, + workspaceDisplayName: automationWorktree?.displayName ?? run.workspaceDisplayName ?? null, + precheckResult: null + } + return { runRepoId, repo, automationWorkspaceScope, automationWorktree, context } +} + +type ResolvedAutomationDispatchWorkspace = ReturnType + +export async function prepareAutomationDispatchWorkspace(args: { + state: AutomationDispatchStoreState + automation: Automation + run: AutomationRun + dispatchToken: string + resolved: ResolvedAutomationDispatchWorkspace & { + repo: NonNullable + } + markDispatchResult: MarkDispatchResult +}): Promise { + const { state, automation, run, dispatchToken, resolved, markDispatchResult } = args + const { repo, runRepoId, automationWorkspaceScope, automationWorktree, context } = resolved + const folderWorkspaceHost = + automationWorkspaceScope?.type === 'folder' + ? resolveFolderWorkspaceHost(state, automationWorkspaceScope.folderWorkspaceId) + : null + const folderWorkspaceConnectionId = + folderWorkspaceHost?.kind === 'ssh' ? folderWorkspaceHost.targetId : null + // A workspace whose host does not resolve to one place is refused, not guessed at. + const folderWorkspaceHostUnresolved = + folderWorkspaceHost !== null && folderWorkspaceHost.kind === 'ambiguous' + const folderWorkspaceHostId = + folderWorkspaceHost && automationWorktree + ? folderWorkspaceConnectionId + ? toSshExecutionHostId(folderWorkspaceConnectionId) + : folderWorkspaceHost.kind === 'local' || folderWorkspaceHost.kind === 'runtime' + ? getResolvedExecutionHostIdForWorktree(state, automationWorktree.id) + : null + : null + const runHostId = + parseExecutionHostId(automation.runContext?.hostId)?.id ?? getRepoExecutionHostId(repo) + const workspaceMatchesRunTarget = + automationWorkspaceScope?.type === 'folder' + ? folderWorkspaceHostId !== null && folderWorkspaceHostId === runHostId + : !automation.runContext?.repoId || + automationWorktree?.repoId === automation.runContext.repoId + if (automation.workspaceMode === 'existing' && automationWorktree && !workspaceMatchesRunTarget) { + await markDispatchResult({ + runId: run.id, + status: 'skipped_unavailable', + workspaceId: automation.workspaceId, + workspaceDisplayName: context.workspaceDisplayName, + error: folderWorkspaceHostUnresolved + ? translate( + 'auto.hooks.useAutomationDispatchEvents.workspaceHostUnresolved', + 'The target workspace spans more than one host, so this run has no single host to use.' + ) + : translate( + 'auto.hooks.useAutomationDispatchEvents.3ad7d77f57', + 'The target workspace is on a different host than this automation run target.' + ) + }) + return null + } + const sshTargetId = + automationWorkspaceScope?.type === 'folder' + ? (folderWorkspaceConnectionId ?? null) + : (repo.connectionId ?? null) + if (sshTargetId) { + const needsPrompt = await window.api.ssh.needsPassphrasePrompt({ + targetId: sshTargetId + }) + if (needsPrompt) { + await markDispatchResult({ + runId: run.id, + status: 'skipped_needs_interactive_auth', + workspaceId: context.workspaceId, + workspaceDisplayName: context.workspaceDisplayName, + error: translate( + 'auto.hooks.useAutomationDispatchEvents.16a21d6413', + 'SSH reconnect requires interactive credentials.' + ) + }) + return null + } + const sshState = await window.api.ssh.getState({ targetId: sshTargetId }) + if (sshState?.status !== 'connected') { + try { + const connected = await window.api.ssh.connect({ targetId: sshTargetId, automatic: true }) + if (connected?.status !== 'connected') { + throw new Error('SSH target is unavailable.') + } + } catch (error) { + await markDispatchResult({ + runId: run.id, + status: 'skipped_unavailable', + workspaceId: context.workspaceId, + workspaceDisplayName: context.workspaceDisplayName, + error: error instanceof Error ? error.message : String(error) + }) + return null + } + } + } + + if (automation.workspaceMode === 'existing' && !automationWorktree) { + await markDispatchResult({ + runId: run.id, + status: 'skipped_unavailable', + workspaceId: automation.workspaceId, + workspaceDisplayName: context.workspaceDisplayName, + error: translate( + 'auto.hooks.useAutomationDispatchEvents.59718b120b', + 'The target workspace is no longer available.' + ) + }) + return null + } + + if (run.trigger === 'scheduled' && automation.precheck) { + context.precheckResult = await window.api.automations.runPrecheck({ + automationId: automation.id, + runId: run.id + }) + if (context.precheckResult && !didAutomationPrecheckPass(context.precheckResult)) { + await markDispatchResult({ + runId: run.id, + status: 'skipped_precheck', + workspaceId: context.workspaceId, + workspaceDisplayName: context.workspaceDisplayName, + precheckResult: context.precheckResult, + error: formatAutomationPrecheckFailure(context.precheckResult) + }) + return null + } + } + + const automationWorkspaceCreateRequestId = createBrowserUuid() + const createResult = + automation.workspaceMode === 'new_per_run' + ? await useAppStore.getState().createWorktree( + runRepoId, + buildAutomationWorkspaceName(run.title, run.scheduledFor), + automation.baseBranch ?? undefined, + automation.setupDecision ?? 'skip', + undefined, + 'unknown', + run.title, + undefined, + undefined, + undefined, + // The automation owns its prompt-bearing tab; createdWithAgent would reopen an empty fallback. + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + { + // Why: only a captured host; with none, a project two hosts publish refuses, never guesses. + executionHostId: parseExecutionHostId(automation.runContext?.hostId)?.id, + automationProvenanceRequest: { + automationId: automation.id, + automationRunId: run.id, + dispatchToken, + createRequestId: automationWorkspaceCreateRequestId + } + } + ) + : null + const worktree = createResult + ? createResult.worktree + : automation.workspaceId + ? automationWorktree + : null + + if (!worktree) { + await markDispatchResult({ + runId: run.id, + status: 'skipped_unavailable', + workspaceId: automation.workspaceId, + workspaceDisplayName: context.workspaceDisplayName, + error: translate( + 'auto.hooks.useAutomationDispatchEvents.59718b120b', + 'The target workspace is no longer available.' + ) + }) + return null + } + context.workspaceId = worktree.id + context.workspaceDisplayName = worktree.displayName + return worktree +} + +function buildAutomationWorkspaceName(runTitle: string, scheduledFor: number): string { + const slug = runTitle + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, '') + .slice(0, 40) + const stamp = new Date(scheduledFor).toISOString().replace(/[-:]/g, '').slice(0, 13) + return `auto-${slug || 'run'}-${stamp}` +} diff --git a/src/renderer/src/hooks/ipc-events/terminal-presentation-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/terminal-presentation-ipc-bridge.ts index 1e444097bc5a..4d97e494a02a 100644 --- a/src/renderer/src/hooks/ipc-events/terminal-presentation-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/terminal-presentation-ipc-bridge.ts @@ -1,7 +1,7 @@ -import { requestBackgroundTerminalWorktreeMount } from '@/components/terminal/background-terminal-worktree-mount' -import { registerTerminalTabMountIpcBridge } from './terminal-tab-mount-ipc-bridge' -import { registerAutomationTerminalLifecycle } from '@/lib/automation-terminal-ownership' import { presentAgentLaunchTab } from '@/lib/agent-launch-tab-presentation' +import { requestBackgroundTerminalWorktreeMount } from '@/components/terminal/background-terminal-worktree-mount' +import { hasRegisteredRuntimeTerminalTab } from '@/runtime/mounted-terminal-tab-registry' +import { planMobileTerminalTabMount } from '@/lib/mobile-terminal-tab-mount' import { resolveTerminalTabPtyOwnership } from '@/lib/terminal-tab-for-pty-id' import { SPLIT_TERMINAL_PANE_EVENT } from '@/constants/terminal' import type { SplitTerminalPaneDetail } from '@/constants/terminal' @@ -22,7 +22,6 @@ import { } from './terminal-command-state' export function registerTerminalPresentationIpcBridge(unsubs: (() => void)[]): void { - unsubs.push(registerAutomationTerminalLifecycle()) unsubs.push( window.api.ui.onLaunchRecipe(registerLaunchRecipe), window.api.ui.onCreateTerminal( @@ -96,19 +95,7 @@ export function registerTerminalPresentationIpcBridge(unsubs: (() => void)[]): v ownership.kind === 'owned' ? worktreeTabs.find((candidate) => candidate.id === ownership.tabId) : undefined - const reservedTab = - tabId && leafId && ptyId && !splitFromLeafId - ? worktreeTabs.find((tab) => { - const root = store.terminalLayoutsByTabId[tab.id]?.root - return ( - tab.id === tabId && - tab.ptyId === null && - root?.type === 'leaf' && - root.leafId === leafId - ) - }) - : undefined - let reusedTab = existingTab ?? splitTargetTab ?? reservedTab + let reusedTab = existingTab ?? splitTargetTab // Reuse main’s frame-drawn tab even if stale records make legacy ownership ambiguous. const frameDrawnTab = ORCA_LAYOUT_OWNER_IS_MAIN && !reusedTab && tabId !== undefined @@ -295,7 +282,30 @@ export function registerTerminalPresentationIpcBridge(unsubs: (() => void)[]): v ) ) - unsubs.push(registerTerminalTabMountIpcBridge()) + // Why: background-mount a mobile-subscribed tab's PTY without navigating the desktop (STA-1840). + unsubs.push( + window.api.ui.onRequestTerminalTabMount(({ worktreeId, tabId, ptyId }) => { + if (!worktreeId) { + return + } + // Why: synthetic pty handles need persisted-tab resolution; a miss must not mount every saved tab in a hidden worktree. + const mount = planMobileTerminalTabMount( + useAppStore.getState(), + { + worktreeId, + ...(tabId ? { tabId } : {}), + ...(ptyId ? { ptyId } : {}) + }, + { + isTabMounted: (tabId, targetWorktreeId) => + hasRegisteredRuntimeTerminalTab(tabId, targetWorktreeId) + } + ) + if (mount) { + requestBackgroundTerminalWorktreeMount(mount) + } + }) + ) // Why: CLI-driven terminal creation waits for the tabId reply so it can hand the caller a usable handle immediately. } diff --git a/src/renderer/src/hooks/ipc-events/terminal-presentation-pane-title.test.ts b/src/renderer/src/hooks/ipc-events/terminal-presentation-pane-title.test.ts index 5f1a1433d53f..2dce478d7f6e 100644 --- a/src/renderer/src/hooks/ipc-events/terminal-presentation-pane-title.test.ts +++ b/src/renderer/src/hooks/ipc-events/terminal-presentation-pane-title.test.ts @@ -75,14 +75,7 @@ async function setup(windowHoldsTab: boolean) { : vi.fn() } ) - vi.stubGlobal('window', { - dispatchEvent: vi.fn(), - api: { - ...createStoreSessionMockApi(), - ui, - automations: { onTerminalLifecycleRequest: () => () => {} } - } - }) + vi.stubGlobal('window', { dispatchEvent: vi.fn(), api: { ...createStoreSessionMockApi(), ui } }) const store = createTestStore() mocks.store.current = store seedStore(store, { @@ -128,7 +121,6 @@ async function setup(windowHoldsTab: boolean) { title: 'Build', presentation: 'background' }) - await vi.dynamicImportSettled() return store.getState() } diff --git a/src/renderer/src/hooks/ipc-events/terminal-tab-mount-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/terminal-tab-mount-ipc-bridge.ts deleted file mode 100644 index 9961acab4340..000000000000 --- a/src/renderer/src/hooks/ipc-events/terminal-tab-mount-ipc-bridge.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { requestBackgroundTerminalWorktreeMount } from '@/components/terminal/background-terminal-worktree-mount' -import { hasRegisteredRuntimeTerminalTab } from '@/runtime/mounted-terminal-tab-registry' -import { planMobileTerminalTabMount } from '@/lib/mobile-terminal-tab-mount' -import { useAppStore } from '../../store' - -export function registerTerminalTabMountIpcBridge(): () => void { - return window.api.ui.onRequestTerminalTabMount(({ worktreeId, tabId, ptyId }) => { - if (!worktreeId) { - return - } - // Why: synthetic pty handles need persisted-tab resolution; a miss must not mount every saved tab in a hidden worktree. - const mount = planMobileTerminalTabMount( - useAppStore.getState(), - { - worktreeId, - ...(tabId ? { tabId } : {}), - ...(ptyId ? { ptyId } : {}) - }, - { - isTabMounted: (tabId, targetWorktreeId) => - hasRegisteredRuntimeTerminalTab(tabId, targetWorktreeId) - } - ) - if (mount) { - requestBackgroundTerminalWorktreeMount(mount) - } - }) -} diff --git a/src/renderer/src/hooks/useAutomationDispatchEvents.test.ts b/src/renderer/src/hooks/useAutomationDispatchEvents.test.ts index 8d2bf7960050..e5eebaccc62a 100644 --- a/src/renderer/src/hooks/useAutomationDispatchEvents.test.ts +++ b/src/renderer/src/hooks/useAutomationDispatchEvents.test.ts @@ -1,17 +1,874 @@ -import { expect, it, vi } from 'vitest' import type * as ReactModule from 'react' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { AUTOMATIONS_CHANGED_EVENT } from '@/lib/automations-changed-window-event' +import { countUnchangedObserverHistoryReads } from './automation-dispatch-observer-test-probe' -it('marks desktop scheduling ready without installing a renderer-only launcher', async () => { - vi.doMock('react', async () => ({ - ...(await vi.importActual('react')), - useEffect: (effect: () => void) => effect() - })) - const rendererReady = vi.fn() - const onDispatchRequested = vi.fn() - vi.stubGlobal('window', { api: { automations: { rendererReady, onDispatchRequested } } }) - const { useAutomationDispatchEvents } = await import('./useAutomationDispatchEvents') - useAutomationDispatchEvents() - expect(rendererReady).toHaveBeenCalledOnce() - expect(onDispatchRequested).not.toHaveBeenCalled() - vi.unstubAllGlobals() +const mockDispatchEvent = vi.fn() + +const mockLaunchAgentBackgroundSession = vi.fn() +const mockFindReusableAutomationSession = vi.fn() +const mockObserveExistingAutomationSession = vi.fn() +const mockSubmitPromptToAgentPty = vi.fn() +const mockCreateWorktree = vi.fn() +const mockMarkDispatchResult = vi.fn() +const mockOnDispatchRequested = vi.fn() +const mockRendererReady = vi.fn() +const mockFinalizeTerminalOwnership = vi.fn() +const mockReleaseTerminalOwnership = vi.fn() +const mockReleaseRuntimeObservers = vi.fn() +const mockSshNeedsPassphrasePrompt = vi.fn() +const mockSshGetState = vi.fn() +const mockSshConnect = vi.fn() +let latestStoreSubscriber: (() => void) | null = null +const mockStoreSubscribe = vi.fn((listener: () => void) => { + latestStoreSubscriber = listener + return () => {} +}) + +const createdWorktree = { + id: 'wt-created', + repoId: 'repo-1', + displayName: 'Automation worktree', + path: '/repo/worktree' +} +type TestWorktree = typeof createdWorktree +type TestRepo = { + id: string + connectionId: string | null + executionHostId: string | null + path: string +} + +function noSelectedHost(): string | null { + return null +} + +const state = { + activeView: 'terminal' as const, + activeWorktreeId: 'wt-active', + activeWorkspaceExecutionHostId: noSelectedHost(), + activeTabId: 'tab-active', + activeTabType: 'terminal' as const, + repos: [{ id: 'repo-1', connectionId: null, executionHostId: null, path: '/repo' }] as TestRepo[], + folderWorkspaces: [] as { + id: string + projectGroupId: string + folderPath: string + connectionId: string | null + }[], + projectGroups: [] as { + id: string + connectionId: string | null + executionHostId?: string | null + }[], + worktreesByRepo: {} as Record, + detectedWorktreesByRepo: {}, + agentStatusByPaneKey: {}, + allWorktrees: vi.fn<() => TestWorktree[]>(() => []), + getKnownWorktreeById: vi.fn<(worktreeId: string) => TestWorktree | undefined>(() => undefined), + createWorktree: mockCreateWorktree, + subscribe: vi.fn(() => () => {}), + setActiveView: vi.fn(), + setActiveWorktree: vi.fn(), + setActiveTab: vi.fn(), + setActiveTabType: vi.fn() +} + +function makeAutomation(overrides: Record = {}) { + return { + id: 'automation-1', + projectId: 'repo-1', + prompt: 'run this', + precheck: null, + agentId: 'claude', + workspaceMode: 'new_per_run', + workspaceId: null, + baseBranch: null, + setupDecision: 'run', + reuseSession: false, + ...overrides + } +} + +function makeRun() { + return { + id: 'run-1', + automationId: 'automation-1', + title: 'Nightly setup run', + scheduledFor: Date.parse('2026-06-24T03:00:00Z'), + trigger: 'scheduled', + workspaceId: null, + workspaceDisplayName: null + } +} + +async function registerAndDispatch(automation = makeAutomation()): Promise { + vi.doMock('react', async () => { + const actual = await vi.importActual('react') + return { + ...actual, + useEffect: (effect: () => void | (() => void)) => { + effect() + } + } + }) + const { useAutomationDispatchEvents: registerAutomationDispatchEvents } = + await import('./useAutomationDispatchEvents') + registerAutomationDispatchEvents() + const handler = mockOnDispatchRequested.mock.calls[0]?.[0] + if (!handler) { + throw new Error('dispatch handler was not registered') + } + await handler({ + automation, + run: makeRun(), + dispatchToken: 'dispatch-token' + }) +} + +vi.mock('@/lib/launch-agent-background-session', () => ({ + launchAgentBackgroundSession: mockLaunchAgentBackgroundSession +})) + +vi.mock('@/lib/agent-paste-draft', () => ({ + submitPromptToAgentPty: mockSubmitPromptToAgentPty +})) + +// The reuse path reads run history over the local runtime target, not IPC. +vi.mock('@/components/automations/automation-host-client', () => ({ + listAutomationRunsForTarget: vi.fn().mockResolvedValue([]) +})) + +vi.mock('@/lib/automation-session-reuse', () => ({ + findReusableAutomationSession: mockFindReusableAutomationSession +})) + +vi.mock('@/lib/automation-session-observer', () => ({ + observeExistingAutomationSession: mockObserveExistingAutomationSession +})) + +vi.mock('@/components/automations/automation-run-output-snapshot', () => ({ + createAutomationRunOutputSnapshotBuffer: () => ({ + append: vi.fn(), + snapshot: () => null + }), + selectAutomationRunOutputSnapshot: ( + assistantMessage: string | null | undefined, + terminalSnapshot: unknown + ) => + assistantMessage + ? { + format: 'plain_text', + content: assistantMessage, + capturedAt: 1, + truncated: false + } + : terminalSnapshot +})) + +vi.mock('@/i18n/i18n', () => ({ + translate: (_key: string, fallback: string) => fallback +})) + +vi.mock('@/lib/browser-uuid', () => ({ + createBrowserUuid: () => 'create-request-id' +})) + +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => state, + subscribe: mockStoreSubscribe + } +})) + +describe('useAutomationDispatchEvents setup launch', () => { + beforeEach(() => { + vi.resetModules() + vi.unstubAllGlobals() + vi.clearAllMocks() + state.activeView = 'terminal' + state.activeWorktreeId = 'wt-active' + state.activeWorkspaceExecutionHostId = null + state.activeTabId = 'tab-active' + state.activeTabType = 'terminal' + state.repos = [{ id: 'repo-1', connectionId: null, executionHostId: null, path: '/repo' }] + state.folderWorkspaces = [] + state.projectGroups = [] + state.worktreesByRepo = {} + state.agentStatusByPaneKey = {} + latestStoreSubscriber = null + state.allWorktrees.mockReturnValue([]) + state.getKnownWorktreeById.mockReturnValue(undefined) + mockCreateWorktree.mockResolvedValue({ worktree: createdWorktree }) + mockLaunchAgentBackgroundSession.mockResolvedValue({ + tabId: 'agent-tab', + paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', + ptyId: 'agent-pty', + startupPlan: {}, + releaseRuntimeObservers: mockReleaseRuntimeObservers, + terminalOwnership: { + finalize: mockFinalizeTerminalOwnership, + release: mockReleaseTerminalOwnership + } + }) + mockOnDispatchRequested.mockReturnValue(() => {}) + mockSshNeedsPassphrasePrompt.mockResolvedValue(false) + mockSshGetState.mockResolvedValue({ status: 'connected' }) + mockSshConnect.mockResolvedValue({ status: 'connected' }) + mockSubmitPromptToAgentPty.mockResolvedValue(true) + vi.stubGlobal('window', { + api: { + automations: { + onDispatchRequested: mockOnDispatchRequested, + rendererReady: mockRendererReady, + markDispatchResult: mockMarkDispatchResult, + runPrecheck: vi.fn() + }, + ssh: { + needsPassphrasePrompt: mockSshNeedsPassphrasePrompt, + getState: mockSshGetState, + connect: mockSshConnect + } + }, + dispatchEvent: mockDispatchEvent + }) + }) + + it('restores the prior workspace on the host it was selected on', async () => { + state.activeWorkspaceExecutionHostId = 'ssh:box' + mockLaunchAgentBackgroundSession.mockImplementationOnce(async () => { + state.activeWorktreeId = createdWorktree.id + return { + tabId: 'agent-tab', + paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', + ptyId: 'agent-pty', + startupPlan: {}, + terminalOwnership: { + finalize: mockFinalizeTerminalOwnership, + release: mockReleaseTerminalOwnership + } + } + }) + + await registerAndDispatch() + + expect(state.setActiveWorktree).toHaveBeenCalledWith('wt-active', 'ssh:box') + }) + + // The writer’s host-scoped event is sufficient; extra local emit would invalidate every catalog host. + it('leaves the automationsChanged event to the host that owns the write', async () => { + await registerAndDispatch() + + expect(mockMarkDispatchResult).toHaveBeenCalled() + expect( + mockDispatchEvent.mock.calls.filter(([event]) => event?.type === AUTOMATIONS_CHANGED_EVENT) + ).toEqual([]) + }) + + it('defaults legacy automations without a setup choice to skipping setup', async () => { + await registerAndDispatch(makeAutomation({ setupDecision: undefined })) + + expect(mockCreateWorktree.mock.calls[0][3]).toBe('skip') + expect(mockLaunchAgentBackgroundSession).toHaveBeenCalled() + }) + + it('creates a new-per-run workspace on the captured run host, and names none without one', async () => { + await registerAndDispatch(makeAutomation({ runContext: { repoId: 'repo-1', hostId: 'local' } })) + expect(mockCreateWorktree.mock.calls[0]?.at(-1)).toEqual( + expect.objectContaining({ executionHostId: 'local' }) + ) + + mockCreateWorktree.mockClear() + await registerAndDispatch() + expect(mockCreateWorktree.mock.calls[0]?.at(-1)).toEqual( + expect.objectContaining({ executionHostId: undefined }) + ) + }) + + it('does not stamp the created workspace with an empty agent-launch fallback', async () => { + await registerAndDispatch() + + expect(mockCreateWorktree.mock.calls[0][10]).toBeUndefined() + expect(mockLaunchAgentBackgroundSession).toHaveBeenCalledWith( + expect.objectContaining({ + agent: 'claude', + prompt: 'run this', + worktreeId: 'wt-created' + }) + ) + }) + + it('does not rerun setup for existing-worktree automations', async () => { + const existingWorktree = { + id: 'wt-existing', + repoId: 'repo-1', + displayName: 'Existing workspace', + path: '/repo/existing' + } + state.allWorktrees.mockReturnValue([existingWorktree]) + + await registerAndDispatch( + makeAutomation({ + workspaceMode: 'existing', + workspaceId: 'wt-existing', + setupDecision: 'run' + }) + ) + + expect(mockCreateWorktree).not.toHaveBeenCalled() + expect(mockLaunchAgentBackgroundSession).toHaveBeenCalledWith( + expect.objectContaining({ + worktreeId: 'wt-existing', + prompt: 'run this' + }) + ) + }) + + it('dispatches an existing SSH folder workspace on its resolved host', async () => { + const folderWorkspace = { + id: 'folder:fw-1', + repoId: 'folder-workspace:group-1', + displayName: 'SSH folder', + path: '/srv/project' + } + state.repos = [ + { + id: 'repo-1', + connectionId: 'ssh-folder', + executionHostId: null, + path: '/srv/project/repo' + } + ] + state.folderWorkspaces = [ + { + id: 'fw-1', + projectGroupId: 'group-1', + folderPath: '/srv/project', + connectionId: 'ssh-folder' + } + ] + state.projectGroups = [{ id: 'group-1', connectionId: 'ssh-folder' }] + state.getKnownWorktreeById.mockReturnValue(folderWorkspace) + mockSshGetState.mockResolvedValue({ status: 'disconnected' }) + + await registerAndDispatch( + makeAutomation({ + workspaceMode: 'existing', + workspaceId: folderWorkspace.id, + setupDecision: 'skip', + runContext: { repoId: 'repo-1', hostId: 'ssh:ssh-folder' } + }) + ) + + expect(state.allWorktrees).not.toHaveBeenCalled() + expect(mockSshConnect).toHaveBeenCalledWith({ targetId: 'ssh-folder', automatic: true }) + expect(mockLaunchAgentBackgroundSession).toHaveBeenCalledWith( + expect.objectContaining({ + worktreeId: folderWorkspace.id, + prompt: 'run this' + }) + ) + expect(mockMarkDispatchResult).toHaveBeenCalledWith( + expect.objectContaining({ + status: 'dispatched', + workspaceId: folderWorkspace.id, + workspaceDisplayName: folderWorkspace.displayName + }) + ) + }) + + it('dispatches a local folder workspace without SSH', async () => { + const folderWorkspace = { + id: 'folder:fw-local', + repoId: 'folder-workspace:group-local', + displayName: 'Local folder', + path: '/project' + } + state.folderWorkspaces = [ + { + id: 'fw-local', + projectGroupId: 'group-local', + folderPath: '/project', + connectionId: null + } + ] + state.projectGroups = [{ id: 'group-local', connectionId: null }] + state.getKnownWorktreeById.mockReturnValue(folderWorkspace) + + await registerAndDispatch( + makeAutomation({ + workspaceMode: 'existing', + workspaceId: folderWorkspace.id, + runContext: { repoId: 'repo-1', hostId: 'local' } + }) + ) + + expect(mockSshNeedsPassphrasePrompt).not.toHaveBeenCalled() + expect(mockLaunchAgentBackgroundSession).toHaveBeenCalledWith( + expect.objectContaining({ worktreeId: folderWorkspace.id }) + ) + }) + + it('skips a folder workspace owned by a different host', async () => { + const folderWorkspace = { + id: 'folder:fw-other', + repoId: 'folder-workspace:group-other', + displayName: 'Other host', + path: '/srv/other' + } + state.folderWorkspaces = [ + { + id: 'fw-other', + projectGroupId: 'group-other', + folderPath: '/srv/other', + connectionId: 'ssh-other' + } + ] + state.projectGroups = [{ id: 'group-other', connectionId: 'ssh-other' }] + state.getKnownWorktreeById.mockReturnValue(folderWorkspace) + + await registerAndDispatch( + makeAutomation({ + workspaceMode: 'existing', + workspaceId: folderWorkspace.id, + runContext: { repoId: 'repo-1', hostId: 'local' } + }) + ) + + expect(mockLaunchAgentBackgroundSession).not.toHaveBeenCalled() + expect(mockMarkDispatchResult).toHaveBeenCalledWith( + expect.objectContaining({ status: 'skipped_unavailable' }) + ) + }) + + it('keeps detected-only non-folder workspaces unavailable', async () => { + state.getKnownWorktreeById.mockReturnValue({ + id: 'wt-detected', + repoId: 'repo-1', + displayName: 'Detected', + path: '/repo/detected' + }) + + await registerAndDispatch( + makeAutomation({ + workspaceMode: 'existing', + workspaceId: 'wt-detected' + }) + ) + + expect(state.getKnownWorktreeById).not.toHaveBeenCalled() + expect(mockLaunchAgentBackgroundSession).not.toHaveBeenCalled() + expect(mockMarkDispatchResult).toHaveBeenCalledWith( + expect.objectContaining({ status: 'skipped_unavailable' }) + ) + }) + + it.each([ + { + workspace: 'a shared workspace', + provenanceRunId: undefined, + retirement: 'closed', + cleared: { terminalSessionId: null, terminalPaneKey: null, terminalPtyId: null } + }, + { + // Why: the slept pane still holds the run's session, so only its stopped process is dropped. + workspace: 'a workspace made for this run', + provenanceRunId: 'run-1', + retirement: 'hibernated', + cleared: { terminalPtyId: null } + } + ])( + 'retires the terminal in $workspace only after completed result persistence', + async ({ provenanceRunId, retirement, cleared }) => { + const order: string[] = [] + let launchArgs: { onAgentStatus?: (payload: { state: string }) => void } = {} + mockCreateWorktree.mockResolvedValue({ + worktree: provenanceRunId + ? { ...createdWorktree, automationProvenance: { automationRunId: provenanceRunId } } + : createdWorktree + }) + mockMarkDispatchResult.mockImplementation(async (result: { status: string }) => { + // Retirement reuses completed state while clearing terminal identity; distinguish it for ordering assertions. + order.push( + result.status === 'completed' && Object.hasOwn(result, 'terminalPtyId') + ? 'clear-terminal-identity' + : `persist:${result.status}` + ) + }) + mockFinalizeTerminalOwnership.mockImplementationOnce(async () => { + order.push('finalize') + return retirement + }) + mockLaunchAgentBackgroundSession.mockImplementation(async (args) => { + launchArgs = args + return { + tabId: 'agent-tab', + paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', + ptyId: 'agent-pty', + startupPlan: {}, + releaseRuntimeObservers: mockReleaseRuntimeObservers, + terminalOwnership: { + finalize: mockFinalizeTerminalOwnership, + release: mockReleaseTerminalOwnership + } + } + }) + + await registerAndDispatch() + launchArgs.onAgentStatus?.({ state: 'done' }) + await vi.waitFor(() => expect(mockFinalizeTerminalOwnership).toHaveBeenCalledOnce()) + + expect(order).toEqual([ + 'persist:dispatched', + 'persist:completed', + 'finalize', + 'clear-terminal-identity' + ]) + expect(mockReleaseTerminalOwnership).not.toHaveBeenCalled() + expect(mockFinalizeTerminalOwnership).toHaveBeenCalledWith({ + preservePane: provenanceRunId !== undefined + }) + // Why: the retired process is gone; "View run" must not dead-end on a pointer to it. + expect(mockMarkDispatchResult).toHaveBeenLastCalledWith({ + runId: expect.any(String), + status: 'completed', + ...cleared + }) + } + ) + + it('ignores a session-boundary done so a connecting agent cannot complete the run (STA-3386)', async () => { + let launchArgs: { + onAgentStatus?: (payload: { state: string; sessionBoundary?: boolean }) => void + } = {} + mockLaunchAgentBackgroundSession.mockImplementation(async (args) => { + launchArgs = args + return { + tabId: 'agent-tab', + paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', + ptyId: 'agent-pty', + startupPlan: {}, + releaseRuntimeObservers: mockReleaseRuntimeObservers, + terminalOwnership: { + finalize: mockFinalizeTerminalOwnership, + release: mockReleaseTerminalOwnership + } + } + }) + + await registerAndDispatch() + // SessionStart boundary-done precedes prompt submission; treating it as completion closes an empty run. + launchArgs.onAgentStatus?.({ state: 'done', sessionBoundary: true }) + await Promise.resolve() + expect(mockFinalizeTerminalOwnership).not.toHaveBeenCalled() + + launchArgs.onAgentStatus?.({ state: 'done' }) + await vi.waitFor(() => expect(mockFinalizeTerminalOwnership).toHaveBeenCalledOnce()) + }) + + it('skips unchanged status and persists batched working→done→working output', async () => { + const paneKey = 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d' + + await registerAndDispatch() + expect(countUnchangedObserverHistoryReads(state, latestStoreSubscriber)).toBe(0) + const transitionStartedAt = Date.now() + 1 + state.agentStatusByPaneKey = { + [paneKey]: { + paneKey, + state: 'working', + prompt: 'second turn', + agentType: 'claude', + updatedAt: transitionStartedAt + 2, + stateStartedAt: transitionStartedAt + 2, + lastCompletedAssistantMessage: 'Summary.\n\nDetails.', + stateHistory: [ + { state: 'working', prompt: 'first turn', startedAt: transitionStartedAt }, + { state: 'done', prompt: 'first turn', startedAt: transitionStartedAt + 1 } + ] + } + } + if (!latestStoreSubscriber) { + throw new Error('agent status observer was not registered') + } + latestStoreSubscriber() + + await vi.waitFor(() => expect(mockFinalizeTerminalOwnership).toHaveBeenCalledOnce()) + expect(mockMarkDispatchResult).toHaveBeenCalledWith( + expect.objectContaining({ + runId: 'run-1', + status: 'completed', + outputSnapshot: { + format: 'plain_text', + content: 'Summary.\n\nDetails.', + capturedAt: 1, + truncated: false + } + }) + ) + }) + + it('does not let later working authorize an earlier historical done on rescan', async () => { + const paneKey = 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d' + mockFindReusableAutomationSession.mockReturnValue({ + tabId: 'agent-tab', + paneKey, + ptyId: 'agent-pty' + }) + mockObserveExistingAutomationSession.mockResolvedValue(() => {}) + + await registerAndDispatch(makeAutomation({ reuseSession: true })) + const transitionStartedAt = Date.now() + 1 + state.agentStatusByPaneKey = { + [paneKey]: { + paneKey, + state: 'working', + prompt: 'new turn', + agentType: 'claude', + updatedAt: transitionStartedAt + 1, + stateStartedAt: transitionStartedAt + 1, + stateHistory: [{ state: 'done', prompt: 'old turn', startedAt: transitionStartedAt }] + } + } + if (!latestStoreSubscriber) { + throw new Error('agent status observer was not registered') + } + + latestStoreSubscriber() + latestStoreSubscriber() + await Promise.resolve() + + expect(mockMarkDispatchResult).not.toHaveBeenCalledWith( + expect.objectContaining({ status: 'completed' }) + ) + }) + + // Recreated entries lose history; preserve the observer’s working edge through transport loss, PTY exit and cap eviction. + it('completes a reuse-session run when the entry is recreated with no history', async () => { + const paneKey = 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d' + mockFindReusableAutomationSession.mockReturnValue({ + tabId: 'agent-tab', + paneKey, + ptyId: 'agent-pty' + }) + mockObserveExistingAutomationSession.mockResolvedValue(() => {}) + + await registerAndDispatch(makeAutomation({ reuseSession: true })) + const workingStartedAt = Date.now() + 1 + state.agentStatusByPaneKey = { + [paneKey]: { + paneKey, + state: 'working', + prompt: 'turn', + agentType: 'claude', + updatedAt: workingStartedAt, + stateStartedAt: workingStartedAt, + stateHistory: [{ state: 'working', prompt: 'turn', startedAt: workingStartedAt }] + } + } + if (!latestStoreSubscriber) { + throw new Error('agent status observer was not registered') + } + latestStoreSubscriber() + await Promise.resolve() + + state.agentStatusByPaneKey = { + [paneKey]: { + paneKey, + state: 'done', + prompt: 'turn', + agentType: 'claude', + updatedAt: workingStartedAt + 2, + stateStartedAt: workingStartedAt + 2, + stateHistory: [] + } + } + latestStoreSubscriber() + await Promise.resolve() + + expect(mockMarkDispatchResult).toHaveBeenCalledWith( + expect.objectContaining({ status: 'completed' }) + ) + }) + + it('consumes duplicate done and zero-exit completion through one finalizer', async () => { + let launchArgs: { + onAgentStatus?: (payload: { state: string }) => void + onExit?: (ptyId: string, code: number) => void + } = {} + mockLaunchAgentBackgroundSession.mockImplementation(async (args) => { + launchArgs = args + return { + tabId: 'agent-tab', + paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', + ptyId: 'agent-pty', + startupPlan: {}, + releaseRuntimeObservers: mockReleaseRuntimeObservers, + terminalOwnership: { + finalize: mockFinalizeTerminalOwnership, + release: mockReleaseTerminalOwnership + } + } + }) + + await registerAndDispatch() + launchArgs.onAgentStatus?.({ state: 'done' }) + launchArgs.onExit?.('agent-pty', 0) + launchArgs.onAgentStatus?.({ state: 'done' }) + await vi.waitFor(() => expect(mockFinalizeTerminalOwnership).toHaveBeenCalledOnce()) + + expect( + mockMarkDispatchResult.mock.calls.filter( + ([result]) => result.status === 'completed' && result.terminalPaneKey !== null + ) + ).toHaveLength(1) + expect(mockReleaseTerminalOwnership).not.toHaveBeenCalled() + }) + + it('releases ownership on nonzero exit without finalizing the tab', async () => { + let onExit: ((ptyId: string, code: number) => void) | undefined + mockLaunchAgentBackgroundSession.mockImplementation(async (args) => { + onExit = args.onExit + return { + tabId: 'agent-tab', + paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', + ptyId: 'agent-pty', + startupPlan: {}, + releaseRuntimeObservers: mockReleaseRuntimeObservers, + terminalOwnership: { + finalize: mockFinalizeTerminalOwnership, + release: mockReleaseTerminalOwnership + } + } + }) + + await registerAndDispatch() + onExit?.('agent-pty', 9) + await vi.waitFor(() => expect(mockReleaseTerminalOwnership).toHaveBeenCalledOnce()) + + expect(mockFinalizeTerminalOwnership).not.toHaveBeenCalled() + expect(mockMarkDispatchResult).toHaveBeenCalledWith( + expect.objectContaining({ status: 'dispatch_failed' }) + ) + }) + + it('releases ownership when dispatched result persistence rejects', async () => { + mockMarkDispatchResult.mockRejectedValueOnce(new Error('persistence unavailable')) + + await registerAndDispatch() + + expect(mockReleaseTerminalOwnership).toHaveBeenCalledOnce() + expect(mockFinalizeTerminalOwnership).not.toHaveBeenCalled() + expect(mockMarkDispatchResult).toHaveBeenLastCalledWith( + expect.objectContaining({ status: 'dispatch_failed' }) + ) + }) + + it('releases ownership when completed result persistence rejects', async () => { + mockMarkDispatchResult + .mockResolvedValueOnce(undefined) + .mockRejectedValueOnce(new Error('completion persistence unavailable')) + .mockResolvedValueOnce(undefined) + mockLaunchAgentBackgroundSession.mockImplementation(async (args) => { + args.onAgentStatus?.({ state: 'done' }) + return { + tabId: 'agent-tab', + paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', + ptyId: 'agent-pty', + startupPlan: {}, + releaseRuntimeObservers: mockReleaseRuntimeObservers, + terminalOwnership: { + finalize: mockFinalizeTerminalOwnership, + release: mockReleaseTerminalOwnership + } + } + }) + + await registerAndDispatch() + + expect(mockReleaseTerminalOwnership).toHaveBeenCalledOnce() + expect(mockFinalizeTerminalOwnership).not.toHaveBeenCalled() + expect(mockMarkDispatchResult).toHaveBeenLastCalledWith( + expect.objectContaining({ status: 'dispatch_failed' }) + ) + }) + + it('diagnoses a late completed-persistence rejection once without terminal cleanup', async () => { + let onAgentStatus: ((payload: { state: string }) => void) | undefined + const persistenceError = new Error('late completion persistence unavailable') + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined) + mockMarkDispatchResult.mockResolvedValueOnce(undefined).mockRejectedValueOnce(persistenceError) + mockLaunchAgentBackgroundSession.mockImplementation(async (args) => { + onAgentStatus = args.onAgentStatus + return { + tabId: 'agent-tab', + paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', + ptyId: 'agent-pty', + startupPlan: {}, + releaseRuntimeObservers: mockReleaseRuntimeObservers, + terminalOwnership: { + finalize: mockFinalizeTerminalOwnership, + release: mockReleaseTerminalOwnership + } + } + }) + + await registerAndDispatch() + onAgentStatus?.({ state: 'done' }) + onAgentStatus?.({ state: 'done' }) + await vi.waitFor(() => expect(errorSpy).toHaveBeenCalledOnce()) + + expect(errorSpy).toHaveBeenCalledWith( + '[automations] Failed to persist late automation result:', + persistenceError + ) + expect(mockReleaseTerminalOwnership).toHaveBeenCalledOnce() + expect(mockFinalizeTerminalOwnership).not.toHaveBeenCalled() + expect( + mockMarkDispatchResult.mock.calls.filter( + ([result]) => result.status === 'completed' && result.terminalPaneKey !== null + ) + ).toHaveLength(1) + errorSpy.mockRestore() + }) + + it('preserves a fresh reuse-enabled session as the future reuse seed', async () => { + mockFindReusableAutomationSession.mockReturnValue(null) + + await registerAndDispatch(makeAutomation({ reuseSession: true })) + + expect(mockReleaseTerminalOwnership).toHaveBeenCalledOnce() + expect(mockFinalizeTerminalOwnership).not.toHaveBeenCalled() + }) + + it('releases the launch runtime observers once when a kept-open run completes', async () => { + mockFindReusableAutomationSession.mockReturnValue(null) + let launchArgs: { onAgentStatus?: (payload: { state: string }) => void } = {} + mockLaunchAgentBackgroundSession.mockImplementation(async (args) => { + launchArgs = args + return { + tabId: 'agent-tab', + paneKey: 'agent-tab:7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d', + ptyId: 'agent-pty', + startupPlan: {}, + releaseRuntimeObservers: mockReleaseRuntimeObservers, + terminalOwnership: { + finalize: mockFinalizeTerminalOwnership, + release: mockReleaseTerminalOwnership + } + } + }) + + await registerAndDispatch(makeAutomation({ reuseSession: true })) + expect(mockReleaseRuntimeObservers).not.toHaveBeenCalled() + launchArgs.onAgentStatus?.({ state: 'done' }) + launchArgs.onAgentStatus?.({ state: 'done' }) + + await vi.waitFor(() => + expect(mockMarkDispatchResult).toHaveBeenCalledWith( + expect.objectContaining({ status: 'completed' }) + ) + ) + expect(mockReleaseRuntimeObservers).toHaveBeenCalledOnce() + expect(mockFinalizeTerminalOwnership).not.toHaveBeenCalled() + }) }) diff --git a/src/renderer/src/hooks/useAutomationDispatchEvents.ts b/src/renderer/src/hooks/useAutomationDispatchEvents.ts index 0ade53d6d9e9..f4963a6dea74 100644 --- a/src/renderer/src/hooks/useAutomationDispatchEvents.ts +++ b/src/renderer/src/hooks/useAutomationDispatchEvents.ts @@ -1,7 +1,10 @@ import { useEffect } from 'react' +import { handleAutomationDispatchRequest } from './automation-dispatch-handler' export function useAutomationDispatchEvents(): void { useEffect(() => { + const unsubscribe = window.api.automations.onDispatchRequested(handleAutomationDispatchRequest) void window.api.automations.rendererReady() + return unsubscribe }, []) } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index dd4271b860b4..6f362e753383 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -49,6 +49,30 @@ "confirm": "Adjust filters and reveal", "cancel": "Keep filters" }, + "wslMoved": { + "movedToHost": "Moved to {{distro}} host", + "useHere": "Use on this computer again", + "useHereTitle": "Use {{name}} on this computer again?", + "useHereDescription": "Orca will open this project here as it was before the move. Your code is not affected: it never moved. Changes made on the {{distro}} host since the move, such as new tabs and chats, stay on the host and do not come back. Projects moved with it come back too. The project also stays on the {{distro}} host until you remove it there. This window reloads.", + "useHereConfirm": "Use on this computer", + "useHereSuperseded": "A later move to the {{distro}} host includes this project. Bring that one back first.", + "useHereRefusedTitle": "Can't use {{name}} here yet", + "useHereRefusedOk": "OK", + "useHereSupersededBy": "{{names}} moved to the {{distro}} host after this project. Use those on this computer again first, then this project.", + "useHereMoveRunning": "A move to the {{distro}} host is still running. Try again once it ends.", + "useHereHostKeptForPeers": "{{project}} moved to the {{distro}} host, which is still running for another Orca. Re-add the host to use it here again.", + "useHereHostUnreachable": "The {{distro}} host isn't answering, so Orca can't stop its copy of this project, and its agents may still be running there. Connect the host in Settings, or remove it, then try again.", + "useHereHostStillRunning": "The {{distro}} host's copy of this project is still running terminals, so its agents could run twice. Wait a moment, then try again.", + "useHereFailed": "Could not bring this project back to this computer.", + "useHereHostRemovalPending": "The {{distro}} host is still being removed, so Orca leaves it alone. Finish removing it in Settings, then try again.", + "useHereHostAutomations": "Orca couldn't turn off this project's automations on the {{distro}} host, so they could run twice. Connect the host in Settings, then try again.", + "useHereUnsavedTitle": "Save your files first", + "useHereUnsavedDescription": "Bringing {{name}} back reloads this window. Save or close these files first: {{files}}", + "automationRunsOnHost": "Runs on the {{distro}} host", + "quitDuringMoveTitle": "Quit while a project is moving?", + "quitDuringMoveDescription": "A project is moving to its WSL host. Quit anyway? The move will be undone at next launch.", + "quitDuringMoveConfirm": "Quit anyway" + }, "startupWorktreeRefresh": { "loading": "Discovering workspaces…", "description": "More workspaces may appear while local and remote projects load." @@ -67,6 +91,21 @@ } }, "browser": { + "googleCookieClear": { + "heading": "Google Cookies", + "signInKeyword": "sign-in", + "unavailable": "Unavailable for this profile on the selected host.", + "explanation": "Google ties its sign-ins to the browser they were made in, so Orca doesn't import Google cookies from other browsers. If Google is stuck on the wrong account or keeps signing you out, clear Google cookies from the active profile, then sign in to Google again in Orca. Other sites stay signed in.", + "action": "Clear Google cookies…", + "confirmTitle": "Clear Google cookies from {{profile}}?", + "confirmDescription": "You'll be signed out of Google in Orca's browser for this profile. Other sites stay signed in.", + "clear": "Clear", + "cancel": "Cancel", + "cleared": "Google cookies cleared from {{profile}}.", + "empty": "No Google cookies to clear in {{profile}}.", + "remaining": "Some Google cookies couldn't be removed from {{profile}}. Try again.", + "unverified": "Couldn't check {{profile}}'s Google cookies. Try again." + }, "loadFailure": { "connectionNotSecure": "Connection isn't secure", "cantReachHost": "Can't reach {{value0}}", @@ -237,6 +276,15 @@ "title": "History", "today": "Today", "yesterday": "Yesterday" + }, + "viewport": { + "mobile-s": "Mobile S — 320 × 568", + "mobile-m": "Mobile M — 375 × 667", + "mobile-l": "Mobile L — 425 × 812", + "tablet": "Tablet — 768 × 1024", + "laptop": "Laptop — 1024 × 768", + "laptop-l": "Laptop L — 1440 × 900", + "desktop": "Desktop — 1920 × 1080" } }, "editor": { @@ -258,6 +306,10 @@ "fileLoad": { "hostUnresolved": "The host couldn't find this file's workspace. It may have been removed, or the host may not know about it yet. Retry, or close this tab from the tab strip.", "remoteTooLarge": "This file is too large to open from its host." + }, + "diffTooLarge": { + "title": "File too large to diff", + "detail": "One version of this file is over 10 MB, so Orca doesn’t load it for a text diff." } }, "githubChecks": { @@ -343,6 +395,10 @@ "openManageSessions": "Open Manage Sessions", "administratorSearchDescription": "See Orca’s Windows permissions or restart with administrator approval.", "administratorApproval": "Windows will ask for approval. Use your usual account." + }, + "wordSeparators": { + "description": "Characters treated as word boundaries for double-click selection, including space.", + "noSpaceHint": "No space included — double-click will select across spaces." } }, "appearance": { @@ -352,11 +408,15 @@ "system": "System", "english": "English", "chinese": "中文(简体)", + "chineseTraditional": "繁體中文(台灣)", "korean": "한국어", "japanese": "日本語", "spanish": "Español", "french": "Français", - "portuguese": "Português (Brasil)" + "portuguese": "Português (Brasil)", + "russian": "Русский", + "turkish": "Türkçe", + "german": "Deutsch" }, "statusBar": { "claudeToggleDescription": "Show Claude token and cost usage for the active workspace.", @@ -588,7 +648,8 @@ "permissionOverrideMore": "and {{count}} more", "permissionOverrideMore_one": "and {{count}} more", "permissionOverrideMore_other": "and {{count}} more", - "permissionOverridesUse": "Use {{mode}}" + "permissionOverridesUse": "Use {{mode}}", + "approveForMe": "approve for me" }, "followSymlinkedDirectoriesKeywords": { "symlink": "symlink", @@ -619,6 +680,48 @@ "actionPermissions": { "sameAsAgent": "Same as {{agent}}" } + }, + "ssh": { + "status": { + "disconnected": "Disconnected", + "connecting": "Connecting…", + "auth-failed": "Auth failed", + "deploying-relay": "Deploying relay…", + "connected": "Connected", + "reconnecting": "Reconnecting…", + "reconnection-failed": "Reconnection failed" + } + }, + "shortcuts": { + "parseFailed": "Unable to parse shortcut." + }, + "mcp": { + "inspectFailed": "Unable to inspect {{directory}}.", + "unreadable": "Unreadable", + "notFound": "Not found", + "invalidJson": "Invalid JSON", + "noServers": "No servers", + "httpServer": "HTTP server", + "stdioServer": "stdio server", + "invalidServer": "Invalid server", + "serverCount_one": "{{count}} server", + "serverCount_other": "{{count}} servers", + "workspace": "Workspace", + "claudeWorkspace": "Claude workspace" + }, + "general": { + "openInMenu": { + "keyword": { + "windsurf": "windsurf", + "devin": "devin", + "devinDesktop": "devin desktop" + } + } + }, + "openInApp": { + "preset": { + "devinDesktop": "Devin Desktop" + } } }, "menu": { @@ -1711,9 +1814,6 @@ "3fdf777817": "Open on GitHub", "c43fe79ee0": "Copy GitHub link", "0caac1a18f": "Start workspace from PR", - "8223320f8d": "updated", - "10ef1afb8e": "· updated", - "55962099bc": "opened this issue", "0ab4664a8b": "Start workspace from issue", "36182aa57f": "Start new workspace", "fe6ff12dc2": "More issue workspace actions", @@ -1786,8 +1886,6 @@ "52b20b56f7": "Description", "4d555d3796": "Edit description", "9df4e74bdf": "Save", - "0ae387d8ca": "by", - "228e2f59d3": "Resolved", "a154ec5224": "Open comment on GitHub", "bca8eb39ac": "Reply to comment", "68cb993d61": "resolved", @@ -1803,13 +1901,11 @@ "d43736d09c": "Code context controls", "bd7be7b1fd": "comment L", "db61d76cd5": "Loading code context…", - "f2d02cdf8c": "files viewed", "1257d1435d": "Show file tree", "a341343303": "Review comment added.", "d1fa2cf888": "Unable to comment without the PR head SHA.", "829674460a": "Diff unavailable because the PR commit SHAs are missing.", "af924014f8": "Viewed", - "2d89a38d9d": "{{value0}} {{value1}} as viewed", "70e84e3d0b": "No matching reviewers.", "1ffce94a8b": "Everyone else", "c2b21818e1": "Suggestions", @@ -1844,8 +1940,6 @@ "ec5c4b3ab2": "Reopen PR", "21860b58d0": "Close pull request", "5932578f51": "Merge requires a registered local repo", - "e2bf3e41a9": "comment", - "28d0d3374f": "thread", "080d071d48": "Reply to @{{value0}}", "86f809e2ce": "Reply in this review thread", "136542c9ba": ":L{{value0}}", @@ -1875,7 +1969,9 @@ "from": "from", "to": "to", "activity": "Activity", - "noActivity": "No activity yet." + "noActivity": "No activity yet.", + "pullRequestReference": "PR #{{number}}", + "issueReference": "issue #{{number}}" }, "checkActionRequiredHint": "Needs a manual action on GitHub (e.g. approving the run) to unblock merging.", "e15a8b77ef": "No inline details are available for this check.", @@ -1889,8 +1985,15 @@ "09d67a0f9b": "Failed to close pull request", "88809e79db": "Failed to reopen pull request", "00f55cc17b": "Repository access is unavailable for this pull request.", - "reactionCountSingular": "{{count}} {{reaction}} reaction", - "reactionCountPlural": "{{count}} {{reaction}} reactions" + "reactionCount_one": "{{count}} {{reaction}} reaction", + "reactionCount_other": "{{count}} {{reaction}} reactions", + "filesViewed_one": "{{viewed}} / {{count}} file viewed", + "filesViewed_other": "{{viewed}} / {{count}} files viewed", + "updatedRelativeTime": "updated {{time}}", + "authorOpenedThisIssue": " opened this issue", + "middotUpdatedRelativeTime": "· updated {{time}}", + "resolvedThreadBy": "Resolved thread by {{author}}", + "resolvedCommentBy": "Resolved comment by {{author}}" }, "GitLabItemDialog": { "65e784c1f1": "Reopen", @@ -1946,14 +2049,15 @@ "f23ea85341": "resolved", "6de8ce0cc6": "{{value0}} required", "22511537d2": "Approved", - "00f3bab87b": " of {{value0}} required", "3a051b8ade": "Work item", "32f8bef818": "No log output.", "4168eb2c51": "Resolve", "commentTooLarge": "Comment is too large to submit safely.", "gitlabActionFailed": "GitLab action failed.", - "approvalsRemainingSingular": "{{count}} approval remaining", - "approvalsRemainingPlural": "{{count}} approvals remaining" + "approvalsRemainingOfRequired_one": "{{count}} approval remaining of {{required}} required", + "approvalsRemainingOfRequired_other": "{{count}} approvals remaining of {{required}} required", + "approvalsRemaining_one": "{{count}} approval remaining", + "approvalsRemaining_other": "{{count}} approvals remaining" }, "JiraIssueWorkspace": { "b0b92666c9": "Comment", @@ -1978,14 +2082,11 @@ "69da9a208c": "Open in Jira", "fa132c8aed": "Failed to add comment.", "ea21952aa3": "Failed to update Jira issue.", - "6c41a9bcea": "Failed to copy {{value0}}", - "2ff69a3545": "{{value0}} copied", "666cfdd835": "Unknown", "ef21405c6d": "Jira issue", "commentTooLarge": "Comment is too large to submit safely." }, "Landing": { - "76a95f7f47": "Create", "f9eaa9e12d": "Add project", "6ca6ff404e": "ORCA", "520304a067": "Orca logo", @@ -2001,7 +2102,12 @@ "0d0ace8861": "Star on GitHub", "ec43b38ba7": "Starred on GitHub", "157bb5ecbb": "Open GitHub", - "preflightDismiss": "Dismiss" + "preflightDismiss": "Dismiss", + "moveUpWorkspace": "Move up workspace", + "moveDownWorkspace": "Move down workspace", + "installGit": "Install Git", + "installGitHubCli": "Install GitHub CLI", + "learnMore": "Learn more" }, "LinearIssueMarkdownDescriptionEditor": { "d9c47069ef": "Markdown", @@ -2026,14 +2132,12 @@ "LinearIssueTextEditor": { "947ba2d6f4": "to save", "04d73b72dc": "Issue title", - "e8ff595db3": "Failed to update {{value0}}", "1e08a1ec80": "Title is required" }, "LinearIssueWorkspace": { "ad5dec37b7": "Preview, edit, and start work from the selected issue.", "c23e79e5c0": "Actions", "b0eac92d85": "Retry", - "fabbd3f974": "updated the issue ·", "543970c87a": "Activity", "df4c86ed12": "Close", "7a4997d8bb": "Close Linear issue preview", @@ -2057,11 +2161,8 @@ "b25e453c9d": "Failed to create sub-issue", "aeed19d003": "Created {{value0}}", "9a1317cdd3": "Failed to load sub-issue", - "9bcbaa2737": "Failed to copy {{value0}}", - "7835483c43": "{{value0}} copied", "61f424f8ca": "Linear issue", "ca8778c124": "Unknown", - "8a33c85e9c": "Someone", "65239a714b": "Linear", "76ffd3c937": "Search for a project to add.", "c11b4e3cc2": "No projects found.", @@ -2072,7 +2173,10 @@ "moreWorkspaceActions": "More issue workspace actions", "startNewWorkspace": "Start new workspace", "workspaceSection": "Workspace", - "noWorkspaceYet": "None yet" + "noWorkspaceYet": "None yet", + "issueDescriptionLabel": "Issue description", + "namedUserUpdatedIssue": "{{name}} updated the issue · {{time}}", + "someoneUpdatedIssue": "Someone updated the issue · {{time}}" }, "LinearItemDrawer": { "04008e6c46": "Start workspace from issue", @@ -2108,7 +2212,9 @@ "openAttachedWorkspace": "Open workspace attached to issue", "openWorkspace": "Open workspace", "moreWorkspaceActions": "More issue workspace actions", - "startNewWorkspace": "Start new workspace" + "startNewWorkspace": "Start new workspace", + "setEstimate": "Set estimate", + "estimateValue": "Estimate {{estimate}}" }, "NewWorkspaceComposerCard": { "reuseExistingBranch": "Reuse branch", @@ -2170,7 +2276,22 @@ "addSshHostHint": "Use an existing machine over SSH", "addRemoteOrcaServer": "Add Remote Orca Server", "addRemoteOrcaServerHint": "Pair another Orca runtime", - "hostConnectionFailed": "Connection failed" + "hostConnectionFailed": "Connection failed", + "connect": "Connect", + "reconnect": "Reconnect", + "setupConfigDefaultTabs": "Default tab commands", + "setupConfigSetupAndDefaultTabs": "Setup and default tab commands", + "setupConfigSetupScript": "Setup script", + "runDefaultTabCommands": "Run default tab commands", + "runSetupAndDefaultTabCommands": "Run setup and default tab commands", + "runSetupCommand": "Run setup command", + "askRunDefaultTabCommands": "Run default tab commands now?", + "askRunSetupAndDefaultTabCommands": "Run setup and default tab commands now?", + "askRunSetup": "Run setup now?", + "runSetupNow": "Run setup now", + "runCommandsNow": "Run commands now", + "skipForNow": "Skip for now", + "skipCommands": "Skip commands" }, "NewWorkspaceComposerModal": { "createWorktree": "Create worktree", @@ -2264,9 +2385,6 @@ "778683ec84": "Description", "da9aaa8bcf": "Edit description", "4a337ac05f": "Save", - "169a93b29a": "updated", - "3c891789f6": "by", - "f4fe47c2bb": "Resolved", "0ac19bb52e": "Open comment on GitHub", "d6c6679de7": "Reply to comment", "76b2a0ac5b": "resolved", @@ -2274,7 +2392,6 @@ "6885c619e7": "Unable to reply without a repository path.", "d94810f652": "Failed to update description.", "9b4190dc98": "Description updated.", - "89e80af1c7": "files viewed", "319cf2d54b": "Show file tree", "eff839f438": "Review comment added.", "d8c3ba91c4": "Unable to comment without the PR head SHA.", @@ -2312,8 +2429,6 @@ "9d5425918e": "Reopen PR", "96d013ed28": "Close pull request", "eca289e593": "Merge requires a registered local repo", - "e01e34f5fa": "comment", - "345b68254c": "thread", "31a7b202f2": "Reply to @{{value0}}", "408e634fbb": "Reply in this review thread", "34b9f7c264": ":L{{value0}}", @@ -2335,7 +2450,19 @@ "4b8ae7303f": "Failed to load diff.", "closePullRequestFailed": "Failed to close pull request", "reopenPullRequestFailed": "Failed to reopen pull request", - "diffLoadTimedOut": "Timed out loading this diff." + "diffLoadTimedOut": "Timed out loading this diff.", + "filesViewed_one": "{{viewed}} / {{count}} file viewed", + "filesViewed_other": "{{viewed}} / {{count}} files viewed", + "updatedRelativeTime": "updated {{time}}", + "resolvedThreadBy": "Resolved thread by {{author}}", + "resolvedCommentBy": "Resolved comment by {{author}}", + "mentionSource": { + "prAuthor": "PR author", + "issueAuthor": "Issue author", + "commenter": "Commenter", + "participant": "Participant", + "teamMember": "Team member" + } }, "QuickOpen": { "1dbd3f59ff": "Move", @@ -2349,13 +2476,12 @@ "9e97f08d0f": "Search for a file to open", "ec31e058f7": "Go to file", "73b44e7bde": "Copy install command", - "1cf8561ab4": "on the remote to enable fast, gitignore-aware listing:", - "5d80dc39bb": "ripgrep", - "2ca749c15d": "Install", - "4725b0e931": "Quick Open scan too large (", - "b227d88520": "{{value0}} files found", "995be8ea22": "Copy", - "cf144856dc": "Copied" + "cf144856dc": "Copied", + "filesFound_one": "{{count}} file found", + "filesFound_other": "{{count}} files found", + "hostCouldNotOpenPath": "The host could not open this file path.", + "chooseFileNotDirectory": "Choose a file rather than a directory." }, "SelectedTextCopyMenu": { "9b40d7b018": "Copy" @@ -2365,8 +2491,6 @@ "serverBody": "These chats were working when Orca on {{machine}} restarted. Resuming restores each one where it stopped and asks the agent to carry on. Your own prompt is not re-sent.", "serverDismiss": "Dismiss", "serverResumeAll": "Resume all {{count}} on {{machine}}", - "serverResumeHereOne": "Resume 1 chat started here", - "serverResumeHere": "Resume {{count}} chats started here", "title": "Resume interrupted chats?", "body": "These chats were working when Orca closed. Resuming restores each one where it stopped, with its full context, and asks the agent to check what it was doing before carrying on. Your own prompt is not re-sent.", "updateBody": "These chats were working when Orca installed an update. Resuming restores each one where it stopped, with its full context, and asks the agent to check what it was doing before carrying on. Your own prompt is not re-sent.", @@ -2374,19 +2498,9 @@ "untitled": "Untitled chat", "listLabel": "Chats that would be resumed", "dontAskAgain": "Don't ask again (resume automatically)", - "dontAskAgainHint": "You can turn this off in Settings → Experimental → Chat UI.", - "continuedOne": "Resumed 1 chat", - "continuedMany": "Resumed {{value0}} chats", + "dontAskAgainHint": "You can turn this off in Settings → Chat → Behavior.", "selectAgent": "Resume {{value0}} chat \"{{value1}}\" in {{value2}}", - "resumeSelected": "Resume {{value0}} chats", - "resumeSelectedOne": "Resume 1 chat", "dismissAll": "Dismiss all", - "notContinuedOne": "1 chat couldn’t be resumed", - "notContinuedMany": "{{value0}} chats couldn’t be resumed", - "notConfirmedOne": "Couldn’t confirm 1 chat was resumed", - "notConfirmedMany": "Couldn’t confirm {{value0}} chats were resumed", - "notConfirmedOtherOne": "Couldn’t confirm 1 other chat was resumed", - "notConfirmedOtherMany": "Couldn’t confirm {{value0}} other chats were resumed", "viewChats": "View chats", "review": "Review", "activityUnnamed": "unnamed", @@ -2394,9 +2508,7 @@ "activityQuestion": "Waiting for your answer: {{value0}}", "activityMidReply": "Was mid-reply", "activitySubagentOne": "Subagent running: {{value0}}", - "activitySubagentMany": "{{value0}} subagents running", "activityMonitorOne": "Monitoring: {{value0}}", - "activityMonitorMany": "Monitoring {{value0}} background tasks", "selectWorkspace": "Select all chats in {{value0}}", "workspaceSelectedCount": "{{value0}} of {{value1}}", "selectAll": "Select all chats", @@ -2408,7 +2520,23 @@ "selectMachine": "Select all chats on {{value0}}", "sshHost": "SSH", "done": "Done", - "resultListLabel": "Chats in this resume" + "resultListLabel": "Chats in this resume", + "resumeChats_one": "Resume {{count}} chat", + "resumeChats_other": "Resume {{count}} chats", + "serverResumeHereCount_one": "Resume {{count}} chat started here", + "serverResumeHereCount_other": "Resume {{count}} chats started here", + "continuedCount_one": "Resumed {{count}} chat", + "continuedCount_other": "Resumed {{count}} chats", + "notContinuedCount_one": "{{count}} chat couldn’t be resumed", + "notContinuedCount_other": "{{count}} chats couldn’t be resumed", + "notConfirmedCount_one": "Couldn’t confirm {{count}} chat was resumed", + "notConfirmedCount_other": "Couldn’t confirm {{count}} chats were resumed", + "notConfirmedOtherCount_one": "Couldn’t confirm {{count}} other chat was resumed", + "notConfirmedOtherCount_other": "Couldn’t confirm {{count}} other chats were resumed", + "activitySubagentCount_other": "{{count}} subagents running", + "activityMonitorCount_other": "Monitoring {{count}} background tasks", + "activityMonitorCount_one": "Monitoring {{count}} background task", + "activitySubagentCount_one": "{{count}} subagent running" }, "StarNagCard": { "30c36231c1": "Orca is open source. If it helped today, a GitHub star helps other developers find it.", @@ -2423,7 +2551,6 @@ "TaskPage": { "ff69a30681": "Cancel", "8ff6fdc368": "Creating…", - "fc0d8a1fa4": "to submit.", "919a20dd5b": "Enter {{value0}}", "56cdb413a2": "Comma-separated values", "1f0fce91e3": "Select {{value0}}", @@ -2471,14 +2598,9 @@ "bdebffcbfe": "Create a Linear project for the selected team.", "1361275ec3": "New Linear project", "7f3f7b4c18": "Description (optional, markdown)", - "9f2b4c03a6": "Filing in", "d3d0998b7d": "New GitHub issue", - "d1e243795c": "issues", - "be8cf68d9f": "view issues", - "67662ade50": "project issues", "6244a02f46": "Open in Linear", "606a85c774": "Open", - "5e8061b088": "Start workspace from {{value0}} {{value1}}", "592a55611b": "Try selecting more teams or refreshing; team filters apply to the current fetched issue set.", "618107fab3": "No fetched issues match the selected teams", "903c7af49f": "No Linear issues found", @@ -2487,7 +2609,6 @@ "f362667d55": "Updated", "b1eaa18ace": "Issue", "37e7ee311e": "Key", - "b7bae28b6a": "shown", "a26a48252e": "Display properties", "5d2d835467": "Ordering", "5659da12fc": "Grouping", @@ -2495,11 +2616,9 @@ "af377b13b1": "{{value0}} view", "d47248df4d": "Linear view mode", "f397d513e3": "Back", - "b39fe6511d": "projects", "8675cd6188": "Linear", "733b8f2421": "Linear / Views", "bc06ed0fb0": "Back to views", - "3cb855080f": "views", "b4e10f096e": "Owner", "a04fe7ba73": "Visibility", "0aa8525950": "Model", @@ -2529,8 +2648,6 @@ "054bf695cc": "Draft", "5b6b2af943": "Retrying…", "0c0de0fc0e": "Couldn't load issues from", - "d1766fd62d": "projects failed to load", - "7762f4b03a": "of", "443f7dd928": "Merge", "a7396b05c6": "Checks", "f6fa3c97d0": "Reviewers", @@ -2712,10 +2829,41 @@ "linearOpenAttachedWorkspace": "Open workspace attached to {{value0}}", "linearWorktreesColumn": "Workspaces", "jiraBoardEmptyColumn": "No issues", - "labelCountPlural": "{{count}} labels", - "labelCountSingular": "{{count}} label", - "memberCountPlural": "{{count}} members", - "memberCountSingular": "{{count}} member" + "backToPullRequests": "Pull requests", + "backToGitHubList": "GitHub list", + "noGitHubRepositoryContext": "No GitHub repository context available for this issue.", + "filingInTarget": "Filing in {{target}}", + "filingInThisRepository": "Filing in this repository", + "shortcutToSubmit": "{{shortcut}} to submit.", + "projectsFailedToLoad_one": "{{failed}} of {{count}} project failed to load", + "projectsFailedToLoad_other": "{{failed}} of {{count}} projects failed to load", + "draftPullRequestNumber": "Draft pull request #{{number}}", + "pullRequestNumber": "Pull request #{{number}}", + "issueNumber": "Issue #{{number}}", + "loadGitHubWorkFailed": "Failed to load GitHub work.", + "gitlabViewIssues": "Issues", + "gitlabViewMrs": "MRs", + "gitlabViewTodos": "My Todos", + "startWorkspaceFromMr": "Start workspace from MR {{number}}", + "startWorkspaceFromIssue": "Start workspace from issue {{number}}", + "shownCount_other": "{{count}} shown", + "linearProjectPlaceholder": "Project", + "labelCount_one": "{{count}} label", + "labelCount_other": "{{count}} labels", + "memberCount_one": "{{count}} member", + "memberCount_other": "{{count}} members", + "groupUnassigned": "Unassigned", + "linearProjectContext": "Project: {{name}}", + "linearViewContext": "View: {{name}}", + "changedFileCount_one": "{{count}} file", + "changedFileCount_other": "{{count}} files", + "resumeRestoration": { + "linearProjectNotFound": "Saved Linear project was not found.", + "linearProjectRestoreFailed": "Failed to restore saved Linear project.", + "linearViewNotFound": "Saved Linear view was not found.", + "linearViewRestoreFailed": "Failed to restore saved Linear view." + }, + "shownCount_one": "{{count}} shown" }, "Terminal": { "73768427cf": "Close", @@ -2790,7 +2938,8 @@ "b1e390250d": "Could not complete the local build switch.", "d29740d175": "The selected build could not be used.", "37d45c9ec1": "Choose Another Build", - "7f1a4c9e02": "Your system package manager installed Orca, so update it from there — Orca cannot install this release itself." + "7f1a4c9e02": "Your system package manager installed Orca, so update it from there — Orca cannot install this release itself.", + "compatibilityModeFailed": "Could not enable compatibility mode. {{message}}" }, "WorktreeJumpPalette": { "ac037cfac2": "Move", @@ -2816,8 +2965,6 @@ "d7d496a451": "Browser page no longer exists", "50a1d11d5b": "Open Tabs", "088d66d980": "Actions & Settings", - "20af998bff": "{{value0}} items available{{value1}}", - "bb72c08e63": "{{value0}} results found{{value1}}", "34c8fbb46e": "SSH remote", "63c2be1914": "SSH disconnected", "95be6587d3": "Create worktree \"{{value0}}\"", @@ -2834,7 +2981,12 @@ "recentChatsTerminalsHeader": "Recent Chats & Terminals", "27f10cca63": "Search chats, terminals, workspaces, tasks, settings, and actions...", "2770f02910": "Search chats, terminals, workspaces, tasks, settings, and actions", - "lastActiveTime": "Last active {{value0}} ago" + "lastActiveTime": "Last active {{value0}} ago", + "resultsFound_one": "{{count}} result found.", + "resultsFound_other": "{{count}} results found.", + "itemsAvailable_one": "{{count}} item available.", + "itemsAvailable_other": "{{count}} items available.", + "createActionAvailable": "Create worktree action available." }, "github": { "pr": { @@ -2875,7 +3027,8 @@ "8f6cb3772f": "Merge this pull request automatically once requirements are met", "def355ff38": "Able to merge", "e42c5bae67": "GitHub says this PR can merge and checks passed", - "cbf0113af6": "GitHub says this PR can merge" + "cbf0113af6": "GitHub says this PR can merge", + "autoMergeOn": "Auto-merge on" } } }, @@ -3049,10 +3202,10 @@ "imageUrlTooLarge": "Image URL is too large." }, "IssueSourceSelector": { - "d6aeb2012b": "Showing issues from", "787c970baf": "Issue source", "51d1608920": "Origin", - "30b2c9df91": "Upstream" + "30b2c9df91": "Upstream", + "showingIssuesFromRepo": "Showing issues from " }, "PRFilterDropdowns": { "979be3cf6b": "Assignee", @@ -3062,12 +3215,18 @@ "01f3f3d161": "Author", "13b3ac0a84": "Status", "79c54552f7": "Filters", - "8a2ffbf9b3": "Remove {{value0}} filter" + "8a2ffbf9b3": "Remove {{value0}} filter", + "anyState": "Any", + "currentUser": "Current user" }, "PRFilterPickers": { - "fdf387297c": "Clear (", "472c12ae03": "Clear", - "2d1f58eda6": "Use" + "pressEnterToUseValue": "Press Enter to use the typed value.", + "useTypedValue": "Use ", + "clearSelected": "Clear ({{count}})", + "loading": "Loading…", + "searchTextTooLarge": "Search text is too large.", + "noMatches": "No matches" }, "PRFilterSections": { "a00830d3f7": "No users", @@ -3077,7 +3236,6 @@ "458ea3602b": "No authors", "b69fa4fa20": "Back", "30ebb6ca44": "Clear all filters", - "8177eda37e": "Filter", "ea3416d646": "Assignee", "b1d9fdea08": "Label", "24754c44ad": "Author", @@ -3089,7 +3247,15 @@ "2b2f019091": "Any state", "0fd3249e2e": "Closed", "d78b60b5c2": "Open", - "bd162b7d5a": "Merged" + "bd162b7d5a": "Merged", + "draft": "Draft", + "labelCount_one": "{{count}} label", + "labelCount_other": "{{count}} labels", + "allStates": "All", + "filterPullRequests": "Filter pull requests", + "filterIssues": "Filter issues", + "filterOrTypeLogin": "Filter or type a login...", + "filterLabels": "Filter labels..." }, "github": { "rate": { @@ -3100,15 +3266,14 @@ "d12d3d6f33": "Refresh GitHub API budget", "d5e5de9070": "Orca uses REST, Search, and GraphQL through the GitHub CLI.", "58c5f88216": "GitHub API Budget", - "6da1858354": "left · resets in", - "f42790d150": "of", "01f7323e58": "GraphQL API", "1daf0f22a9": "GraphQL", "1f2f28a4de": "Search API", "c377a4f06a": "Search", "c392c749a6": "REST API", "bb227706a6": "REST", - "budget_scope_prefix": "Budget scope" + "budget_scope_prefix": "Budget scope", + "remainingOfLimitResetsIn": "{{remaining}} of {{limit}} left · resets in {{reset}}" } } } @@ -3116,7 +3281,29 @@ "CommentReactions": { "addReaction": "Add reaction", "removeNamedReaction": "Remove {{value0}} reaction", - "addNamedReaction": "Add {{value0}} reaction" + "addNamedReaction": "Add {{value0}} reaction", + "reaction": { + "thumbsUp": "thumbs up", + "thumbsDown": "thumbs down", + "laugh": "laugh", + "confused": "confused", + "heart": "heart", + "hooray": "hooray", + "rocket": "rocket", + "eyes": "eyes" + } + }, + "CommentCodeContext": { + "showSurroundingCodeBlock": "Show surrounding code block", + "showNearbyCodeContext": "Show nearby code context" + }, + "prCheckPresentation": { + "successful": "Successful", + "inProgress": "In progress" + }, + "IssueSourceIndicator": { + "issueFromRepo": "Issue from ", + "issuesFromRepo": "Issues from " } }, "linear": { @@ -3136,11 +3323,6 @@ } } }, - "priority": { - "icon": { - "c43d3e065b": "Priority:" - } - }, "project": { "view": { "surfaces": { @@ -3159,7 +3341,6 @@ "c8db98b73b": "Resources", "bb1405eff8": "Milestones", "5d99315fb8": "Planning", - "3ad562bdf4": "scoped issues", "563501f191": "Progress", "bb5664d456": "No project description.", "7b147907dc": "Linear", @@ -3170,8 +3351,6 @@ "7616c986c6": "Open {{value0}} issues", "openInLinear": "Open {{value0}} in Linear", "93e1f6bfca": "Loading", - "98730088a6": ". Search or open Linear for the full set.", - "06b887d622": "Showing first", "linearLoginUnreadable": "Unable to read saved Linear login. Reconnect it in Settings.", "f2cc1e0ff6": "Linear / Projects", "906b5e4cb8": "Linear / Projects / {{value0}}", @@ -3186,7 +3365,10 @@ "df4bd63c1d": "Unassigned", "30402d2c6e": "Try search or refresh.", "a2f31c4cd6": "No Linear projects found", - "c9b6e9f90d": "Unable to load Linear projects" + "c9b6e9f90d": "Unable to load Linear projects", + "scopedIssueCount_one": "{{count}} scoped issue", + "scopedIssueCount_other": "{{count}} scoped issues", + "backlog": "Backlog" } } }, @@ -3199,7 +3381,14 @@ "05baa5ae90": "Workspace", "89f6580dbf": "Search teams...", "b3488fad3c": "No teams were fetched. Access can depend on key scope, private-team membership, archived teams, permissions, or a fetch failure.", - "405b33c378": "No fetched teams match your search." + "405b33c378": "No fetched teams match your search.", + "teamCount_one": "{{count}} team", + "teamCount_other": "{{count}} teams" + } + }, + "priority": { + "icon": { + "priorityValue": "Priority: {{label}}" } } }, @@ -3518,9 +3707,12 @@ "orcaBrowser": "Orca Browser", "terminalLinkSettings": "Terminal link settings", "copyLink": "Copy link", + "copyFilePath": "Copy file path", "copied": "Copied", "copiedLink": "Copied link", + "copiedFilePath": "Copied file path", "copyLinkFailed": "Failed to copy link", + "copyFilePathFailed": "Failed to copy file path", "downloadOpenWithDefaultApp": "Download & open with default app", "downloadOpenFailed": "Failed to download '{{value0}}'.", "openInThisGroup": "Open in this group", @@ -4705,10 +4897,7 @@ }, "UsageBreakdownSection": { "7765a4c3e1": "n/a", - "247c93ca92": "• inferred pricing", - "32176e1d44": "turns", - "79a69522a5": "events", - "02a046792e": "sessions •" + "247c93ca92": "• inferred pricing" }, "GrokUsagePane": { "g8h9i0j1k2": "Grok usage", @@ -5637,7 +5826,8 @@ }, "sidebarHostOptions": { "3e102f111c": "All hosts", - "visibleHostsCount": "{{value0}} hosts" + "hosts": "Hosts", + "visibleHosts_other": "{{count}} hosts" }, "SidebarWorkspaceOptionsMenu": { "hosts": "Hosts", @@ -6176,12 +6366,10 @@ "oneWorkspace": "1 workspace", "manyWorkspaces": "{{count}} workspaces", "hostHasWorkspacesDefault": "Removes {{value0}} and its credentials from this computer. Its {{value1}} stay in Orca — remote files are not touched.", - "alsoDeleteRemote": "Also delete these {{value0}} on {{value1}}", "alsoForgetLocal": "Also remove these {{value0}} from Orca", "advanced": "Advanced", - "alsoDeleteRemoteHint": "Permanently deletes the remote Git worktrees and their branches. Cannot be undone.", "alsoForgetLocalHint": "Clears them from Orca only. Remote files, worktrees, and branches are left untouched.", - "wslHostEndsTerminals": "Removes {{value0}} from Orca, ends its open terminals and stops Orca’s server in that distro. Files in the distro are untouched." + "wslHostEndsTerminalsUnlessShared": "Removes {{value0}} from Orca. Unless another Orca that’s open on this computer is using it, this also ends its open terminals and stops Orca’s server in that distro. Files in the distro are untouched." }, "HostRenameDialog": { "1a2b3c4d5e": "Rename host", @@ -6364,14 +6552,11 @@ "sshImportSyncedSingular": "Added {{count}} host to Orca." }, "ForgetSshWorkspaceDialog": { - "reconnectFailed": "Reconnection failed", - "forgetBody": "Removes this workspace from Orca only. Files, the Git worktree, and branches on {{host}} are left untouched.", - "title": "Delete “{{name}}”?", - "disconnectedBody": "The SSH host for this workspace is not connected. Reconnect to delete it on the remote too, or remove it from Orca only.", "ghostBody": "{{host}} is no longer a saved SSH host, so this workspace is no longer connected to a live host. It can only be removed from Orca — files and branches on the remote are left untouched.", "cancel": "Cancel", "forget": "Remove from Orca", - "reconnectAndDelete": "Reconnect & Delete" + "removeTitle": "Remove “{{name}}” from Orca?", + "savedHostBody": "This workspace’s project isn’t served by Orca’s server on {{host}}, so Orca can’t delete it there. You can remove it from Orca; files, the Git worktree, and branches on {{host}} are left untouched." }, "MarkdownImageLightbox": { "image": "Image", @@ -6511,7 +6696,7 @@ "running": "Running", "stopped": "Stopped", "title": "Add WSL distro", - "description": "Orca runs its server inside the distro, so git, files and terminals run natively in Linux. Use it for new projects; projects you opened through \\\\wsl.localhost keep working as they are.", + "description": "Orca runs its server inside the distro, so git, files and terminals run natively in Linux. Projects in this distro that you opened through \\\\wsl.localhost move to this host automatically once their terminals are idle; projects on a Windows drive (/mnt/…) stay on this computer. You can bring a moved project back from the sidebar.", "distro": "Distro", "loading": "Looking for WSL distros…", "placeholder": "Choose a distro", @@ -6521,7 +6706,8 @@ "adding": "Setting up…", "startAndAdd": "Start and add", "add": "Add host", - "refresh": "Refresh" + "refresh": "Refresh", + "wsl1Hint": "WSL 1 distros can’t be hosts. Convert one in a Windows terminal with: wsl --set-version {{value0}} 2" }, "wslHostRowStatus": { "connecting": "Starting", @@ -6535,9 +6721,12 @@ "turnedOffShort": "Turned off in Settings → Experimental", "serverFilesMissing": "This build of Orca can’t run WSL hosts (server files missing).", "serverFilesMissingShort": "This build can’t run WSL hosts", - "removalPending": "Removal didn’t finish" + "removalPending": "Removal didn’t finish", + "paused": "WSL hosts are paused in this build. Your saved hosts and their projects keep working; adding hosts and moving projects onto them is paused.", + "pausedShort": "Adding WSL distros is paused in this build." }, "wslHostRemoval": { + "keptForOthers": "Removed from this Orca. The host keeps running for {{value0}}.", "partial": "The host was removed, but something in the distro is still running: {{value0}}", "pending": "Orca didn’t remove the host yet: {{value0}} Remove it again to retry, or connect it to keep it." }, @@ -6600,7 +6789,11 @@ "c34fb1098d": "Terminal tabs closed and shutdown requested.", "d9657ac204": "Terminal session shutdown requested.", "e8f25bd903": "Couldn’t finish terminal cleanup.", - "a702d4196e": "This closes every terminal tab across all workspaces and requests shutdown for its current terminal sessions. Any unsaved terminal work is lost. The daemon itself keeps running, and new terminals can be opened immediately. This can't be undone." + "a702d4196e": "This closes every terminal tab across all workspaces and requests shutdown for its current terminal sessions. Any unsaved terminal work is lost. The daemon itself keeps running, and new terminals can be opened immediately. This can't be undone.", + "confirmRestart": "Restart", + "busyRestarting": "Restarting…", + "confirmKillAll": "Kill all sessions", + "busyKilling": "Killing…" }, "MacFolderAccessFixDialog": { "stepAllow": "Allow Orca under Files and Folders", @@ -8265,7 +8458,9 @@ "fbb428db98": "Selected:", "search_terminal_themes": "Search terminal themes", "cb330ef7f8": " of {{value0}}", - "c822571b2e": " matching \"{{value0}}\"" + "c822571b2e": " matching \"{{value0}}\"", + "plugin_themes": "Plugins", + "from_plugin": "From {{value0}}" }, "SettingsSidebar": { "e0900f83e7": "SSH", @@ -8555,7 +8750,6 @@ "a016ffbeed": "Auto uses Windows PowerShell now and switches to PowerShell 7+ when installed.", "5ed5c95344": "Choose between Windows PowerShell and PowerShell 7+ for new terminal panes.", "3d88af864d": "Choose whether the PowerShell shell option launches Windows PowerShell or PowerShell 7+ for new terminal panes.", - "8a956cc91e": "Characters treated as word boundaries for double-click selection.", "4bebcc2b2c": "Word Separators", "12e06178fa": "rows", "907b0b9d3e": "Custom", @@ -11242,7 +11436,7 @@ "mixedTitle": "Review access and content", "instructionalTitle": "Review plugin content", "subtitle": "{{value0}} v{{value1}} · {{value2}}", - "reconsent": "Permissions, the worker trust tier, or instructional content changed since you last reviewed this plugin. Review it again before it can run.", + "reconsent": "This plugin changed since you approved it. Review it to run it again.", "capabilities": "This plugin can", "warning": "These permissions limit how the plugin uses Orca's API. Its worker still runs as a normal process on your computer with full access to your files, network, and other processes.", "instructionalWarning": "This plugin has no worker process. Its instructional content can still cause actions when you or an agent use it. Review the instructions and commands below before enabling it.", @@ -11991,7 +12185,8 @@ "migration": "Not done: a move onto this server is unfinished. Resume it first.", "deferred": "Not done yet: the server isn’t ready for this. Try again later.", "failed": "Orca couldn’t finish this on the server. Try again.", - "defaultServer": "Not done: this server is the default host for new projects. Choose another one under New projects open on before stopping it." + "defaultServer": "Not done: this server is the default host for new projects. Choose another one under New projects open on before stopping it.", + "wslMoveRunning": "Not done: a project is moving onto this server. Orca updates it once the move finishes." }, "reassurance": "Runs on each host, reached over your own SSH connection. Your code and files stay where they are. Only Orca’s list of projects, tabs and terminals moves to the host." }, @@ -12406,6 +12601,9 @@ "shortcut": "shortcut" } }, + "AppearanceThemeControl": { + "useTerminalTheme": "Use its terminal colors" + }, "notification": { "settings": { "copy": { @@ -12420,14 +12618,14 @@ "right": { "sidebar": { "BulkActionBar": { - "79a9f5f712": "Unstage (", - "ef5f5bd06e": "Stage (", - "60ed678138": "selected" + "selectedCount_one": "{{count}} selected", + "selectedCount_other": "{{count}} selected", + "stageCount": "Stage ({{count}})", + "unstageCount": "Unstage ({{count}})" }, "ChecksPanel": { "2ef90c9819": "Started an AI agent for the broken checks.", "a0181a8d76": "Started an AI agent for the conflicts.", - "34464d00b9": "updated", "058039787c": "Cancel", "2ab7fd4b6d": "Save", "dda5924a40": "Checks require a Git branch and hosted review context", @@ -12473,7 +12671,8 @@ "430f1a62d4": "Could not resolve the selected thread on the host.", "updateReactionFailed": "Failed to update reaction.", "gitlabMoreActions": "More MR actions", - "gitlabLinkAnother": "Link another MR" + "gitlabLinkAnother": "Link another MR", + "reviewUpdatedAt": "{{review}} updated {{time}}" }, "CreateHostedReviewComposer": { "741ff8a0d2": "Push & Create {{value0}}" @@ -12630,7 +12829,14 @@ "740aca88ab": "Workspace port scan failed.", "5be4f7f727": "Port {{value0}} menu", "1004af16ab": "Copy {{value0}}", - "153d3a8026": "Workspace host unknown" + "153d3a8026": "Workspace host unknown", + "unknownProcess": "Unknown process", + "containerOrForwardedService": "Container or forwarded service", + "unassigned": "Unassigned", + "remotePortOutOfRange": "Remote port must be 1–65535", + "localPortOutOfRange": "Local port must be 1–65535", + "localPortInUse": "Port {{port}} is already in use. Choose a different local port.", + "localPortRequiresPrivileges": "Port {{port}} requires elevated privileges. Use a local port ≥ 1024." }, "Search": { "1abfb25a66": "Type to search in files", @@ -12687,7 +12893,6 @@ "476b77745b": "Change Base Ref", "ed34038d0d": "Refresh branch compare", "493f963029": "Change base ref", - "3278b2767b": "ahead", "11b5dd8e41": "Comparing against", "a9bf7c171a": "Commit Failed", "011f9713fc": "Commit blocked", @@ -12732,7 +12937,6 @@ "574d2f4413": "Clear Notes", "05bb8f4a48": "Cancel", "48db37cca9": "View all", - "78ce2d37ac": "Pushes to fork", "c05fe04839": "Pushes to the fork at {{value0}} (not origin)", "c35baf2f1e": "Filter files…", "2fe2a67580": "More note actions", @@ -12740,14 +12944,12 @@ "cc474e0b8c": "Notes", "e131cd7128": "Source Control is only available for Git repositories", "c07b236287": "Select a workspace to view changes", - "dc5a6465fc": "{{value0}} (e.g. {{value1}}{{value2}})", "a5e5a11090": "Discard all failed — unable to unstage files before discard", "8a5ba6a988": "Failed to load commit diff", "fe5bd1a610": "Creating {{value0}}...", "812cb992ee": "Open on {{value0}}", "eef5446523": "{{value0}} #{{value1}} is already open", "0453ca3a9a": "{{value0}} created, but Orca could not refresh it yet.", - "f99560ab29": "Abort {{value0}} failed", "eae7a1da5f": "Failed to clear notes.", "df5040e3c3": "Unstage", "8cde1a2fb0": "Stage", @@ -12775,8 +12977,6 @@ "aaf1451654": "Create draft {{value0}}", "26511c22b4": "Creating...", "d7ae61269b": "Committed on Branch", - "branchFilesChangedVsBaseOne": "1 file changed vs {{ref}}", - "branchFilesChangedVsBaseOther": "{{count}} files changed vs {{ref}}", "48a003c1b1": "Staged Changes", "d4ef4bafc5": "Changes", "9339382454": "Unstage all", @@ -12786,8 +12986,6 @@ "72f2bea3f4": "Expand notes", "d13edef890": "Collapse notes", "d6fb1df5fe": "{{value0}} is already open", - "05838cfdeb": "{{value0}} conflict", - "d206117f90": "{{value0}} conflict ({{value1}})", "0b5b8c234c": "Open {{value0}} ({{value1}})", "d97ef8f221": "lines {{value0}}-{{value1}}", "6f8bfa0eb9": "line {{value0}}", @@ -12840,10 +13038,6 @@ "b3c8f1a902": "Filter files by name", "d4f8c2a901": "Clear and close filter", "e8a1c4b203": "vs", - "compareBaseCommitsAheadOne": "1 commit ahead of {{ref}}", - "compareBaseCommitsAheadOther": "{{count}} commits ahead of {{ref}}", - "compareBaseCommitsBehindOne": "1 commit behind {{ref}}", - "compareBaseCommitsBehindOther": "{{count}} commits behind {{ref}}", "4b4a7de138": "Open review page in browser", "createPrIntentCommitBlockedSummary": "Commit blocked: {{value0}} Fix the issue, then retry Create PR.", "pushRecovery": { @@ -12874,17 +13068,51 @@ "diffCommentNotesCopyFailed": "Failed to copy notes", "conflictCount_one": "{{count}} conflict", "conflictCount_other": "{{count}} conflicts", - "discardFailedSingular": "Failed to discard {{count}} file", - "discardFailedPlural": "Failed to discard {{count}} files", - "noteCountSingular": "{{count}} note", - "noteCountPlural": "{{count}} notes" + "statusReadFailed": "Git could not read this workspace. Changes shown may be out of date.", + "discardFailedSampleMore_one": "{{paths}}, +{{count}} more", + "discardFailedSampleMore_other": "{{paths}}, +{{count}} more", + "discardFailed_one": "Failed to discard {{count}} file", + "discardFailed_other": "Failed to discard {{count}} files", + "discardFailedWithSample": "{{error}} (e.g. {{paths}})", + "compareBaseCommitsAhead_one": "{{count}} commit ahead of {{ref}}", + "compareBaseCommitsAhead_other": "{{count}} commits ahead of {{ref}}", + "compareBaseCommitsBehind_one": "{{count}} commit behind {{ref}}", + "compareBaseCommitsBehind_other": "{{count}} commits behind {{ref}}", + "branchFilesChangedVsBase_one": "{{count}} file changed vs {{ref}}", + "branchFilesChangedVsBase_other": "{{count}} files changed vs {{ref}}", + "noteCount_one": "{{count}} note", + "noteCount_other": "{{count}} notes", + "comparingAgainstRef": "Comparing against {{ref}}", + "commitsAheadShort_one": "{{count}} ahead", + "commitsAheadShort_other": "{{count}} ahead", + "unresolvedConflictOfKind": "Unresolved conflict ({{kind}})", + "unresolvedConflict": "Unresolved conflict", + "locallyResolvedConflictOfKind": "Conflict resolved locally ({{kind}})", + "locallyResolvedConflict": "Conflict resolved locally", + "pushesToForkTarget": "Pushes to fork {{target}}", + "abortRebaseConfirmTitle": "Abort rebase?", + "abortMergeConfirmTitle": "Abort merge?", + "abortRebaseConfirmDescription": "This cancels the rebase in progress and can discard conflict resolutions made during this rebase.", + "abortMergeConfirmDescription": "This cancels the merge in progress and can discard conflict resolutions made during this merge.", + "abortRebaseFailedFallback": "Failed to abort rebase", + "abortMergeFailedFallback": "Failed to abort merge", + "abortRebaseFailed": "Abort rebase failed", + "abortMergeFailed": "Abort merge failed", + "clearNotesFromWorkspace_one": "Clear {{count}} note from this workspace?", + "clearNotesFromWorkspace_other": "Clear {{count}} notes from this workspace?", + "clearNotesFromFile_one": "Clear {{count}} note from {{path}}?", + "clearNotesFromFile_other": "Clear {{count}} notes from {{path}}?" }, "SourceControlAgentActionDialog": { "8e856842d1": "Could not start the selected agent.", "c075d00de1": "Unable to resolve the workspace connection.", "38b899cc02": "All repositories", "808cfe0a3b": "This repository", - "994cddd1f7": "Don't save" + "994cddd1f7": "Don't save", + "agentNotEnabledOrDetected": "{{agent}} is not enabled or was not detected on this workspace host.", + "workspaceConnectionUnresolved": "Unable to resolve the workspace connection.", + "noEnabledAgentsDetected": "No enabled agents were detected on this workspace host.", + "startAgent": "Start agent" }, "SourceControlAgentActionDialogForm": { "013c9ac04a": "Save for", @@ -12950,10 +13178,6 @@ "cbcc4ab3db": "Showing first 100 checks", "0dca6bfab5": "Open check details", "991f50c7e4": "No checks configured", - "9ad98f2a17": "pending", - "5e52f4ef7f": "failing", - "02ca4f9074": "passing", - "checksUnresolvedChip": "unresolved", "checksUnresolvedStripHint": "These checks finished without a pass or fail verdict.", "e15a8b77ef": "No inline details are available for this check.", "dcb3c546fe": "Retry", @@ -12972,7 +13196,6 @@ "1f2b980522": "Loading check details…", "0c96cd25e5": "Resolve", "3a71a6ed0b": "Resolve conflicts before checks and merge can complete.", - "60186d8498": "Conflicts block this", "c16762ac8c": "Checks and comments below show the current fetched context.", "9d0e7bcefc": "No blocking PR action", "5856874b59": "Orca will refresh checks while this panel stays open.", @@ -12997,7 +13220,6 @@ "084c516efb": "Copy commands", "5dc3af25c0": "Select comment", "d7a2f9c401": "Send unresolved {{value0}} comments", - "d91f2a6c39": "Send {{value0}} queued comments to AI", "a6de3e5a20": "Clear queued comments", "f8a2c91d04": "Queue for agent", "b4e8a1c902": "Queued", @@ -13020,7 +13242,28 @@ "pendingChecks_one": "{{count}} check pending", "pendingChecks_other": "{{count}} checks pending", "unresolvedChecks_one": "{{count}} check unresolved", - "unresolvedChecks_other": "{{count}} checks unresolved" + "unresolvedChecks_other": "{{count}} checks unresolved", + "passingCount_one": "{{count}} passing", + "passingCount_other": "{{count}} passing", + "failingCount_one": "{{count}} failing", + "failingCount_other": "{{count}} failing", + "pendingCount_one": "{{count}} pending", + "pendingCount_other": "{{count}} pending", + "unresolvedCount_one": "{{count}} unresolved", + "unresolvedCount_other": "{{count}} unresolved", + "sendQueuedCommentsToAi_one": "Send {{count}} queued comment to AI", + "sendQueuedCommentsToAi_other": "Send {{count}} queued comments to AI", + "conflictsBlockThisMr": "Conflicts block this MR", + "conflictsBlockThisPr": "Conflicts block this PR", + "copyComment": "Copy comment", + "sendComment": "Send", + "commentingRequiresGitHubPrTarget": "Commenting requires a GitHub PR repository target.", + "selectWorkspaceBeforeAiAction": "Select a workspace before launching an AI action.", + "operation": { + "rebase": "Rebase", + "merge": "Merge", + "cherryPick": "Cherry-pick" + } }, "empty": { "state": { @@ -13261,10 +13504,10 @@ "dialog": { "3bc61dc989": "Cancel", "15efa778e3": "Discard", - "42f89dd030": "files", - "e7611dca35": "file", "0d2d88cba5": "This cannot be undone.", - "1551c14668": "Discard changes?" + "1551c14668": "Discard changes?", + "fileCount_one": "{{count}} file", + "fileCount_other": "{{count}} files" } }, "dropdown": { @@ -13426,8 +13669,8 @@ }, "compare": { "summary": { - "commitsAheadSingular": "{{count}} commit ahead of {{ref}}", - "commitsAheadPlural": "{{count}} commits ahead of {{ref}}" + "commitsAhead_one": "{{count}} commit ahead of {{ref}}", + "commitsAhead_other": "{{count}} commits ahead of {{ref}}" } }, "conflict": { @@ -13491,24 +13734,30 @@ "unresolved": "Couldn't determine which host owns this workspace. Check the connection and try again." }, "useFileDeletion": { - "72691dfebc": "Failed to {{value0}} '{{value1}}'.", "d979a4fbb5": "Permanently delete '{{value0}}'?", "92276aceb7": "Delete", "7fb9435c86": "This permanently deletes the directory and its contents on the remote host. This cannot be undone.", "23e98f192f": "This permanently deletes the file on the remote host. This cannot be undone.", "8b8ee9d22f": "Couldn't determine which host owns this file. Check the workspace connection and try again.", - "af1270b90d": "Permanently delete {{count}} items?", "dd029aa5cd": "This permanently deletes the selected items and any directory contents on the remote host. This cannot be undone.", - "77fdc36183": "Delete {{count}} items?", - "fca915a67a": "Remote items are permanently deleted and cannot be undone. Local items move to the {{value0}}." + "deleteFailed": "Failed to delete '{{name}}'.", + "recycleBinFailed": "Failed to move '{{name}}' to the Recycle Bin.", + "trashFailed": "Failed to move '{{name}}' to the Trash.", + "deleteItems_other": "Delete {{count}} items?", + "permanentlyDeleteItems_other": "Permanently delete {{count}} items?", + "mixedRecycleBin": "Remote items are permanently deleted and cannot be undone. Local items move to the Recycle Bin.", + "mixedTrash": "Remote items are permanently deleted and cannot be undone. Local items move to the Trash." }, "useFileExplorerHandlers": { "32cd9fd991": "Cannot open symlink target", "folderLinksOutsideProject": "This folder links outside the project, so it can't be opened here." }, "useFileExplorerImport": { - "25919b2050": "Skipped {{value0}} {{value1}}.", - "132fd0e1e9": "Failed to import {{value0}} {{value1}}." + "importFailedCount_one": "Failed to import {{count}} file.", + "importFailedCount_other": "Failed to import {{count}} files.", + "importSkippedCount_one": "Skipped {{count}} file.", + "importSkippedCount_other": "Skipped {{count}} files.", + "importFailed": "Failed to import files." }, "useFileExplorerKeys": { "8adb953095": "Operation failed" @@ -13546,7 +13795,6 @@ "refreshSessionHistory": "Refresh Session History", "searchSessions": "Search sessions", "clearSearch": "Clear search", - "transcriptsSkipped": "{{count}} transcript skipped", "noAgentSessionsFound": "No agent sessions found", "noSessionsMatchFilters": "No sessions match the current filters", "noAgentsSelected": "No agents selected", @@ -13565,7 +13813,9 @@ "resumeInChatFailed": "Could not resume this session in a new chat.", "resumeInNewCliUnavailable": "This session cannot be opened in the CLI.", "resumeInNewCliHostTooOld": "Update Orca on the host that runs this chat to resume it in a new CLI.", - "folderWorkspaceUnavailable": "Folder workspace is no longer available." + "folderWorkspaceUnavailable": "Folder workspace is no longer available.", + "transcriptsSkippedCount_one": "{{count}} transcript skipped", + "transcriptsSkippedCount_other": "{{count}} transcripts skipped" }, "AiVaultPanelControls": { "scanningSessions": "Scanning sessions", @@ -13596,11 +13846,8 @@ "latestTurns": "Latest turns", "noPreviewAvailable": "No conversation preview available", "conversationNotSaved": "Conversation not saved", - "recoverableEmptyDetail": "This session has no saved conversation, but {{value0}} recoverable item(s) survive.", "recoverableEmptyOpenLogHint": "Open the log to recover them.", "emptyConversationDetail": "This session has no saved conversation and cannot be resumed.", - "queuedMessages": "{{value0}} queued message(s)", - "subagentTranscripts": "{{value0}} subagent transcript(s)", "resumeInWorktree": "Resume in Worktree", "viewLog": "View Log", "unknownTime": "Unknown time", @@ -13629,7 +13876,13 @@ "noFirstPromptAvailable": "No first prompt available", "loadingFirstPrompt": "Loading first prompt…", "folder": "Folder", - "resumeInFolder": "Resume in Folder" + "resumeInFolder": "Resume in Folder", + "recoverableEmptyDetailCount_one": "This session has no saved conversation, but {{count}} recoverable item survives.", + "recoverableEmptyDetailCount_other": "This session has no saved conversation, but {{count}} recoverable items survive.", + "queuedMessageCount_one": "{{count}} queued message", + "queuedMessageCount_other": "{{count}} queued messages", + "subagentTranscriptCount_one": "{{count}} subagent transcript", + "subagentTranscriptCount_other": "{{count}} subagent transcripts" }, "AiVaultSessionRow": { "noPreviewAvailable": "No conversation preview available", @@ -13763,26 +14016,26 @@ "confirmation": { "84f6f5b9eb": "Included: {{numbers}}. ", "541984b2eb": "Queue through #{{pr}}?", - "4809f55cdb": "{{included}}GitHub will add {{count}} pull request to the merge queue together. The queue chooses the merge method and may merge them in separate groups.", - "be8f2621be": "{{included}}GitHub will add {{count}} pull requests to the merge queue together. The queue chooses the merge method and may merge them in separate groups.", - "92ca033e72": "Queue {{count}} PR", - "478a527b15": "Queue {{count}} PRs", "1feef35ca4": "Merge through #{{pr}}?", - "c3e036c99f": "{{included}}GitHub will merge {{count}} pull request atomically using {{method}}. If it cannot merge, nothing will be merged.", - "369aba4b32": "{{included}}GitHub will merge {{count}} pull requests atomically using {{method}}. If any cannot merge, none will.", - "493c78f521": "Merge {{count}} PR", - "eb7051d268": "Merge {{count}} PRs" + "queueDescription_one": "{{included}}GitHub will add {{count}} pull request to the merge queue together. The queue chooses the merge method and may merge them in separate groups.", + "queueDescription_other": "{{included}}GitHub will add {{count}} pull requests to the merge queue together. The queue chooses the merge method and may merge them in separate groups.", + "queueConfirm_one": "Queue {{count}} PR", + "queueConfirm_other": "Queue {{count}} PRs", + "mergeDescription_one": "{{included}}GitHub will merge {{count}} pull request atomically using {{method}}. If it cannot merge, nothing will be merged.", + "mergeDescription_other": "{{included}}GitHub will merge {{count}} pull requests atomically using {{method}}. If any cannot merge, none will.", + "mergeConfirm_one": "Merge {{count}} PR", + "mergeConfirm_other": "Merge {{count}} PRs" }, "merge": { - "55ae29b907": "Merge through #{{pr}} · {{count}} PR", - "b8446f6ec2": "Merge through #{{pr}} · {{count}} PRs", "189d0ec614": "#{{pr}} is still a draft.", "640fb50d9c": "#{{pr}} is closed.", "46ffcbda75": "#{{pr}} has merge conflicts.", "6dabefd63e": "#{{pr}} has requested changes.", "2bb21fc326": "#{{pr}} still needs review approval.", "c23faf74df": "#{{pr}} must be updated.", - "f561e80968": "#{{pr}} is blocked." + "f561e80968": "#{{pr}} is blocked.", + "mergeThroughLabel_one": "Merge through #{{pr}} · {{count}} PR", + "mergeThroughLabel_other": "Merge through #{{pr}} · {{count}} PRs" } } } @@ -13839,14 +14092,15 @@ "sourceActionsUnavailable": "The transcript source is unavailable." }, "AiVaultScanProgressStrip": { - "agentChecked": "{{agent}}: {{settled}} of {{total}} history candidates checked", "fileCount_one": "{{value0}} file", "fileCount_other": "{{value0}} files", "databaseCount_one": "{{value0}} database", "databaseCount_other": "{{value0}} databases", "scanning": "Scanning {{value0}}", "checking": "Checking {{value0}}", - "scanned": "Scanned {{value0}}" + "scanned": "Scanned {{value0}}", + "agentCheckedCount_one": "{{agent}}: {{settled}} of {{total}} history candidate checked", + "agentCheckedCount_other": "{{agent}}: {{settled}} of {{total}} history candidates checked" }, "run": { "source": { @@ -13875,6 +14129,15 @@ } } } + }, + "fileExplorerMultiDrag": { + "moreItems_one": "+{{count}} more", + "moreItems_other": "+{{count}} more" + }, + "CreatePullRequest": { + "createInProgress": "Create PR in progress...", + "workspaceHostUnresolved": "The workspace host is unresolved. Refresh the workspace and retry.", + "branchDiscoveryFailed": "Branch discovery failed." } } }, @@ -14399,11 +14662,11 @@ "a2f68645ac": "Refresh GitLab API budget", "2f9c16d6c3": "Orca uses REST through the GitLab CLI.", "14e144f7a7": "GitLab API Budget", - "3e2c982cfa": "left, resets in", - "ea8ad0bae8": "of", "0a891e8935": "REST API", "953f7c6062": "This GitLab host did not return rate-limit headers.", - "budget_scope_prefix": "Budget scope" + "budget_scope_prefix": "Budget scope", + "resetUnknown": "unknown", + "remainingOfLimit": "{{remaining}} of {{limit}} left, resets in {{reset}}" } } } @@ -14475,13 +14738,13 @@ "9ee54037a4": "Custom command", "4b2fc4b80c": "Thinking effort", "be8917699e": "Model", - "4d9b6d84df": "unsupported. Choose Claude, Codex, or Custom.", "560d4feb00": "Custom", "29d119fe95": "Agent", "f9382b48a1": "Enable AI author", "1c0cb4fabb": "AI author", "bd14e9c42a": "Not configured", - "1f9468c5c9": "{{value0}} unsupported" + "1f9468c5c9": "{{value0}} unsupported", + "unsupportedAgent": "{{agent}} is not supported. Choose Claude, Codex, or Custom." }, "BrowserAnimatedVisual": { "46df009982": "Start your free trial", @@ -15022,17 +15285,14 @@ "ConflictComponents": { "f338288514": "Loading conflict contents...", "90d576adb2": "Refresh", - "a1ce36f77d": "Snapshot captured at", "c8ca989aea": "Show file tree", "58ad5ad431": "Dismiss", "28e7db4a90": "Source Control", "31931dec46": "This review snapshot no longer has any live unresolved conflicts.", "992145ff5a": "All conflicts resolved", - "d5edd81755": "Renamed from", "6e459867ad": "Session-local continuity state. Git is no longer reporting this file as unmerged.", "9c2901ef8a": "Next conflict", "41d9af2e7a": "Previous conflict", - "55d61a0ccd": "conflict ·", "da539359b6": "No working-tree file is available to edit for this conflict.", "unresolvedConflicts_one": "{{count}} unresolved conflict", "unresolvedConflicts_other": "{{count}} unresolved conflicts" @@ -15728,7 +15988,9 @@ "6978871a3d": "Open", "cce596969e": "Delete note", "cad3384faa": "Edit note", - "508ee678a5": "Open in browser" + "508ee678a5": "Open in browser", + "noteAuthorFallback": "Note", + "sentMeta": "sent" }, "DiffCommentPopover": { "2b3ce6d394": "Cancel", @@ -15741,6 +16003,9 @@ }, "useDiffCommentDecorator": { "995fa28b50": "This note" + }, + "diffCommentZoneCard": { + "noteAlreadySent": "Note already sent" } } }, @@ -16306,7 +16571,21 @@ "b09b2384fd": "Paused", "eaa02014f8": "Enabled", "29baf8f4c2": "Source", - "lastRunFailed": "Last run failed." + "lastRunFailed": "Last run failed.", + "noGrace": "No grace", + "graceMinutes_one": "{{count}} minute", + "graceMinutes_other": "{{count}} minutes", + "graceHours_one": "{{count}} hour", + "graceHours_other": "{{count}} hours", + "usageCoverageRuns_one": "{{known}}/{{count}} run", + "usageCoverageRuns_other": "{{known}}/{{count}} runs", + "usageUnavailable": "Unavailable", + "noRuns": "No runs", + "projectDefault": "Project default", + "reuseLiveSession": "Reuse live session", + "freshEachRun": "Fresh each run", + "precheckEnabled": "Enabled, {{timeout}}", + "precheckNone": "None" }, "AutomationEditorDialog": { "fb1896a5e7": "Cancel", @@ -16410,11 +16689,8 @@ "2faecab10b": "Run Now", "13118faadf": "Unknown project", "73f630b49d": "Cancel", - "1b586f0e2b": "on", - "02a33e3204": "from", "9adfab2596": "Delete External Automation", "1e2e41392f": "Don't ask again", - "b264564427": "and its run history. Workspaces created by previous runs are not deleted.", "080dcb5fbb": "Delete Automation", "19a6e30eae": "Refresh automations", "77c2778945": "Automations", @@ -16449,7 +16725,6 @@ "pendingAutomationRunMissing": "Run history no longer available.", "paused": "Paused", "missingWorkspace": "Missing workspace", - "runUsageSummary": "{{cost}} est. · {{tokens}} tokens", "usageUnavailable": "Usage unavailable", "noRunUsageYet": "No run usage yet", "noWorkspace": "No workspace", @@ -16464,7 +16739,11 @@ "rowActions": "Automation actions", "tableLastRun": "Last run", "ownerChanged": "This automation changed hosts. Refresh and try again.", - "runError": "Error:" + "runError": "Error:", + "deleteAutomationDescription": "Delete and its run history. Workspaces created by previous runs are not deleted.", + "deleteExternalAutomationDescription": "Delete from on .", + "runUsageSummaryTokens_one": "{{cost}} est. · {{tokens}} token", + "runUsageSummaryTokens_other": "{{cost}} est. · {{tokens}} tokens" }, "AutomationsPageSkeleton": { "55527b7bcf": "Loading automations" @@ -16494,8 +16773,8 @@ "92405f1431": "Unavailable", "dbdcec22bd": "Read-only", "0a2d4359a8": "Manageable", - "e2532150ed": "automations", - "701515f010": "automation" + "automationCount_one": "{{count}} automation", + "automationCount_other": "{{count}} automations" }, "WorkspaceCombobox": { "ee5b280eba": "No workspaces found.", @@ -16537,7 +16816,8 @@ "last": { "run": { "done": "Done", - "failed": "Failed" + "failed": "Failed", + "statusWithRelative": "{{status}} {{relative}}" } } }, @@ -16682,15 +16962,12 @@ }, "externalScope": { "uncheckedHost": "External automation managers on {{hostLabel}} could not be checked.", - "uncheckedHosts": "External automation managers on {{count}} hosts could not be checked." + "uncheckedHostCount_other": "External automation managers on {{count}} hosts could not be checked.", + "uncheckedHostCount_one": "External automation managers on {{count}} host could not be checked." }, "enablement": { "paused": "Paused" }, - "runHistory": { - "occurrencesWithLatest": "{{times}} times, most recently {{date}}", - "occurrences": "{{times}} times" - }, "createDestination": { "label": "Host", "placeholder": "Select a host", @@ -16744,6 +17021,71 @@ "useFreshSessions": "Use fresh sessions", "helper": "Added to this host's default arguments for each fresh session.", "detailLabel": "Extra arguments" + }, + "runHistory": { + "runCountSummary_one": "{{count}} run · {{completed}} completed", + "runCountSummary_other": "{{count}} runs · {{completed}} completed", + "occurrencesWithLatestCount_other": "{{count}} times, most recently {{date}}", + "occurrencesCount_other": "{{count}} times", + "occurrencesCount_one": "{{count}} time", + "occurrencesWithLatestCount_one": "{{count}} time, most recently {{date}}" + }, + "capabilityProbe": { + "createIdempotencyUpdateRequired": "Moving automations to this host requires a newer Orca server. Update the HUB and try again." + }, + "editDraft": { + "unsupportedSchedule": "This automation has an unsupported saved schedule. Pick a supported schedule before saving changes." + }, + "hostCatalog": { + "orphanEntryLabel": "Unassigned legacy automations" + }, + "automationPageParts": { + "never": "Never", + "now": "now", + "runStatusPending": "Queued", + "runStatusDispatching": "Starting", + "runStatusDispatched": "Launched", + "runStatusCompleted": "Done", + "runStatusSkippedPrecheck": "Precheck skipped", + "runStatusSkippedMissed": "Skipped", + "runStatusSkippedUnavailable": "Unavailable", + "runStatusSkippedNeedsInteractiveAuth": "Needs credentials", + "runStatusDispatchFailed": "Failed" + }, + "runContent": { + "noOutput": "No output content available." + }, + "runViewState": { + "viewRun": "View run", + "runOpen": "Run is open", + "terminalOnPairedServer": "Run terminal is on the paired server.", + "terminalUnavailable": "Run terminal is unavailable.", + "openWorkspace": "Open workspace", + "workspaceAvailable": "Workspace is available.", + "snapshotSaved": "Snapshot saved", + "showingSnapshot": "Showing saved run snapshot.", + "namedWorkspaceGone": "{{name}} no longer available", + "workspaceGone": "Workspace no longer available", + "noWorkspaceLaunched": "No workspace launched" + }, + "runWorkspaceDisplay": { + "notLaunched": "Not launched", + "namedWorkspaceGone": "{{name}} (no longer available)" + }, + "usage": { + "tokensAndCost_one": "{{tokens}} token · {{cost}}", + "tokensAndCost_other": "{{tokens}} tokens · {{cost}}" + }, + "externalDisplay": { + "sshHost": "SSH host", + "local": "Local" + }, + "externalActionDisabled": { + "actionInProgress": "Another automation action is still running.", + "sshConnecting": "Wait for this SSH host to finish connecting.", + "connectSshHost": "Connect this SSH host before managing {{provider}} automations.", + "cannotManageOnSshHost": "{{provider}} cannot manage automations on this SSH host.", + "cannotManageLocally": "{{provider}} cannot manage automations on this machine." } }, "agent": { @@ -16884,8 +17226,6 @@ "63ce735809": "Connect", "4a2ab52781": "Verifying…", "79e7aaed39": "Cancel", - "fdd26d81cc": "Atlassian account settings", - "8090504a3e": "Create a token in", "7b3967c12f": "Atlassian API token", "3d81bf3ab3": "API token", "e91b9a4073": "you@example.com", @@ -16910,17 +17250,18 @@ "be9eba0a1b": "username", "70035652d7": "Password", "c50abbf340": "Jira account password", - "d8737db691": "Use your Jira Server or Data Center account username and password." + "d8737db691": "Use your Jira Server or Data Center account username and password.", + "createTokenInSettings": "Create a token in Atlassian account settings." } } }, "rightSidebar": { "FolderWorkspaceWorktreesPanel": { "unavailable": "Workspaces are only shown for folder workspaces.", - "countOne": "1 attached worktree", - "countMany": "{{value0}} attached worktrees", "emptyTitle": "No attached worktrees yet", - "emptyCopy": "Worktrees created from this workspace will show up here." + "emptyCopy": "Worktrees created from this workspace will show up here.", + "attachedCount_one": "{{count}} attached worktree", + "attachedCount_other": "{{count}} attached worktrees" }, "FolderWorkspacePrChecksPanel": { "unavailable": "PR checks are only shown for folder workspaces.", @@ -16932,12 +17273,12 @@ "hideDetails": "Hide {{value0}} PR check details", "reviewChecks": "Review checks", "allChecksPassing": "all checks passing", - "oneWorktree": "1 worktree", - "worktreeCount": "{{value0}} worktrees", - "oneFailing": "1 failing", - "failingCount": "{{value0}} failing", - "onePending": "1 pending", - "pendingCount": "{{value0}} pending" + "worktreeCountLabel_one": "{{count}} worktree", + "worktreeCountLabel_other": "{{count}} worktrees", + "failingCountLabel_one": "{{count}} failing", + "failingCountLabel_other": "{{count}} failing", + "pendingCountLabel_one": "{{count}} pending", + "pendingCountLabel_other": "{{count}} pending" }, "parentPrChecks": { "rowSummary": { @@ -17019,10 +17360,11 @@ "combobox": { "noProjects": "No projects", "allProjects": "All projects", - "hostCount": "{{value0}} hosts", "searchProjects": "Search projects...", "noMatches": "No projects match your search.", - "chooseSource": "Choose task source" + "chooseSource": "Choose task source", + "hostCount_other": "{{count}} hosts", + "hostCount_one": "{{count}} host" } } }, @@ -17059,7 +17401,35 @@ "taskSourceContextSummary": { "sourceUnavailable": "{{value0}} source unavailable: {{value1}}", "someSourceHostsUnavailable": "Some {{value0}} source hosts unavailable: {{value1}}", - "reconnectOrUpdateTitle": "Reconnect or update {{value0}} to load this source." + "reconnectOrUpdateTitle": "Reconnect or update {{value0}} to load this source.", + "providerSourceTitle": "{{provider}} source", + "hostTitle": "Host: {{hosts}}", + "accountTitle": "Account: {{accounts}}", + "sourceTitle": "Source: {{source}}", + "sourceHostCount_other": "{{count}} source hosts", + "noHost": "No host", + "projectCount_other": "{{count}} projects", + "selectedProject": "Selected project", + "selectedProjectCount_other": "{{count}} selected projects", + "currentAccount": "Current account", + "statusCheckingCapabilities": "checking server capabilities", + "statusServerUpdateForTaskSources": "server update needed for task sources", + "statusProviderAuthNeeded": "provider auth needed", + "statusSourceToolUnavailable": "source tool unavailable", + "statusProviderUnsupported": "provider unsupported on this host", + "statusServerUpdateNeeded": "server update needed", + "unavailableCount_other": "{{count}} unavailable", + "statusConnected": "connected", + "statusAuthNeeded": "auth needed", + "statusConnecting": "connecting", + "statusConnectionIssue": "connection issue", + "statusDisconnected": "disconnected", + "hostStatus": "{{host}} {{status}}", + "availabilityTitle": "Availability: {{hosts}}", + "projectCount_one": "{{count}} project", + "selectedProjectCount_one": "{{count}} selected project", + "sourceHostCount_one": "{{count}} source host", + "unavailableCount_one": "{{count}} unavailable" }, "ShortcutKeyCombo": { "07eb4985a1": "Double-tap {{value0}}" @@ -17452,15 +17822,15 @@ } }, "NativeChatResumeRunPanel": { - "resumedTitle": "Resumed {{value0}} of {{value1}} chats", - "resumingTitleOne": "Resuming 1 chat", - "resumingTitle": "Resuming {{value0}} chats", "description": "Each chat is restored with its full context and asked to check where it stopped. You can close this; the status bar keeps track.", - "resumedTitleOne": "Resumed {{value0}} of 1 chat", "finished": "These chats were working when Orca closed. Orca restored each one where it stopped, with its full context, and asked the agent to check what it was doing before carrying on. Your own prompts weren’t re-sent.", "finishedUpdate": "These chats were working when Orca installed an update. Orca restored each one where it stopped, with its full context, and asked the agent to check what it was doing before carrying on. Your own prompts weren’t re-sent.", "finishedPartial": "These chats were working when Orca closed. The ones Orca resumed were restored where they stopped, with their full context, and asked to check what they were doing before carrying on. Your own prompts weren’t re-sent. Check the list for chats that still need attention or can be resumed.", - "finishedPartialUpdate": "These chats were working when Orca installed an update. The ones Orca resumed were restored where they stopped, with their full context, and asked to check what they were doing before carrying on. Your own prompts weren’t re-sent. Check the list for chats that still need attention or can be resumed." + "finishedPartialUpdate": "These chats were working when Orca installed an update. The ones Orca resumed were restored where they stopped, with their full context, and asked to check what they were doing before carrying on. Your own prompts weren’t re-sent. Check the list for chats that still need attention or can be resumed.", + "resumedOfTotal_one": "Resumed {{resumed}} of {{count}} chat", + "resumedOfTotal_other": "Resumed {{resumed}} of {{count}} chats", + "resumingCount_one": "Resuming {{count}} chat", + "resumingCount_other": "Resuming {{count}} chats" }, "NativeChatResumeRunStatusIcon": { "waitingForReply": "Waiting for a reply", @@ -17525,6 +17895,72 @@ "cancelled": "This plain SSH terminal was closed before it started.", "terminalUnavailable": "Orca couldn’t open a terminal here.", "openHint": "Keeps you working on the host while Orca can’t set up there." + }, + "AgentStateDot": { + "working": "Working", + "monitoring": "Monitoring background tasks", + "blocked": "Blocked", + "waiting": "Waiting for input", + "interrupted": "Interrupted", + "failed": "Failed", + "done": "Done", + "idle": "Idle", + "unverifiable": "No recent update", + "unconfirmed": "Couldn’t confirm", + "permission": "Needs attention" + }, + "issueComments": { + "you": "You" + }, + "ZoomOverlay": { + "uiZoom": "UI Zoom", + "editorZoom": "Editor Zoom", + "terminalZoom": "Terminal Zoom" + }, + "issueCopy": { + "urlCopied": "URL copied", + "keyCopied": "Key copied", + "identifierCopied": "Identifier copied", + "branchNameCopied": "Branch name copied", + "promptCopied": "Prompt copied", + "urlCopyFailed": "Failed to copy URL", + "keyCopyFailed": "Failed to copy key", + "identifierCopyFailed": "Failed to copy identifier", + "branchNameCopyFailed": "Failed to copy branch name", + "promptCopyFailed": "Failed to copy prompt" + }, + "prCheckCounts": { + "noChecksFound": "No checks found", + "checksFailing_one": "{{count}} check failing", + "checksFailing_other": "{{count}} checks failing", + "checksNeedAction_one": "{{count}} check needs action", + "checksNeedAction_other": "{{count}} checks need action", + "checksPending_one": "{{count}} check pending", + "checksPending_other": "{{count}} checks pending", + "allChecksPassing": "All checks passing", + "checksPassingOfTotal_one": "{{passing}} of {{count}} check passing", + "checksPassingOfTotal_other": "{{passing}} of {{count}} checks passing" + }, + "taskPageJiraBoard": { + "changeStatusFailed": "Failed to change status." + }, + "jiraIssue": { + "loadStatusChangesFailed": "Failed to load status changes.", + "loadCommentsFailed": "Failed to load comments." + }, + "taskPageJiraLinkedIssues": { + "someIssuesFailed": "Some Jira issues linked to workspaces could not be loaded. Refresh to try again." + }, + "taskPageJiraLoadState": { + "failedToLoadIssues": "Failed to load Jira issues.", + "authFailed": "Jira authentication failed. Reconnect Jira in Settings, then try again.", + "accessDenied": "Jira denied access to this issue search. Check project permissions or try a different JQL query.", + "rateLimited": "Jira rate-limited this issue search. Try again in a moment.", + "serverError": "Jira had a server error while loading issues. Try again in a moment.", + "jqlFailed": "Jira couldn't run this JQL query. Check the syntax and try again.", + "unreachable": "Couldn't reach Jira. Check your connection and try again.", + "loadFailed": "Couldn't load Jira issues. Try again in a moment.", + "errorWithCode": "Error {{code}}: {{summary}}" } }, "i18n": { @@ -17728,6 +18164,7 @@ "agentCommandNotRunnable": "{{agent}}'s Command in Settings → Agents must be a program path or name Orca can find, with no arguments or variables. Change it or reset it.", "runtimeNotInstalled": "{{agent}} isn't installed on the computer running this chat. Install it from the chat in a current version of Orca.", "fullAccessAsRoot": "{{agent}} won't use Full access while it runs as root. Choose another permission for {{agent}} in Settings → Agents for the computer running this chat, then start a new chat.", + "launchPreparationFailed": "Orca couldn't prepare {{agent}} to start on the computer running this chat.", "conversationOpenElsewhere": "Codex is still holding this conversation open. Try again in a moment, or close other Codex terminals.", "conversationOpenInTerminal": "{{agent}} is already running this conversation in another terminal. Quit {{agent}} there or close that terminal to continue here.", "chooseClaudeAccount": "Choose or add one in Claude Accounts settings.", @@ -17736,6 +18173,7 @@ "providerExitedRow": "{{agent}} stopped while this response was in progress. You can continue in this conversation.", "providerExitedRejection": "{{agent}} stopped before this message was sent.", "providerExitedAnswer": "{{agent}} has stopped, so your answer was not sent. Send a message to continue.", + "claudeEffortInvalid": "Claude effort is invalid; choose low, medium, high, xhigh, or max and send again.", "providerRejected": "{{agent}} didn't accept this message.", "providerRejectedQuoted": "{{agent}} didn't accept this message: {{detail}}.", "attachmentEmpty": "An image on this message is empty, so the message was not sent.", @@ -18416,7 +18854,6 @@ "pausedSendFailedWaiting": "Couldn't send — press Send to retry once the agent finishes.", "save": "Save", "editingMessage": "Editing message", - "cancelEditing": "Cancel editing", "editChanged": "This message changed while you were editing. Your edit is in the chat box.", "editChangedPrompt": "This message changed while you were editing. Your edit will be in the chat box after you answer the agent.", "editChangedNotSaved": "This message changed while you were editing. Your edit wasn't saved.", @@ -18430,12 +18867,13 @@ "expand": "Expand", "queued": "Queued", "clearAll": "Clear all", - "pasteOrDropImages": "Paste or drop images", - "saveNeedsContent": "Add text or an image to save" + "editReturned": "Your edit is in the chat box.", + "commandsUnsupported": "Commands can't be saved in a queued message." }, "thought": "Thought", "thoughtForDuration": "Thought for {{duration}}", "explicitChatWsl": "Chat is not available in WSL. Open the agent in a terminal instead.", + "explicitChatWslAddHost": "Chat is not available in a WSL folder opened from Windows. Add the distro as a WSL host (Add a project → Add remote host → Add WSL distro) to chat there, or open the agent in a terminal.", "explicitChatSsh": "Chat is not available over SSH. Open the agent in a terminal instead.", "explicitChatUnavailable": "This workspace cannot run the chat. Check the agent installation or open it in a terminal.", "structuredSessionHostDeclined": "Opened {{value0}} in a terminal", @@ -18446,7 +18884,9 @@ "hostOutage": { "offline": "{{hostName}} is offline", "reconnecting": "{{hostName}} is reconnecting…", - "reconnect": "Reconnect" + "reconnect": "Reconnect", + "stopped": "{{distro}} is stopped", + "start": "Start" }, "interruptedContinue": { "continue": "Continue", @@ -18561,6 +19001,15 @@ "settings": "Open settings in Terminal", "extensions": "Open the extension dashboard in Terminal", "hotkeys": "Show keyboard shortcuts in Terminal" + }, + "modelDescriptions": { + "grok_4_7": "xAI's latest frontier model", + "grok_4_6": "xAI's previous frontier model", + "grok_4_5": "An earlier xAI frontier model", + "fable": "Most capable for the hardest, longest-running tasks", + "opus": "Best for everyday, complex tasks", + "sonnet": "Efficient for routine tasks", + "haiku": "Fastest for quick answers" } }, "tab": { @@ -19092,7 +19541,7 @@ "subagents_other": "{{count}} subagents" }, "terminal": { - "closed": "No live terminal — this agent's pane has closed.", + "previewUnavailable": "No preview available — open the workspace to view this agent.", "remotePreviewUnavailable": "No preview for this remote session — open the workspace to view the terminal.", "focusWorktree": "Open worktree", "close": "Close" @@ -19229,7 +19678,9 @@ }, "quickOpen": { "moreMatchesAvailable": "More matches may be available. Refine your search to narrow the results.", - "recentValidationFailed": "Recent files could not be checked: {{error}}" + "recentValidationFailed": "Recent files could not be checked: {{error}}", + "installRipgrepOnRemote": "Install ripgrep on the remote to enable fast, gitignore-aware listing:", + "scanTooLarge": "Quick Open scan too large ({{reason}})." }, "checksPanel": { "unlinked": { @@ -19242,11 +19693,18 @@ "actionSaveFailed": "Could not save this action. Try saving it again in Settings.", "discard": { "deleteUntrackedFileDescription": "This will permanently delete this untracked file. This cannot be undone.", - "deleteUntrackedFilesDescription": "This will permanently delete these {{count}} untracked files. This cannot be undone.", + "deleteUntrackedFilesDescription_other": "This will permanently delete these {{count}} untracked files. This cannot be undone.", "restoreStagedVersionDescription": "This will restore the last staged version and discard the deletion. This cannot be undone.", "unstagedChangesDescription": "This will revert the unstaged changes to this file. This cannot be undone.", "unstagedSelectionIncludingUntrackedDescription": "This will revert unstaged changes and permanently delete any untracked files in this selection. This cannot be undone.", - "unstagedFilesIncludingUntrackedDescription": "This will revert unstaged changes and permanently delete any untracked files among these {{count}} files. This cannot be undone." + "unstagedFilesIncludingUntrackedDescription_other": "This will revert unstaged changes and permanently delete any untracked files among these {{count}} files. This cannot be undone.", + "delete": "Delete", + "restore": "Restore", + "discard": "Discard", + "discardAll": "Discard all", + "deleteUntrackedTitle_one": "Delete {{count}} untracked file?", + "deleteUntrackedTitle_other": "Delete {{count}} untracked files?", + "deleteCount": "Delete {{count}}" }, "unlinkedPr": { "status": "PR #{{number}} unlinked" @@ -19280,6 +19738,34 @@ "creationUnconfirmed": "{{shortLabel}} creation may have completed. Refreshing branch review state...", "withDetail": "Create {{shortLabel}} failed: {{detail}}", "pushFailed": "Push failed. Resolve the push error, then try again." + }, + "variables": { + "basePrompt": "Orca’s built-in prompt for this action, including the context Orca knows how to gather safely.", + "branch": "The current source-control branch name.", + "stagedFiles": "A newline-separated list of staged files for commit-message generation.", + "stagedPatch": "The staged git patch used for commit-message generation.", + "baseBranch": "The target branch selected in the Create PR composer.", + "currentTitle": "The PR title currently typed in the composer before generation starts.", + "currentBody": "The PR description currently typed in the composer before generation starts.", + "commitSummary": "A newline-separated list of commits on the branch compared to the base.", + "changedFiles": "A summary of files changed between the branch and the base branch.", + "patch": "The branch diff against the base branch used for PR-details generation.", + "firstPrompt": "The first user request for this workspace or chat.", + "assistantMessage": "The initial agent response, when Orca has one available.", + "linkedIssue": "The GitHub issue number linked to this workspace. Empty when no GitHub issue is linked (including GitLab-linked workspaces). Prefer instructional templates: a bare \"Fixes #{linkedIssue}\" becomes \"Fixes #\" when unlinked." + }, + "model": { + "configDefault": "Config default", + "auto": "Auto" + }, + "thinking": { + "off": "Off", + "minimal": "Minimal", + "low": "Low", + "medium": "Medium", + "high": "High", + "xhigh": "Extra High", + "max": "Max" } }, "agentsSidebarIntro": { @@ -19345,8 +19831,6 @@ }, "sessionSearch": { "panel": { - "resultsOne": "{{count}} result", - "resultsOther": "{{count}} results", "noMatches": "No matching sessions in the indexed history. Try another query or scope.", "loadMore": "Load more matches", "indexedHistory": "Indexed history", @@ -19368,11 +19852,23 @@ "retry": "Try again", "scopeUnknown": "This computer does not have this workspace or project. Switch the scope to All to search everything on it.", "sortSessionsAriaLabel": "Sort sessions: {{value0}}", - "sessionsOne": "{{count}} session", - "sessionsOther": "{{count}} sessions", - "sessionsOfLoaded": "{{value0}} of {{value1}} sessions", "showMoreSessions": "Show more sessions", - "loadingMoreSessions": "Loading more sessions…" + "loadingMoreSessions": "Loading more sessions…", + "resultCount_one": "{{count}} result", + "resultCount_other": "{{count}} results", + "sessionCount_one": "{{count}} session", + "sessionCount_other": "{{count}} sessions", + "sessionsShownOfLoaded_one": "{{shown}} of {{count}} session", + "sessionsShownOfLoaded_other": "{{shown}} of {{count}} sessions", + "hostSkipReason": { + "indexChanged": "index changed", + "searchOff": "search off", + "notReady": "not ready", + "unavailable": "unavailable", + "unreachable": "unreachable", + "scopeNotFound": "scope not found there", + "agentNotSupported": "agent not supported" + } } }, "sessionHistory": { @@ -19542,7 +20038,9 @@ "confirmTitle": "Restart the terminal daemon?", "confirmBody": "Restarting ends every process running in {{sessions}}. Agents that support resume can be resumed afterwards; shells and other jobs cannot and must be started again. Do this when your agents are idle.", "cancel": "Cancel", - "confirm": "Restart and end processes" + "confirm": "Restart and end processes", + "count_one": "{{count}} running terminal", + "count_other": "{{count}} running terminals" }, "restartedInputNotSent": "The terminal restarted while you were typing, so some input may not have reached it. Check the new shell before typing it again." }, @@ -19599,9 +20097,9 @@ "pathAdded": "Added", "openFolder": "Open {{name}}", "findOrTypePath": "Find a folder, or type any path…", - "addTypedPath": "Add", "noDirectories": "No folders added yet.", - "removePath": "Remove {{name}}" + "removePath": "Remove {{name}}", + "addTypedPathCode": "Add " }, "accounts": { "wslAccountNotApplied": { @@ -19678,13 +20176,10 @@ "signInLinkCopyFailed": "Could not copy the link.", "switchSessions": { "title": "Switched to {{account}}", - "bodyOne": "1 Claude session is still running on {{previous}}. Restarting continues the conversation on {{next}}. Busy sessions wait for idle before restarting.", - "bodyOther": "{{count}} Claude sessions are still running on {{previous}}. Restarting continues each conversation on {{next}}. Busy sessions wait for idle before restarting.", "dontAskAgain": "Don't ask again (restart automatically)", "dontAskAgainHint": "You can turn this off in Settings → AI Provider Accounts.", "keep": "Keep as is", "restartOne": "Restart session", - "restartOther": "Restart {{count}} sessions", "listLabel": "Claude sessions to restart", "session": "Claude session", "busy": "Working", @@ -19710,11 +20205,15 @@ "reasonOwnFolder": "Uses your own Claude folder", "reasonUnknownAccount": "Account unknown", "reasonNoSession": "Can't resume", - "reviewBodyOne": "1 other Claude session wasn't moved to {{next}}.", - "reviewBodyOther": "{{count}} other Claude sessions weren't moved to {{next}}.", "notMovedOne": "1 other session wasn't moved.", "notMovedOther": "{{count}} other sessions weren't moved.", - "review": "Review" + "review": "Review", + "restartCount_other": "Restart {{count}} sessions", + "reviewBody_one": "{{count}} other Claude session wasn't moved to {{next}}.", + "reviewBody_other": "{{count}} other Claude sessions weren't moved to {{next}}.", + "body_one": "{{count}} Claude session is still running on {{previous}}. Restarting continues the conversation on {{next}}. Busy sessions wait for idle before restarting.", + "body_other": "{{count}} Claude sessions are still running on {{previous}}. Restarting continues each conversation on {{next}}. Busy sessions wait for idle before restarting.", + "restartCount_one": "Restart {{count}} session" } }, "managedData": { @@ -19822,7 +20321,11 @@ "picker": { "pasteUnparseable": "Expected a project URL or owner/number", "ownerLoadFailed": "Couldn't load projects from {{owner}}.", - "organizationsLoadFailed": "Some organizations didn't load ({{failureCount}})." + "organizationsLoadFailed": "Some organizations didn't load ({{failureCount}}).", + "organizations": "Organizations", + "listFailed": "Failed to list projects", + "detailsFailed": "Failed to load details", + "viewFailed": "Failed to fetch project view" }, "error": { "notFoundState": "Could not find this project or view.", @@ -19855,8 +20358,12 @@ "rateLimited": "GitHub rate limit hit. Try again in a few minutes.", "network": "Network error — check your connection.", "tooLargeUnknownCount": "This view has too many items to render in Orca. Narrow the view's filter on GitHub.", - "tooLarge": "This view has {{itemCount}} items — too large to render in Orca. Narrow the view's filter on GitHub.", - "schemaDriftDetail": "Could not read this project view: {{detail}}." + "schemaDriftDetail": "Could not read this project view: {{detail}}.", + "tooLargeCount_one": "This view has {{count}} item — too large to render in Orca. Narrow the view's filter on GitHub.", + "tooLargeCount_other": "This view has {{count}} items — too large to render in Orca. Narrow the view's filter on GitHub." + }, + "columns": { + "type": "Type" } }, "projectField": { @@ -19939,6 +20446,27 @@ "attachments": { "updateRuntime": "Update the remote runtime to change workspace links", "updateRuntimeSafely": "Update the remote runtime to safely change workspace links" + }, + "activity": { + "active": "Active", + "working": "Working", + "monitoring": "Monitoring background tasks", + "permission": "Needs permission", + "failed": "Failed", + "interrupted": "Interrupted", + "unconfirmed": "Couldn’t confirm", + "done": "Done", + "inactive": "Inactive", + "unreadLabel": "{{status}} · Unread" + }, + "reviewStatus": { + "merged": "{{review}}: Merged", + "closed": "{{review}}: Closed", + "draft": "{{review}}: Draft", + "checksFailed": "{{review}} checks: Failed", + "checksPending": "{{review}} checks: Pending", + "checksPassing": "{{review}} checks: Passing", + "open": "{{review}}: Open" } }, "tabHoverCard": { @@ -19988,7 +20516,9 @@ "waitingAriaLabel": "Update waiting for other Orca instances. Click to expand.", "preparingLabel": "Preparing update", "preparingAriaLabel": "Preparing update. Click to expand." - } + }, + "wslMoveInstallHeld": "A project is moving to its WSL host. Install the update once the move finishes.", + "wslMoveUndoInstallHeld": "A project is coming back from its WSL host. Install the update once that finishes." }, "jira": { "connect": { @@ -19998,13 +20528,13 @@ "optionalEmail": "Atlassian email (optional for scoped tokens)" }, "workspace": { - "count": "{{count}} workspaces linked to {{key}}", "startAnother": "Start new workspace", "empty": "Link a Jira issue to a workspace, or choose another view.", "openFailed": "Unable to open the workspace linked to this Jira issue.", "mode": "Has Workspace", "search": "Search linked issues", - "single": "1 workspace linked to {{key}}" + "linkedCount_one": "{{count}} workspace linked to {{key}}", + "linkedCount_other": "{{count}} workspaces linked to {{key}}" }, "prompt": { "dialogTitle": "Copy prompt from template", @@ -20142,6 +20672,162 @@ }, "rowActions": "Actions for {{name}}" }, + "wslMove": { + "entry": { + "hostRow": "Move projects from this distro…", + "projectMenu": "Move to {{distro}} host…" + }, + "blockers": { + "title": "Before these projects can move", + "inProjects": "In {{names}}", + "skipOne": "Leave {{name}} out of this move", + "skipMany": "Leave these {{n}} projects out of this move" + }, + "title": "Move projects to the {{distro}} host", + "loading": "Checking the projects in {{distro}}…", + "runningTitle": "Moving to the {{distro}} host", + "preview": { + "counts": "Projects: {{projects}} · Workspaces: {{workspaces}} · Terminals: {{terminals}} · Chats: {{chats}}", + "whatHappens": "Your files stay where they are. Terminals restart in the same folder; their output, shell history and agent conversations are kept.", + "projects": "Projects in {{distro}}", + "folderBadge": "Folder", + "notMoving": "Not moving", + "checking": "Checking the selected projects…", + "checkAgain": "Check again", + "moveOne": "Move 1 project", + "moveMany": "Move {{n}} projects", + "heldByHost": "Already on the {{distro}} host.", + "changed": "Moved earlier, then changed here by an older version of Orca. It is not moved again.", + "chatsStay": "Existing chats stay on this computer. New chats in this project start on the WSL host.", + "browserLoginsConflict": "Browser sign-ins won’t carry over, because the host’s browser profile is already in use. Sign in again in the host’s browser tabs after the move.", + "browserLoginsNotCarried": "Browser sign-ins won’t carry over to this host. Sign in again in its browser tabs after the move." + }, + "cancel": "Cancel", + "progress": { + "bytes": "{{sent}} of {{total}}", + "tooLate": "Too late to cancel: the host is already switching over. Keep Orca open until it finishes.", + "switching": "The switch cannot be cancelled. Keep Orca open until it finishes.", + "readOnly": "These projects are read-only while they move. You can cancel until the switch starts.", + "cancelUntilSwitch": "You can cancel until the switch starts.", + "closeKeepsGoing": "Closing this dialog does not stop the move; it opens again when the move ends.", + "cancelling": "Cancelling…", + "cancel": "Cancel move" + }, + "result": { + "movedTitle": "Moved to the {{distro}} host", + "resetTitle": "Nothing was moved", + "waitingTitle": "Waiting for the {{distro}} host", + "earlierMoveTitle": "An earlier move finished first", + "refusedTitle": "Projects not moved", + "reloadCheckpointRefused": "Orca could not back up unsaved files, so the window did not reload. Close this dialog, save or close those files, then use Reload now in the notice that stays open.", + "reloadVetoed": "Something kept the window from reloading. Close this dialog, save your work, then use Reload now in the notice that stays open.", + "reloadFailed": "The window did not reload. Try again.", + "moved": "Reload this window to see the projects under the {{distro}} host. Orca backs up unsaved files before it reloads.", + "automationsPendingOne": "One automation is off on the host for now. Orca keeps asking the host to turn it back on.", + "automationsPendingMany": "{{n}} automations are off on the host for now. Orca keeps asking the host to turn them back on.", + "undoHint": "Changed your mind? After the reload, the sidebar lists these projects as “Moved to {{distro}} host”. Choose “Use on this computer again” there to bring them back as they were before the move.", + "reset": "The move stopped and everything was put back. The projects work on this computer as before; paused terminals start again when you open them.", + "resetReason": "Why it stopped: {{detail}}", + "waiting": "The move may have reached the {{distro}} host, but the host is not answering. These projects stay read-only here until it does. Connect the host in Settings, then open this dialog again and start a move: Orca finishes or undoes this one first.", + "reloading": "Reloading…", + "reload": "Reload now", + "close": "Close", + "review": "Back to projects", + "browserLoginsHostUnknown": "Browser logins were not copied, because Orca could not identify the host’s browser profile. Sign in again in the host’s browser tabs.", + "browserLoginsConflict": "Browser logins were not copied, because the host’s browser profile is already in use. Sign in again in the host’s browser tabs.", + "browserLoginsNotCopied": "Browser logins were not copied to the host. Sign in again in the host’s browser tabs." + }, + "runtime": { + "label": "Project runtime", + "description": "This project runs in {{distro}} through this computer. Move it to the {{distro}} host to run it there.", + "move": "Move project" + }, + "unfinished": { + "one": "One automation moved to the {{distro}} host is still off. Orca keeps asking the host to turn it back on.", + "many": "{{n}} automations moved to the {{distro}} host are still off. Orca keeps asking the host to turn them back on." + }, + "refusal": { + "previewFailed": "Orca could not check these projects. Try again.", + "startFailed": "Orca lost contact with the move. Open this dialog again to see where it stands.", + "unavailable": "Moving projects to a WSL host is not available in this window.", + "alreadyRunning": "A move into {{distro}} is already running. Wait for it to finish, then try again.", + "undoRunning": "A project is coming back from {{distro}}. Try again once that finishes.", + "alreadyInFlightPreview": "A move of {{distro}} is still finishing. Starting this move first finishes or undoes it where Orca can.", + "alreadyInFlight": "A move of {{distro}} is still finishing, so this one did not start. Keep the {{distro}} host connected and try again later.", + "nothingNew": "These projects are already on the {{distro}} host.", + "destinationChanged": "Earlier projects from {{distro}} moved to a different WSL host. Connect that host to move more.", + "hostUnavailable": "The {{distro}} host is not connected. Connect it in Settings, then try again.", + "hostUpdateRequired": "The {{distro}} host runs an older version of Orca. Update it in Settings, then try again.", + "terminalsBlocked": "Some terminals, agents or automations in these projects are busy. Nothing was moved.", + "exportIncomplete": "Some saved state in these projects cannot move yet, so nothing was moved:", + "exportIncompletePreview": "Some saved state in these projects can't move yet:", + "tooLarge": "These projects have too much saved state to move in one step. Move fewer projects at a time.", + "pauseFailed": "Orca could not pause the terminals in these projects, so nothing was moved. Paused terminals start again when you open them. Try again.", + "scopeChanged": "A project changed while the move was getting ready, so nothing was moved. Check the projects and try again.", + "cancelled": "Move cancelled. Nothing was moved.", + "finishedEarlierMove": "Orca first finished an earlier move into {{distro}}. Reload the window, then start this move again." + }, + "step": { + "preparing": "Preparing", + "pausingTerminals": "Pausing terminals", + "copying": "Copying", + "switching": "Switching", + "finishing": "Finishing", + "done": "Done" + }, + "blocker": { + "agentWorkingOne": "An agent is working or waiting for an answer", + "agentWorkingMany": "{{n}} agents are working or waiting for an answer", + "processRunningOne": "A terminal is running a program", + "processRunningMany": "{{n}} terminals are running a program", + "agentNotResumableOne": "An agent cannot be resumed after the move", + "agentNotResumableMany": "{{n}} agents cannot be resumed after the move", + "unverifiableOne": "Orca cannot check a terminal right now", + "unverifiableMany": "Orca cannot check {{n}} terminals right now", + "automationRunningOne": "An automation run is active", + "automationRunningMany": "{{n}} automation runs are active", + "dispatchRunningOne": "An agent task is in progress", + "dispatchRunningMany": "{{n}} agent tasks are in progress", + "scrollbackTooLargeOne": "A terminal has too much output history to move", + "scrollbackTooLargeMany": "{{n}} terminals have too much output history to move" + }, + "blockerHint": { + "agentWorking": "Let it finish, or stop it in its terminal, then check again.", + "processRunning": "Stop the program (for example a dev server or editor), then check again.", + "agentNotResumable": "Exit the agent in its terminal, then check again.", + "unverifiable": "Wait a moment, then check again. Nothing is stopped to make the move happen.", + "wait": "Wait for it to finish, then check again.", + "scrollbackTooLarge": "Clear the terminal output in those terminals, then check again." + }, + "scopeRefused": { + "windowsDrive": "Its folder is on a Windows drive, so it stays on this computer.", + "mixedLocations": "Some of its folders are outside this distro, so it stays on this computer.", + "notLocal": "It already runs on another host.", + "other": "It cannot move." + }, + "reloadToast": { + "title": "Reload to finish the move" + }, + "orchestrator": { + "showTerminal": "Show terminal", + "moveAgain": "Move again", + "checkAgain": "Check again", + "deferred": "Finishing your move to the {{distro}} host: some terminals are still busy.", + "stuck": "An earlier move to the {{distro}} host hasn't finished settling.", + "declined": "Moving is paused because you brought these projects back to this computer.", + "doneToast": "Projects moved to the {{distro}} host", + "terminalGone": "That terminal isn't open in this window any more. Check again to refresh.", + "blocker": "{{title}}. {{hint}}", + "paused": "Moving projects to the {{distro}} host is paused: {{reason}}.", + "pausedReason": { + "exportIncomplete": "some saved state can't be carried over yet", + "manifestTooLarge": "there is more saved state than one move can carry", + "hostUpdate": "the host needs an update first", + "attemptsExhausted": "it didn't complete after several tries" + }, + "finishPending": "An earlier move to the {{distro}} host is done there. Orca finishes it here when it restarts, or now with Check again." + } + }, "onboarding": { "language": { "back": "Languages", @@ -20243,7 +20929,8 @@ "email": "Know your email address", "allSites": "Read and change all your data on all websites", "someSites": "Read and change your data on {{hosts}}", - "manySites": "Read and change your data on {{hosts}} and {{count}} other sites" + "manyOtherSites_one": "Read and change your data on {{hosts}} and {{count}} other site", + "manyOtherSites_other": "Read and change your data on {{hosts}} and {{count}} other sites" }, "install": { "title": "Add {{name}}?", @@ -20494,5 +21181,185 @@ }, "startupFailure": { "title": "Orca could not start" + }, + "runtime": { + "health": { + "mixed": "Mixed", + "local": "Local", + "available": "Connected", + "connecting": "Connecting", + "disconnected": "Disconnected", + "error": "Needs attention", + "repair": "Re-pair needed", + "update": "Update needed" + }, + "compat": { + "compatible": "Runtime client and server are compatible.", + "clientTooOld": "This Orca client is too old for the selected server. Update Orca on this machine. Client protocol {{clientProtocol}}, server requires client protocol {{requiredProtocol}}.", + "serverTooOld": "The selected Orca server is too old for this client. Update Orca on the server. Server protocol {{serverProtocol}}, client requires server protocol {{requiredProtocol}}." + } + }, + "native": { + "about": { + "gpu": { + "safeMode": "Disabled (Safe Graphics Mode)", + "unknownStatus": "Status unavailable", + "enabled": "Enabled", + "software": "Software rendering", + "disabled": "Disabled", + "unavailable": "Unavailable", + "unknown": "Unknown ({{status}})", + "summary": "GPU acceleration: {{status}}" + } + }, + "dialog": { + "spaceTitle": "Orca Space Beta", + "dashboardTitle": "Orca Agent Dashboard", + "importCookies": "Import Cookies", + "cookieFiles": "Cookie Files", + "allFiles": "All Files", + "importPetBundle": "Pick a .codex-pet bundle", + "pickPet": "Pick pet", + "petImage": "Pet image", + "importWarpTheme": "Import Warp Theme", + "warpThemeYaml": "Warp theme YAML", + "importWarpFolder": "Import Warp Theme Folder", + "images": "Images", + "repoIconImages": "Repo icon images", + "audio": "Audio" + } + }, + "taskProviders": { + "linear": { + "updateAccess": "Update access", + "addAccess": "Add Linear access", + "listLabel": "Linear list", + "fetchMore": "Fetch more", + "projectsLoadFailed": "Failed to load projects.", + "projectNotFound": "Project was not found.", + "projectLoadFailed": "Failed to load project.", + "projectIssuesLoadFailed": "Failed to load project issues.", + "viewsLoadFailed": "Failed to load views.", + "viewContentsLoadFailed": "Failed to load view contents.", + "issuesLoadFailed": "Failed to load Linear issues.", + "connectionFailed": "Connection failed", + "apiKeyHint": "Paste a Personal API key for the Linear workspace you want Orca to use. If that workspace is already connected, Orca replaces its stored key.", + "remoteKeyStorage": "This key is stored by the active remote runtime.", + "localKeyStorage": "Local runtime keys are stored on this device using Electron encrypted storage when available.", + "commentsLoadFailed": "Failed to load comments.", + "updateWorkspaceAccess": "Update Linear access for {{workspace}}", + "workspaceApiKeyHint": "Paste a Personal API key for {{workspace}}. If this workspace is already connected, Orca replaces its stored key.", + "connect": "Connect", + "titleUpdateFailed": "Failed to update title", + "descriptionUpdateFailed": "Failed to update description", + "truncated": { + "views_one": "Showing the first {{count}} view. Search or open Linear for the full set.", + "views_other": "Showing the first {{count}} views. Search or open Linear for the full set.", + "projects_one": "Showing the first {{count}} project. Search or open Linear for the full set.", + "projects_other": "Showing the first {{count}} projects. Search or open Linear for the full set.", + "projectIssues_one": "Showing the first {{count}} project issue. Search or open Linear for the full set.", + "projectIssues_other": "Showing the first {{count}} project issues. Search or open Linear for the full set.", + "viewIssues_one": "Showing the first {{count}} view issue. Search or open Linear for the full set.", + "viewIssues_other": "Showing the first {{count}} view issues. Search or open Linear for the full set.", + "issues_one": "Showing the first {{count}} issue. Search or open Linear for the full set.", + "issues_other": "Showing the first {{count}} issues. Search or open Linear for the full set." + } + }, + "jira": { + "remoteTokenStorage": "Your token is sent to the selected remote runtime and stored there with runtime-supported encryption.", + "localTokenStorage": "Your token is stored locally and encrypted when local runtime storage supports it.", + "connectionFailed": "Connection failed" + }, + "errors": { + "linear": { + "notConnected": "Not connected to Linear", + "createFailed": "Linear create failed", + "createdButUnavailable": "Issue was created but could not be retrieved", + "updateFailed": "Linear update failed", + "commentFailed": "Failed to create comment", + "projectCreateFailed": "Linear project create failed", + "noApiKey": "No API key stored.", + "workspaceAuthExpired": "Linear authentication expired for this workspace.", + "projectNameRequired": "Project name is required", + "projectIdRequired": "Project ID is required", + "projectNotFound": "Project was not found", + "viewIdRequired": "Custom view ID is required", + "viewHasNoIssues": "Custom view does not contain issues", + "viewHasNoProjects": "Custom view does not contain projects" + }, + "jira": { + "notConnected": "Not connected to Jira.", + "titleRequired": "Title is required.", + "labelsConflict": "Pass labels or labelOperations, not both.", + "createFailed": "Failed to create issue.", + "updateFailed": "Failed to update issue.", + "commentFailed": "Failed to add comment.", + "credentialsRequired": "Site URL, email, and API token are required.", + "projectRequired": "Project is required.", + "issueTypeRequired": "Issue type is required.", + "issueKeyRequired": "Issue key is required.", + "updatesRequired": "Updates object is required.", + "commentBodyRequired": "Comment body is required.", + "invalidSiteUrl": "Enter a valid Jira site URL.", + "passwordRequired": "Password is required.", + "personalTokenRequired": "Personal access token is required.", + "apiTokenRequired": "API token is required.", + "connectionFailed": "Connection failed.", + "invalidSiteIdentity": "Enter an HTTP or HTTPS Jira site URL without credentials.", + "missingProjectIdentity": "Jira returned a project without an ID or key.", + "invalidIssuePage": "Jira returned an invalid issue page.", + "incompleteIssuePage": "Jira returned an incomplete issue page.", + "repeatedIssueToken": "Jira returned an invalid or repeated issue page token.", + "issueSearchLimit": "Jira issue search exceeded the page limit. Select a project with JQL instead.", + "invalidProjectPage": "Jira returned an invalid project page.", + "incompleteProjectPage": "Jira returned an incomplete project page.", + "projectListLimit": "Jira project list exceeded the page limit. Select a project with JQL instead.", + "invalidCloudId": "The site did not report a valid Atlassian cloud ID." + } + } + }, + "workspaceOptions": { + "activeFilterCount_one": "{{count}} filter", + "activeFilterCount_other": "{{count}} filters" + }, + "editorConflicts": { + "kind": { + "addedByUs": "Added by us", + "bothAdded": "Both added", + "deletedByUs": "Deleted by us", + "addedByThem": "Added by them", + "bothDeleted": "Both deleted", + "bothModified": "Both modified", + "deletedByThem": "Deleted by them" + }, + "resolvedBanner": "Conflict resolved locally · {{kind}}", + "hint": { + "addedByUs": "Review whether to keep the added file", + "bothModified": "Resolve the conflict markers", + "addedByThem": "Review the added file before keeping it", + "bothDeleted": "Resolve in Git or restore one side before editing", + "deletedByThem": "Decide whether to keep the file or accept deletion", + "deletedByUs": "Decide whether to restore the file", + "bothAdded": "Choose which version to keep, or combine them" + }, + "renamedFrom": "Renamed from {{path}}", + "snapshotCapturedAt": "Snapshot captured at {{time}}.", + "unresolvedBanner": "Unresolved conflict · {{kind}}" + }, + "stats": { + "usageBreakdown": { + "turns_one": "{{count}} turn", + "events_one": "{{count}} event", + "sessions_one": "{{count}} session", + "events_other": "{{count}} events", + "sessions_other": "{{count}} sessions", + "turns_other": "{{count}} turns" + } + }, + "github": { + "viewed": { + "markFile": "Mark {{path}} as viewed", + "unmarkFile": "Unmark {{path}} as viewed" + } } } diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 21fbe40c1563..7cc7d58cdb48 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -110,11 +110,15 @@ "system": "Sistema", "english": "Inglés", "chinese": "中文(简体)", + "chineseTraditional": "繁體中文(台灣)", "korean": "한국어", "japanese": "日本語", "spanish": "Español", "french": "Français", - "portuguese": "Português (Brasil)" + "portuguese": "Português (Brasil)", + "russian": "Русский", + "turkish": "Türkçe", + "german": "Deutsch" }, "statusBar": { "claudeToggleDescription": "Muestra el consumo de tokens y el costo de Claude para el espacio de trabajo activo.", @@ -346,7 +350,8 @@ "permissionOverrideMore": "y {{count}} más", "permissionOverrideMore_one": "y {{count}} más", "permissionOverrideMore_other": "y {{count}} más", - "permissionOverridesUse": "Usar {{mode}}" + "permissionOverridesUse": "Usar {{mode}}", + "approveForMe": "aprobar por mí" }, "followSymlinkedDirectoriesKeywords": { "symlink": "enlace simbólico", @@ -377,6 +382,34 @@ "actionPermissions": { "sameAsAgent": "Igual que {{agent}}" } + }, + "ssh": { + "status": { + "disconnected": "Desconectado", + "connecting": "Conectando…", + "auth-failed": "Error de autenticación", + "connected": "Conectado", + "reconnection-failed": "Error de reconexión", + "deploying-relay": "Desplegando relay…", + "reconnecting": "Reconectando…" + } + }, + "mcp": { + "workspace": "Espacio de trabajo", + "inspectFailed": "No se pudo inspeccionar {{directory}}.", + "unreadable": "No se puede leer", + "notFound": "No se encontró", + "invalidJson": "JSON no válido", + "noServers": "Sin servidores", + "httpServer": "Servidor HTTP", + "stdioServer": "Servidor stdio", + "invalidServer": "Servidor no válido", + "serverCount_one": "{{count}} servidor", + "serverCount_other": "{{count}} servidores", + "claudeWorkspace": "Espacio de trabajo de Claude" + }, + "shortcuts": { + "parseFailed": "No se pudo interpretar el atajo." } }, "menu": { @@ -1480,9 +1513,6 @@ "3fdf777817": "Abrir en GitHub", "c43fe79ee0": "Copiar enlace de GitHub", "0caac1a18f": "Iniciar espacio de trabajo desde PR", - "8223320f8d": "actualizado", - "10ef1afb8e": "· actualizado", - "55962099bc": "abrió este issue", "0ab4664a8b": "Iniciar espacio de trabajo desde issue", "36182aa57f": "Iniciar nuevo espacio de trabajo", "fe6ff12dc2": "Más acciones del espacio de trabajo de issue", @@ -1555,8 +1585,6 @@ "52b20b56f7": "Descripción", "4d555d3796": "Editar descripción", "9df4e74bdf": "Guardar", - "0ae387d8ca": "por", - "228e2f59d3": "Resuelto", "a154ec5224": "Abrir comentario en GitHub", "bca8eb39ac": "Responder al comentario", "68cb993d61": "resuelto", @@ -1572,13 +1600,11 @@ "d43736d09c": "Controles de contexto de código", "bd7be7b1fd": "comentario L", "db61d76cd5": "Cargando contexto de código...", - "f2d02cdf8c": "archivos vistos", "1257d1435d": "Mostrar árbol de archivos", "a341343303": "Se agregó el comentario de revisión.", "d1fa2cf888": "No se puede comentar sin el SHA del head del PR.", "829674460a": "El diff no está disponible porque faltan los SHA de commits del PR.", "af924014f8": "Visto", - "2d89a38d9d": "Cambiar estado de visto de {{value1}} ({{value0}})", "70e84e3d0b": "No hay revisores que coincidan.", "1ffce94a8b": "Todos los demás", "c2b21818e1": "Sugerencias", @@ -1613,8 +1639,6 @@ "ec5c4b3ab2": "Reabrir PR", "21860b58d0": "Cerrar pull request", "5932578f51": "El merge requiere un repositorio local registrado", - "e2bf3e41a9": "comentario", - "28d0d3374f": "hilo", "080d071d48": "Responder a @{{value0}}", "86f809e2ce": "Responder en este hilo de revisión", "136542c9ba": ":L{{value0}}", @@ -1644,7 +1668,9 @@ "from": "de", "to": "a", "activity": "Actividad", - "noActivity": "Sin actividad aún." + "noActivity": "Sin actividad aún.", + "pullRequestReference": "PR #{{number}}", + "issueReference": "issue #{{number}}" }, "checkActionRequiredHint": "Requiere una acción manual en GitHub (por ejemplo, aprobar la ejecución) para desbloquear la fusión.", "e15a8b77ef": "No hay detalles en línea disponibles para esta verificación.", @@ -1658,8 +1684,15 @@ "09d67a0f9b": "No se pudo cerrar la PR", "88809e79db": "No se pudo reabrir la PR", "00f55cc17b": "El acceso al repositorio no está disponible para esta PR.", - "reactionCountSingular": "{{count}} {{reaction}} reacción", - "reactionCountPlural": "{{count}} {{reaction}} reacciones" + "reactionCount_one": "{{count}} reacción de {{reaction}}", + "reactionCount_other": "{{count}} reacciones de {{reaction}}", + "filesViewed_one": "{{viewed}} / {{count}} archivo visto", + "filesViewed_other": "{{viewed}} / {{count}} archivos vistos", + "updatedRelativeTime": "actualizado {{time}}", + "authorOpenedThisIssue": " abrió este issue", + "middotUpdatedRelativeTime": "· actualizado {{time}}", + "resolvedThreadBy": "Hilo resuelto de {{author}}", + "resolvedCommentBy": "Comentario resuelto de {{author}}" }, "GitLabItemDialog": { "65e784c1f1": "Reabrir", @@ -1715,14 +1748,15 @@ "f23ea85341": "resuelto", "6de8ce0cc6": "{{value0}} obligatorias", "22511537d2": "Aprobado", - "00f3bab87b": " de {{value0}} obligatorias", "3a051b8ade": "Work item", "32f8bef818": "Sin output de log.", "4168eb2c51": "Resolver", "commentTooLarge": "El comentario es demasiado grande para enviarlo de forma segura.", "gitlabActionFailed": "La acción de GitLab falló.", - "approvalsRemainingSingular": "{{count}} aprobación restante", - "approvalsRemainingPlural": "{{count}} aprobaciones restantes" + "approvalsRemainingOfRequired_one": "Falta {{count}} aprobación de las {{required}} requeridas", + "approvalsRemainingOfRequired_other": "Faltan {{count}} aprobaciones de las {{required}} requeridas", + "approvalsRemaining_one": "{{count}} aprobación restante", + "approvalsRemaining_other": "{{count}} aprobaciones restantes" }, "JiraIssueWorkspace": { "b0b92666c9": "Comentar", @@ -1747,14 +1781,11 @@ "69da9a208c": "Abrir en Jira", "fa132c8aed": "No se pudo agregar el comentario.", "ea21952aa3": "No se pudo actualizar el issue de Jira.", - "6c41a9bcea": "No se pudo copiar {{value0}}", - "2ff69a3545": "{{value0}} copiado", "666cfdd835": "Desconocido", "ef21405c6d": "Issue de Jira", "commentTooLarge": "El comentario es demasiado grande para enviarlo de forma segura." }, "Landing": { - "76a95f7f47": "Crear", "f9eaa9e12d": "Agregar proyecto", "6ca6ff404e": "ORCA", "520304a067": "logotipo de Orca", @@ -1770,7 +1801,12 @@ "0d0ace8861": "Dar estrella en GitHub", "ec43b38ba7": "Con estrella en GitHub", "157bb5ecbb": "Abrir GitHub", - "preflightDismiss": "Descartar" + "preflightDismiss": "Descartar", + "moveUpWorkspace": "Seleccionar espacio de trabajo anterior", + "moveDownWorkspace": "Seleccionar espacio de trabajo siguiente", + "installGit": "Instalar Git", + "installGitHubCli": "Instalar GitHub CLI", + "learnMore": "Más información" }, "LinearIssueMarkdownDescriptionEditor": { "d9c47069ef": "Markdown", @@ -1795,14 +1831,12 @@ "LinearIssueTextEditor": { "947ba2d6f4": "guardar", "04d73b72dc": "Título del issue", - "e8ff595db3": "No se pudo actualizar {{value0}}", "1e08a1ec80": "El título es obligatorio" }, "LinearIssueWorkspace": { "ad5dec37b7": "Previsualiza, edita y empieza a trabajar desde el issue seleccionado.", "c23e79e5c0": "Acciones", "b0eac92d85": "Reintentar", - "fabbd3f974": "actualizó el issue ·", "543970c87a": "Actividad", "df4c86ed12": "Cerrar", "7a4997d8bb": "Cerrar vista previa del issue de Linear", @@ -1826,11 +1860,8 @@ "b25e453c9d": "No se pudo crear el sub-issue", "aeed19d003": "Se creó {{value0}}", "9a1317cdd3": "No se pudo cargar el sub-issue", - "9bcbaa2737": "No se pudo copiar {{value0}}", - "7835483c43": "{{value0}} copiado", "61f424f8ca": "Issue de Linear", "ca8778c124": "Desconocido", - "8a33c85e9c": "Alguien", "65239a714b": "Linear", "76ffd3c937": "Busca un proyecto para agregar.", "c11b4e3cc2": "No se encontraron proyectos.", @@ -1841,7 +1872,10 @@ "moreWorkspaceActions": "Más acciones del espacio de trabajo del issue", "startNewWorkspace": "Iniciar un espacio de trabajo nuevo", "workspaceSection": "Espacio de trabajo", - "noWorkspaceYet": "Ninguno todavía" + "noWorkspaceYet": "Ninguno todavía", + "issueDescriptionLabel": "Descripción del issue", + "namedUserUpdatedIssue": "{{name}} actualizó el issue · {{time}}", + "someoneUpdatedIssue": "Alguien actualizó el issue · {{time}}" }, "LinearItemDrawer": { "04008e6c46": "Iniciar espacio de trabajo desde el issue", @@ -1877,7 +1911,9 @@ "openAttachedWorkspace": "Abrir el espacio de trabajo vinculado al issue", "openWorkspace": "Abrir espacio de trabajo", "moreWorkspaceActions": "Más acciones del espacio de trabajo del issue", - "startNewWorkspace": "Iniciar un espacio de trabajo nuevo" + "startNewWorkspace": "Iniciar un espacio de trabajo nuevo", + "setEstimate": "Establecer estimación", + "estimateValue": "Estimación {{estimate}}" }, "NewWorkspaceComposerCard": { "cbb47ee0dc": "Solo disponible para proyectos Git locales.", @@ -1939,7 +1975,22 @@ "defaultBranchUpdateFailed": "No se pudo actualizar la rama predeterminada del proyecto. Inténtalo de nuevo.", "setLocation": "Establecer ubicación del proyecto", "setLocationOnHost": "Establecer ubicación del proyecto en {{host}}", - "setLocationTooltip": "Elige una carpeta o clona este proyecto en {{host}}." + "setLocationTooltip": "Elige una carpeta o clona este proyecto en {{host}}.", + "connect": "Conectar", + "reconnect": "Reconectar", + "setupConfigDefaultTabs": "Comandos de pestañas predeterminadas", + "setupConfigSetupAndDefaultTabs": "Configuración y comandos de pestañas predeterminadas", + "setupConfigSetupScript": "Script de configuración", + "runDefaultTabCommands": "Ejecutar comandos de pestañas predeterminadas", + "runSetupAndDefaultTabCommands": "Ejecutar configuración y comandos de pestañas predeterminadas", + "runSetupCommand": "Ejecutar comando de configuración", + "askRunDefaultTabCommands": "¿Ejecutar ahora los comandos de pestañas predeterminadas?", + "askRunSetupAndDefaultTabCommands": "¿Ejecutar ahora la configuración y los comandos de pestañas predeterminadas?", + "askRunSetup": "¿Ejecutar la configuración ahora?", + "runSetupNow": "Ejecutar configuración ahora", + "runCommandsNow": "Ejecutar comandos ahora", + "skipForNow": "Omitir por ahora", + "skipCommands": "Omitir comandos" }, "NewWorkspaceComposerModal": { "createWorktree": "Crear worktree", @@ -2029,9 +2080,6 @@ "778683ec84": "Descripción", "da9aaa8bcf": "Editar descripción", "4a337ac05f": "Guardar", - "169a93b29a": "actualizado", - "3c891789f6": "por", - "f4fe47c2bb": "Resuelto", "0ac19bb52e": "Abrir comentario en GitHub", "d6c6679de7": "Responder al comentario", "76b2a0ac5b": "resuelto", @@ -2039,7 +2087,6 @@ "6885c619e7": "No se puede responder sin una ruta al repositorio.", "d94810f652": "No se pudo actualizar la descripción.", "9b4190dc98": "Descripción actualizada.", - "89e80af1c7": "archivos vistos", "319cf2d54b": "Mostrar árbol de archivos", "eff839f438": "Se agregó el comentario de revisión.", "d8c3ba91c4": "No se puede comentar sin el SHA del head del PR.", @@ -2077,8 +2124,6 @@ "9d5425918e": "Reabrir PR", "96d013ed28": "Cerrar pull request", "eca289e593": "El merge requiere un repositorio local registrado", - "e01e34f5fa": "comentario", - "345b68254c": "hilo", "31a7b202f2": "Responder a @{{value0}}", "408e634fbb": "Responder en este hilo de revisión", "34b9f7c264": ":L{{value0}}", @@ -2104,7 +2149,19 @@ "diffLoadTimedOut": "Se agotó el tiempo de espera al cargar esta diferencia.", "6b1d5ee3e4": "No hay detalles en línea disponibles para esta verificación.", "e04c027d98": "No se pudieron cargar los detalles de la verificación.", - "5df7c41d2a": "Reintentar" + "5df7c41d2a": "Reintentar", + "filesViewed_one": "{{viewed}} / {{count}} archivo visto", + "filesViewed_other": "{{viewed}} / {{count}} archivos vistos", + "updatedRelativeTime": "actualizado {{time}}", + "resolvedThreadBy": "Hilo resuelto de {{author}}", + "resolvedCommentBy": "Comentario resuelto de {{author}}", + "mentionSource": { + "prAuthor": "Autor del PR", + "issueAuthor": "Autor del issue", + "commenter": "Comentarista", + "participant": "Participante", + "teamMember": "Miembro del equipo" + } }, "QuickOpen": { "1dbd3f59ff": "Mover", @@ -2118,13 +2175,12 @@ "9e97f08d0f": "Buscar un archivo para abrir", "ec31e058f7": "Ir al archivo", "73b44e7bde": "Copiar comando de instalación", - "1cf8561ab4": "en el remoto para habilitar un listado rápido y compatible con gitignore:", - "5d80dc39bb": "ripgrep", - "2ca749c15d": "Instalar", - "4725b0e931": "El escaneo de apertura rápida es demasiado grande (", - "b227d88520": "{{value0}} archivos encontrados", "995be8ea22": "Copiar", - "cf144856dc": "Copiado" + "cf144856dc": "Copiado", + "filesFound_one": "{{count}} archivo encontrado", + "filesFound_other": "{{count}} archivos encontrados", + "hostCouldNotOpenPath": "El host no pudo abrir esta ruta de archivo.", + "chooseFileNotDirectory": "Elige un archivo en lugar de un directorio." }, "SelectedTextCopyMenu": { "9b40d7b018": "Copiar" @@ -2142,7 +2198,6 @@ "TaskPage": { "ff69a30681": "Cancelar", "8ff6fdc368": "Creando…", - "fc0d8a1fa4": "para enviar.", "919a20dd5b": "Ingresa {{value0}}", "56cdb413a2": "Valores separados por comas", "1f0fce91e3": "Selecciona {{value0}}", @@ -2190,14 +2245,9 @@ "bdebffcbfe": "Crea un proyecto Linear para el equipo seleccionado.", "1361275ec3": "Nuevo proyecto Linear", "7f3f7b4c18": "Descripción (opcional, markdown)", - "9f2b4c03a6": "Creando en", "d3d0998b7d": "Nuevo issue de GitHub", - "d1e243795c": "issues", - "be8cf68d9f": "ver issues", - "67662ade50": "issues del proyecto", "6244a02f46": "Abrir en Linear", "606a85c774": "Abierto", - "5e8061b088": "Iniciar espacio de trabajo desde {{value0}} {{value1}}", "592a55611b": "Prueba a seleccionar más equipos o actualizar; los filtros de equipo se aplican al conjunto de issues obtenido actualmente.", "618107fab3": "No hay issues obtenidos que coincidan con los equipos seleccionados.", "903c7af49f": "No se encontraron issues de Linear", @@ -2206,7 +2256,6 @@ "f362667d55": "Actualizado", "b1eaa18ace": "Issue", "37e7ee311e": "Clave", - "b7bae28b6a": "mostrado", "a26a48252e": "Propiedades de visualización", "5d2d835467": "Orden", "5659da12fc": "Agrupación", @@ -2214,11 +2263,9 @@ "af377b13b1": "Vista {{value0}}", "d47248df4d": "Modo de vista de Linear", "f397d513e3": "Atrás", - "b39fe6511d": "proyectos", "8675cd6188": "Linear", "733b8f2421": "Linear / Vistas", "bc06ed0fb0": "Volver a vistas", - "3cb855080f": "vistas", "b4e10f096e": "Propietario", "a04fe7ba73": "Visibilidad", "0aa8525950": "Modelo", @@ -2248,8 +2295,6 @@ "054bf695cc": "Borrador", "5b6b2af943": "Reintentando…", "0c0de0fc0e": "No se pudieron cargar los issues de", - "d1766fd62d": "los proyectos no pudieron cargarse", - "7762f4b03a": "de", "443f7dd928": "Merge", "a7396b05c6": "Checks", "f6fa3c97d0": "Revisores", @@ -2431,10 +2476,41 @@ "jiraColumnOriginalEstimate": "Estimación", "jiraColumnRemainingEstimate": "Restante", "jiraBoardEmptyColumn": "Sin incidencias", - "labelCountPlural": "{{count}} etiquetas", - "labelCountSingular": "{{count}} etiqueta", - "memberCountPlural": "{{count}} miembros", - "memberCountSingular": "{{count}} miembro" + "backToPullRequests": "Pull requests", + "backToGitHubList": "Lista de GitHub", + "noGitHubRepositoryContext": "No hay contexto de repositorio de GitHub disponible para este issue.", + "filingInTarget": "Se creará en {{target}}", + "filingInThisRepository": "Se creará en este repositorio", + "shortcutToSubmit": "{{shortcut}} para enviar.", + "projectsFailedToLoad_one": "Error al cargar proyectos: {{failed}} de {{count}}", + "projectsFailedToLoad_other": "Error al cargar proyectos: {{failed}} de {{count}}", + "draftPullRequestNumber": "Pull request en borrador #{{number}}", + "pullRequestNumber": "Pull request #{{number}}", + "issueNumber": "Issue #{{number}}", + "loadGitHubWorkFailed": "No se pudo cargar el trabajo de GitHub.", + "gitlabViewIssues": "Issues", + "gitlabViewMrs": "MRs", + "gitlabViewTodos": "Mis tareas pendientes", + "startWorkspaceFromMr": "Iniciar espacio de trabajo desde MR {{number}}", + "startWorkspaceFromIssue": "Iniciar espacio de trabajo desde issue {{number}}", + "shownCount_one": "{{count}} mostrado", + "shownCount_other": "{{count}} mostrados", + "linearProjectPlaceholder": "Proyecto", + "labelCount_one": "{{count}} etiqueta", + "labelCount_other": "{{count}} etiquetas", + "memberCount_one": "{{count}} miembro", + "memberCount_other": "{{count}} miembros", + "groupUnassigned": "Sin asignar", + "linearProjectContext": "Proyecto: {{name}}", + "linearViewContext": "Vista: {{name}}", + "changedFileCount_one": "{{count}} archivo", + "changedFileCount_other": "{{count}} archivos", + "resumeRestoration": { + "linearProjectNotFound": "No se encontró el proyecto de Linear guardado.", + "linearProjectRestoreFailed": "No se pudo restaurar el proyecto de Linear guardado.", + "linearViewNotFound": "No se encontró la vista de Linear guardada.", + "linearViewRestoreFailed": "No se pudo restaurar la vista de Linear guardada." + } }, "Terminal": { "73768427cf": "Cerrar", @@ -2509,7 +2585,8 @@ "b1e390250d": "No se pudo completar el cambio de compilación local.", "d29740d175": "La compilación seleccionada no pudo ser usada.", "37d45c9ec1": "Elegir otra compilación", - "7f1a4c9e02": "Tu gestor de paquetes del sistema instaló Orca, así que actualízalo desde allí; Orca no puede instalar esta versión por sí mismo." + "7f1a4c9e02": "Tu gestor de paquetes del sistema instaló Orca, así que actualízalo desde allí; Orca no puede instalar esta versión por sí mismo.", + "compatibilityModeFailed": "No se pudo activar el modo de compatibilidad. {{message}}" }, "WorktreeJumpPalette": { "ac037cfac2": "Mover", @@ -2535,8 +2612,6 @@ "d7d496a451": "La página del navegador ya no existe", "50a1d11d5b": "Pestañas abiertas", "088d66d980": "Acciones y ajustes", - "20af998bff": "{{value0}} elementos disponibles{{value1}}", - "bb72c08e63": "{{value0}} resultados encontrados{{value1}}", "34c8fbb46e": "SSH remoto", "63c2be1914": "SSH desconectado", "95be6587d3": "Crear worktree \"{{value0}}\"", @@ -2553,7 +2628,12 @@ "27f10cca63": "Busca chats, terminales, espacios de trabajo, tareas, ajustes y acciones...", "2770f02910": "Busca chats, terminales, espacios de trabajo, tareas, ajustes y acciones", "recentChatsTerminalsHeader": "Chats y terminales recientes", - "lastActiveTime": "Última actividad hace {{value0}}" + "lastActiveTime": "Última actividad hace {{value0}}", + "resultsFound_one": "{{count}} resultado encontrado.", + "resultsFound_other": "{{count}} resultados encontrados.", + "itemsAvailable_one": "{{count}} elemento disponible.", + "itemsAvailable_other": "{{count}} elementos disponibles.", + "createActionAvailable": "Acción para crear un worktree disponible." }, "github": { "pr": { @@ -2594,7 +2674,8 @@ "8f6cb3772f": "Mergear este pull request automáticamente cuando se cumplan los requisitos", "def355ff38": "Se puede mergear", "e42c5bae67": "GitHub dice que este PR se puede mergear y los checks pasaron", - "cbf0113af6": "GitHub dice que este PR se puede mergear" + "cbf0113af6": "GitHub dice que este PR se puede mergear", + "autoMergeOn": "Fusión automática activada" } } }, @@ -2768,10 +2849,10 @@ "imageUrlTooLarge": "La URL de la imagen es demasiado grande." }, "IssueSourceSelector": { - "d6aeb2012b": "Mostrando issues de", "787c970baf": "Fuente de issues", "51d1608920": "Origen", - "30b2c9df91": "Upstream" + "30b2c9df91": "Upstream", + "showingIssuesFromRepo": "Mostrando issues de " }, "PRFilterDropdowns": { "979be3cf6b": "Asignado", @@ -2781,12 +2862,18 @@ "01f3f3d161": "Autor", "13b3ac0a84": "Estado", "79c54552f7": "Filtros", - "8a2ffbf9b3": "Quitar filtro {{value0}}" + "8a2ffbf9b3": "Quitar filtro {{value0}}", + "anyState": "Cualquiera", + "currentUser": "Usuario actual" }, "PRFilterPickers": { - "fdf387297c": "Limpiar (", "472c12ae03": "Limpiar", - "2d1f58eda6": "Usar" + "pressEnterToUseValue": "Pulsa Enter para usar el valor escrito.", + "useTypedValue": "Usar ", + "clearSelected": "Limpiar ({{count}})", + "loading": "Cargando…", + "searchTextTooLarge": "El texto de búsqueda es demasiado grande.", + "noMatches": "Sin coincidencias" }, "PRFilterSections": { "a00830d3f7": "Sin usuarios", @@ -2796,7 +2883,6 @@ "458ea3602b": "Sin autores", "b69fa4fa20": "Volver", "30ebb6ca44": "Limpiar todos los filtros", - "8177eda37e": "Filtrar", "ea3416d646": "Asignado", "b1d9fdea08": "Etiqueta", "24754c44ad": "Autor", @@ -2808,7 +2894,15 @@ "2b2f019091": "Cualquier estado", "0fd3249e2e": "Cerrado", "d78b60b5c2": "Abierto", - "bd162b7d5a": "Mergeado" + "bd162b7d5a": "Mergeado", + "draft": "Borrador", + "labelCount_one": "{{count}} etiqueta", + "labelCount_other": "{{count}} etiquetas", + "allStates": "Todos", + "filterPullRequests": "Filtrar pull requests", + "filterIssues": "Filtrar issues", + "filterOrTypeLogin": "Filtrar o escribir un nombre de usuario...", + "filterLabels": "Filtrar etiquetas..." }, "github": { "rate": { @@ -2819,15 +2913,14 @@ "d12d3d6f33": "Actualizar el presupuesto de la API de GitHub", "d5e5de9070": "Orca usa REST, Search y GraphQL a través de la CLI de GitHub.", "58c5f88216": "Presupuesto de la API de GitHub", - "6da1858354": "restantes · se reinicia en", - "f42790d150": "de", "01f7323e58": "API GraphQL", "1daf0f22a9": "GraphQL", "1f2f28a4de": "API de búsqueda", "c377a4f06a": "Buscar", "c392c749a6": "API REST", "bb227706a6": "REST", - "budget_scope_prefix": "Ámbito del presupuesto" + "budget_scope_prefix": "Ámbito del presupuesto", + "remainingOfLimitResetsIn": "Restante: {{remaining}} de {{limit}} · se reinicia en {{reset}}" } } } @@ -2835,7 +2928,29 @@ "CommentReactions": { "addReaction": "Añadir reacción", "removeNamedReaction": "Eliminar la reacción {{value0}}", - "addNamedReaction": "Añadir reacción {{value0}}" + "addNamedReaction": "Añadir reacción {{value0}}", + "reaction": { + "thumbsUp": "pulgar arriba", + "thumbsDown": "pulgar abajo", + "laugh": "risa", + "confused": "confusión", + "heart": "corazón", + "hooray": "hurra", + "rocket": "cohete", + "eyes": "ojos" + } + }, + "CommentCodeContext": { + "showSurroundingCodeBlock": "Mostrar el bloque de código circundante", + "showNearbyCodeContext": "Mostrar el contexto de código cercano" + }, + "prCheckPresentation": { + "successful": "Correcto", + "inProgress": "En curso" + }, + "IssueSourceIndicator": { + "issueFromRepo": "Issue de ", + "issuesFromRepo": "Issues de " } }, "linear": { @@ -2855,11 +2970,6 @@ } } }, - "priority": { - "icon": { - "c43d3e065b": "Prioridad:" - } - }, "project": { "view": { "surfaces": { @@ -2878,7 +2988,6 @@ "c8db98b73b": "Recursos", "bb1405eff8": "Hitos", "5d99315fb8": "Planificación", - "3ad562bdf4": "issues con alcance", "563501f191": "Progreso", "bb5664d456": "Sin descripción del proyecto.", "7b147907dc": "Linear", @@ -2889,8 +2998,6 @@ "7616c986c6": "Abrir issues de {{value0}}", "openInLinear": "Abrir {{value0}} en Linear", "93e1f6bfca": "Cargando", - "98730088a6": ". Busca o abre Linear para ver el conjunto completo.", - "06b887d622": "Mostrando primero", "linearLoginUnreadable": "No se puede leer el inicio de sesión guardado de Linear. Vuelve a conectarlo en Configuración.", "f2cc1e0ff6": "Linear / Proyectos", "906b5e4cb8": "Linear / Proyectos / {{value0}}", @@ -2905,7 +3012,10 @@ "df4bd63c1d": "No asignado", "30402d2c6e": "Intenta buscar o actualizar.", "a2f31c4cd6": "No se encontraron proyectos de Linear", - "c9b6e9f90d": "No se pueden cargar proyectos de Linear" + "c9b6e9f90d": "No se pueden cargar proyectos de Linear", + "scopedIssueCount_one": "{{count}} issue en el ámbito seleccionado", + "scopedIssueCount_other": "{{count}} issues en el ámbito seleccionado", + "backlog": "Backlog" } } }, @@ -2918,7 +3028,14 @@ "05baa5ae90": "Espacio de trabajo", "89f6580dbf": "Buscar equipos...", "b3488fad3c": "No se obtuvo ningún equipo. El acceso puede depender del scope de la clave, membresía en equipos privados, equipos archivados, permisos o un error al obtener datos.", - "405b33c378": "Ningún equipo obtenido coincide con tu búsqueda." + "405b33c378": "Ningún equipo obtenido coincide con tu búsqueda.", + "teamCount_one": "{{count}} equipo", + "teamCount_other": "{{count}} equipos" + } + }, + "priority": { + "icon": { + "priorityValue": "Prioridad: {{label}}" } } }, @@ -4413,10 +4530,7 @@ }, "UsageBreakdownSection": { "7765a4c3e1": "n/a", - "247c93ca92": "• precios inferidos", - "32176e1d44": "vueltas", - "79a69522a5": "eventos", - "02a046792e": "sesiones •" + "247c93ca92": "• precios inferidos" }, "GrokUsagePane": { "g8h9i0j1k2": "Uso de Grok", @@ -5911,7 +6025,9 @@ }, "sidebarHostOptions": { "3e102f111c": "Todos los hosts", - "visibleHostsCount": "{{value0}} hosts" + "hosts": "Hosts", + "visibleHosts_one": "{{count}} host", + "visibleHosts_other": "{{count}} hosts" }, "HostRemoveDialog": { "1a2b3c4d5e": "Se quitó {{value0}}", @@ -5926,12 +6042,10 @@ "oneWorkspace": "1 espacio de trabajo", "manyWorkspaces": "{{count}} espacios de trabajo", "hostHasWorkspacesDefault": "Elimina {{value0}} y sus credenciales de esta computadora. Sus {{value1}} permanecen en Orca — los archivos remotos no se tocan.", - "alsoDeleteRemote": "También eliminar estos {{value0}} en {{value1}}", "alsoForgetLocal": "También eliminar estos {{value0}} de Orca", "advanced": "Avanzado", - "alsoDeleteRemoteHint": "Elimina permanentemente los espacios de trabajo Git remotos y sus ramas. Esta acción no se puede deshacer.", "alsoForgetLocalHint": "Solo limpia de Orca. Los archivos, espacios de trabajo y ramas remotas permanecen intactos.", - "wslHostEndsTerminals": "Quita {{value0}} de Orca, cierra sus terminales abiertas y detiene el servidor de Orca en esa distro. Los archivos de la distro no se tocan." + "wslHostEndsTerminalsUnlessShared": "Quita {{value0}} de Orca. Salvo que otro Orca abierto en este equipo lo esté usando, también cierra sus terminales abiertas y detiene el servidor de Orca en esa distro. Los archivos de la distro no se tocan." }, "HostRenameDialog": { "1a2b3c4d5e": "Renombrar host", @@ -6085,14 +6199,9 @@ "sshImportSyncedSingular": "Se agregó {{count}} host a Orca." }, "ForgetSshWorkspaceDialog": { - "reconnectFailed": "Error de reconexión", - "forgetBody": "Elimina este espacio de trabajo solo de Orca. Los archivos, el worktree de Git y las ramas en {{host}} permanecen intactos.", - "title": "¿Eliminar “{{name}}”?", - "disconnectedBody": "El host SSH de este espacio de trabajo no está conectado. Reconéctalo para eliminarlo también en el remoto, o elimínalo solo de Orca.", "ghostBody": "{{host}} ya no es un host SSH guardado, por lo que este espacio de trabajo ya no está conectado a un host activo. Solo se puede eliminar de Orca — los archivos y ramas en el remoto permanecen intactos.", "cancel": "Cancelar", - "forget": "Eliminar de Orca", - "reconnectAndDelete": "Reconectar y eliminar" + "forget": "Eliminar de Orca" }, "MarkdownImageLightbox": { "image": "Image", @@ -6206,7 +6315,7 @@ "running": "En ejecución", "stopped": "Detenida", "title": "Agregar distro WSL", - "description": "Orca ejecuta su servidor dentro de la distro, así que git, los archivos y las terminales se ejecutan de forma nativa en Linux. Úsala para proyectos nuevos; los proyectos que abriste a través de \\\\wsl.localhost siguen funcionando tal como están.", + "description": "Orca ejecuta su servidor dentro de la distro, así que git, los archivos y las terminales se ejecutan de forma nativa en Linux. Los proyectos de esta distro que abriste a través de \\\\wsl.localhost se mueven a este host automáticamente cuando sus terminales están inactivas; los proyectos en una unidad de Windows (/mnt/…) se quedan en este equipo. Puedes devolver un proyecto movido desde la barra lateral.", "distro": "Distro", "loading": "Buscando distros WSL…", "placeholder": "Elige una distro", @@ -6233,6 +6342,7 @@ "removalPending": "La eliminación no terminó" }, "wslHostRemoval": { + "keptForOthers": "Se quitó de este Orca. El host sigue en marcha para {{value0}}.", "partial": "Se quitó el host, pero algo en la distro sigue en ejecución: {{value0}}", "pending": "Orca aún no eliminó el host: {{value0}} Vuelve a eliminarlo para reintentarlo o conéctalo para conservarlo." }, @@ -6309,7 +6419,11 @@ "e8f25bd903": "No se pudo completar la limpieza del terminal.", "a702d4196e": "Esto cierra cada pestaña de terminal en todos los espacios de trabajo y solicita el apagado de sus sesiones de terminal actuales. Cualquier trabajo de terminal no guardado se pierde. El daemon en sí continúa ejecutándose y se pueden abrir terminales nuevas inmediatamente. Esta acción no se puede deshacer.", "01d6b7c64e": "Las terminales abiertas y los agentes se reiniciarán. Los terminales en hosts remotos no se ven afectados.", - "922548bc66": "¿Reiniciar el servicio de terminal?" + "922548bc66": "¿Reiniciar el servicio de terminal?", + "confirmRestart": "Reiniciar", + "busyRestarting": "Reiniciando…", + "confirmKillAll": "Terminar todas las sesiones", + "busyKilling": "Terminando…" }, "MacFolderAccessFixDialog": { "stepAllow": "Permitir Orca en Archivos y Carpetas", @@ -7931,7 +8045,9 @@ "builtin_themes": "Integrados", "imported_from": "Importado desde {{value0}}", "imported_themes": "Importados", - "search_terminal_themes": "Buscar temas de terminal" + "search_terminal_themes": "Buscar temas de terminal", + "plugin_themes": "Plugins", + "from_plugin": "De {{value0}}" }, "SettingsSidebar": { "e0900f83e7": "SSH", @@ -8217,7 +8333,6 @@ "a016ffbeed": "Auto usa Windows PowerShell ahora y cambia a PowerShell 7+ cuando está instalado.", "5ed5c95344": "Elige entre Windows PowerShell y PowerShell 7+ para nuevos paneles de terminal.", "3d88af864d": "Elige si la opción de shell PowerShell inicia Windows PowerShell o PowerShell 7+ para nuevos paneles de terminal.", - "8a956cc91e": "Caracteres tratados como límites de palabras para la selección con doble clic.", "4bebcc2b2c": "Separadores de palabras", "12e06178fa": "filas", "907b0b9d3e": "Personalizado", @@ -10955,7 +11070,7 @@ "mixedTitle": "Revisar acceso y contenido", "instructionalTitle": "Revisar el contenido del plugin", "subtitle": "{{value0}} v{{value1}} · {{value2}}", - "reconsent": "Los permisos, el nivel de confianza del proceso o el contenido instructivo cambiaron desde la última revisión de este plugin. Revísalo de nuevo antes de ejecutarlo.", + "reconsent": "Este plugin cambió desde que lo aprobaste. Revísalo para volver a ejecutarlo.", "capabilities": "Este plugin puede", "warning": "Estos permisos limitan cómo usa el plugin la API de Orca. Su proceso se ejecuta como un proceso normal en tu equipo, con acceso completo a tus archivos, red y otros procesos.", "instructionalWarning": "Este plugin no tiene ningún proceso en segundo plano. Aun así, su contenido instructivo puede provocar acciones cuando tú o un agente lo usen. Revisa las instrucciones y los comandos siguientes antes de habilitarlo.", @@ -11744,7 +11859,8 @@ "migration": "No se hizo: un movimiento a este servidor quedó sin terminar. Reanúdalo primero.", "deferred": "Aún no se hizo: el servidor no está listo para esto. Inténtalo más tarde.", "failed": "Orca no pudo completar esto en el servidor. Inténtalo de nuevo.", - "defaultServer": "No se hizo: este servidor es el host predeterminado para proyectos nuevos. Elige otro en «Los proyectos nuevos se abren en» antes de detenerlo." + "defaultServer": "No se hizo: este servidor es el host predeterminado para proyectos nuevos. Elige otro en «Los proyectos nuevos se abren en» antes de detenerlo.", + "wslMoveRunning": "No se hizo: un proyecto se está moviendo a este servidor. Orca lo actualizará cuando termine el traslado." }, "reassurance": "Se ejecuta en cada host y se accede a través de tu propia conexión SSH. Tu código y tus archivos se quedan donde están. Solo la lista de proyectos, pestañas y terminales de Orca pasa al host." }, @@ -12082,6 +12198,9 @@ "noMatches": "No hay compilaciones coincidentes.", "searchPlaceholder": "Buscar compilaciones…" }, + "AppearanceThemeControl": { + "useTerminalTheme": "Usar sus colores de terminal" + }, "notification": { "settings": { "copy": { @@ -12146,14 +12265,14 @@ } }, "BulkActionBar": { - "79a9f5f712": "Unstage (", - "ef5f5bd06e": "Stage (", - "60ed678138": "seleccionados" + "selectedCount_one": "{{count}} seleccionado", + "selectedCount_other": "{{count}} seleccionados", + "stageCount": "Agregar al stage ({{count}})", + "unstageCount": "Quitar del stage ({{count}})" }, "ChecksPanel": { "2ef90c9819": "Se inició un agente de IA para los checks con errores.", "a0181a8d76": "Se inició un agente de IA para los conflictos.", - "34464d00b9": "actualizado", "058039787c": "Cancelar", "2ab7fd4b6d": "Guardar", "dda5924a40": "Los checks requieren una rama de Git y contexto de revisión alojada", @@ -12199,7 +12318,8 @@ "430f1a62d4": "No se pudo resolver el hilo seleccionado en el host.", "updateReactionFailed": "No se pudo actualizar la reacción.", "gitlabMoreActions": "Más acciones de MR", - "gitlabLinkAnother": "Vincular otro MR" + "gitlabLinkAnother": "Vincular otro MR", + "reviewUpdatedAt": "{{review}} actualizado {{time}}" }, "CreateHostedReviewComposer": { "741ff8a0d2": "Hacer push y crear {{value0}}" @@ -12356,7 +12476,14 @@ "740aca88ab": "Error al escanear los puertos del espacio de trabajo.", "5be4f7f727": "Menú del puerto {{value0}}", "1004af16ab": "Copiar {{value0}}", - "153d3a8026": "Host del espacio de trabajo desconocido" + "153d3a8026": "Host del espacio de trabajo desconocido", + "unknownProcess": "Proceso desconocido", + "containerOrForwardedService": "Contenedor o servicio reenviado", + "unassigned": "Sin asignar", + "remotePortOutOfRange": "El puerto remoto debe estar en el rango 1–65535", + "localPortOutOfRange": "El puerto local debe estar en el rango 1–65535", + "localPortInUse": "El puerto {{port}} ya está en uso. Elige otro puerto local.", + "localPortRequiresPrivileges": "El puerto {{port}} requiere privilegios elevados. Usa un puerto local ≥ 1024." }, "Search": { "1abfb25a66": "Escriba para buscar en archivos", @@ -12413,7 +12540,6 @@ "476b77745b": "Cambiar referencia base", "ed34038d0d": "Actualizar comparación de ramas", "493f963029": "Cambiar ref base", - "3278b2767b": "por delante", "11b5dd8e41": "Comparando contra", "a9bf7c171a": "Falló el commit", "011f9713fc": "Commit bloqueado", @@ -12458,7 +12584,6 @@ "574d2f4413": "Borrar notas", "05bb8f4a48": "Cancelar", "48db37cca9": "Ver todo", - "78ce2d37ac": "Push al fork", "c05fe04839": "Hace push al fork en {{value0}} (no a origin)", "c35baf2f1e": "Filtrar archivos…", "2fe2a67580": "Más acciones de notas", @@ -12466,14 +12591,12 @@ "cc474e0b8c": "Notas", "e131cd7128": "Source Control sólo está disponible para repositorios Git", "c07b236287": "Seleccione un espacio de trabajo para ver los cambios", - "dc5a6465fc": "{{value0}} (por ejemplo, {{value1}}{{value2}})", "a5e5a11090": "Descartar todo falló: no se pueden eliminar los archivos antes de descartarlos", "8a5ba6a988": "No se pudo cargar la diferencia de commit", "fe5bd1a610": "Creando {{value0}}...", "812cb992ee": "Abrir en {{value0}}", "eef5446523": "{{value0}} #{{value1}} ya está abierto", "0453ca3a9a": "{{value0}} creado, pero Orca no pudo actualizarlo todavía.", - "f99560ab29": "No se pudo abortar {{value0}}", "eae7a1da5f": "No se pudieron borrar las notas.", "df5040e3c3": "Quitar del stage", "8cde1a2fb0": "Agregar al stage", @@ -12501,8 +12624,6 @@ "aaf1451654": "Crear borrador {{value0}}", "26511c22b4": "Creando...", "d7ae61269b": "Commits en la rama", - "branchFilesChangedVsBaseOne": "1 archivo cambiado respecto a {{ref}}", - "branchFilesChangedVsBaseOther": "{{count}} archivos cambiados respecto a {{ref}}", "48a003c1b1": "Cambios preparados", "d4ef4bafc5": "Cambios", "9339382454": "Quitar todo del stage", @@ -12512,8 +12633,6 @@ "72f2bea3f4": "Expandir notas", "d13edef890": "Contraer notas", "d6fb1df5fe": "{{value0}} ya está abierto", - "05838cfdeb": "{{value0}} conflicto", - "d206117f90": "{{value0}} conflicto ({{value1}})", "0b5b8c234c": "Abrir {{value0}} ({{value1}})", "d97ef8f221": "líneas {{value0}}-{{value1}}", "6f8bfa0eb9": "línea {{value0}}", @@ -12566,10 +12685,6 @@ "b3c8f1a902": "Filtrar archivos por nombre", "d4f8c2a901": "Limpiar y cerrar filtro", "e8a1c4b203": "vs", - "compareBaseCommitsAheadOne": "1 commit por delante de {{ref}}", - "compareBaseCommitsAheadOther": "{{count}} commits por delante de {{ref}}", - "compareBaseCommitsBehindOne": "1 commit por detrás de {{ref}}", - "compareBaseCommitsBehindOther": "{{count}} commits por detrás de {{ref}}", "4b4a7de138": "Abrir página de revisión en el navegador", "createPrIntentCommitBlockedSummary": "Commit bloqueado: {{value0}} Corrige el issue y reintenta crear PR.", "pushRecovery": { @@ -12600,17 +12715,50 @@ "diffCommentNotesCopyFailed": "No se pudieron copiar notas", "conflictCount_one": "{{count}} conflicto", "conflictCount_other": "{{count}} conflictos", - "discardFailedSingular": "No se pudo descartar {{count}} archivo", - "discardFailedPlural": "No se pudieron descartar {{count}} archivos", - "noteCountSingular": "{{count}} nota", - "noteCountPlural": "{{count}} notas" + "discardFailedSampleMore_one": "{{paths}}, +{{count}} más", + "discardFailedSampleMore_other": "{{paths}}, +{{count}} más", + "discardFailed_one": "No se pudo descartar {{count}} archivo", + "discardFailed_other": "No se pudieron descartar {{count}} archivos", + "discardFailedWithSample": "{{error}} (por ejemplo, {{paths}})", + "compareBaseCommitsAhead_one": "{{count}} commit por delante de {{ref}}", + "compareBaseCommitsAhead_other": "{{count}} commits por delante de {{ref}}", + "compareBaseCommitsBehind_one": "{{count}} commit por detrás de {{ref}}", + "compareBaseCommitsBehind_other": "{{count}} commits por detrás de {{ref}}", + "branchFilesChangedVsBase_one": "{{count}} archivo cambiado respecto a {{ref}}", + "branchFilesChangedVsBase_other": "{{count}} archivos cambiados respecto a {{ref}}", + "noteCount_one": "{{count}} nota", + "noteCount_other": "{{count}} notas", + "comparingAgainstRef": "Comparando con {{ref}}", + "commitsAheadShort_one": "{{count}} por delante", + "commitsAheadShort_other": "{{count}} por delante", + "unresolvedConflictOfKind": "Conflicto sin resolver ({{kind}})", + "unresolvedConflict": "Conflicto sin resolver", + "locallyResolvedConflictOfKind": "Conflicto resuelto localmente ({{kind}})", + "locallyResolvedConflict": "Conflicto resuelto localmente", + "pushesToForkTarget": "Push al fork {{target}}", + "abortRebaseConfirmTitle": "¿Abortar rebase?", + "abortMergeConfirmTitle": "¿Cancelar fusión?", + "abortRebaseConfirmDescription": "Esto cancela el rebase en curso y puede descartar las resoluciones de conflictos realizadas durante este rebase.", + "abortMergeConfirmDescription": "Esto cancela la fusión en curso y puede descartar las resoluciones de conflictos realizadas durante esta fusión.", + "abortRebaseFailedFallback": "No se pudo abortar el rebase", + "abortMergeFailedFallback": "No se pudo cancelar la fusión", + "abortRebaseFailed": "No se pudo abortar el rebase", + "abortMergeFailed": "No se pudo cancelar la fusión", + "clearNotesFromWorkspace_one": "¿Borrar {{count}} nota de este espacio de trabajo?", + "clearNotesFromWorkspace_other": "¿Borrar {{count}} notas de este espacio de trabajo?", + "clearNotesFromFile_one": "¿Borrar {{count}} nota de {{path}}?", + "clearNotesFromFile_other": "¿Borrar {{count}} notas de {{path}}?" }, "SourceControlAgentActionDialog": { "8e856842d1": "No se pudo iniciar el agente seleccionado.", "c075d00de1": "No se puede resolver la conexión del espacio de trabajo.", "38b899cc02": "Todos los repositorios", "808cfe0a3b": "Este repositorio", - "994cddd1f7": "No guardar" + "994cddd1f7": "No guardar", + "agentNotEnabledOrDetected": "{{agent}} no está habilitado o no se ha detectado en el host de este espacio de trabajo.", + "workspaceConnectionUnresolved": "No se pudo determinar la conexión del espacio de trabajo.", + "noEnabledAgentsDetected": "No se han detectado agentes habilitados en el host de este espacio de trabajo.", + "startAgent": "Iniciar agente" }, "SourceControlAgentActionDialogForm": { "013c9ac04a": "Guardar para", @@ -12675,9 +12823,6 @@ "cbcc4ab3db": "Mostrando los primeros 100 checks", "0dca6bfab5": "Abrir detalles del check", "991f50c7e4": "No hay checks configurados", - "9ad98f2a17": "pendiente", - "5e52f4ef7f": "fallando", - "02ca4f9074": "correcto", "e15a8b77ef": "No hay detalles en línea disponibles para este check.", "679bf2093c": "Copiar extracto del log", "d713f500b2": "Extracto del log", @@ -12694,7 +12839,6 @@ "1f2b980522": "Cargando detalles del check…", "0c96cd25e5": "Resolver", "3a71a6ed0b": "Resuelve los conflictos antes de que los checks y el merge puedan completarse.", - "60186d8498": "Los conflictos bloquean esto", "c16762ac8c": "Los checks y comentarios a continuación muestran el contexto obtenido actualmente.", "9d0e7bcefc": "Sin acciones de PR de bloqueo", "5856874b59": "Orca actualizará los checks mientras este panel permanezca abierto.", @@ -12719,7 +12863,6 @@ "084c516efb": "Copiar comandos", "5dc3af25c0": "Seleccionar comentario", "d7a2f9c401": "Enviar {{value0}} comentarios sin resolver", - "d91f2a6c39": "Enviar {{value0}} comentarios en cola a la IA", "a6de3e5a20": "Limpiar comentarios en cola", "f8a2c91d04": "Poner en cola para el agente", "b4e8a1c902": "En cola", @@ -12735,7 +12878,6 @@ "f588b46a6c": "Marcar autor como bot", "e45324fbed": "No se pudieron cargar los detalles del check.", "dcb3c546fe": "Reintentar", - "checksUnresolvedChip": "irresoluto", "checksUnresolvedStripHint": "Estas comprobaciones finalizaron sin un veredicto de aprobación o desaprobación.", "commitsBehind_one": "{{count}} commit por detrás", "commitsBehind_other": "{{count}} commits por detrás", @@ -12745,7 +12887,28 @@ "pendingChecks_one": "{{count}} comprobación pendiente", "pendingChecks_other": "{{count}} comprobaciones pendientes", "unresolvedChecks_one": "{{count}} comprobación sin resolver", - "unresolvedChecks_other": "{{count}} comprobaciones sin resolver" + "unresolvedChecks_other": "{{count}} comprobaciones sin resolver", + "passingCount_one": "{{count}} correcto", + "passingCount_other": "{{count}} correctos", + "failingCount_one": "{{count}} fallando", + "failingCount_other": "{{count}} fallando", + "pendingCount_one": "{{count}} pendiente", + "pendingCount_other": "{{count}} pendientes", + "unresolvedCount_one": "{{count}} sin resolver", + "unresolvedCount_other": "{{count}} sin resolver", + "sendQueuedCommentsToAi_one": "Enviar {{count}} comentario en cola a la IA", + "sendQueuedCommentsToAi_other": "Enviar {{count}} comentarios en cola a la IA", + "conflictsBlockThisMr": "Los conflictos bloquean este MR", + "conflictsBlockThisPr": "Los conflictos bloquean este PR", + "copyComment": "Copiar comentario", + "sendComment": "Enviar", + "commentingRequiresGitHubPrTarget": "Para comentar se necesita un repositorio de destino para el PR de GitHub.", + "selectWorkspaceBeforeAiAction": "Selecciona un espacio de trabajo antes de iniciar una acción de IA.", + "operation": { + "rebase": "Rebase", + "merge": "Fusión", + "cherryPick": "Cherry-pick" + } }, "empty": { "state": { @@ -12987,10 +13150,10 @@ "dialog": { "3bc61dc989": "Cancelar", "15efa778e3": "Descartar", - "42f89dd030": "archivos", - "e7611dca35": "archivo", "0d2d88cba5": "Esto no se puede deshacer.", - "1551c14668": "¿Descartar cambios?" + "1551c14668": "¿Descartar cambios?", + "fileCount_one": "{{count}} archivo", + "fileCount_other": "{{count}} archivos" } }, "dropdown": { @@ -13152,8 +13315,8 @@ }, "compare": { "summary": { - "commitsAheadSingular": "{{count}} commit por delante de {{ref}}", - "commitsAheadPlural": "{{count}} commits por delante de {{ref}}" + "commitsAhead_one": "{{count}} commit por delante de {{ref}}", + "commitsAhead_other": "{{count}} commits por delante de {{ref}}" } }, "conflict": { @@ -13217,24 +13380,32 @@ "unresolved": "No se pudo determinar qué host posee este espacio de trabajo. Comprueba la conexión e inténtalo de nuevo." }, "useFileDeletion": { - "72691dfebc": "No se pudo {{value0}} '{{value1}}'.", "d979a4fbb5": "¿Eliminar '{{value0}}' permanentemente?", "92276aceb7": "Eliminar", "7fb9435c86": "Esto elimina permanentemente el directorio y su contenido en el host remoto. Esto no se puede deshacer.", "23e98f192f": "Esto elimina permanentemente el archivo en el host remoto. Esto no se puede deshacer.", "8b8ee9d22f": "No se pudo determinar qué host posee este archivo. Comprueba la conexión del espacio de trabajo e inténtalo de nuevo.", - "af1270b90d": "¿Eliminar {{count}} elementos permanentemente?", "dd029aa5cd": "Esto elimina permanentemente los elementos seleccionados y el contenido de cualquier directorio en el host remoto. Esto no se puede deshacer.", - "77fdc36183": "Delete {{count}} items?", - "fca915a67a": "Los elementos remotos se eliminan permanentemente y esta acción no se puede deshacer. Los elementos locales se mueven a {{value0}}." + "deleteFailed": "No se pudo eliminar '{{name}}'.", + "deleteItems_one": "¿Eliminar {{count}} elemento?", + "deleteItems_other": "¿Eliminar {{count}} elementos?", + "mixedRecycleBin": "Los elementos remotos se eliminan permanentemente y esta acción no se puede deshacer. Los elementos locales se mueven a la Papelera de reciclaje.", + "mixedTrash": "Los elementos remotos se eliminan permanentemente y esta acción no se puede deshacer. Los elementos locales se mueven a la Papelera.", + "permanentlyDeleteItems_one": "¿Eliminar {{count}} elemento permanentemente?", + "permanentlyDeleteItems_other": "¿Eliminar {{count}} elementos permanentemente?", + "recycleBinFailed": "No se pudo mover '{{name}}' a la Papelera de reciclaje.", + "trashFailed": "No se pudo mover '{{name}}' a la Papelera." }, "useFileExplorerHandlers": { "32cd9fd991": "No se puede abrir el destino del enlace simbólico", "folderLinksOutsideProject": "Esta carpeta enlaza fuera del proyecto, así que no se puede abrir aquí." }, "useFileExplorerImport": { - "25919b2050": "Se omitió {{value0}} {{value1}}.", - "132fd0e1e9": "No se pudo importar {{value0}} {{value1}}." + "importFailedCount_one": "No se pudo importar {{count}} archivo.", + "importFailedCount_other": "No se pudieron importar {{count}} archivos.", + "importSkippedCount_one": "Se omitió {{count}} archivo.", + "importSkippedCount_other": "Se omitieron {{count}} archivos.", + "importFailed": "No se pudieron importar los archivos." }, "useFileExplorerKeys": { "8adb953095": "Operación fallida" @@ -13271,7 +13442,6 @@ "refreshSessionHistory": "Actualizar historial de sesiones", "searchSessions": "Buscar sesiones", "clearSearch": "Limpiar búsqueda", - "transcriptsSkipped": "{{count}} transcripciones omitidas", "noAgentSessionsFound": "No se encontraron sesiones de agentes", "noSessionsMatchFilters": "Ninguna sesión coincide con los filtros actuales", "noAgentsSelected": "Ningún agente seleccionado", @@ -13291,7 +13461,9 @@ "resumeInChatFailed": "No se pudo reanudar esta sesión en un chat nuevo.", "resumeInNewCliUnavailable": "Esta sesión no se puede abrir en la CLI.", "resumeInNewCliHostTooOld": "Actualiza Orca en el host que ejecuta este chat para reanudarlo en una nueva CLI.", - "folderWorkspaceUnavailable": "El espacio de trabajo de carpeta ya no está disponible." + "folderWorkspaceUnavailable": "El espacio de trabajo de carpeta ya no está disponible.", + "transcriptsSkippedCount_one": "{{count}} transcripción omitida", + "transcriptsSkippedCount_other": "{{count}} transcripciones omitidas" }, "AiVaultPanelControls": { "scanningSessions": "Buscando sesiones", @@ -13337,11 +13509,8 @@ "sessionRole": "Sesión", "worktree": "Worktree", "conversationNotSaved": "Conversación no guardada", - "recoverableEmptyDetail": "Esta sesión no tiene conversación guardada, pero quedan {{value0}} elemento(s) recuperable(s).", "recoverableEmptyOpenLogHint": "Abre el registro para recuperarlos.", "emptyConversationDetail": "Esta sesión no tiene conversación guardada y no se puede reanudar.", - "queuedMessages": "{{value0}} mensaje(s) en cola", - "subagentTranscripts": "{{value0}} transcripción(es) de subagente", "prompt": "Prompt", "firstPrompt": "Primer prompt", "recentPrompt": "Prompt reciente", @@ -13355,7 +13524,13 @@ "noFirstPromptAvailable": "No hay primer prompt disponible", "loadingFirstPrompt": "Cargando primer prompt…", "folder": "Carpeta", - "resumeInFolder": "Reanudar en carpeta" + "resumeInFolder": "Reanudar en carpeta", + "recoverableEmptyDetailCount_one": "Esta sesión no tiene conversación guardada, pero queda {{count}} elemento recuperable.", + "recoverableEmptyDetailCount_other": "Esta sesión no tiene conversación guardada, pero quedan {{count}} elementos recuperables.", + "queuedMessageCount_one": "{{count}} mensaje en cola", + "queuedMessageCount_other": "{{count}} mensajes en cola", + "subagentTranscriptCount_one": "{{count}} transcripción de subagente", + "subagentTranscriptCount_other": "{{count}} transcripciones de subagentes" }, "AiVaultSessionRow": { "resumeInNewTab": "Reanudar en nueva pestaña", @@ -13489,26 +13664,26 @@ "confirmation": { "84f6f5b9eb": "Incluye: {{numbers}}.", "541984b2eb": "¿Cola hasta #{{pr}}?", - "4809f55cdb": "{{included}}GitHub agregará la solicitud de extracción {{count}} a la cola de combinación. La cola elige el método de combinación y puede fusionarlos en grupos separados.", - "be8f2621be": "{{included}}GitHub agregará {{count}} solicitudes de extracción a la cola de combinación juntas. La cola elige el método de combinación y puede fusionarlos en grupos separados.", - "92ca033e72": "Poner en cola {{count}} PR", - "478a527b15": "Poner en cola {{count}} PR", "1feef35ca4": "¿Fusionar a través de #{{pr}}?", - "c3e036c99f": "{{included}}GitHub fusionará {{count}} PR de forma atómica usando {{method}}. Si no puede fusionarla, no se fusionará nada.", - "369aba4b32": "{{included}}GitHub fusionará {{count}} PR de forma atómica usando {{method}}. Si alguna no se puede fusionar, no se fusionará ninguna.", - "493c78f521": "Fusionar {{count}} PR", - "eb7051d268": "Fusionar {{count}} PR" + "queueDescription_one": "{{included}}GitHub agregará {{count}} pull request a la cola de fusión. La cola elige el método de fusión y puede fusionar los pull requests en grupos separados.", + "queueDescription_other": "{{included}}GitHub agregará {{count}} pull requests juntos a la cola de fusión. La cola elige el método de fusión y puede fusionarlos en grupos separados.", + "queueConfirm_one": "Poner en cola {{count}} PR", + "queueConfirm_other": "Poner en cola {{count}} PR", + "mergeDescription_one": "{{included}}GitHub fusionará {{count}} pull request de forma atómica usando {{method}}. Si no se puede fusionar, no se fusionará nada.", + "mergeDescription_other": "{{included}}GitHub fusionará {{count}} pull requests de forma atómica usando {{method}}. Si alguno no se puede fusionar, no se fusionará ninguno.", + "mergeConfirm_one": "Fusionar {{count}} PR", + "mergeConfirm_other": "Fusionar {{count}} PR" }, "merge": { - "55ae29b907": "Fusionar a través de #{{pr}} · {{count}} PR", - "b8446f6ec2": "Fusionar a través de #{{pr}} · {{count}} PR", "189d0ec614": "#{{pr}} sigue siendo un borrador.", "640fb50d9c": "#{{pr}} está cerrada.", "46ffcbda75": "#{{pr}} tiene conflictos de fusión.", "6dabefd63e": "#{{pr}} tiene cambios solicitados.", "2bb21fc326": "#{{pr}} aún necesita aprobación de revisión.", "c23faf74df": "#{{pr}} debe actualizarse.", - "f561e80968": "#{{pr}} está bloqueada." + "f561e80968": "#{{pr}} está bloqueada.", + "mergeThroughLabel_one": "Fusionar hasta #{{pr}} incluido · {{count}} PR", + "mergeThroughLabel_other": "Fusionar hasta #{{pr}} incluido · {{count}} PR" } } } @@ -13565,14 +13740,15 @@ "sourceActionsUnavailable": "La fuente de la transcripción no está disponible." }, "AiVaultScanProgressStrip": { - "agentChecked": "{{agent}}: {{settled}} de {{total}} candidatos del historial comprobados", "fileCount_one": "{{value0}} archivo", "fileCount_other": "{{value0}} archivos", "databaseCount_one": "{{value0}} base de datos", "databaseCount_other": "{{value0}} bases de datos", "scanning": "Analizando {{value0}}", "checking": "Comprobando {{value0}}", - "scanned": "Analizados {{value0}}" + "scanned": "Analizados {{value0}}", + "agentCheckedCount_one": "{{agent}}: {{settled}} de {{total}} candidato del historial comprobado", + "agentCheckedCount_other": "{{agent}}: {{settled}} de {{total}} candidatos del historial comprobados" }, "ssh": { "unrestored": { @@ -13584,6 +13760,15 @@ } } } + }, + "fileExplorerMultiDrag": { + "moreItems_one": "+{{count}} más", + "moreItems_other": "+{{count}} más" + }, + "CreatePullRequest": { + "createInProgress": "Creación del PR en curso...", + "workspaceHostUnresolved": "No se ha podido resolver el host del espacio de trabajo. Actualiza el espacio de trabajo e inténtalo de nuevo.", + "branchDiscoveryFailed": "No se pudieron detectar las ramas." } } }, @@ -14108,11 +14293,11 @@ "a2f68645ac": "Actualizar la cuota de la API de GitLab", "2f9c16d6c3": "Orca usa REST a través de la CLI de GitLab.", "14e144f7a7": "Cuota de la API de GitLab", - "3e2c982cfa": "restantes, se restablece en", - "ea8ad0bae8": "de", "0a891e8935": "API REST", "953f7c6062": "Este host de GitLab no devolvió cabeceras de rate limit.", - "budget_scope_prefix": "Ámbito de la cuota" + "budget_scope_prefix": "Ámbito de la cuota", + "resetUnknown": "desconocido", + "remainingOfLimit": "Quedan {{remaining}} de {{limit}}, se restablece en {{reset}}" } } } @@ -14184,13 +14369,13 @@ "9ee54037a4": "Comando personalizado", "4b2fc4b80c": "Esfuerzo de razonamiento", "be8917699e": "Modelo", - "4d9b6d84df": "no compatible. Elige Claude, Codex o Personalizado.", "560d4feb00": "Personalizado", "29d119fe95": "Agente", "f9382b48a1": "Habilitar autor de IA", "1c0cb4fabb": "Autor de IA", "bd14e9c42a": "No configurado", - "1f9468c5c9": "{{value0}} no compatible" + "1f9468c5c9": "{{value0}} no compatible", + "unsupportedAgent": "{{agent}} no es compatible. Elige Claude, Codex o Personalizado." }, "BrowserAnimatedVisual": { "46df009982": "Comienza tu prueba gratuita", @@ -14731,17 +14916,14 @@ "ConflictComponents": { "f338288514": "Cargando contenido del conflicto…", "90d576adb2": "Actualizar", - "a1ce36f77d": "Instantánea capturada a las ", "c8ca989aea": "Mostrar árbol de archivos", "58ad5ad431": "Descartar", "28e7db4a90": "Control de código fuente", "31931dec46": "Esta instantánea de revisión ya no tiene conflictos activos sin resolver.", "992145ff5a": "Todos los conflictos resueltos", - "d5edd81755": "Renombrado desde ", "6e459867ad": "Estado de continuidad local de la sesión. Git ya no informa que este archivo está sin merge.", "9c2901ef8a": "Siguiente conflicto", "41d9af2e7a": "Conflicto anterior", - "55d61a0ccd": "conflicto ·", "da539359b6": "No hay ningún archivo del worktree disponible para editar este conflicto.", "unresolvedConflicts_one": "{{count}} conflicto no resuelto", "unresolvedConflicts_other": "{{count}} conflictos no resueltos" @@ -15437,7 +15619,9 @@ "6978871a3d": "Abierto", "cce596969e": "Eliminar nota", "cad3384faa": "Editar nota", - "508ee678a5": "Abrir en el navegador" + "508ee678a5": "Abrir en el navegador", + "noteAuthorFallback": "Nota", + "sentMeta": "enviado" }, "DiffCommentPopover": { "2b3ce6d394": "Cancelar", @@ -15450,6 +15634,9 @@ }, "useDiffCommentDecorator": { "995fa28b50": "esta nota" + }, + "diffCommentZoneCard": { + "noteAlreadySent": "Nota ya enviada" } } }, @@ -16044,7 +16231,21 @@ "b09b2384fd": "En pausa", "eaa02014f8": "Activado", "29baf8f4c2": "Source", - "lastRunFailed": "La última ejecución falló." + "lastRunFailed": "La última ejecución falló.", + "noGrace": "Sin período de gracia", + "graceMinutes_one": "{{count}} minuto", + "graceMinutes_other": "{{count}} minutos", + "graceHours_one": "{{count}} hora", + "graceHours_other": "{{count}} horas", + "usageCoverageRuns_one": "{{known}}/{{count}} ejecución", + "usageCoverageRuns_other": "{{known}}/{{count}} ejecuciones", + "usageUnavailable": "No disponible", + "noRuns": "Sin ejecuciones", + "projectDefault": "Predeterminado del proyecto", + "reuseLiveSession": "Reutilizar sesión activa", + "freshEachRun": "Nueva en cada ejecución", + "precheckEnabled": "Activada, {{timeout}}", + "precheckNone": "Ninguna" }, "AutomationEditorDialog": { "fb1896a5e7": "Cancelar", @@ -16145,11 +16346,8 @@ "2faecab10b": "Ejecutar ahora", "13118faadf": "Proyecto desconocido", "73f630b49d": "Cancelar", - "1b586f0e2b": "en", - "02a33e3204": "de", "9adfab2596": "Eliminar automatización externa", "1e2e41392f": "no vuelvas a preguntar", - "b264564427": "y su historial de ejecución. Los espacios de trabajo creados por ejecuciones anteriores no se eliminan.", "080dcb5fbb": "Eliminar automatización", "19a6e30eae": "Actualizar automatizaciones", "77c2778945": "Automatizaciones", @@ -16184,7 +16382,6 @@ "pendingAutomationRunMissing": "El historial de ejecuciones ya no está disponible.", "paused": "Pausada", "missingWorkspace": "Espacio de trabajo ausente", - "runUsageSummary": "{{cost}} aprox. · {{tokens}} tokens", "usageUnavailable": "Uso no disponible", "noRunUsageYet": "Aún no hay uso de ejecución", "noWorkspace": "Sin espacio de trabajo", @@ -16199,7 +16396,11 @@ "rowActions": "Acciones de automatización", "tableLastRun": "Última ejecución", "ownerChanged": "Esta automatización cambió de host. Actualiza e inténtalo de nuevo.", - "runError": "Error:" + "runError": "Error:", + "deleteAutomationDescription": "Eliminar y su historial de ejecuciones. No se eliminarán los espacios de trabajo creados por ejecuciones anteriores.", + "deleteExternalAutomationDescription": "Eliminar de en .", + "runUsageSummaryTokens_one": "{{cost}} aprox. · {{tokens}} token", + "runUsageSummaryTokens_other": "{{cost}} aprox. · {{tokens}} tokens" }, "CreateFromPicker": { "f061f49e3f": "Buscar ramas del repositorio...", @@ -16226,8 +16427,8 @@ "92405f1431": "Indisponible", "dbdcec22bd": "Sólo lectura", "0a2d4359a8": "Manejable", - "e2532150ed": "automatizaciones", - "701515f010": "automatización" + "automationCount_one": "{{count}} automatización", + "automationCount_other": "{{count}} automatizaciones" }, "WorkspaceCombobox": { "ee5b280eba": "No se encontraron espacios de trabajo.", @@ -16279,7 +16480,8 @@ "last": { "run": { "done": "Hecho", - "failed": "Fallido" + "failed": "Fallido", + "statusWithRelative": "{{status}} · {{relative}}" } } } @@ -16435,15 +16637,12 @@ }, "externalScope": { "uncheckedHost": "No se pudieron comprobar los gestores de automatizaciones externas en {{hostLabel}}.", - "uncheckedHosts": "No se pudieron comprobar los gestores de automatizaciones externas en {{count}} hosts." + "uncheckedHostCount_one": "No se pudieron comprobar los gestores de automatizaciones externos en {{count}} host.", + "uncheckedHostCount_other": "No se pudieron comprobar los gestores de automatizaciones externos en {{count}} hosts." }, "enablement": { "paused": "En pausa" }, - "runHistory": { - "occurrencesWithLatest": "{{times}} veces, la más reciente {{date}}", - "occurrences": "{{times}} veces" - }, "extraAgentArgs": { "advanced": "Avanzado", "clear": "Borrar argumentos", @@ -16453,6 +16652,71 @@ "useFreshSessions": "Usar sesiones nuevas", "helper": "Se añaden a los argumentos predeterminados de este host en cada sesión nueva.", "detailLabel": "Argumentos adicionales" + }, + "runHistory": { + "runCountSummary_one": "{{count}} ejecución · completadas: {{completed}}", + "runCountSummary_other": "{{count}} ejecuciones · completadas: {{completed}}", + "occurrencesWithLatestCount_one": "{{count}} vez, la última el {{date}}", + "occurrencesWithLatestCount_other": "{{count}} veces, la última el {{date}}", + "occurrencesCount_one": "{{count}} vez", + "occurrencesCount_other": "{{count}} veces" + }, + "capabilityProbe": { + "createIdempotencyUpdateRequired": "Mover automatizaciones a este host requiere un servidor de Orca más reciente. Actualiza el HUB y vuelve a intentarlo." + }, + "editDraft": { + "unsupportedSchedule": "Esta automatización tiene una programación guardada no compatible. Elige una programación compatible antes de guardar los cambios." + }, + "hostCatalog": { + "orphanEntryLabel": "Automatizaciones antiguas sin asignar" + }, + "automationPageParts": { + "never": "Nunca", + "now": "ahora mismo", + "runStatusPending": "En cola", + "runStatusDispatching": "Iniciando", + "runStatusDispatched": "Iniciada", + "runStatusCompleted": "Completada", + "runStatusSkippedPrecheck": "Omitida por verificación previa", + "runStatusSkippedMissed": "Omitida", + "runStatusSkippedUnavailable": "No disponible", + "runStatusSkippedNeedsInteractiveAuth": "Requiere credenciales", + "runStatusDispatchFailed": "Fallida" + }, + "runContent": { + "noOutput": "No hay contenido de salida disponible." + }, + "runViewState": { + "viewRun": "Ver ejecución", + "runOpen": "La ejecución está abierta", + "terminalOnPairedServer": "El terminal de la ejecución está en el servidor vinculado.", + "terminalUnavailable": "El terminal de la ejecución no está disponible.", + "openWorkspace": "Abrir espacio de trabajo", + "workspaceAvailable": "El espacio de trabajo está disponible.", + "snapshotSaved": "Instantánea guardada", + "showingSnapshot": "Mostrando la instantánea guardada de la ejecución.", + "namedWorkspaceGone": "{{name}} ya no está disponible", + "workspaceGone": "El espacio de trabajo ya no está disponible", + "noWorkspaceLaunched": "No se inició ningún espacio de trabajo" + }, + "runWorkspaceDisplay": { + "notLaunched": "No iniciado", + "namedWorkspaceGone": "{{name}} (ya no disponible)" + }, + "usage": { + "tokensAndCost_one": "{{tokens}} token · {{cost}}", + "tokensAndCost_other": "{{tokens}} tokens · {{cost}}" + }, + "externalDisplay": { + "sshHost": "Host SSH", + "local": "Local" + }, + "externalActionDisabled": { + "actionInProgress": "Otra acción de automatización sigue en ejecución.", + "sshConnecting": "Espera a que este host SSH termine de conectarse.", + "connectSshHost": "Conecta este host SSH antes de gestionar automatizaciones de {{provider}}.", + "cannotManageOnSshHost": "{{provider}} no puede gestionar automatizaciones en este host SSH.", + "cannotManageLocally": "{{provider}} no puede gestionar automatizaciones en este equipo." } }, "agent": { @@ -16593,8 +16857,6 @@ "63ce735809": "Conectar", "4a2ab52781": "Verificando…", "79e7aaed39": "Cancelar", - "fdd26d81cc": "Ajustes de cuenta de Atlassian", - "8090504a3e": "Crea un token en", "7b3967c12f": "Token API de Atlassian", "3d81bf3ab3": "Token de API", "e91b9a4073": "you@example.com", @@ -16619,17 +16881,18 @@ "be9eba0a1b": "username", "70035652d7": "Password", "c50abbf340": "Jira account password", - "d8737db691": "Usa el nombre de usuario y la contraseña de tu cuenta de Jira Server o Data Center." + "d8737db691": "Usa el nombre de usuario y la contraseña de tu cuenta de Jira Server o Data Center.", + "createTokenInSettings": "Crea un token en la configuración de tu cuenta de Atlassian." } } }, "rightSidebar": { "FolderWorkspaceWorktreesPanel": { "unavailable": "Los workspaces solo se muestran para workspaces de carpeta.", - "countOne": "1 worktree adjunto", - "countMany": "{{value0}} worktrees adjuntos", "emptyTitle": "Aún no hay worktrees adjuntos", - "emptyCopy": "Los worktrees creados desde este workspace aparecerán aquí." + "emptyCopy": "Los worktrees creados desde este workspace aparecerán aquí.", + "attachedCount_one": "{{count}} worktree adjunto", + "attachedCount_other": "{{count}} worktrees adjuntos" }, "FolderWorkspacePrChecksPanel": { "unavailable": "Las comprobaciones de PR solo se muestran en espacios de trabajo de carpeta.", @@ -16641,12 +16904,12 @@ "hideDetails": "Ocultar detalles de checks de PR de {{value0}}", "reviewChecks": "Checks de revisión", "allChecksPassing": "todos los checks correctos", - "oneWorktree": "1 worktree", - "worktreeCount": "{{value0}} worktrees", - "oneFailing": "1 fallando", - "failingCount": "{{value0}} fallando", - "onePending": "1 pendiente", - "pendingCount": "{{value0}} pendientes" + "worktreeCountLabel_one": "{{count}} worktree", + "worktreeCountLabel_other": "{{count}} worktrees", + "failingCountLabel_one": "{{count}} fallando", + "failingCountLabel_other": "{{count}} fallando", + "pendingCountLabel_one": "{{count}} pendiente", + "pendingCountLabel_other": "{{count}} pendientes" }, "parentPrChecks": { "rowSummary": { @@ -16728,10 +16991,11 @@ "combobox": { "noProjects": "Sin proyectos", "allProjects": "Todos los proyectos", - "hostCount": "{{value0}} hosts", "searchProjects": "Buscar proyectos...", "noMatches": "Ningún proyecto coincide con tu búsqueda.", - "chooseSource": "Elige el origen de tareas" + "chooseSource": "Elige el origen de tareas", + "hostCount_one": "{{count}} host", + "hostCount_other": "{{count}} hosts" } } }, @@ -16768,7 +17032,35 @@ "taskSourceContextSummary": { "sourceUnavailable": "Origen {{value0}} no disponible: {{value1}}", "someSourceHostsUnavailable": "Algunos hosts de origen de {{value0}} no están disponibles: {{value1}}", - "reconnectOrUpdateTitle": "Reconecta o actualiza {{value0}} para cargar este origen." + "reconnectOrUpdateTitle": "Reconecta o actualiza {{value0}} para cargar este origen.", + "providerSourceTitle": "Fuente de {{provider}}", + "hostTitle": "Host: {{hosts}}", + "accountTitle": "Cuenta: {{accounts}}", + "sourceTitle": "Fuente: {{source}}", + "sourceHostCount_one": "{{count}} host de origen", + "sourceHostCount_other": "{{count}} hosts de origen", + "noHost": "Sin host", + "projectCount_one": "{{count}} proyecto", + "projectCount_other": "{{count}} proyectos", + "selectedProject": "Proyecto seleccionado", + "selectedProjectCount_one": "{{count}} proyecto seleccionado", + "selectedProjectCount_other": "{{count}} proyectos seleccionados", + "currentAccount": "Cuenta actual", + "statusCheckingCapabilities": "comprobando capacidades del servidor", + "statusServerUpdateForTaskSources": "requiere actualizar el servidor para las fuentes de tareas", + "statusProviderAuthNeeded": "requiere autenticación del proveedor", + "statusSourceToolUnavailable": "herramienta de origen no disponible", + "statusProviderUnsupported": "proveedor no compatible con este host", + "statusServerUpdateNeeded": "requiere actualizar el servidor", + "unavailableCount_one": "{{count}} no disponible", + "unavailableCount_other": "{{count}} no disponibles", + "statusConnected": "conectado", + "statusAuthNeeded": "requiere autenticación", + "statusConnecting": "conectando", + "statusConnectionIssue": "problema de conexión", + "statusDisconnected": "desconectado", + "hostStatus": "{{host}} {{status}}", + "availabilityTitle": "Disponibilidad: {{hosts}}" }, "ShortcutKeyCombo": { "07eb4985a1": "Doble toque en {{value0}}" @@ -17012,20 +17304,12 @@ "noMatches": "No hay coincidencias." }, "NativeChatResumeOnRestartModal": { - "notContinuedOne": "1 chat no pudo reanudarse", - "notContinuedMany": "{{value0}} chats no pudieron reanudarse", - "notConfirmedOne": "No se pudo confirmar que 1 chat se reanudó", - "notConfirmedMany": "No se pudo confirmar que {{value0}} chats se reanudaron", - "notConfirmedOtherOne": "No se pudo confirmar que 1 otro chat se reanudó", - "notConfirmedOtherMany": "No se pudo confirmar que {{value0}} otros chats se reanudaron", "viewChats": "Ver chats", "review": "Revisar", "activityApproval": "Esperando tu aprobación: {{value0}}", "activityMidReply": "Estaba respondiendo", - "activityMonitorMany": "Supervisando {{value0}} tareas en segundo plano", "activityMonitorOne": "Supervisando: {{value0}}", "activityQuestion": "Esperando tu respuesta: {{value0}}", - "activitySubagentMany": "{{value0}} subagentes en ejecución", "activitySubagentOne": "Subagente en ejecución: {{value0}}", "activityUnnamed": "sin nombre", "updateBody": "Estos chats estaban trabajando cuando Orca instaló una actualización. Al reanudarlos, cada uno se restaura donde se detuvo, con su contexto completo, y se pide al agente que revise lo que estaba haciendo antes de continuar. Tu propio prompt no se vuelve a enviar.", @@ -17035,12 +17319,8 @@ "untitled": "Chat sin título", "listLabel": "Chats que se reanudarían", "dontAskAgain": "No volver a preguntar (reanudar automáticamente)", - "dontAskAgainHint": "Puedes desactivarlo en Ajustes → Experimental → Interfaz de chat.", - "continuedOne": "Se reanudó 1 chat", - "continuedMany": "Se reanudaron {{value0}} chats", + "dontAskAgainHint": "Puedes desactivarlo en Ajustes → Chat → Comportamiento.", "selectAgent": "Reanudar {{value0}} chat \"{{value1}}\" en {{value2}}", - "resumeSelected": "Reanudar {{value0}} chats", - "resumeSelectedOne": "Reanudar 1 chat", "dismissAll": "Descartar todo", "selectWorkspace": "Seleccionar todos los chats en {{value0}}", "workspaceSelectedCount": "{{value0}} de {{value1}}", @@ -17058,8 +17338,22 @@ "serverBody": "Estos chats estaban trabajando cuando Orca se reinició en {{machine}}. Al reanudarlos, cada uno se restaura donde se detuvo y se le pide al agente que continúe. Tu propio prompt no se vuelve a enviar.", "serverDismiss": "Descartar", "serverResumeAll": "Reanudar los {{count}} en {{machine}}", - "serverResumeHereOne": "Reanudar 1 chat iniciado aquí", - "serverResumeHere": "Reanudar {{count}} chats iniciados aquí" + "resumeChats_one": "Reanudar {{count}} chat", + "resumeChats_other": "Reanudar {{count}} chats", + "serverResumeHereCount_one": "Reanudar {{count}} chat iniciado aquí", + "serverResumeHereCount_other": "Reanudar {{count}} chats iniciados aquí", + "continuedCount_one": "{{count}} chat reanudado", + "continuedCount_other": "{{count}} chats reanudados", + "notContinuedCount_one": "No se pudo reanudar {{count}} chat", + "notContinuedCount_other": "No se pudieron reanudar {{count}} chats", + "notConfirmedCount_one": "No se pudo confirmar la reanudación de {{count}} chat", + "notConfirmedCount_other": "No se pudo confirmar la reanudación de {{count}} chats", + "notConfirmedOtherCount_one": "No se pudo confirmar la reanudación de {{count}} chat más", + "notConfirmedOtherCount_other": "No se pudo confirmar la reanudación de {{count}} chats más", + "activitySubagentCount_one": "{{count}} subagente en ejecución", + "activitySubagentCount_other": "{{count}} subagentes en ejecución", + "activityMonitorCount_one": "Supervisando {{count}} tarea en segundo plano", + "activityMonitorCount_other": "Supervisando {{count}} tareas en segundo plano" }, "NativeChatResumeOutcomeRow": { "openChat": "Abrir chat", @@ -17215,15 +17509,15 @@ "description": "Orca ocultará los detalles de {{value0}} {{value1}} en este espacio de trabajo. El {{value0}} y la rama en {{value2}} no se modificarán." }, "NativeChatResumeRunPanel": { - "resumedTitle": "Se reanudaron {{value0}} de {{value1}} chats", - "resumedTitleOne": "{{value0}} de 1 chat reanudado", - "resumingTitleOne": "Reanudando 1 chat", - "resumingTitle": "Reanudando {{value0}} chats", "description": "Cada chat se restaura con todo su contexto y se le pide que revise dónde se detuvo. Puedes cerrar esto; la barra de estado sigue el progreso.", "finished": "Estos chats estaban trabajando cuando Orca se cerró. Orca restauró cada uno donde se detuvo, con todo su contexto, y pidió al agente que revisara lo que estaba haciendo antes de continuar. Tus propios mensajes no se reenviaron.", "finishedUpdate": "Estos chats estaban trabajando cuando Orca instaló una actualización. Orca restauró cada uno donde se detuvo, con todo su contexto, y pidió al agente que revisara lo que estaba haciendo antes de continuar. Tus propios mensajes no se reenviaron.", "finishedPartial": "Estos chats estaban trabajando cuando Orca se cerró. Los que Orca reanudó se restauraron donde se detuvieron, con todo su contexto, y se les pidió revisar lo que estaban haciendo antes de continuar. Tus propios mensajes no se reenviaron. Consulta la lista para ver los chats que aún necesitan atención o que se pueden reanudar.", - "finishedPartialUpdate": "Estos chats estaban trabajando cuando Orca instaló una actualización. Los que Orca reanudó se restauraron donde se detuvieron, con todo su contexto, y se les pidió revisar lo que estaban haciendo antes de continuar. Tus propios mensajes no se reenviaron. Consulta la lista para ver los chats que aún necesitan atención o que se pueden reanudar." + "finishedPartialUpdate": "Estos chats estaban trabajando cuando Orca instaló una actualización. Los que Orca reanudó se restauraron donde se detuvieron, con todo su contexto, y se les pidió revisar lo que estaban haciendo antes de continuar. Tus propios mensajes no se reenviaron. Consulta la lista para ver los chats que aún necesitan atención o que se pueden reanudar.", + "resumedOfTotal_one": "Chats reanudados: {{resumed}} de {{count}}", + "resumedOfTotal_other": "Chats reanudados: {{resumed}} de {{count}}", + "resumingCount_one": "Reanudando {{count}} chat", + "resumingCount_other": "Reanudando {{count}} chats" }, "NativeChatResumeRunStatusIcon": { "waitingForReply": "Esperando respuesta", @@ -17273,6 +17567,72 @@ "copyFailed": "No se pudo copiar el enlace.", "signingIn": "Iniciando sesión…", "cancel": "Cancelar" + }, + "AgentStateDot": { + "working": "Trabajando", + "monitoring": "Supervisando tareas en segundo plano", + "blocked": "Bloqueado", + "waiting": "Esperando entrada", + "interrupted": "Interrumpido", + "failed": "Fallido", + "done": "Completado", + "idle": "Inactivo", + "unverifiable": "Sin actualización reciente", + "unconfirmed": "No se pudo confirmar", + "permission": "Requiere atención" + }, + "issueComments": { + "you": "Tú" + }, + "ZoomOverlay": { + "uiZoom": "Zoom de la interfaz", + "editorZoom": "Zoom del editor", + "terminalZoom": "Zoom del terminal" + }, + "issueCopy": { + "urlCopied": "URL copiada", + "keyCopied": "Clave copiada", + "identifierCopied": "Identificador copiado", + "branchNameCopied": "Nombre de rama copiado", + "promptCopied": "Prompt copiado", + "urlCopyFailed": "No se pudo copiar la URL", + "keyCopyFailed": "No se pudo copiar la clave", + "identifierCopyFailed": "No se pudo copiar el identificador", + "branchNameCopyFailed": "No se pudo copiar el nombre de rama", + "promptCopyFailed": "No se pudo copiar el prompt" + }, + "prCheckCounts": { + "noChecksFound": "No se encontraron verificaciones", + "checksFailing_one": "{{count}} verificación fallida", + "checksFailing_other": "{{count}} verificaciones fallidas", + "checksNeedAction_one": "{{count}} verificación requiere acción", + "checksNeedAction_other": "{{count}} verificaciones requieren acción", + "checksPending_one": "{{count}} verificación pendiente", + "checksPending_other": "{{count}} verificaciones pendientes", + "allChecksPassing": "Todas las verificaciones superadas", + "checksPassingOfTotal_one": "Verificaciones superadas: {{passing}} de {{count}}", + "checksPassingOfTotal_other": "Verificaciones superadas: {{passing}} de {{count}}" + }, + "taskPageJiraBoard": { + "changeStatusFailed": "No se pudo cambiar el estado." + }, + "jiraIssue": { + "loadStatusChangesFailed": "No se pudieron cargar los cambios de estado.", + "loadCommentsFailed": "No se pudieron cargar los comentarios." + }, + "taskPageJiraLinkedIssues": { + "someIssuesFailed": "No se pudieron cargar algunas incidencias de Jira vinculadas a espacios de trabajo. Actualiza para volver a intentarlo." + }, + "taskPageJiraLoadState": { + "failedToLoadIssues": "No se pudieron cargar las incidencias de Jira.", + "authFailed": "Falló la autenticación de Jira. Reconecta Jira en Ajustes y vuelve a intentarlo.", + "accessDenied": "Jira denegó el acceso a esta búsqueda de incidencias. Comprueba los permisos del proyecto o prueba otra consulta JQL.", + "rateLimited": "Jira limitó esta búsqueda de incidencias por exceso de solicitudes. Vuelve a intentarlo en un momento.", + "serverError": "Jira tuvo un error de servidor al cargar las incidencias. Vuelve a intentarlo en un momento.", + "jqlFailed": "Jira no pudo ejecutar esta consulta JQL. Comprueba la sintaxis y vuelve a intentarlo.", + "unreachable": "No se pudo contactar con Jira. Comprueba tu conexión y vuelve a intentarlo.", + "loadFailed": "No se pudieron cargar las incidencias de Jira. Vuelve a intentarlo en un momento.", + "errorWithCode": "Error {{code}}: {{summary}}" } }, "i18n": { @@ -17441,6 +17801,7 @@ "agentCommandNotRunnable": "{{agent}}: el Comando en Ajustes → Agentes debe ser la ruta o el nombre de un programa que Orca pueda encontrar, sin argumentos ni variables. Cámbielo o restablézcalo con Reiniciar.", "runtimeNotInstalled": "{{agent}} no está instalado en el equipo que ejecuta este chat. Instálelo desde el chat en una versión actual de Orca.", "fullAccessAsRoot": "{{agent}} no usará Acceso total mientras se ejecute como root. Elija otro permiso para {{agent}} en Configuración → Agentes para el equipo que ejecuta este chat y luego inicie un chat nuevo.", + "launchPreparationFailed": "Orca no pudo preparar el inicio de {{agent}} en el equipo que ejecuta este chat.", "conversationOpenElsewhere": "Codex sigue manteniendo abierta esta conversación. Inténtalo de nuevo en un momento o cierra otras terminales de Codex.", "conversationOpenInTerminal": "{{agent}} ya está ejecutando esta conversación en otra terminal. Sal de {{agent}} allí o cierra esa terminal para continuar aquí.", "chooseClaudeAccount": "Elija o agregue una en la configuración de Cuentas de Claude.", @@ -17590,7 +17951,8 @@ "compactAfterRetry": "Reintente su mensaje anterior y luego ejecute /compact.", "clearAfterSending": "Su mensaje anterior todavía se está enviando. Ejecute /clear cuando se haya enviado.", "compactAfterSending": "Su mensaje anterior todavía se está enviando. Ejecute /compact cuando se haya enviado.", - "pendingWork": "Espera a que terminen el trabajo y los mensajes pendientes antes de usar este comando." + "pendingWork": "Espera a que terminen el trabajo y los mensajes pendientes antes de usar este comando.", + "notDoneGoalChangeIncomplete": "No se pudo terminar de cambiar el objetivo. Revisa el chat." }, "composer": { "imageUnavailable": "Vista previa no disponible", @@ -17951,7 +18313,6 @@ "pausedSendFailedWaiting": "No se pudo enviar. Cuando el agente termine, pulsa Enviar para reintentar.", "save": "Guardar", "editingMessage": "Editando mensaje", - "cancelEditing": "Cancelar edición", "editChanged": "Este mensaje cambió mientras lo editabas. Tu edición está en el cuadro de chat.", "editChangedPrompt": "Este mensaje cambió mientras lo editabas. Tu edición estará en el cuadro de chat cuando respondas al agente.", "editChangedNotSaved": "Este mensaje cambió mientras lo editabas. Tu edición no se guardó.", @@ -17965,8 +18326,6 @@ "expand": "Expandir", "queued": "En cola", "clearAll": "Borrar todo", - "pasteOrDropImages": "Pega o suelta imágenes", - "saveNeedsContent": "Añade texto o una imagen para guardar", "moveChanged": "La cola cambió antes de este movimiento. Intenta arrastrar el mensaje de nuevo.", "reorderHint": "Arrastra para reordenar o usa las teclas de flecha arriba y abajo.", "reorderMessage": "Reordenar mensaje" @@ -18262,6 +18621,15 @@ "settings": "Abrir la configuración en la terminal", "extensions": "Abrir el panel de extensiones en la terminal", "hotkeys": "Mostrar los atajos de teclado en la terminal" + }, + "modelDescriptions": { + "grok_4_7": "El modelo de vanguardia más reciente de xAI", + "grok_4_6": "El modelo de vanguardia anterior de xAI", + "grok_4_5": "Un modelo de vanguardia anterior de xAI", + "fable": "El más capaz para las tareas más difíciles y largas", + "opus": "Ideal para tareas cotidianas y complejas", + "sonnet": "Eficiente para tareas rutinarias", + "haiku": "El más rápido para respuestas breves" } }, "tab": { @@ -18833,7 +19201,6 @@ "subagents_other": "{{count}} subagentes" }, "terminal": { - "closed": "No hay terminal activa: el panel de este agente se ha cerrado.", "focusWorktree": "Open worktree", "close": "Close", "remotePreviewUnavailable": "No hay vista previa para esta sesión remota: abre el espacio de trabajo para ver la terminal." @@ -19056,6 +19423,15 @@ "empty": "No hay extensiones activadas para este perfil", "visitWebStore": "Visitar Chrome Web Store", "manage": "Administrar extensiones" + }, + "viewport": { + "mobile-s": "Móvil S — 320 × 568", + "mobile-m": "Móvil M — 375 × 667", + "mobile-l": "Móvil L — 425 × 812", + "tablet": "Tableta — 768 × 1024", + "laptop": "Portátil — 1024 × 768", + "laptop-l": "Portátil L — 1440 × 900", + "desktop": "Escritorio — 1920 × 1080" } }, "runtimeRpc": { @@ -19241,9 +19617,9 @@ "pathAdded": "Added", "openFolder": "Open {{name}}", "findOrTypePath": "Busque una carpeta o escriba cualquier ruta...", - "addTypedPath": "Add", "noDirectories": "Aún no se han agregado carpetas.", - "removePath": "Remove {{name}}" + "removePath": "Remove {{name}}", + "addTypedPathCode": "Agregar " }, "editor": { "markdownPreview": { @@ -19361,13 +19737,10 @@ "running": "en ejecución" }, "settingAsk": "Preguntar", - "bodyOther": "{{count}} sesiones de Claude siguen en ejecución con {{previous}}. Al reiniciarlas, cada conversación continúa con {{next}}. Las sesiones ocupadas esperan a estar inactivas antes de reiniciarse.", - "bodyOne": "1 sesión de Claude sigue en ejecución con {{previous}}. Al reiniciarla, la conversación continúa con {{next}}. Las sesiones ocupadas esperan a estar inactivas antes de reiniciarse.", "dontAskAgain": "No volver a preguntar (se reinicia automáticamente)", "restartOne": "Reiniciar sesión", "title": "Cambiado a {{account}}", "keep": "Mantener como está", - "restartOther": "Reiniciar {{count}} sesiones", "listLabel": "Sesiones de Claude que se reiniciarán", "dontAskAgainHint": "Puede desactivar esto en Configuración → Cuentas de proveedores de IA.", "session": "Sesión de Claude", @@ -19385,13 +19758,17 @@ "reasonOwnFolder": "Usa tu propia carpeta de Claude", "reasonUnknownAccount": "Cuenta desconocida", "reasonNoSession": "No se puede reanudar", - "reviewBodyOne": "Otra sesión de Claude no se movió a {{next}}.", - "reviewBodyOther": "Otras {{count}} sesiones de Claude no se movieron a {{next}}.", "notMovedOne": "Otra sesión no se movió.", "notMovedOther": "Otras {{count}} sesiones no se movieron.", "review": "Revisar", "uncheckedOne": "No se pudo comprobar si Claude se ejecuta en 1 terminal. Si Claude se está ejecutando allí, seguirá usando {{previous}} hasta que se reinicie.", - "uncheckedOther": "No se pudo comprobar si Claude se ejecuta en {{count}} terminales. Cualquier Claude que se esté ejecutando allí seguirá usando {{previous}} hasta que se reinicie." + "uncheckedOther": "No se pudo comprobar si Claude se ejecuta en {{count}} terminales. Cualquier Claude que se esté ejecutando allí seguirá usando {{previous}} hasta que se reinicie.", + "restartCount_one": "Reiniciar {{count}} sesión", + "restartCount_other": "Reiniciar {{count}} sesiones", + "reviewBody_one": "No se trasladó {{count}} sesión más de Claude a {{next}}.", + "reviewBody_other": "No se trasladaron {{count}} sesiones más de Claude a {{next}}.", + "body_one": "{{count}} sesión de Claude sigue ejecutándose en {{previous}}. Al reiniciarla, la conversación continúa en {{next}}. Las sesiones ocupadas esperan a estar inactivas antes de reiniciarse.", + "body_other": "{{count}} sesiones de Claude siguen ejecutándose en {{previous}}. Al reiniciarlas, cada conversación continúa en {{next}}. Las sesiones ocupadas esperan a estar inactivas antes de reiniciarse." } }, "hostSignIn": { @@ -19421,6 +19798,30 @@ "confirm": "Ajustar filtros y mostrar", "cancel": "Mantener filtros" }, + "wslMoved": { + "movedToHost": "Movido al host de {{distro}}", + "useHere": "Usar de nuevo en este equipo", + "useHereTitle": "¿Usar {{name}} de nuevo en este equipo?", + "useHereDescription": "Orca abrirá este proyecto aquí tal como estaba antes de moverlo. Tu código no se ve afectado: nunca se movió. Los cambios hechos en el host {{distro}} desde el traslado, como pestañas y chats nuevos, se quedan en el host y no vuelven. Los proyectos que se movieron junto con este también vuelven. El proyecto también sigue en el host {{distro}} hasta que lo quites allí. Esta ventana se recargará.", + "useHereConfirm": "Usar en este equipo", + "useHereSuperseded": "Un traslado posterior al host {{distro}} incluye este proyecto. Trae ese de vuelta primero.", + "useHereRefusedTitle": "Aún no puedes usar {{name}} aquí", + "useHereRefusedOk": "Aceptar", + "useHereSupersededBy": "{{names}} se movieron al host {{distro}} después de este proyecto. Úsalos de nuevo en este equipo primero y luego este proyecto.", + "useHereMoveRunning": "Todavía hay un traslado al host {{distro}} en curso. Inténtalo de nuevo cuando termine.", + "useHereHostKeptForPeers": "{{project}} se movió al host {{distro}}, que sigue en marcha para otro Orca. Vuelve a añadir el host para usarlo aquí de nuevo.", + "useHereHostUnreachable": "El host {{distro}} no responde, así que Orca no puede detener su copia de este proyecto y sus agentes podrían seguir ejecutándose allí. Conecta el host en Configuración, o quítalo, e inténtalo de nuevo.", + "useHereHostStillRunning": "La copia de este proyecto en el host {{distro}} todavía tiene terminales en ejecución, así que sus agentes podrían ejecutarse dos veces. Espera un momento e inténtalo de nuevo.", + "useHereFailed": "No se pudo devolver este proyecto a este equipo.", + "useHereHostRemovalPending": "El host {{distro}} todavía se está quitando, así que Orca no lo toca. Termina de quitarlo en Configuración e inténtalo de nuevo.", + "useHereHostAutomations": "Orca no pudo desactivar las automatizaciones de este proyecto en el host {{distro}}, así que podrían ejecutarse dos veces. Conecta el host en Configuración e inténtalo de nuevo.", + "useHereUnsavedTitle": "Guarda primero tus archivos", + "useHereUnsavedDescription": "Recuperar {{name}} recarga esta ventana. Guarda o cierra primero estos archivos: {{files}}", + "automationRunsOnHost": "Se ejecuta en el host {{distro}}", + "quitDuringMoveTitle": "¿Salir mientras se mueve un proyecto?", + "quitDuringMoveDescription": "Un proyecto se está moviendo a su host WSL. ¿Salir de todos modos? El traslado se deshará en el próximo inicio.", + "quitDuringMoveConfirm": "Salir de todos modos" + }, "startupWorktreeRefresh": { "loading": "Buscando espacios de trabajo…", "description": "Pueden aparecer más espacios de trabajo mientras se cargan los proyectos locales y remotos." @@ -19449,8 +19850,6 @@ "sessionSearch": { "panel": { "retry": "Probar de nuevo", - "resultsOne": "{{count}} resultado", - "resultsOther": "{{count}} resultados", "noMatches": "No hay sesiones coincidentes en el historial indexado. Prueba otra consulta o ámbito.", "loadMore": "Cargar más coincidencias", "indexedHistory": "Historial indexado", @@ -19471,11 +19870,23 @@ "enable": "Activar", "scopeUnknown": "Esta computadora no tiene este espacio de trabajo ni este proyecto. Cambia el ámbito a Todo para buscar en todo lo que contiene.", "sortSessionsAriaLabel": "Ordenar sesiones: {{value0}}", - "sessionsOne": "{{count}} sesión", - "sessionsOther": "{{count}} sesiones", - "sessionsOfLoaded": "{{value0}} de {{value1}} sesiones", "showMoreSessions": "Mostrar más sesiones", - "loadingMoreSessions": "Cargando más sesiones…" + "loadingMoreSessions": "Cargando más sesiones…", + "resultCount_one": "{{count}} resultado", + "resultCount_other": "{{count}} resultados", + "sessionCount_one": "{{count}} sesión", + "sessionCount_other": "{{count}} sesiones", + "sessionsShownOfLoaded_one": "{{shown}} de {{count}} sesión", + "sessionsShownOfLoaded_other": "{{shown}} de {{count}} sesiones", + "hostSkipReason": { + "indexChanged": "índice modificado", + "searchOff": "búsqueda desactivada", + "notReady": "no preparado", + "unavailable": "no disponible", + "unreachable": "inaccesible", + "scopeNotFound": "ámbito de búsqueda no encontrado allí", + "agentNotSupported": "agente no compatible" + } } }, "sessionHistory": { @@ -19622,7 +20033,9 @@ "confirmTitle": "¿Reiniciar el daemon de terminal?", "confirmBody": "Reiniciar termina todos los procesos que se ejecutan en {{sessions}}. Los agentes que admiten reanudación pueden reanudarse después; los shells y otros trabajos no, y deben iniciarse de nuevo. Hazlo cuando tus agentes estén inactivos.", "cancel": "Cancelar", - "confirm": "Reiniciar y terminar procesos" + "confirm": "Reiniciar y terminar procesos", + "count_other": "{{count}} terminales en ejecución", + "count_one": "{{count}} terminal en ejecución" }, "restartedInputNotSent": "El terminal se reinició mientras escribías, así que parte de la entrada puede no haberle llegado. Revisa el nuevo shell antes de volver a escribirla.", "stalledDaemonBanner": { @@ -19638,7 +20051,9 @@ }, "quickOpen": { "moreMatchesAvailable": "Puede haber más coincidencias disponibles. Refina tu búsqueda para acotar los resultados.", - "recentValidationFailed": "No se pudieron comprobar los archivos recientes: {{error}}" + "recentValidationFailed": "No se pudieron comprobar los archivos recientes: {{error}}", + "installRipgrepOnRemote": "Instala ripgrep en el host remoto para listar archivos rápidamente respetando .gitignore:", + "scanTooLarge": "El escaneo de Apertura rápida es demasiado amplio ({{reason}})." }, "checksPanel": { "unlinked": { @@ -19651,11 +20066,20 @@ "actionSaveFailed": "No se pudo guardar esta acción. Intenta guardarla de nuevo en Ajustes.", "discard": { "deleteUntrackedFileDescription": "Esto eliminará permanentemente este archivo sin seguimiento. No se puede deshacer.", - "deleteUntrackedFilesDescription": "Esto eliminará permanentemente estos {{count}} archivos sin seguimiento. No se puede deshacer.", + "deleteUntrackedFilesDescription_other": "Esto eliminará permanentemente estos {{count}} archivos sin seguimiento. No se puede deshacer.", "restoreStagedVersionDescription": "Esto restaurará la última versión preparada y descartará la eliminación. No se puede deshacer.", "unstagedChangesDescription": "Esto revertirá los cambios no preparados de este archivo. No se puede deshacer.", "unstagedSelectionIncludingUntrackedDescription": "Esto revertirá los cambios no preparados y eliminará permanentemente cualquier archivo sin seguimiento de esta selección. No se puede deshacer.", - "unstagedFilesIncludingUntrackedDescription": "Esto revertirá los cambios no preparados y eliminará permanentemente cualquier archivo sin seguimiento entre estos {{count}} archivos. No se puede deshacer." + "unstagedFilesIncludingUntrackedDescription_other": "Esto revertirá los cambios no preparados y eliminará permanentemente cualquier archivo sin seguimiento entre estos {{count}} archivos. No se puede deshacer.", + "delete": "Eliminar", + "restore": "Restaurar", + "discard": "Descartar", + "discardAll": "Descartar todo", + "deleteUntrackedTitle_one": "¿Eliminar {{count}} archivo sin seguimiento?", + "deleteUntrackedTitle_other": "¿Eliminar {{count}} archivos sin seguimiento?", + "deleteCount": "Eliminar {{count}}", + "deleteUntrackedFilesDescription_one": "Esto eliminará permanentemente {{count}} archivo sin seguimiento. No se puede deshacer.", + "unstagedFilesIncludingUntrackedDescription_one": "Esto revertirá los cambios no preparados de {{count}} archivo y lo eliminará permanentemente si no tiene seguimiento. No se puede deshacer." }, "unlinkedPr": { "status": "PR #{{number}} desvinculada" @@ -19689,6 +20113,34 @@ "creationUnconfirmed": "Puede que la creación de {{shortLabel}} se haya completado. Actualizando el estado de revisión de la rama...", "withDetail": "No se pudo crear {{shortLabel}}: {{detail}}", "pushFailed": "El push falló. Resuelve el error de push y vuelve a intentarlo." + }, + "model": { + "auto": "Automático", + "configDefault": "Predeterminado de la configuración" + }, + "thinking": { + "off": "Desactivado", + "minimal": "Mínimo", + "low": "Bajo", + "medium": "Medio", + "high": "Alto", + "max": "Máximo", + "xhigh": "Muy alto" + }, + "variables": { + "basePrompt": "El prompt integrado de Orca para esta acción, incluido el contexto que Orca puede recopilar de forma segura.", + "branch": "El nombre de la rama actual del control de versiones.", + "stagedFiles": "Una lista de archivos en staging, separados por saltos de línea, para generar el mensaje de commit.", + "stagedPatch": "El parche de Git en staging usado para generar el mensaje de commit.", + "baseBranch": "La rama de destino seleccionada al crear el PR.", + "currentTitle": "El título del PR introducido en el editor antes de iniciar la generación.", + "currentBody": "La descripción del PR introducida en el editor antes de iniciar la generación.", + "commitSummary": "Una lista de commits de la rama respecto a la base, separados por saltos de línea.", + "changedFiles": "Un resumen de los archivos modificados entre la rama y su base.", + "patch": "El diff de la rama respecto a su base usado para generar los detalles del PR.", + "firstPrompt": "La primera solicitud del usuario en este espacio de trabajo o chat.", + "assistantMessage": "La respuesta inicial del agente, cuando Orca dispone de ella.", + "linkedIssue": "El número del issue de GitHub vinculado a este espacio de trabajo. Vacío si no hay un issue de GitHub vinculado (también en espacios vinculados a GitLab). Usa plantillas con instrucciones: \"Fixes #{linkedIssue}\" por sí solo se convierte en \"Fixes #\" si no hay vínculo." } }, "aiVault": { @@ -19865,7 +20317,11 @@ "picker": { "pasteUnparseable": "Se esperaba una URL de proyecto o owner/number", "ownerLoadFailed": "No se pudieron cargar los proyectos de {{owner}}.", - "organizationsLoadFailed": "Algunas organizaciones no se cargaron ({{failureCount}})." + "organizationsLoadFailed": "Algunas organizaciones no se cargaron ({{failureCount}}).", + "organizations": "Organizaciones", + "listFailed": "No se pudieron listar los proyectos", + "detailsFailed": "No se pudieron cargar los detalles", + "viewFailed": "No se pudo obtener la vista del proyecto" }, "error": { "notFoundState": "No se pudo encontrar este proyecto o vista.", @@ -19898,8 +20354,12 @@ "rateLimited": "Se alcanzó el límite de velocidad de GitHub. Inténtalo de nuevo en unos minutos.", "network": "Error de red — comprueba tu conexión.", "tooLargeUnknownCount": "Esta vista tiene demasiados elementos para mostrarla en Orca. Restringe el filtro de la vista en GitHub.", - "tooLarge": "Esta vista tiene {{itemCount}} elementos, demasiados para mostrarla en Orca. Restringe el filtro de la vista en GitHub.", - "schemaDriftDetail": "No se pudo leer esta vista del proyecto: {{detail}}." + "schemaDriftDetail": "No se pudo leer esta vista del proyecto: {{detail}}.", + "tooLargeCount_one": "Esta vista tiene {{count}} elemento — es demasiado grande para mostrarla en Orca. Restringe el filtro de la vista en GitHub.", + "tooLargeCount_other": "Esta vista tiene {{count}} elementos — es demasiado grande para mostrarla en Orca. Restringe el filtro de la vista en GitHub." + }, + "columns": { + "type": "Tipo" } }, "projectField": { @@ -19986,6 +20446,27 @@ "attachments": { "updateRuntime": "Actualiza el tiempo de ejecución remoto para cambiar los enlaces del espacio de trabajo", "updateRuntimeSafely": "Actualiza el tiempo de ejecución remoto para cambiar de forma segura los enlaces del espacio de trabajo" + }, + "activity": { + "active": "Activo", + "working": "Trabajando", + "monitoring": "Supervisando tareas en segundo plano", + "failed": "Fallido", + "interrupted": "Interrumpido", + "unconfirmed": "No se pudo confirmar", + "done": "Listo", + "inactive": "Inactivo", + "permission": "Necesita permiso", + "unreadLabel": "{{status}} · Sin leer" + }, + "reviewStatus": { + "checksFailed": "Checks de {{review}}: Fallidos", + "checksPassing": "Checks de {{review}}: Correctos", + "checksPending": "Checks de {{review}}: Pendientes", + "closed": "{{review}}: Cerrada", + "draft": "{{review}}: Borrador", + "merged": "{{review}}: Fusionada", + "open": "{{review}}: Abierta" } }, "tabHoverCard": { @@ -20035,7 +20516,9 @@ "preparingAriaLabel": "Preparando actualización. Haz clic para expandir.", "browserSummary": "El navegador de un servidor Orca en segundo plano todavía usa esta aplicación.", "browserGuidance": "Finaliza el proceso que aparece abajo y vuelve a intentarlo: su servidor seguirá funcionando sin navegador. Si otro equipo usa este Mac como host SSH, actualiza Orca en ese equipo para que el navegador pueda pausarse automáticamente durante las actualizaciones." - } + }, + "wslMoveInstallHeld": "Un proyecto se está moviendo a su host WSL. Instala la actualización cuando termine el movimiento.", + "wslMoveUndoInstallHeld": "Un proyecto está volviendo desde su host WSL. Instala la actualización cuando termine." }, "jira": { "savedFilters": { @@ -20062,13 +20545,13 @@ "optionalEmail": "Email de Atlassian (opcional para tokens con alcance)" }, "workspace": { - "count": "{{count}} espacios de trabajo vinculados a {{key}}", "startAnother": "Iniciar un espacio de trabajo nuevo", "empty": "Vincula una incidencia de Jira a un espacio de trabajo o elige otra vista.", "openFailed": "No se pudo abrir el espacio de trabajo vinculado a esta incidencia de Jira.", "mode": "Con espacio de trabajo", "search": "Buscar incidencias vinculadas", - "single": "1 espacio de trabajo vinculado a {{key}}" + "linkedCount_one": "{{count}} espacio de trabajo vinculado a {{key}}", + "linkedCount_other": "{{count}} espacios de trabajo vinculados a {{key}}" }, "prompt": { "dialogTitle": "Copiar prompt desde plantilla", @@ -20453,7 +20936,8 @@ "email": "Conocer tu dirección de correo electrónico", "allSites": "Leer y cambiar todos tus datos en todos los sitios web", "someSites": "Leer y cambiar tus datos en {{hosts}}", - "manySites": "Leer y cambiar tus datos en {{hosts}} y en otros {{count}} sitios" + "manyOtherSites_one": "Leer y cambiar tus datos en {{hosts}} y {{count}} sitio más", + "manyOtherSites_other": "Leer y cambiar tus datos en {{hosts}} y {{count}} sitios más" }, "install": { "title": "¿Agregar {{name}}?", @@ -20483,5 +20967,340 @@ "math": { "scrollDisplayEquation": "Desplazar ecuación en bloque" } + }, + "runtime": { + "health": { + "available": "Conectado", + "connecting": "Conectando", + "disconnected": "Desconectado", + "error": "Requiere atención", + "mixed": "Mixto", + "local": "Local", + "repair": "Requiere volver a emparejar", + "update": "Requiere actualización" + }, + "compat": { + "compatible": "El cliente y el servidor del entorno de ejecución son compatibles.", + "clientTooOld": "Este cliente de Orca es demasiado antiguo para el servidor seleccionado. Actualiza Orca en este equipo. Protocolo del cliente: {{clientProtocol}}; el servidor requiere el protocolo de cliente {{requiredProtocol}}.", + "serverTooOld": "El servidor de Orca seleccionado es demasiado antiguo para este cliente. Actualiza Orca en el servidor. Protocolo del servidor: {{serverProtocol}}; el cliente requiere el protocolo de servidor {{requiredProtocol}}." + } + }, + "native": { + "about": { + "gpu": { + "unknownStatus": "Estado no disponible", + "enabled": "Activado", + "disabled": "Desactivado", + "unavailable": "No disponible", + "safeMode": "Desactivada (modo gráfico seguro)", + "software": "Renderizado por software", + "unknown": "Desconocido ({{status}})", + "summary": "Aceleración GPU: {{status}}" + } + }, + "dialog": { + "importCookies": "Importar cookies", + "spaceTitle": "Espacio de Orca (beta)", + "dashboardTitle": "Panel de agentes de Orca", + "cookieFiles": "Archivos de cookies", + "allFiles": "Todos los archivos", + "importPetBundle": "Seleccionar un paquete .codex-pet", + "pickPet": "Seleccionar mascota", + "petImage": "Imagen de mascota", + "importWarpTheme": "Importar tema de Warp", + "warpThemeYaml": "YAML de tema de Warp", + "importWarpFolder": "Importar carpeta de temas de Warp", + "images": "Imágenes", + "repoIconImages": "Imágenes de icono del repositorio", + "audio": "Audio" + } + }, + "taskProviders": { + "linear": { + "updateAccess": "Actualizar acceso", + "addAccess": "Agregar acceso Linear", + "fetchMore": "Cargar más", + "connectionFailed": "La conexión falló", + "listLabel": "Lista de Linear", + "projectsLoadFailed": "No se pudieron cargar los proyectos.", + "projectNotFound": "No se encontró el proyecto.", + "projectLoadFailed": "No se pudo cargar el proyecto.", + "projectIssuesLoadFailed": "No se pudieron cargar los issues del proyecto.", + "viewsLoadFailed": "No se pudieron cargar las vistas.", + "viewContentsLoadFailed": "No se pudo cargar el contenido de la vista.", + "issuesLoadFailed": "No se pudieron cargar los issues de Linear.", + "apiKeyHint": "Pega una clave API personal del espacio de trabajo de Linear que quieras usar en Orca. Si ya está conectado, Orca sustituirá la clave guardada.", + "remoteKeyStorage": "Esta clave se guarda en el entorno de ejecución remoto activo.", + "localKeyStorage": "Las claves del entorno de ejecución local se guardan en este dispositivo con el almacenamiento cifrado de Electron cuando está disponible.", + "commentsLoadFailed": "No se pudieron cargar los comentarios.", + "updateWorkspaceAccess": "Actualizar el acceso a Linear para {{workspace}}", + "workspaceApiKeyHint": "Pega una clave API personal de {{workspace}}. Si ya está conectado, Orca sustituirá la clave guardada.", + "connect": "Conectar", + "descriptionUpdateFailed": "No se pudo actualizar la descripción", + "titleUpdateFailed": "No se pudo actualizar el título", + "truncated": { + "issues_one": "Se muestra {{count}} issue, el primero de la lista. Busca o abre Linear para ver la lista completa.", + "issues_other": "Se muestran los primeros {{count}} issues. Busca o abre Linear para ver la lista completa.", + "projectIssues_one": "Se muestra {{count}} issue del proyecto, el primero de la lista. Busca o abre Linear para ver la lista completa.", + "projectIssues_other": "Se muestran los primeros {{count}} issues del proyecto. Busca o abre Linear para ver la lista completa.", + "projects_one": "Se muestra {{count}} proyecto, el primero de la lista. Busca o abre Linear para ver la lista completa.", + "projects_other": "Se muestran los primeros {{count}} proyectos. Busca o abre Linear para ver la lista completa.", + "viewIssues_one": "Se muestra {{count}} issue de la vista, el primero de la lista. Busca o abre Linear para ver la lista completa.", + "viewIssues_other": "Se muestran los primeros {{count}} issues de la vista. Busca o abre Linear para ver la lista completa.", + "views_one": "Se muestra {{count}} vista, la primera de la lista. Busca o abre Linear para ver la lista completa.", + "views_other": "Se muestran las primeras {{count}} vistas. Busca o abre Linear para ver la lista completa." + } + }, + "jira": { + "connectionFailed": "La conexión falló", + "remoteTokenStorage": "Tu token se envía al entorno de ejecución remoto seleccionado y se almacena allí con el cifrado que admita.", + "localTokenStorage": "Tu token se almacena localmente y se cifra si el almacenamiento del entorno de ejecución local lo admite." + }, + "errors": { + "jira": { + "createFailed": "No se pudo crear el issue.", + "commentFailed": "No se pudo agregar el comentario.", + "notConnected": "Sin conexión a Jira.", + "titleRequired": "El título es obligatorio.", + "labelsConflict": "Proporciona labels o labelOperations, pero no ambos.", + "updateFailed": "No se pudo actualizar el issue.", + "credentialsRequired": "La URL del sitio, el correo y el token de API son obligatorios.", + "projectRequired": "El proyecto es obligatorio.", + "issueTypeRequired": "El tipo de issue es obligatorio.", + "issueKeyRequired": "La clave del issue es obligatoria.", + "updatesRequired": "El objeto de actualización es obligatorio.", + "commentBodyRequired": "El contenido del comentario es obligatorio.", + "invalidSiteUrl": "Introduce una URL válida del sitio de Jira.", + "passwordRequired": "La contraseña es obligatoria.", + "personalTokenRequired": "El token de acceso personal es obligatorio.", + "apiTokenRequired": "El token de API es obligatorio.", + "connectionFailed": "Error de conexión.", + "invalidSiteIdentity": "Introduce una URL de Jira HTTP o HTTPS sin credenciales.", + "missingProjectIdentity": "Jira devolvió un proyecto sin ID o clave.", + "invalidIssuePage": "Jira devolvió una página de issues no válida.", + "incompleteIssuePage": "Jira devolvió una página de issues incompleta.", + "repeatedIssueToken": "Jira devolvió un token de página de issues no válido o repetido.", + "issueSearchLimit": "La búsqueda de issues de Jira superó el límite de páginas. Selecciona un proyecto mediante JQL.", + "invalidProjectPage": "Jira devolvió una página de proyectos no válida.", + "incompleteProjectPage": "Jira devolvió una página de proyectos incompleta.", + "projectListLimit": "La lista de proyectos de Jira superó el límite de páginas. Selecciona un proyecto mediante JQL.", + "invalidCloudId": "El sitio no proporcionó un ID válido de Atlassian Cloud." + }, + "linear": { + "notConnected": "Sin conexión a Linear", + "createFailed": "Error al crear en Linear", + "createdButUnavailable": "El issue se creó, pero no se pudo recuperar", + "updateFailed": "Error al actualizar en Linear", + "commentFailed": "No se pudo crear el comentario", + "projectCreateFailed": "Error al crear el proyecto de Linear", + "noApiKey": "No hay ninguna clave API guardada.", + "workspaceAuthExpired": "La autenticación de Linear ha caducado para este espacio de trabajo.", + "projectNameRequired": "El nombre del proyecto es obligatorio", + "projectIdRequired": "El ID del proyecto es obligatorio", + "projectNotFound": "No se encontró el proyecto", + "viewIdRequired": "El ID de la vista personalizada es obligatorio", + "viewHasNoIssues": "La vista personalizada no contiene issues", + "viewHasNoProjects": "La vista personalizada no contiene proyectos" + } + } + }, + "workspaceOptions": { + "activeFilterCount_one": "{{count}} filtro", + "activeFilterCount_other": "{{count}} filtros" + }, + "editorConflicts": { + "kind": { + "addedByUs": "Añadido por nosotros", + "bothAdded": "Añadido por ambos", + "deletedByUs": "Eliminado por nosotros", + "addedByThem": "Añadido por ellos", + "bothDeleted": "Eliminado por ambos", + "bothModified": "Modificado por ambos", + "deletedByThem": "Eliminado por ellos" + }, + "resolvedBanner": "Conflicto resuelto localmente · {{kind}}", + "hint": { + "addedByUs": "Evalúa si conservar el archivo añadido", + "bothModified": "Resuelve los conflictos señalados por los marcadores", + "addedByThem": "Revisa el archivo añadido antes de conservarlo", + "bothDeleted": "Resuelve el conflicto en Git o restaura una de las versiones antes de editar", + "deletedByThem": "Decide si conservar el archivo o aceptar su eliminación", + "deletedByUs": "Decide si restaurar el archivo", + "bothAdded": "Elige qué versión conservar o combínalas" + }, + "renamedFrom": "Nombre anterior: {{path}}", + "snapshotCapturedAt": "Instantánea capturada a las {{time}}.", + "unresolvedBanner": "Conflicto sin resolver · {{kind}}" + }, + "stats": { + "usageBreakdown": { + "turns_one": "{{count}} turno", + "events_one": "{{count}} evento", + "sessions_one": "{{count}} sesión", + "events_other": "{{count}} eventos", + "sessions_other": "{{count}} sesiones", + "turns_other": "{{count}} turnos" + } + }, + "github": { + "viewed": { + "markFile": "Marcar {{path}} como visto", + "unmarkFile": "Desmarcar {{path}} como visto" + } + }, + "wslMove": { + "entry": { + "hostRow": "Mover proyectos de esta distro…", + "projectMenu": "Mover al host {{distro}}…" + }, + "blockers": { + "title": "Antes de que estos proyectos puedan moverse", + "inProjects": "En {{names}}", + "skipOne": "Dejar {{name}} fuera de este traslado", + "skipMany": "Dejar estos {{n}} proyectos fuera de este traslado" + }, + "title": "Mover proyectos al host {{distro}}", + "loading": "Comprobando los proyectos de {{distro}}…", + "runningTitle": "Moviendo al host {{distro}}", + "preview": { + "counts": "Proyectos: {{projects}} · Espacios de trabajo: {{workspaces}} · Terminales: {{terminals}} · Chats: {{chats}}", + "whatHappens": "Tus archivos se quedan donde están. Las terminales se reinician en la misma carpeta; se conservan su salida, el historial del shell y las conversaciones con agentes.", + "projects": "Proyectos en {{distro}}", + "folderBadge": "Carpeta", + "notMoving": "No se mueve", + "checking": "Comprobando los proyectos seleccionados…", + "checkAgain": "Verificar de nuevo", + "moveOne": "Mover 1 proyecto", + "moveMany": "Mover {{n}} proyectos", + "heldByHost": "Ya está en el host {{distro}}.", + "changed": "Se movió antes y luego una versión anterior de Orca lo cambió aquí. No se vuelve a mover.", + "chatsStay": "Los chats existentes se quedan en este equipo. Los chats nuevos de este proyecto se inician en el host WSL.", + "browserLoginsConflict": "Las sesiones iniciadas en el navegador no se trasladarán, porque el perfil del navegador del host ya está en uso. Vuelve a iniciar sesión en las pestañas del navegador del host después del traslado.", + "browserLoginsNotCarried": "Las sesiones iniciadas en el navegador no se trasladarán a este host. Vuelve a iniciar sesión en sus pestañas del navegador después del traslado." + }, + "cancel": "Cancelar", + "progress": { + "bytes": "{{sent}} de {{total}}", + "tooLate": "Ya es tarde para cancelar: el host ya está haciendo el cambio. Mantén Orca abierto hasta que termine.", + "switching": "El cambio no se puede cancelar. Mantén Orca abierto hasta que termine.", + "readOnly": "Estos proyectos son de solo lectura mientras se mueven. Puedes cancelar hasta que empiece el cambio.", + "cancelUntilSwitch": "Puedes cancelar hasta que empiece el cambio.", + "closeKeepsGoing": "Cerrar este diálogo no detiene el traslado; se volverá a abrir cuando termine.", + "cancelling": "Cancelando…", + "cancel": "Cancelar traslado" + }, + "result": { + "movedTitle": "Movido al host {{distro}}", + "resetTitle": "No se movió nada", + "waitingTitle": "Esperando al host {{distro}}", + "earlierMoveTitle": "Un traslado anterior terminó primero", + "refusedTitle": "Proyectos no movidos", + "reloadCheckpointRefused": "Orca no pudo guardar una copia de los archivos sin guardar, así que la ventana no se recargó. Cierra este diálogo, guarda o cierra esos archivos y luego usa Recargar ahora en el aviso que sigue abierto.", + "reloadVetoed": "Algo impidió que la ventana se recargara. Cierra este diálogo, guarda tu trabajo y luego usa Recargar ahora en el aviso que sigue abierto.", + "reloadFailed": "La ventana no se recargó. Inténtalo de nuevo.", + "moved": "Recarga esta ventana para ver los proyectos en el host {{distro}}. Orca guarda una copia de los archivos sin guardar antes de recargar.", + "automationsPendingOne": "Una automatización está desactivada en el host por ahora. Orca sigue pidiendo al host que la vuelva a activar.", + "automationsPendingMany": "{{n}} automatizaciones están desactivadas en el host por ahora. Orca sigue pidiendo al host que las vuelva a activar.", + "undoHint": "¿Cambiaste de idea? Después de recargar, la barra lateral muestra estos proyectos como “Movido al host de {{distro}}”. Elige “Usar de nuevo en este equipo” allí para recuperarlos tal como estaban antes del traslado.", + "reset": "El traslado se detuvo y todo volvió a su sitio. Los proyectos funcionan en este equipo como antes; las terminales en pausa se reinician al abrirlas.", + "resetReason": "Por qué se detuvo: {{detail}}", + "waiting": "Puede que el traslado haya llegado al host {{distro}}, pero el host no responde. Estos proyectos siguen en solo lectura aquí hasta que responda. Conecta el host en Configuración, vuelve a abrir este diálogo e inicia un traslado: Orca primero termina o deshace este.", + "reloading": "Recargando…", + "reload": "Recargar ahora", + "close": "Cerrar", + "review": "Volver a los proyectos", + "browserLoginsHostUnknown": "No se copiaron las sesiones del navegador, porque Orca no pudo identificar el perfil del navegador del host. Vuelve a iniciar sesión en las pestañas del navegador del host.", + "browserLoginsConflict": "No se copiaron las sesiones del navegador, porque el perfil del navegador del host ya está en uso. Vuelve a iniciar sesión en las pestañas del navegador del host.", + "browserLoginsNotCopied": "No se copiaron las sesiones del navegador al host. Vuelve a iniciar sesión en las pestañas del navegador del host." + }, + "runtime": { + "label": "Entorno de ejecución del proyecto", + "description": "Este proyecto se ejecuta en {{distro}} a través de este equipo. Muévelo al host {{distro}} para ejecutarlo allí.", + "move": "Mover proyecto" + }, + "unfinished": { + "one": "Una automatización movida al host {{distro}} sigue desactivada. Orca sigue pidiendo al host que la vuelva a activar.", + "many": "{{n}} automatizaciones movidas al host {{distro}} siguen desactivadas. Orca sigue pidiendo al host que las vuelva a activar." + }, + "refusal": { + "previewFailed": "Orca no pudo comprobar estos proyectos. Inténtalo de nuevo.", + "startFailed": "Orca perdió el contacto con el traslado. Vuelve a abrir este diálogo para ver en qué punto está.", + "unavailable": "Mover proyectos a un host WSL no está disponible en esta ventana.", + "alreadyRunning": "Ya hay un traslado a {{distro}} en curso. Espera a que termine e inténtalo de nuevo.", + "alreadyInFlightPreview": "Un traslado de {{distro}} todavía está terminando. Al iniciar este traslado, Orca primero lo termina o lo deshace cuando puede.", + "alreadyInFlight": "Un traslado de {{distro}} todavía está terminando, así que este no se inició. Mantén conectado el host {{distro}} e inténtalo de nuevo más tarde.", + "nothingNew": "Estos proyectos ya están en el host {{distro}}.", + "destinationChanged": "Proyectos anteriores de {{distro}} se movieron a otro host WSL. Conecta ese host para mover más.", + "hostUnavailable": "El host {{distro}} no está conectado. Conéctalo en Configuración e inténtalo de nuevo.", + "hostUpdateRequired": "El host {{distro}} usa una versión anterior de Orca. Actualízalo en Configuración e inténtalo de nuevo.", + "terminalsBlocked": "Algunas terminales, agentes o automatizaciones de estos proyectos están ocupados. No se movió nada.", + "exportIncomplete": "Parte del estado guardado de estos proyectos aún no se puede mover, así que no se movió nada:", + "exportIncompletePreview": "Parte del estado guardado de estos proyectos aún no se puede mover:", + "tooLarge": "Estos proyectos tienen demasiado estado guardado para moverlos de una vez. Mueve menos proyectos cada vez.", + "pauseFailed": "Orca no pudo pausar las terminales de estos proyectos, así que no se movió nada. Las terminales en pausa se reinician al abrirlas. Inténtalo de nuevo.", + "scopeChanged": "Un proyecto cambió mientras se preparaba el traslado, así que no se movió nada. Revisa los proyectos e inténtalo de nuevo.", + "cancelled": "Traslado cancelado. No se movió nada.", + "finishedEarlierMove": "Orca terminó primero un traslado anterior a {{distro}}. Recarga la ventana y vuelve a iniciar este traslado." + }, + "step": { + "preparing": "Preparando", + "pausingTerminals": "Pausando terminales", + "copying": "Copiando", + "switching": "Cambiando", + "finishing": "Terminando", + "done": "Listo" + }, + "blocker": { + "agentWorkingOne": "Un agente está trabajando o esperando una respuesta", + "agentWorkingMany": "{{n}} agentes están trabajando o esperando una respuesta", + "processRunningOne": "Una terminal está ejecutando un programa", + "processRunningMany": "{{n}} terminales están ejecutando un programa", + "agentNotResumableOne": "Un agente no se podrá reanudar después del traslado", + "agentNotResumableMany": "{{n}} agentes no se podrán reanudar después del traslado", + "unverifiableOne": "Orca no puede comprobar una terminal en este momento", + "unverifiableMany": "Orca no puede comprobar {{n}} terminales en este momento", + "automationRunningOne": "Hay una ejecución de automatización activa", + "automationRunningMany": "Hay {{n}} ejecuciones de automatización activas", + "dispatchRunningOne": "Hay una tarea de agente en curso", + "dispatchRunningMany": "Hay {{n}} tareas de agente en curso", + "scrollbackTooLargeOne": "Una terminal tiene demasiado historial de salida para moverla", + "scrollbackTooLargeMany": "{{n}} terminales tienen demasiado historial de salida para moverlas" + }, + "blockerHint": { + "agentWorking": "Deja que termine, o detenlo en su terminal, y vuelve a comprobarlo.", + "processRunning": "Detén el programa (por ejemplo, un servidor de desarrollo o un editor) y vuelve a comprobarlo.", + "agentNotResumable": "Sal del agente en su terminal y vuelve a comprobarlo.", + "unverifiable": "Espera un momento y vuelve a comprobarlo. No se detiene nada para hacer el traslado.", + "wait": "Espera a que termine y vuelve a comprobarlo.", + "scrollbackTooLarge": "Borra la salida de esas terminales y vuelve a comprobarlo." + }, + "scopeRefused": { + "windowsDrive": "Su carpeta está en una unidad de Windows, así que se queda en este equipo.", + "mixedLocations": "Algunas de sus carpetas están fuera de esta distro, así que se queda en este equipo.", + "notLocal": "Ya se ejecuta en otro host.", + "other": "No se puede mover." + }, + "reloadToast": { + "title": "Recarga para terminar el traslado" + }, + "orchestrator": { + "showTerminal": "Mostrar terminal", + "moveAgain": "Mover de nuevo", + "checkAgain": "Verificar de nuevo", + "deferred": "Terminando tu traslado al host {{distro}}: algunas terminales siguen ocupadas.", + "stuck": "Un traslado anterior al host {{distro}} todavía no ha terminado de asentarse.", + "declined": "El traslado está en pausa porque devolviste estos proyectos a este equipo.", + "doneToast": "Proyectos movidos al host {{distro}}", + "terminalGone": "Esa terminal ya no está abierta en esta ventana. Verifica de nuevo para actualizar.", + "blocker": "{{title}}. {{hint}}", + "paused": "El traslado de proyectos al host {{distro}} está en pausa: {{reason}}.", + "pausedReason": { + "exportIncomplete": "parte del estado guardado aún no se puede trasladar", + "manifestTooLarge": "hay más estado guardado del que cabe en un traslado", + "hostUpdate": "primero hay que actualizar el host", + "attemptsExhausted": "no se completó después de varios intentos" + }, + "finishPending": "Un traslado anterior al host {{distro}} ya terminó allí. Orca lo termina aquí cuando se reinicie, o ahora con Verificar de nuevo." + } } } diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 55aec2a3883e..304e564c1071 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -189,6 +189,15 @@ "empty": "Aucune extension n'est activée pour ce profil", "visitWebStore": "Visiter le Chrome Web Store", "manage": "Gérer les extensions" + }, + "viewport": { + "mobile-s": "Mobile S — 320 × 568", + "mobile-m": "Mobile M — 375 × 667", + "mobile-l": "Mobile L — 425 × 812", + "tablet": "Tablette — 768 × 1024", + "laptop": "Ordinateur portable — 1024 × 768", + "laptop-l": "Grand ordinateur portable — 1440 × 900", + "desktop": "Ordinateur de bureau — 1920 × 1080" } }, "githubChecks": { @@ -283,11 +292,15 @@ "system": "Système", "english": "English", "chinese": "中文(简体)", + "chineseTraditional": "繁體中文(台灣)", "korean": "한국어", "japanese": "日本語", "spanish": "Español", "french": "Français", - "portuguese": "Português (Brasil)" + "portuguese": "Português (Brasil)", + "russian": "Русский", + "turkish": "Türkçe", + "german": "Deutsch" }, "statusBar": { "claudeToggleDescription": "Afficher l'utilisation des tokens et des coûts de Claude pour l'espace de travail actif.", @@ -519,7 +532,8 @@ "permissionOverrideMore": "et {{count}} de plus", "permissionOverrideMore_one": "et {{count}} de plus", "permissionOverrideMore_other": "et {{count}} de plus", - "permissionOverridesUse": "Utiliser {{mode}}" + "permissionOverridesUse": "Utiliser {{mode}}", + "approveForMe": "approuver pour moi" }, "followSymlinkedDirectoriesKeywords": { "symlink": "lien symbolique", @@ -550,6 +564,34 @@ "actionPermissions": { "sameAsAgent": "Comme {{agent}}" } + }, + "ssh": { + "status": { + "disconnected": "Déconnecté", + "connecting": "Connexion…", + "auth-failed": "Échec de l'authentification", + "connected": "Connecté", + "reconnection-failed": "Échec de la reconnexion", + "deploying-relay": "Déploiement du relais…", + "reconnecting": "Reconnexion…" + } + }, + "mcp": { + "workspace": "Espace de travail", + "inspectFailed": "Impossible d’inspecter {{directory}}.", + "unreadable": "Illisible", + "notFound": "Introuvable", + "invalidJson": "JSON invalide", + "noServers": "Aucun serveur", + "httpServer": "Serveur HTTP", + "stdioServer": "Serveur stdio", + "invalidServer": "Serveur invalide", + "serverCount_one": "{{count}} serveur", + "serverCount_other": "{{count}} serveurs", + "claudeWorkspace": "Espace de travail Claude" + }, + "shortcuts": { + "parseFailed": "Impossible d’analyser le raccourci." } }, "menu": { @@ -1657,9 +1699,6 @@ "3fdf777817": "Ouvrir sur GitHub", "c43fe79ee0": "Copier le lien GitHub", "0caac1a18f": "Démarrer un espace de travail à partir de la PR", - "8223320f8d": "mis à jour", - "10ef1afb8e": "· mis à jour", - "55962099bc": "a ouvert cette issue", "0ab4664a8b": "Démarrer un espace de travail à partir de l'issue", "36182aa57f": "Démarrer un nouvel espace de travail", "fe6ff12dc2": "Plus d'actions d'espace de travail pour l'issue", @@ -1732,8 +1771,6 @@ "52b20b56f7": "Description", "4d555d3796": "Modifier la description", "9df4e74bdf": "Enregistrer", - "0ae387d8ca": "par", - "228e2f59d3": "Résolu", "a154ec5224": "Ouvrir le commentaire sur GitHub", "bca8eb39ac": "Répondre au commentaire", "68cb993d61": "résolu", @@ -1749,13 +1786,11 @@ "d43736d09c": "Contrôles du contexte de code", "bd7be7b1fd": "commentaire L", "db61d76cd5": "Chargement du contexte de code…", - "f2d02cdf8c": "fichiers consultés", "1257d1435d": "Afficher l'arborescence des fichiers", "a341343303": "Commentaire de review ajouté.", "d1fa2cf888": "Impossible de commenter sans le SHA head de la PR.", "829674460a": "Diff indisponible car les SHA des commits de la PR manquent.", "af924014f8": "Consulté", - "2d89a38d9d": "{{value0}} {{value1}} comme consultés", "70e84e3d0b": "Aucun reviewer correspondant.", "1ffce94a8b": "Tous les autres", "c2b21818e1": "Suggestions", @@ -1790,8 +1825,6 @@ "ec5c4b3ab2": "Rouvrir la PR", "21860b58d0": "Fermer la pull request", "5932578f51": "Le merge exige un dépôt local enregistré", - "e2bf3e41a9": "comment", - "28d0d3374f": "thread", "080d071d48": "Répondre à @{{value0}}", "86f809e2ce": "Répondre dans ce fil de review", "136542c9ba": ":L{{value0}}", @@ -1821,7 +1854,9 @@ "from": "de", "to": "vers", "activity": "Activité", - "noActivity": "Aucune activité pour l'instant." + "noActivity": "Aucune activité pour l'instant.", + "pullRequestReference": "PR #{{number}}", + "issueReference": "issue #{{number}}" }, "checkActionRequiredHint": "Nécessite une action manuelle sur GitHub (par exemple, approuver l'exécution) pour débloquer le merge.", "e15a8b77ef": "Aucun détail en ligne n'est disponible pour cette vérification.", @@ -1835,8 +1870,15 @@ "09d67a0f9b": "Échec de la fermeture de la pull request", "88809e79db": "Échec de la réouverture de la pull request", "00f55cc17b": "L'accès au dépôt est indisponible pour cette pull request.", - "reactionCountSingular": "{{count}} {{reaction}} réaction", - "reactionCountPlural": "{{count}} {{reaction}} réactions" + "reactionCount_one": "{{count}} réaction « {{reaction}} »", + "reactionCount_other": "{{count}} réactions « {{reaction}} »", + "filesViewed_one": "{{viewed}} / {{count}} fichier consulté", + "filesViewed_other": "{{viewed}} / {{count}} fichiers consultés", + "updatedRelativeTime": "mis à jour {{time}}", + "authorOpenedThisIssue": " a ouvert cette issue", + "middotUpdatedRelativeTime": "· mis à jour {{time}}", + "resolvedThreadBy": "Discussion résolue de {{author}}", + "resolvedCommentBy": "Commentaire résolu de {{author}}" }, "GitLabItemDialog": { "65e784c1f1": "Rouvrir", @@ -1892,14 +1934,15 @@ "f23ea85341": "résolu", "6de8ce0cc6": "{{value0}} requis", "22511537d2": "Approuvé", - "00f3bab87b": " sur {{value0}} requis", "3a051b8ade": "Élément de travail", "32f8bef818": "Aucune sortie de log.", "4168eb2c51": "Résoudre", "commentTooLarge": "Le commentaire est trop volumineux pour être envoyé sans risque.", "gitlabActionFailed": "L'action GitLab a échoué.", - "approvalsRemainingSingular": "Il reste {{count}} approbation", - "approvalsRemainingPlural": "Il reste {{count}} approbations" + "approvalsRemainingOfRequired_one": "Il reste {{count}} approbation sur les {{required}} requises", + "approvalsRemainingOfRequired_other": "Il reste {{count}} approbations sur les {{required}} requises", + "approvalsRemaining_one": "Il reste {{count}} approbation", + "approvalsRemaining_other": "Il reste {{count}} approbations" }, "JiraIssueWorkspace": { "b0b92666c9": "Commentaire", @@ -1924,14 +1967,11 @@ "69da9a208c": "Ouvrir dans Jira", "fa132c8aed": "Échec de l'ajout du commentaire.", "ea21952aa3": "Échec de la mise à jour du ticket Jira.", - "6c41a9bcea": "Échec de la copie : {{value0}}", - "2ff69a3545": "{{value0}} copié", "666cfdd835": "Inconnu", "ef21405c6d": "Ticket Jira", "commentTooLarge": "Le commentaire est trop volumineux pour être envoyé sans risque." }, "Landing": { - "76a95f7f47": "Créer", "f9eaa9e12d": "Ajouter un projet", "6ca6ff404e": "ORCA", "520304a067": "Logo Orca", @@ -1947,7 +1987,12 @@ "0d0ace8861": "Mettre une étoile sur GitHub", "ec43b38ba7": "Étoile ajoutée sur GitHub", "157bb5ecbb": "Ouvrir GitHub", - "preflightDismiss": "Ignorer" + "preflightDismiss": "Ignorer", + "moveUpWorkspace": "Sélectionner l’espace de travail précédent", + "moveDownWorkspace": "Sélectionner l’espace de travail suivant", + "installGit": "Installer Git", + "installGitHubCli": "Installer GitHub CLI", + "learnMore": "En savoir plus" }, "LinearIssueMarkdownDescriptionEditor": { "d9c47069ef": "Markdown", @@ -1972,14 +2017,12 @@ "LinearIssueTextEditor": { "947ba2d6f4": "pour enregistrer", "04d73b72dc": "Titre du ticket", - "e8ff595db3": "Échec de la mise à jour de {{value0}}", "1e08a1ec80": "Le titre est obligatoire" }, "LinearIssueWorkspace": { "ad5dec37b7": "Prévisualisez, modifiez et démarrez le travail depuis le ticket sélectionné.", "c23e79e5c0": "Actions", "b0eac92d85": "Réessayer", - "fabbd3f974": "a mis à jour le ticket ·", "543970c87a": "Activité", "df4c86ed12": "Fermer", "7a4997d8bb": "Fermer l'aperçu du ticket Linear", @@ -2003,11 +2046,8 @@ "b25e453c9d": "Échec de la création du sous-ticket", "aeed19d003": "{{value0}} créé", "9a1317cdd3": "Échec du chargement du sous-ticket", - "9bcbaa2737": "Échec de la copie : {{value0}}", - "7835483c43": "{{value0}} copié", "61f424f8ca": "Ticket Linear", "ca8778c124": "Inconnu", - "8a33c85e9c": "Quelqu'un", "65239a714b": "Linear", "76ffd3c937": "Recherchez un projet à ajouter.", "c11b4e3cc2": "Aucun projet trouvé.", @@ -2018,7 +2058,10 @@ "moreWorkspaceActions": "Plus d'actions d'espace de travail pour l'issue", "startNewWorkspace": "Démarrer un nouvel espace de travail", "workspaceSection": "Espace de travail", - "noWorkspaceYet": "Aucun pour l'instant" + "noWorkspaceYet": "Aucun pour l'instant", + "issueDescriptionLabel": "Description de l’issue", + "namedUserUpdatedIssue": "{{name}} a mis à jour l’issue · {{time}}", + "someoneUpdatedIssue": "Quelqu’un a mis à jour l’issue · {{time}}" }, "LinearItemDrawer": { "04008e6c46": "Démarrer un espace de travail à partir de l'issue", @@ -2054,7 +2097,9 @@ "openAttachedWorkspace": "Ouvrir l'espace de travail associé à l'issue", "openWorkspace": "Ouvrir l'espace de travail", "moreWorkspaceActions": "Plus d'actions d'espace de travail pour l'issue", - "startNewWorkspace": "Démarrer un nouvel espace de travail" + "startNewWorkspace": "Démarrer un nouvel espace de travail", + "setEstimate": "Définir l’estimation", + "estimateValue": "Estimation {{estimate}}" }, "NewWorkspaceComposerCard": { "reuseExistingBranch": "Réutiliser la branche", @@ -2116,7 +2161,22 @@ "addRemoteOrcaServer": "Ajouter un serveur Orca distant", "addRemoteOrcaServerHint": "Appairer un autre runtime Orca", "hostConnectionFailed": "Échec de la connexion", - "defaultBranchUpdateFailed": "Impossible de mettre à jour la branche par défaut du projet. Essayer à nouveau." + "defaultBranchUpdateFailed": "Impossible de mettre à jour la branche par défaut du projet. Essayer à nouveau.", + "connect": "Se connecter", + "reconnect": "Reconnecter", + "setupConfigDefaultTabs": "Commandes des onglets par défaut", + "setupConfigSetupAndDefaultTabs": "Setup et commandes des onglets par défaut", + "setupConfigSetupScript": "Script de setup", + "runDefaultTabCommands": "Exécuter les commandes des onglets par défaut", + "runSetupAndDefaultTabCommands": "Exécuter le setup et les commandes des onglets par défaut", + "runSetupCommand": "Exécuter la commande de setup", + "askRunDefaultTabCommands": "Exécuter les commandes des onglets par défaut maintenant ?", + "askRunSetupAndDefaultTabCommands": "Exécuter le setup et les commandes des onglets par défaut maintenant ?", + "askRunSetup": "Exécuter le setup maintenant ?", + "runSetupNow": "Exécuter le setup maintenant", + "runCommandsNow": "Exécuter les commandes maintenant", + "skipForNow": "Ignorer pour le moment", + "skipCommands": "Ignorer les commandes" }, "NewWorkspaceComposerModal": { "createWorktree": "Créer un worktree", @@ -2210,9 +2270,6 @@ "778683ec84": "Description", "da9aaa8bcf": "Modifier la description", "4a337ac05f": "Enregistrer", - "169a93b29a": "mis à jour", - "3c891789f6": "par", - "f4fe47c2bb": "Résolu", "0ac19bb52e": "Ouvrir le commentaire sur GitHub", "d6c6679de7": "Répondre au commentaire", "76b2a0ac5b": "résolu", @@ -2220,7 +2277,6 @@ "6885c619e7": "Impossible de répondre sans chemin de dépôt.", "d94810f652": "Échec de la mise à jour de la description.", "9b4190dc98": "Description mise à jour.", - "89e80af1c7": "fichiers consultés", "319cf2d54b": "Afficher l'arborescence des fichiers", "eff839f438": "Commentaire de review ajouté.", "d8c3ba91c4": "Impossible de commenter sans le SHA head de la PR.", @@ -2258,8 +2314,6 @@ "9d5425918e": "Rouvrir la PR", "96d013ed28": "Fermer la pull request", "eca289e593": "Le merge exige un dépôt local enregistré", - "e01e34f5fa": "comment", - "345b68254c": "thread", "31a7b202f2": "Répondre à @{{value0}}", "408e634fbb": "Répondre dans ce fil de review", "34b9f7c264": ":L{{value0}}", @@ -2281,7 +2335,19 @@ "4b8ae7303f": "Échec du chargement du diff.", "closePullRequestFailed": "Échec de la fermeture de la pull request", "reopenPullRequestFailed": "Échec de la réouverture de la pull request", - "diffLoadTimedOut": "Délai dépassé lors du chargement de ce diff." + "diffLoadTimedOut": "Délai dépassé lors du chargement de ce diff.", + "filesViewed_one": "{{viewed}} / {{count}} fichier consulté", + "filesViewed_other": "{{viewed}} / {{count}} fichiers consultés", + "updatedRelativeTime": "mis à jour {{time}}", + "resolvedThreadBy": "Discussion résolue de {{author}}", + "resolvedCommentBy": "Commentaire résolu de {{author}}", + "mentionSource": { + "prAuthor": "Auteur de la PR", + "issueAuthor": "Auteur de l'issue", + "commenter": "Auteur de commentaire", + "participant": "Participant", + "teamMember": "Membre de l'équipe" + } }, "QuickOpen": { "1dbd3f59ff": "Déplacer", @@ -2295,13 +2361,12 @@ "9e97f08d0f": "Rechercher un fichier à ouvrir", "ec31e058f7": "Accéder au fichier", "73b44e7bde": "Copier la commande d'installation", - "1cf8561ab4": "sur le remote pour activer un listage rapide respectant .gitignore :", - "5d80dc39bb": "ripgrep", - "2ca749c15d": "Installer", - "4725b0e931": "Scan Quick Open trop volumineux (", - "b227d88520": "{{value0}} fichiers trouvés", "995be8ea22": "Copier", - "cf144856dc": "Copied" + "cf144856dc": "Copied", + "filesFound_one": "{{count}} fichier trouvé", + "filesFound_other": "{{count}} fichiers trouvés", + "hostCouldNotOpenPath": "L’hôte n’a pas pu ouvrir ce chemin de fichier.", + "chooseFileNotDirectory": "Choisissez un fichier plutôt qu’un répertoire." }, "SelectedTextCopyMenu": { "9b40d7b018": "Copier" @@ -2319,7 +2384,6 @@ "TaskPage": { "ff69a30681": "Annuler", "8ff6fdc368": "Création…", - "fc0d8a1fa4": "pour valider.", "919a20dd5b": "Saisissez {{value0}}", "56cdb413a2": "Valeurs séparées par des virgules", "1f0fce91e3": "Sélectionner {{value0}}", @@ -2367,14 +2431,9 @@ "bdebffcbfe": "Créez un projet Linear pour l'équipe sélectionnée.", "1361275ec3": "Nouveau projet Linear", "7f3f7b4c18": "Description (facultatif, markdown)", - "9f2b4c03a6": "Création dans", "d3d0998b7d": "Nouveau ticket GitHub", - "d1e243795c": "tickets", - "be8cf68d9f": "voir les tickets", - "67662ade50": "tickets du projet", "6244a02f46": "Ouvrir dans Linear", "606a85c774": "Ouvert", - "5e8061b088": "Démarrer un espace de travail depuis {{value0}} {{value1}}", "592a55611b": "Essayez de sélectionner plus d'équipes ou d'actualiser ; les filtres d'équipe s'appliquent aux tickets déjà récupérés.", "618107fab3": "Aucun ticket récupéré ne correspond aux équipes sélectionnées", "903c7af49f": "Aucun ticket Linear trouvé", @@ -2383,7 +2442,6 @@ "f362667d55": "Mis à jour", "b1eaa18ace": "Issue", "37e7ee311e": "Clé", - "b7bae28b6a": "affichés", "a26a48252e": "Propriétés affichées", "5d2d835467": "Tri", "5659da12fc": "Regroupement", @@ -2391,11 +2449,9 @@ "af377b13b1": "Vue {{value0}}", "d47248df4d": "Mode d'affichage Linear", "f397d513e3": "Retour", - "b39fe6511d": "projets", "8675cd6188": "Linear", "733b8f2421": "Linear / Vues", "bc06ed0fb0": "Retour aux vues", - "3cb855080f": "vues", "b4e10f096e": "Propriétaire", "a04fe7ba73": "Visibilité", "0aa8525950": "Modèle", @@ -2425,8 +2481,6 @@ "054bf695cc": "Brouillon", "5b6b2af943": "Nouvelle tentative…", "0c0de0fc0e": "Impossible de charger les tickets depuis", - "d1766fd62d": "projets n'ont pas pu être chargés", - "7762f4b03a": "sur", "443f7dd928": "Merge", "a7396b05c6": "Vérifications", "f6fa3c97d0": "Reviewers", @@ -2608,10 +2662,41 @@ "jiraColumnOriginalEstimate": "Estimation", "jiraColumnRemainingEstimate": "Restant", "jiraBoardEmptyColumn": "Aucune issue", - "labelCountPlural": "{{count}} labels", - "labelCountSingular": "{{count}} label", - "memberCountPlural": "{{count}} membres", - "memberCountSingular": "{{count}} membre" + "backToPullRequests": "Pull requests", + "backToGitHubList": "Liste GitHub", + "noGitHubRepositoryContext": "Aucun contexte de dépôt GitHub disponible pour cette issue.", + "filingInTarget": "Création dans {{target}}", + "filingInThisRepository": "Création dans ce dépôt", + "shortcutToSubmit": "{{shortcut}} pour envoyer.", + "projectsFailedToLoad_one": "Projets non chargés : {{failed}} sur {{count}}", + "projectsFailedToLoad_other": "Projets non chargés : {{failed}} sur {{count}}", + "draftPullRequestNumber": "Brouillon de pull request #{{number}}", + "pullRequestNumber": "Pull request #{{number}}", + "issueNumber": "Issue #{{number}}", + "loadGitHubWorkFailed": "Impossible de charger le travail GitHub.", + "gitlabViewIssues": "Issues", + "gitlabViewMrs": "MRs", + "gitlabViewTodos": "Mes tâches", + "startWorkspaceFromMr": "Démarrer un espace de travail depuis la MR {{number}}", + "startWorkspaceFromIssue": "Démarrer un espace de travail depuis l’issue {{number}}", + "shownCount_one": "{{count}} affiché", + "shownCount_other": "{{count}} affichés", + "linearProjectPlaceholder": "Projet", + "labelCount_one": "{{count}} label", + "labelCount_other": "{{count}} labels", + "memberCount_one": "{{count}} membre", + "memberCount_other": "{{count}} membres", + "groupUnassigned": "Non assigné", + "linearProjectContext": "Projet : {{name}}", + "linearViewContext": "Vue : {{name}}", + "changedFileCount_one": "{{count}} fichier", + "changedFileCount_other": "{{count}} fichiers", + "resumeRestoration": { + "linearProjectNotFound": "Le projet Linear enregistré est introuvable.", + "linearProjectRestoreFailed": "Impossible de restaurer le projet Linear enregistré.", + "linearViewNotFound": "La vue Linear enregistrée est introuvable.", + "linearViewRestoreFailed": "Impossible de restaurer la vue Linear enregistrée." + } }, "Terminal": { "73768427cf": "Fermer", @@ -2686,7 +2771,8 @@ "b1e390250d": "Impossible de finaliser le basculement vers le build local.", "d29740d175": "Le build sélectionné n'a pas pu être utilisé.", "37d45c9ec1": "Choisir un autre build", - "7f1a4c9e02": "Votre gestionnaire de packages système a installé Orca, alors mettez-le à jour à partir de là – Orca ne peut pas installer cette version lui-même." + "7f1a4c9e02": "Votre gestionnaire de packages système a installé Orca, alors mettez-le à jour à partir de là – Orca ne peut pas installer cette version lui-même.", + "compatibilityModeFailed": "Impossible d’activer le mode de compatibilité. {{message}}" }, "WorktreeJumpPalette": { "ac037cfac2": "Déplacer", @@ -2712,8 +2798,6 @@ "d7d496a451": "La page du navigateur n'existe plus", "50a1d11d5b": "Onglets ouverts", "088d66d980": "Actions et paramètres", - "20af998bff": "{{value0}} éléments disponibles{{value1}}", - "bb72c08e63": "{{value0}} résultats trouvés{{value1}}", "34c8fbb46e": "Remote SSH", "63c2be1914": "SSH déconnecté", "95be6587d3": "Créer le worktree « {{value0}} »", @@ -2730,7 +2814,12 @@ "recentChatsTerminalsHeader": "Chats et terminaux récents", "27f10cca63": "Rechercher chats, terminaux, espaces de travail, tâches, paramètres et actions...", "2770f02910": "Rechercher chats, terminaux, espaces de travail, tâches, paramètres et actions", - "lastActiveTime": "Dernière activité il y a {{value0}}" + "lastActiveTime": "Dernière activité il y a {{value0}}", + "resultsFound_one": "{{count}} résultat trouvé.", + "resultsFound_other": "{{count}} résultats trouvés.", + "itemsAvailable_one": "{{count}} élément disponible.", + "itemsAvailable_other": "{{count}} éléments disponibles.", + "createActionAvailable": "Action de création de worktree disponible." }, "github": { "pr": { @@ -2771,7 +2860,8 @@ "8f6cb3772f": "Merger automatiquement cette pull request une fois les conditions remplies", "def355ff38": "Peut merger", "e42c5bae67": "GitHub indique que cette PR peut merger et que les checks ont réussi", - "cbf0113af6": "GitHub indique que cette PR peut merger" + "cbf0113af6": "GitHub indique que cette PR peut merger", + "autoMergeOn": "Fusion automatique activée" } } }, @@ -2945,10 +3035,10 @@ "imageUrlTooLarge": "L'URL de l'image est trop volumineuse." }, "IssueSourceSelector": { - "d6aeb2012b": "Affichage des issues de", "787c970baf": "Source des issues", "51d1608920": "Origine", - "30b2c9df91": "Upstream" + "30b2c9df91": "Upstream", + "showingIssuesFromRepo": "Affichage des issues de " }, "PRFilterDropdowns": { "979be3cf6b": "Assigné", @@ -2958,12 +3048,18 @@ "01f3f3d161": "Auteur", "13b3ac0a84": "Statut", "79c54552f7": "Filtres", - "8a2ffbf9b3": "Retirer le filtre {{value0}}" + "8a2ffbf9b3": "Retirer le filtre {{value0}}", + "anyState": "Tous", + "currentUser": "Utilisateur actuel" }, "PRFilterPickers": { - "fdf387297c": "Effacer (", "472c12ae03": "Effacer", - "2d1f58eda6": "Utiliser" + "pressEnterToUseValue": "Appuyez sur Enter pour utiliser la valeur saisie.", + "useTypedValue": "Utiliser ", + "clearSelected": "Effacer ({{count}})", + "loading": "Chargement…", + "searchTextTooLarge": "Le texte recherché est trop long.", + "noMatches": "Aucun résultat" }, "PRFilterSections": { "a00830d3f7": "Aucun utilisateur", @@ -2973,7 +3069,6 @@ "458ea3602b": "Aucun auteur", "b69fa4fa20": "Retour", "30ebb6ca44": "Effacer tous les filtres", - "8177eda37e": "Filtre", "ea3416d646": "Assigné", "b1d9fdea08": "Label", "24754c44ad": "Auteur", @@ -2985,7 +3080,15 @@ "2b2f019091": "Tout état", "0fd3249e2e": "Fermé", "d78b60b5c2": "Ouvert", - "bd162b7d5a": "Fusionnés" + "bd162b7d5a": "Fusionnés", + "draft": "Brouillon", + "labelCount_one": "{{count}} étiquette", + "labelCount_other": "{{count}} étiquettes", + "allStates": "Tous", + "filterPullRequests": "Filtrer les pull requests", + "filterIssues": "Filtrer les issues", + "filterOrTypeLogin": "Filtrer ou saisir un identifiant...", + "filterLabels": "Filtrer les étiquettes..." }, "github": { "rate": { @@ -2996,15 +3099,14 @@ "d12d3d6f33": "Actualiser le quota d'API GitHub", "d5e5de9070": "Orca utilise REST, Search et GraphQL via GitHub CLI.", "58c5f88216": "Quota d'API GitHub", - "6da1858354": "restant · réinitialisation dans", - "f42790d150": "sur", "01f7323e58": "API GraphQL", "1daf0f22a9": "GraphQL", "1f2f28a4de": "API Search", "c377a4f06a": "Recherche", "c392c749a6": "API REST", "bb227706a6": "REST", - "budget_scope_prefix": "Périmètre du quota" + "budget_scope_prefix": "Périmètre du quota", + "remainingOfLimitResetsIn": "Quota restant : {{remaining}} sur {{limit}} · réinitialisation dans {{reset}}" } } } @@ -3012,7 +3114,29 @@ "CommentReactions": { "addReaction": "Ajouter une réaction", "removeNamedReaction": "Retirer la réaction {{value0}}", - "addNamedReaction": "Ajouter la réaction {{value0}}" + "addNamedReaction": "Ajouter la réaction {{value0}}", + "reaction": { + "thumbsUp": "pouce levé", + "thumbsDown": "pouce baissé", + "laugh": "rire", + "confused": "confusion", + "heart": "cœur", + "hooray": "hourra", + "rocket": "fusée", + "eyes": "yeux" + } + }, + "CommentCodeContext": { + "showSurroundingCodeBlock": "Afficher le bloc de code environnant", + "showNearbyCodeContext": "Afficher le contexte de code voisin" + }, + "prCheckPresentation": { + "successful": "Réussi", + "inProgress": "En cours" + }, + "IssueSourceIndicator": { + "issueFromRepo": "Issue de ", + "issuesFromRepo": "Issues de " } }, "linear": { @@ -3032,11 +3156,6 @@ } } }, - "priority": { - "icon": { - "c43d3e065b": "Priorité :" - } - }, "project": { "view": { "surfaces": { @@ -3055,7 +3174,6 @@ "c8db98b73b": "Ressources", "bb1405eff8": "Jalons", "5d99315fb8": "Planification", - "3ad562bdf4": "issues du périmètre", "563501f191": "Progression", "bb5664d456": "Aucune description de projet.", "7b147907dc": "Linear", @@ -3066,8 +3184,6 @@ "7616c986c6": "Ouvrir {{value0}} issues", "openInLinear": "Ouvrir {{value0}} dans Linear", "93e1f6bfca": "Chargement", - "98730088a6": ". Recherchez ou ouvrez Linear pour voir l'ensemble complet.", - "06b887d622": "Affichage des premières", "linearLoginUnreadable": "Impossible de lire la connexion Linear enregistrée. Reconnectez-la dans les réglages.", "f2cc1e0ff6": "Linear / Projets", "906b5e4cb8": "Linear / Projets / {{value0}}", @@ -3082,7 +3198,10 @@ "df4bd63c1d": "Non assigné", "30402d2c6e": "Essayez la recherche ou actualisez.", "a2f31c4cd6": "Aucun projet Linear trouvé", - "c9b6e9f90d": "Impossible de charger les projets Linear" + "c9b6e9f90d": "Impossible de charger les projets Linear", + "scopedIssueCount_one": "{{count}} issue dans le périmètre", + "scopedIssueCount_other": "{{count}} issues dans le périmètre", + "backlog": "Backlog" } } }, @@ -3095,7 +3214,14 @@ "05baa5ae90": "Espace de travail", "89f6580dbf": "Rechercher des équipes...", "b3488fad3c": "Aucune équipe n'a été récupérée. L'accès peut dépendre du périmètre de la clé, de l'appartenance à des équipes privées, d'équipes archivées, des permissions ou d'un échec de récupération.", - "405b33c378": "Aucune équipe récupérée ne correspond à votre recherche." + "405b33c378": "Aucune équipe récupérée ne correspond à votre recherche.", + "teamCount_one": "{{count}} équipe", + "teamCount_other": "{{count}} équipes" + } + }, + "priority": { + "icon": { + "priorityValue": "Priorité : {{label}}" } } }, @@ -4590,10 +4716,7 @@ }, "UsageBreakdownSection": { "7765a4c3e1": "n/d", - "247c93ca92": "• tarification déduite", - "32176e1d44": "tours", - "79a69522a5": "événements", - "02a046792e": "sessions •" + "247c93ca92": "• tarification déduite" }, "GrokUsagePane": { "g8h9i0j1k2": "Utilisation Grok", @@ -5522,7 +5645,9 @@ }, "sidebarHostOptions": { "3e102f111c": "Tous les hôtes", - "visibleHostsCount": "{{value0}} hôtes" + "hosts": "Hôtes", + "visibleHosts_one": "{{count}} hôte", + "visibleHosts_other": "{{count}} hôtes" }, "SidebarWorkspaceOptionsMenu": { "hosts": "Hôtes", @@ -6048,12 +6173,10 @@ "oneWorkspace": "1 espace de travail", "manyWorkspaces": "{{count}} espaces de travail", "hostHasWorkspacesDefault": "Retire {{value0}} et ses identifiants de cet ordinateur. Ses {{value1}} restent dans Orca — les fichiers distants ne sont pas touchés.", - "alsoDeleteRemote": "Supprimer aussi ces {{value0}} sur {{value1}}", "alsoForgetLocal": "Retirer aussi ces {{value0}} d'Orca", "advanced": "Avancé", - "alsoDeleteRemoteHint": "Supprime définitivement les worktrees Git distants et leurs branches. Irréversible.", "alsoForgetLocalHint": "Les retire uniquement d'Orca. Les fichiers, worktrees et branches distants restent intacts.", - "wslHostEndsTerminals": "Retire {{value0}} d'Orca, ferme ses terminaux ouverts et arrête le serveur d'Orca dans cette distro. Les fichiers de la distro restent intacts." + "wslHostEndsTerminalsUnlessShared": "Retire {{value0}} d'Orca. Sauf si un autre Orca ouvert sur cet ordinateur l'utilise, cela ferme aussi ses terminaux ouverts et arrête le serveur d'Orca dans cette distro. Les fichiers de la distro restent intacts." }, "HostRenameDialog": { "1a2b3c4d5e": "Renommer l'hôte", @@ -6236,14 +6359,9 @@ "sshImportSyncedSingular": "Ajout de {{count}} hôte à Orca." }, "ForgetSshWorkspaceDialog": { - "reconnectFailed": "Échec de la reconnexion", - "forgetBody": "Retire uniquement cet espace de travail d'Orca. Les fichiers, le worktree Git et les branches sur {{host}} restent intacts.", - "title": "Supprimer « {{name}} » ?", - "disconnectedBody": "L'hôte SSH de cet espace de travail n'est pas connecté. Reconnectez-le pour le supprimer aussi à distance, ou retirez-le seulement d'Orca.", "ghostBody": "{{host}} n'est plus un hôte SSH enregistré ; cet espace de travail n'est donc plus connecté à un hôte actif. Il ne peut être que retiré d'Orca — les fichiers et branches distants restent intacts.", "cancel": "Annuler", - "forget": "Retirer d'Orca", - "reconnectAndDelete": "Reconnecter et supprimer" + "forget": "Retirer d'Orca" }, "MarkdownImageLightbox": { "image": "Image", @@ -6383,7 +6501,7 @@ "running": "En cours", "stopped": "Arrêtée", "title": "Ajouter une distro WSL", - "description": "Orca exécute son serveur dans la distro, de sorte que git, les fichiers et les terminaux s'exécutent nativement sous Linux. Utilisez-la pour les nouveaux projets ; les projets que vous avez ouverts via \\\\wsl.localhost continuent de fonctionner tels quels.", + "description": "Orca exécute son serveur dans la distro, de sorte que git, les fichiers et les terminaux s'exécutent nativement sous Linux. Les projets de cette distro que vous avez ouverts via \\\\wsl.localhost sont déplacés automatiquement vers cet hôte dès que leurs terminaux sont inactifs ; les projets situés sur un lecteur Windows (/mnt/…) restent sur cet ordinateur. Vous pouvez ramener un projet déplacé depuis la barre latérale.", "distro": "Distro", "loading": "Recherche des distros WSL…", "placeholder": "Choisissez une distro", @@ -6410,6 +6528,7 @@ "removalPending": "La suppression n'a pas abouti" }, "wslHostRemoval": { + "keptForOthers": "Retiré de cet Orca. L'hôte reste actif pour {{value0}}.", "partial": "L'hôte a été retiré, mais quelque chose dans la distro est encore en cours d'exécution : {{value0}}", "pending": "Orca n'a pas encore supprimé l'hôte : {{value0}} Supprimez-le à nouveau pour réessayer, ou connectez-le pour le conserver." }, @@ -6486,7 +6605,11 @@ "e8f25bd903": "Impossible de terminer le nettoyage des terminaux.", "a702d4196e": "Ceci ferme tous les onglets de terminal de tous les espaces de travail et demande l'arrêt des sessions de terminal en cours. Tout travail non enregistré dans un terminal est perdu. Le daemon continue de tourner et de nouveaux terminaux peuvent être ouverts immédiatement. Cette action est irréversible.", "01d6b7c64e": "Les terminaux ouverts et les agents redémarreront. Les terminaux sur les hôtes distants ne sont pas affectés.", - "922548bc66": "Redémarrer le service du terminal ?" + "922548bc66": "Redémarrer le service du terminal ?", + "confirmRestart": "Redémarrer", + "busyRestarting": "Redémarrage…", + "confirmKillAll": "Terminer toutes les sessions", + "busyKilling": "Arrêt…" }, "MacFolderAccessFixDialog": { "stepAllow": "Autoriser Orca sous Fichiers et dossiers", @@ -8146,7 +8269,9 @@ "fbb428db98": "Sélectionné :", "search_terminal_themes": "Rechercher des thèmes de terminal", "cb330ef7f8": " sur {{value0}}", - "c822571b2e": " correspondant à \"{{value0}}\"" + "c822571b2e": " correspondant à \"{{value0}}\"", + "plugin_themes": "Plugins", + "from_plugin": "De {{value0}}" }, "SettingsSidebar": { "e0900f83e7": "SSH", @@ -8436,7 +8561,6 @@ "a016ffbeed": "Auto utilise Windows PowerShell pour le moment et bascule vers PowerShell 7+ une fois installé.", "5ed5c95344": "Choisissez entre Windows PowerShell et PowerShell 7+ pour les nouveaux volets de terminal.", "3d88af864d": "Choisissez si l'option de shell PowerShell lance Windows PowerShell ou PowerShell 7+ pour les nouveaux volets de terminal.", - "8a956cc91e": "Caractères traités comme séparateurs de mots pour la sélection par double-clic.", "4bebcc2b2c": "Séparateurs de mots", "12e06178fa": "lignes", "907b0b9d3e": "Personnalisé", @@ -11123,7 +11247,7 @@ "mixedTitle": "Examiner l'accès et le contenu", "instructionalTitle": "Examiner le contenu du plugin", "subtitle": "{{value0}} v{{value1}} · {{value2}}", - "reconsent": "Les autorisations, le niveau de confiance du worker ou le contenu instructif ont changé depuis votre dernière revue de ce plugin. Revoyez-le avant qu'il puisse s'exécuter.", + "reconsent": "Ce plugin a changé depuis votre approbation. Vérifiez-le pour le relancer.", "capabilities": "Ce plugin peut", "warning": "Ces autorisations limitent la façon dont le plugin utilise l'API d'Orca. Son worker s'exécute néanmoins comme un processus normal sur votre ordinateur, avec un accès complet à vos fichiers, votre réseau et vos autres processus.", "instructionalWarning": "Ce plugin n'a pas de processus worker. Son contenu instructif peut malgré tout déclencher des actions quand vous ou un agent l'utilisez. Examinez les instructions et commandes ci-dessous avant de l'activer.", @@ -11921,7 +12045,8 @@ "migration": "Non effectué : un déplacement vers ce serveur est inachevé. Reprenez-le d'abord.", "deferred": "Pas encore effectué : le serveur n'est pas prêt pour cela. Réessayez plus tard.", "failed": "Orca n'a pas pu terminer cette action sur le serveur. Réessayez.", - "defaultServer": "Non effectué : ce serveur est l’hôte par défaut des nouveaux projets. Choisissez-en un autre dans « Les nouveaux projets s’ouvrent sur » avant de l’arrêter." + "defaultServer": "Non effectué : ce serveur est l’hôte par défaut des nouveaux projets. Choisissez-en un autre dans « Les nouveaux projets s’ouvrent sur » avant de l’arrêter.", + "wslMoveRunning": "Non effectué : un projet est en cours de déplacement vers ce serveur. Orca le mettra à jour une fois le déplacement terminé." }, "reassurance": "S’exécute sur chaque hôte, accessible via votre propre connexion SSH. Votre code et vos fichiers restent où ils sont. Seule la liste des projets, onglets et terminaux d’Orca passe sur l’hôte." }, @@ -12259,6 +12384,9 @@ "searchLabel": "Rechercher des versions", "noMatches": "Aucune version correspondante." }, + "AppearanceThemeControl": { + "useTerminalTheme": "Utiliser ses couleurs de terminal" + }, "notification": { "settings": { "copy": { @@ -12323,14 +12451,14 @@ } }, "BulkActionBar": { - "79a9f5f712": "Retirer du staging (", - "ef5f5bd06e": "Ajouter au staging (", - "60ed678138": "sélectionnés" + "selectedCount_one": "{{count}} sélectionné", + "selectedCount_other": "{{count}} sélectionnés", + "stageCount": "Ajouter au staging ({{count}})", + "unstageCount": "Retirer du staging ({{count}})" }, "ChecksPanel": { "2ef90c9819": "Un agent IA a été démarré pour les vérifications cassées.", "a0181a8d76": "Un agent IA a été lancé pour les conflits.", - "34464d00b9": "mis à jour", "058039787c": "Annuler", "2ab7fd4b6d": "Enregistrer", "dda5924a40": "Les checks exigent une branche Git et un contexte de revue hébergée", @@ -12376,7 +12504,8 @@ "430f1a62d4": "Impossible de résoudre le fil sélectionné côté hôte.", "updateReactionFailed": "Échec de la mise à jour de la réaction.", "gitlabMoreActions": "Plus d'actions MR", - "gitlabLinkAnother": "Associer un autre MR" + "gitlabLinkAnother": "Associer un autre MR", + "reviewUpdatedAt": "{{review}} : mise à jour {{time}}" }, "CreateHostedReviewComposer": { "741ff8a0d2": "Pusher & créer {{value0}}" @@ -12533,7 +12662,14 @@ "740aca88ab": "Échec du scan des ports de l'espace de travail.", "5be4f7f727": "Menu du port {{value0}}", "1004af16ab": "Copier {{value0}}", - "153d3a8026": "Hôte de l'espace de travail inconnu" + "153d3a8026": "Hôte de l'espace de travail inconnu", + "unknownProcess": "Processus inconnu", + "containerOrForwardedService": "Conteneur ou service redirigé", + "unassigned": "Non assigné", + "remotePortOutOfRange": "Le port distant doit être dans la plage 1–65535", + "localPortOutOfRange": "Le port local doit être dans la plage 1–65535", + "localPortInUse": "Le port {{port}} est déjà utilisé. Choisissez un autre port local.", + "localPortRequiresPrivileges": "Le port {{port}} nécessite des privilèges élevés. Utilisez un port local ≥ 1024." }, "Search": { "1abfb25a66": "Saisissez pour rechercher dans les fichiers", @@ -12590,7 +12726,6 @@ "476b77745b": "Modifier la ref de base", "ed34038d0d": "Actualiser la comparaison de branches", "493f963029": "Modifier la ref de base", - "3278b2767b": "en avance", "11b5dd8e41": "Comparaison avec", "a9bf7c171a": "Échec du commit", "011f9713fc": "Commit bloqué", @@ -12635,7 +12770,6 @@ "574d2f4413": "Effacer les notes", "05bb8f4a48": "Annuler", "48db37cca9": "Tout afficher", - "78ce2d37ac": "Pousse vers le fork", "c05fe04839": "Pousse vers le fork situé à {{value0}} (pas origin)", "c35baf2f1e": "Filtrer les fichiers…", "2fe2a67580": "Autres actions de note", @@ -12643,14 +12777,12 @@ "cc474e0b8c": "Notes", "e131cd7128": "Le contrôle de code source n'est disponible que pour les dépôts Git", "c07b236287": "Sélectionnez un espace de travail pour afficher les modifications", - "dc5a6465fc": "{{value0}} (ex. {{value1}}{{value2}})", "a5e5a11090": "Échec de l'abandon global — impossible de sortir les fichiers de l'index avant l'abandon", "8a5ba6a988": "Échec du chargement du diff du commit", "fe5bd1a610": "Création de {{value0}}...", "812cb992ee": "Ouvrir sur {{value0}}", "eef5446523": "{{value0}} #{{value1}} est déjà ouvert", "0453ca3a9a": "Création de {{value0}} effectuée, mais Orca n'a pas encore pu l'actualiser.", - "f99560ab29": "Échec de l'abandon de {{value0}}", "eae7a1da5f": "Échec de l'effacement des notes.", "df5040e3c3": "Déstager", "8cde1a2fb0": "Stager", @@ -12687,8 +12819,6 @@ "72f2bea3f4": "Déplier les notes", "d13edef890": "Replier les notes", "d6fb1df5fe": "{{value0}} est déjà ouvert", - "05838cfdeb": "Conflit {{value0}}", - "d206117f90": "Conflit {{value0}} ({{value1}})", "0b5b8c234c": "Ouvrir {{value0}} ({{value1}})", "d97ef8f221": "lignes {{value0}}-{{value1}}", "6f8bfa0eb9": "ligne {{value0}}", @@ -12763,12 +12893,6 @@ "a4e93c21d7": "Branche actuelle : {{value0}}", "c7d4e2f801": "Modifier la ref de base : {{value0}}", "createPrIntentGenerateDetailsFailed": "Impossible de générer les détails de revue. Réessayez Créer une PR.", - "branchFilesChangedVsBaseOne": "1 fichier modifié par rapport à {{ref}}", - "branchFilesChangedVsBaseOther": "Fichiers {{count}} modifiés par rapport à {{ref}}", - "compareBaseCommitsAheadOne": "1 commit avant {{ref}}", - "compareBaseCommitsAheadOther": "{{count}} s'engage avant {{ref}}", - "compareBaseCommitsBehindOne": "1 commit derrière {{ref}}", - "compareBaseCommitsBehindOther": "{{count}} s'engage derrière {{ref}}", "entryStageFailed": "Échec de la préparation de « {{value0}} »", "entryUnstageFailed": "Échec de la désactivation de « {{value0}} »", "entryDiscardFailed": "Échec de la suppression de « {{value0}} »", @@ -12777,17 +12901,50 @@ "diffCommentNotesCopyFailed": "Échec de la copie des notes", "conflictCount_one": "{{count}} conflit", "conflictCount_other": "{{count}} conflits", - "discardFailedSingular": "Échec de l'abandon de {{count}} fichier", - "discardFailedPlural": "Échec de l'abandon de {{count}} fichiers", - "noteCountSingular": "{{count}} note", - "noteCountPlural": "{{count}} notes" + "discardFailedSampleMore_one": "{{paths}}, +{{count}} autre", + "discardFailedSampleMore_other": "{{paths}}, +{{count}} autres", + "discardFailed_one": "Échec de l'abandon de {{count}} fichier", + "discardFailed_other": "Échec de l'abandon de {{count}} fichiers", + "discardFailedWithSample": "{{error}} (ex. {{paths}})", + "compareBaseCommitsAhead_one": "{{count}} commit d'avance sur {{ref}}", + "compareBaseCommitsAhead_other": "{{count}} commits d'avance sur {{ref}}", + "compareBaseCommitsBehind_one": "{{count}} commit de retard sur {{ref}}", + "compareBaseCommitsBehind_other": "{{count}} commits de retard sur {{ref}}", + "branchFilesChangedVsBase_one": "{{count}} fichier modifié par rapport à {{ref}}", + "branchFilesChangedVsBase_other": "{{count}} fichiers modifiés par rapport à {{ref}}", + "noteCount_one": "{{count}} note", + "noteCount_other": "{{count}} notes", + "comparingAgainstRef": "Comparaison avec {{ref}}", + "commitsAheadShort_one": "{{count}} en avance", + "commitsAheadShort_other": "{{count}} en avance", + "unresolvedConflictOfKind": "Conflit non résolu ({{kind}})", + "unresolvedConflict": "Conflit non résolu", + "locallyResolvedConflictOfKind": "Conflit résolu localement ({{kind}})", + "locallyResolvedConflict": "Conflit résolu localement", + "pushesToForkTarget": "Pousse vers le fork {{target}}", + "abortRebaseConfirmTitle": "Abandonner le rebase ?", + "abortMergeConfirmTitle": "Abandonner le merge ?", + "abortRebaseConfirmDescription": "Cela annule le rebase en cours et peut abandonner les résolutions de conflits effectuées pendant ce rebase.", + "abortMergeConfirmDescription": "Cela annule le merge en cours et peut abandonner les résolutions de conflits effectuées pendant ce merge.", + "abortRebaseFailedFallback": "Impossible d'abandonner le rebase", + "abortMergeFailedFallback": "Impossible d'abandonner le merge", + "abortRebaseFailed": "Échec de l'abandon du rebase", + "abortMergeFailed": "Échec de l'abandon du merge", + "clearNotesFromWorkspace_one": "Effacer {{count}} note de cet espace de travail ?", + "clearNotesFromWorkspace_other": "Effacer {{count}} notes de cet espace de travail ?", + "clearNotesFromFile_one": "Effacer {{count}} note de {{path}} ?", + "clearNotesFromFile_other": "Effacer {{count}} notes de {{path}} ?" }, "SourceControlAgentActionDialog": { "8e856842d1": "Impossible de démarrer l'agent sélectionné.", "c075d00de1": "Impossible de résoudre la connexion de l'espace de travail.", "38b899cc02": "Tous les dépôts", "808cfe0a3b": "Ce dépôt", - "994cddd1f7": "Ne pas enregistrer" + "994cddd1f7": "Ne pas enregistrer", + "agentNotEnabledOrDetected": "{{agent}} n'est pas activé ou n'a pas été détecté sur l'hôte de cet espace de travail.", + "workspaceConnectionUnresolved": "Impossible de déterminer la connexion de l'espace de travail.", + "noEnabledAgentsDetected": "Aucun agent activé n'a été détecté sur l'hôte de cet espace de travail.", + "startAgent": "Démarrer l'agent" }, "SourceControlAgentActionDialogForm": { "013c9ac04a": "Enregistrer pour", @@ -12852,10 +13009,6 @@ "cbcc4ab3db": "Affichage des 100 premières vérifications", "0dca6bfab5": "Ouvrir les détails de la vérification", "991f50c7e4": "Aucune vérification configurée", - "9ad98f2a17": "en attente", - "5e52f4ef7f": "en échec", - "02ca4f9074": "en succès", - "checksUnresolvedChip": "non résolu", "checksUnresolvedStripHint": "Ces vérifications se sont terminées sans verdict de succès ni d'échec.", "e15a8b77ef": "Aucun détail en ligne n'est disponible pour cette vérification.", "dcb3c546fe": "Réessayer", @@ -12874,7 +13027,6 @@ "1f2b980522": "Chargement des détails de la vérification…", "0c96cd25e5": "Résoudre", "3a71a6ed0b": "Résolvez les conflits pour que les vérifications et le merge puissent aboutir.", - "60186d8498": "Des conflits bloquent ceci", "c16762ac8c": "Les vérifications et commentaires ci-dessous montrent le contexte récupéré actuellement.", "9d0e7bcefc": "Aucune action PR bloquante", "5856874b59": "Orca actualisera les vérifications tant que ce panneau reste ouvert.", @@ -12899,7 +13051,6 @@ "084c516efb": "Copier les commandes", "5dc3af25c0": "Sélectionner le commentaire", "d7a2f9c401": "Envoyer les {{value0}} commentaires non résolus", - "d91f2a6c39": "Envoyer les {{value0}} commentaires en file à l'IA", "a6de3e5a20": "Vider les commentaires en file", "f8a2c91d04": "Mettre en file pour l'agent", "b4e8a1c902": "En file d'attente", @@ -12922,7 +13073,28 @@ "pendingChecks_one": "{{count}} vérification en attente", "pendingChecks_other": "{{count}} vérifications en attente", "unresolvedChecks_one": "{{count}} vérification non résolue", - "unresolvedChecks_other": "{{count}} vérifications non résolues" + "unresolvedChecks_other": "{{count}} vérifications non résolues", + "passingCount_one": "{{count}} réussi", + "passingCount_other": "{{count}} réussis", + "failingCount_one": "{{count}} en échec", + "failingCount_other": "{{count}} en échec", + "pendingCount_one": "{{count}} en attente", + "pendingCount_other": "{{count}} en attente", + "unresolvedCount_one": "{{count}} non résolu", + "unresolvedCount_other": "{{count}} non résolus", + "sendQueuedCommentsToAi_one": "Envoyer {{count}} commentaire en file d'attente à l'IA", + "sendQueuedCommentsToAi_other": "Envoyer {{count}} commentaires en file d'attente à l'IA", + "conflictsBlockThisMr": "Des conflits bloquent cette MR", + "conflictsBlockThisPr": "Des conflits bloquent cette PR", + "copyComment": "Copier le commentaire", + "sendComment": "Envoyer", + "commentingRequiresGitHubPrTarget": "Pour commenter, un dépôt cible de PR GitHub est nécessaire.", + "selectWorkspaceBeforeAiAction": "Sélectionnez un espace de travail avant de lancer une action IA.", + "operation": { + "rebase": "Rebase", + "merge": "Merge", + "cherryPick": "Cherry-pick" + } }, "empty": { "state": { @@ -13164,10 +13336,10 @@ "dialog": { "3bc61dc989": "Annuler", "15efa778e3": "Abandonner", - "42f89dd030": "fichiers", - "e7611dca35": "fichier", "0d2d88cba5": "Cette action est irréversible.", - "1551c14668": "Abandonner les modifications ?" + "1551c14668": "Abandonner les modifications ?", + "fileCount_one": "{{count}} fichier", + "fileCount_other": "{{count}} fichiers" } }, "dropdown": { @@ -13329,8 +13501,8 @@ }, "compare": { "summary": { - "commitsAheadSingular": "{{count}} commit d'avance sur {{ref}}", - "commitsAheadPlural": "{{count}} commits d'avance sur {{ref}}" + "commitsAhead_one": "{{count}} commit d'avance sur {{ref}}", + "commitsAhead_other": "{{count}} commits d'avance sur {{ref}}" } }, "conflict": { @@ -13394,24 +13566,32 @@ "unresolved": "Impossible de déterminer quel hôte possède cet espace de travail. Vérifiez la connexion et réessayez." }, "useFileDeletion": { - "72691dfebc": "Échec : {{value0}} « {{value1}} ».", "d979a4fbb5": "Supprimer définitivement « {{value0}} » ?", "92276aceb7": "Supprimer", "7fb9435c86": "Cette action supprime définitivement le répertoire et son contenu sur l'hôte distant. Elle est irréversible.", "23e98f192f": "Cette action supprime définitivement le fichier sur l'hôte distant. Elle est irréversible.", "8b8ee9d22f": "Impossible de déterminer quel hôte possède ce fichier. Vérifiez la connexion de l'espace de travail et réessayez.", - "af1270b90d": "Supprimer définitivement {{count}} éléments ?", "dd029aa5cd": "Cette action supprime définitivement les éléments sélectionnés ainsi que le contenu des répertoires sur l'hôte distant. Elle est irréversible.", - "77fdc36183": "Supprimer {{count}} éléments ?", - "fca915a67a": "Les éléments distants sont définitivement supprimés, sans retour arrière. Les éléments locaux sont déplacés dans {{value0}}." + "deleteFailed": "Impossible de supprimer « {{name}} ».", + "deleteItems_one": "Supprimer {{count}} élément ?", + "deleteItems_other": "Supprimer {{count}} éléments ?", + "mixedRecycleBin": "Les éléments distants sont supprimés définitivement. Cette action est irréversible. Les éléments locaux sont déplacés vers la Corbeille.", + "mixedTrash": "Les éléments distants sont supprimés définitivement. Cette action est irréversible. Les éléments locaux sont déplacés vers la Corbeille.", + "permanentlyDeleteItems_one": "Supprimer définitivement {{count}} élément ?", + "permanentlyDeleteItems_other": "Supprimer définitivement {{count}} éléments ?", + "recycleBinFailed": "Impossible de déplacer « {{name}} » vers la Corbeille.", + "trashFailed": "Impossible de déplacer « {{name}} » vers la Corbeille." }, "useFileExplorerHandlers": { "32cd9fd991": "Impossible d'ouvrir la cible du symlink", "folderLinksOutsideProject": "Ce dossier pointe en dehors du projet ; il ne peut pas être ouvert ici." }, "useFileExplorerImport": { - "25919b2050": "Ignoré : {{value0}} {{value1}}.", - "132fd0e1e9": "Échec de l'importation de {{value0}} {{value1}}." + "importFailedCount_one": "Échec de l'importation de {{count}} fichier.", + "importFailedCount_other": "Échec de l'importation de {{count}} fichiers.", + "importSkippedCount_one": "{{count}} fichier ignoré.", + "importSkippedCount_other": "{{count}} fichiers ignorés.", + "importFailed": "Échec de l'importation des fichiers." }, "useFileExplorerKeys": { "8adb953095": "Échec de l'opération" @@ -13449,7 +13629,6 @@ "refreshSessionHistory": "Actualiser l'historique des sessions", "searchSessions": "Rechercher des sessions", "clearSearch": "Effacer la recherche", - "transcriptsSkipped": "{{count}} transcript ignoré", "noAgentSessionsFound": "Aucune session d'agent trouvée", "noSessionsMatchFilters": "Aucune session ne correspond aux filtres actuels", "noAgentsSelected": "Aucun agent sélectionné", @@ -13468,7 +13647,9 @@ "resumeInChatFailed": "Impossible de reprendre cette session dans un nouveau chat.", "resumeInNewCliUnavailable": "Impossible d'ouvrir cette session dans la CLI.", "resumeInNewCliHostTooOld": "Mettez à jour Orca sur l'hôte qui exécute ce chat pour le reprendre dans une nouvelle CLI.", - "folderWorkspaceUnavailable": "L'espace de travail de type dossier n'est plus disponible." + "folderWorkspaceUnavailable": "L'espace de travail de type dossier n'est plus disponible.", + "transcriptsSkippedCount_one": "{{count}} transcript ignoré", + "transcriptsSkippedCount_other": "{{count}} transcripts ignorés" }, "AiVaultPanelControls": { "scanningSessions": "Analyse des sessions", @@ -13499,11 +13680,8 @@ "latestTurns": "Derniers échanges", "noPreviewAvailable": "Aucun aperçu de conversation disponible", "conversationNotSaved": "Conversation non enregistrée", - "recoverableEmptyDetail": "Cette session n'a pas de conversation enregistrée, mais {{value0}} élément(s) récupérable(s) subsistent.", "recoverableEmptyOpenLogHint": "Ouvrez le log pour les récupérer.", "emptyConversationDetail": "Cette session n'a pas de conversation enregistrée et ne peut pas être reprise.", - "queuedMessages": "{{value0}} message(s) en file d'attente", - "subagentTranscripts": "{{value0}} transcript(s) de sous-agent", "resumeInWorktree": "Reprendre dans le worktree", "viewLog": "Afficher le log", "unknownTime": "Heure inconnue", @@ -13532,7 +13710,13 @@ "noFirstPromptAvailable": "Aucun premier prompt disponible", "loadingFirstPrompt": "Chargement du premier prompt…", "folder": "Dossier", - "resumeInFolder": "Reprendre dans le dossier" + "resumeInFolder": "Reprendre dans le dossier", + "recoverableEmptyDetailCount_one": "Cette session n'a pas de conversation enregistrée, mais {{count}} élément récupérable subsiste.", + "recoverableEmptyDetailCount_other": "Cette session n'a pas de conversation enregistrée, mais {{count}} éléments récupérables subsistent.", + "queuedMessageCount_one": "{{count}} message en file d'attente", + "queuedMessageCount_other": "{{count}} messages en file d'attente", + "subagentTranscriptCount_one": "{{count}} transcript de sous-agent", + "subagentTranscriptCount_other": "{{count}} transcripts de sous-agents" }, "AiVaultSessionRow": { "noPreviewAvailable": "Aucun aperçu de conversation disponible", @@ -13666,26 +13850,26 @@ "confirmation": { "84f6f5b9eb": "Inclus : {{numbers}}. ", "541984b2eb": "Ajouter à la file via #{{pr}} ?", - "4809f55cdb": "{{included}}GitHub ajoutera {{count}} pull request à la file de fusion en une seule fois. La file choisit la méthode de fusion et peut les fusionner en groupes séparés.", - "be8f2621be": "{{included}}GitHub ajoutera {{count}} pull requests à la file de fusion en une seule fois. La file choisit la méthode de fusion et peut les fusionner en groupes séparés.", - "92ca033e72": "Mettre {{count}} PR en file", - "478a527b15": "Mettre {{count}} PR en file", "1feef35ca4": "Fusionner via #{{pr}} ?", - "c3e036c99f": "{{included}}GitHub fusionnera {{count}} pull request de manière atomique avec {{method}}. Si elle ne peut pas être fusionnée, rien ne le sera.", - "369aba4b32": "{{included}}GitHub fusionnera {{count}} pull requests de manière atomique avec {{method}}. Si l'une ne peut pas être fusionnée, aucune ne le sera.", - "493c78f521": "Fusionner {{count}} PR", - "eb7051d268": "Fusionner {{count}} PR" + "queueDescription_one": "{{included}}GitHub ajoutera {{count}} pull request à la file de fusion en une seule fois. La file choisit la méthode de fusion et peut fusionner les pull requests en groupes séparés.", + "queueDescription_other": "{{included}}GitHub ajoutera {{count}} pull requests à la file de fusion en une seule fois. La file choisit la méthode de fusion et peut les fusionner en groupes séparés.", + "queueConfirm_one": "Mettre {{count}} PR en file", + "queueConfirm_other": "Mettre {{count}} PR en file", + "mergeDescription_one": "{{included}}GitHub fusionnera {{count}} pull request de manière atomique avec {{method}}. Si elle ne peut pas être fusionnée, rien ne le sera.", + "mergeDescription_other": "{{included}}GitHub fusionnera {{count}} pull requests de manière atomique avec {{method}}. Si l'une ne peut pas être fusionnée, aucune ne le sera.", + "mergeConfirm_one": "Fusionner {{count}} PR", + "mergeConfirm_other": "Fusionner {{count}} PR" }, "merge": { - "55ae29b907": "Fusionner via #{{pr}} · {{count}} PR", - "b8446f6ec2": "Fusionner via #{{pr}} · {{count}} PR", "189d0ec614": "#{{pr}} est toujours un brouillon.", "640fb50d9c": "#{{pr}} est fermée.", "46ffcbda75": "#{{pr}} présente des conflits de fusion.", "6dabefd63e": "#{{pr}} a demandé des modifications.", "2bb21fc326": "#{{pr}} attend encore une approbation de relecture.", "c23faf74df": "#{{pr}} doit être mise à jour.", - "f561e80968": "#{{pr}} est bloquée." + "f561e80968": "#{{pr}} est bloquée.", + "mergeThroughLabel_one": "Fusionner jusqu'à #{{pr}} inclus · {{count}} PR", + "mergeThroughLabel_other": "Fusionner jusqu'à #{{pr}} inclus · {{count}} PR" } } } @@ -13742,14 +13926,15 @@ "sourceActionsUnavailable": "La source de la transcription n'est pas disponible." }, "AiVaultScanProgressStrip": { - "agentChecked": "{{agent}} : {{settled}} candidats de l’historique vérifiés sur {{total}}", "fileCount_one": "{{value0}} fichier", "fileCount_other": "{{value0}} fichiers", "databaseCount_one": "{{value0}} base de données", "databaseCount_other": "{{value0}} bases de données", "scanning": "Analyse de {{value0}}", "checking": "Vérification de {{value0}}", - "scanned": "{{value0}} analysés" + "scanned": "{{value0}} analysés", + "agentCheckedCount_one": "{{agent}} : {{settled}} sur {{total}} candidat de l’historique vérifié", + "agentCheckedCount_other": "{{agent}} : {{settled}} sur {{total}} candidats de l’historique vérifiés" }, "ssh": { "unrestored": { @@ -13761,6 +13946,15 @@ } } } + }, + "fileExplorerMultiDrag": { + "moreItems_one": "+{{count}} autre", + "moreItems_other": "+{{count}} autres" + }, + "CreatePullRequest": { + "createInProgress": "Création de la PR en cours...", + "workspaceHostUnresolved": "L'hôte de l'espace de travail n'a pas pu être résolu. Actualisez l'espace de travail et réessayez.", + "branchDiscoveryFailed": "Échec de la détection des branches." } } }, @@ -14285,11 +14479,11 @@ "a2f68645ac": "Actualiser le quota de l'API GitLab", "2f9c16d6c3": "Orca utilise REST via le CLI GitLab.", "14e144f7a7": "Budget API GitLab", - "3e2c982cfa": "restants, réinitialisation dans", - "ea8ad0bae8": "sur", "0a891e8935": "API REST", "953f7c6062": "Cet hôte GitLab n'a pas renvoyé d'en-têtes de limite de débit.", - "budget_scope_prefix": "Périmètre du quota" + "budget_scope_prefix": "Périmètre du quota", + "resetUnknown": "inconnu", + "remainingOfLimit": "{{remaining}} sur {{limit}} restants, réinitialisation dans {{reset}}" } } } @@ -14361,13 +14555,13 @@ "9ee54037a4": "Commande personnalisée", "4b2fc4b80c": "Effort de réflexion", "be8917699e": "Modèle", - "4d9b6d84df": "non pris en charge. Choisissez Claude, Codex ou Personnalisé.", "560d4feb00": "Personnalisé", "29d119fe95": "Agent", "f9382b48a1": "Activer l'auteur IA", "1c0cb4fabb": "Auteur IA", "bd14e9c42a": "Non configuré", - "1f9468c5c9": "{{value0}} non pris en charge" + "1f9468c5c9": "{{value0}} non pris en charge", + "unsupportedAgent": "{{agent}} n'est pas pris en charge. Choisissez Claude, Codex ou Personnalisé." }, "BrowserAnimatedVisual": { "46df009982": "Démarrer l'essai gratuit", @@ -14908,17 +15102,14 @@ "ConflictComponents": { "f338288514": "Chargement du contenu des conflits...", "90d576adb2": "Actualiser", - "a1ce36f77d": "Instantané capturé le", "c8ca989aea": "Afficher l'arborescence des fichiers", "58ad5ad431": "Ignorer", "28e7db4a90": "Contrôle de code source", "31931dec46": "Cet instantané de revue ne contient plus aucun conflit non résolu actif.", "992145ff5a": "Tous les conflits sont résolus", - "d5edd81755": "Renommé depuis", "6e459867ad": "État de continuité valable pour la session. Git ne signale plus ce fichier comme non fusionné.", "9c2901ef8a": "Conflit suivant", "41d9af2e7a": "Conflit précédent", - "55d61a0ccd": "conflit ·", "da539359b6": "Aucun fichier de l'arbre de travail n'est modifiable pour ce conflit.", "unresolvedConflicts_one": "{{count}} conflit non résolu", "unresolvedConflicts_other": "{{count}} conflits non résolus" @@ -15614,7 +15805,9 @@ "6978871a3d": "Ouvert", "cce596969e": "Supprimer la note", "cad3384faa": "Modifier la note", - "508ee678a5": "Ouvrir dans le navigateur" + "508ee678a5": "Ouvrir dans le navigateur", + "noteAuthorFallback": "Note", + "sentMeta": "envoyé" }, "DiffCommentPopover": { "2b3ce6d394": "Annuler", @@ -15627,6 +15820,9 @@ }, "useDiffCommentDecorator": { "995fa28b50": "Cette note" + }, + "diffCommentZoneCard": { + "noteAlreadySent": "Note déjà envoyée" } } }, @@ -16192,7 +16388,21 @@ "eaa02014f8": "Activé", "29baf8f4c2": "Source", "host": "Hôte", - "lastRunFailed": "La dernière exécution a échoué." + "lastRunFailed": "La dernière exécution a échoué.", + "noGrace": "Pas de marge", + "graceMinutes_one": "{{count}} minute", + "graceMinutes_other": "{{count}} minutes", + "graceHours_one": "{{count}} heure", + "graceHours_other": "{{count}} heures", + "usageCoverageRuns_one": "{{known}}/{{count}} exécution", + "usageCoverageRuns_other": "{{known}}/{{count}} exécutions", + "usageUnavailable": "Indisponible", + "noRuns": "Aucune exécution", + "projectDefault": "Valeur par défaut du projet", + "reuseLiveSession": "Réutiliser la session active", + "freshEachRun": "Nouvelle à chaque exécution", + "precheckEnabled": "Activée, {{timeout}}", + "precheckNone": "Aucune" }, "AutomationEditorDialog": { "fb1896a5e7": "Annuler", @@ -16296,11 +16506,8 @@ "2faecab10b": "Exécuter maintenant", "13118faadf": "Projet inconnu", "73f630b49d": "Annuler", - "1b586f0e2b": "activé", - "02a33e3204": "de", "9adfab2596": "Supprimer l'automatisation externe", "1e2e41392f": "Ne plus demander", - "b264564427": "et son historique d'exécution. Les espaces de travail créés par les exécutions précédentes ne sont pas supprimés.", "080dcb5fbb": "Supprimer l'automatisation", "19a6e30eae": "Actualiser les automatisations", "77c2778945": "Automatisations", @@ -16332,7 +16539,6 @@ "pendingAutomationRunMissing": "L'historique d'exécution n'est plus disponible.", "paused": "En pause", "missingWorkspace": "Espace de travail manquant", - "runUsageSummary": "{{cost}} estimés · {{tokens}} jetons", "usageUnavailable": "Utilisation indisponible", "noRunUsageYet": "Aucune utilisation d'exécution pour l'instant", "noWorkspace": "Aucun espace de travail", @@ -16350,7 +16556,11 @@ "moveOriginalUnverified": "Créé sur {host}, mais la suppression d'origine n'a pas pu être vérifiée. Vérifiez l'ancien hôte avant de réessayer.", "tableHost": "Hôte", "ownerChanged": "Cette automatisation a changé d'hôtes. Actualisez et réessayez.", - "runError": "Erreur :" + "runError": "Erreur :", + "deleteAutomationDescription": "Supprimer et son historique d’exécution. Les espaces de travail créés par les exécutions précédentes ne seront pas supprimés.", + "deleteExternalAutomationDescription": "Supprimer de sur .", + "runUsageSummaryTokens_one": "{{cost}} (est.) · {{tokens}} token", + "runUsageSummaryTokens_other": "{{cost}} (est.) · {{tokens}} tokens" }, "AutomationsPageSkeleton": { "55527b7bcf": "Chargement des automatisations" @@ -16380,8 +16590,8 @@ "92405f1431": "Indisponible", "dbdcec22bd": "Lecture seule", "0a2d4359a8": "Gérable", - "e2532150ed": "automatisations", - "701515f010": "automatisation" + "automationCount_one": "{{count}} automatisation", + "automationCount_other": "{{count}} automatisations" }, "WorkspaceCombobox": { "ee5b280eba": "Aucun espace de travail trouvé.", @@ -16423,7 +16633,8 @@ "last": { "run": { "done": "Terminé", - "failed": "Échec" + "failed": "Échec", + "statusWithRelative": "{{status}} · {{relative}}" } } }, @@ -16568,15 +16779,12 @@ }, "externalScope": { "uncheckedHost": "Les gestionnaires d'automatisation externes sur {{hostLabel}} n'ont pas pu être vérifiés.", - "uncheckedHosts": "Les gestionnaires d'automatisation externes sur les hôtes {{count}} n'ont pas pu être vérifiés." + "uncheckedHostCount_one": "Impossible de vérifier les gestionnaires d’automatisations externes sur {{count}} hôte.", + "uncheckedHostCount_other": "Impossible de vérifier les gestionnaires d’automatisations externes sur {{count}} hôtes." }, "enablement": { "paused": "En pause" }, - "runHistory": { - "occurrencesWithLatest": "{{times}} fois, le plus récemment {{date}}", - "occurrences": "{{times}} fois" - }, "createDestination": { "label": "Hôte", "placeholder": "Sélectionnez un hôte", @@ -16630,6 +16838,71 @@ "useFreshSessions": "Utiliser de nouvelles sessions", "helper": "Ajoutés aux arguments par défaut de cet hôte à chaque nouvelle session.", "detailLabel": "Arguments supplémentaires" + }, + "runHistory": { + "runCountSummary_one": "{{count}} exécution · terminées : {{completed}}", + "runCountSummary_other": "{{count}} exécutions · terminées : {{completed}}", + "occurrencesWithLatestCount_one": "{{count}} fois, dernièrement le {{date}}", + "occurrencesWithLatestCount_other": "{{count}} fois, dernièrement le {{date}}", + "occurrencesCount_one": "{{count}} fois", + "occurrencesCount_other": "{{count}} fois" + }, + "capabilityProbe": { + "createIdempotencyUpdateRequired": "Le déplacement d’automatisations vers cet hôte nécessite un serveur Orca plus récent. Mettez le HUB à jour et réessayez." + }, + "editDraft": { + "unsupportedSchedule": "Cette automatisation a une planification enregistrée non prise en charge. Choisissez une planification prise en charge avant d’enregistrer les modifications." + }, + "hostCatalog": { + "orphanEntryLabel": "Anciennes automatisations non assignées" + }, + "automationPageParts": { + "never": "Jamais", + "now": "à l’instant", + "runStatusPending": "En file d’attente", + "runStatusDispatching": "Démarrage", + "runStatusDispatched": "Lancée", + "runStatusCompleted": "Terminée", + "runStatusSkippedPrecheck": "Ignorée par pré-vérification", + "runStatusSkippedMissed": "Ignorée", + "runStatusSkippedUnavailable": "Indisponible", + "runStatusSkippedNeedsInteractiveAuth": "Identifiants requis", + "runStatusDispatchFailed": "Échec" + }, + "runContent": { + "noOutput": "Aucun contenu de sortie disponible." + }, + "runViewState": { + "viewRun": "Voir l’exécution", + "runOpen": "L’exécution est ouverte", + "terminalOnPairedServer": "Le terminal de l’exécution est sur le serveur associé.", + "terminalUnavailable": "Le terminal de l’exécution est indisponible.", + "openWorkspace": "Ouvrir l’espace de travail", + "workspaceAvailable": "L’espace de travail est disponible.", + "snapshotSaved": "Instantané enregistré", + "showingSnapshot": "Affichage de l’instantané enregistré de l’exécution.", + "namedWorkspaceGone": "{{name}} n’est plus disponible", + "workspaceGone": "L’espace de travail n’est plus disponible", + "noWorkspaceLaunched": "Aucun espace de travail lancé" + }, + "runWorkspaceDisplay": { + "notLaunched": "Non lancé", + "namedWorkspaceGone": "{{name}} (plus disponible)" + }, + "usage": { + "tokensAndCost_one": "{{tokens}} token · {{cost}}", + "tokensAndCost_other": "{{tokens}} tokens · {{cost}}" + }, + "externalDisplay": { + "sshHost": "Hôte SSH", + "local": "Local" + }, + "externalActionDisabled": { + "actionInProgress": "Une autre action d’automatisation est toujours en cours.", + "sshConnecting": "Attendez la fin de la connexion de cet hôte SSH.", + "connectSshHost": "Connectez cet hôte SSH avant de gérer les automatisations {{provider}}.", + "cannotManageOnSshHost": "{{provider}} ne peut pas gérer les automatisations sur cet hôte SSH.", + "cannotManageLocally": "{{provider}} ne peut pas gérer les automatisations sur cette machine." } }, "agent": { @@ -16770,8 +17043,6 @@ "63ce735809": "Se connecter", "4a2ab52781": "Vérification…", "79e7aaed39": "Annuler", - "fdd26d81cc": "Paramètres du compte Atlassian", - "8090504a3e": "Créez un token dans", "7b3967c12f": "Token API Atlassian", "3d81bf3ab3": "Token API", "e91b9a4073": "you@example.com", @@ -16796,17 +17067,18 @@ "be9eba0a1b": "nom d'utilisateur", "70035652d7": "Mot de passe", "c50abbf340": "Mot de passe du compte Jira", - "d8737db691": "Utilisez le nom d'utilisateur et le mot de passe de votre compte Jira Server ou Data Center." + "d8737db691": "Utilisez le nom d'utilisateur et le mot de passe de votre compte Jira Server ou Data Center.", + "createTokenInSettings": "Créez un jeton dans les paramètres du compte Atlassian." } } }, "rightSidebar": { "FolderWorkspaceWorktreesPanel": { "unavailable": "Les espaces de travail ne sont affichés que pour les espaces de travail de type dossier.", - "countOne": "1 worktree attaché", - "countMany": "{{value0}} worktrees attachés", "emptyTitle": "Aucun worktree attaché pour l'instant", - "emptyCopy": "Les worktrees créés depuis cet espace de travail apparaîtront ici." + "emptyCopy": "Les worktrees créés depuis cet espace de travail apparaîtront ici.", + "attachedCount_one": "{{count}} worktree attaché", + "attachedCount_other": "{{count}} worktrees attachés" }, "FolderWorkspacePrChecksPanel": { "unavailable": "Les vérifications PR ne sont affichées que pour les espaces de travail de type dossier.", @@ -16818,12 +17090,12 @@ "hideDetails": "Masquer les détails des vérifications PR de {{value0}}", "reviewChecks": "Vérifications de revue", "allChecksPassing": "toutes les vérifications passent", - "oneWorktree": "1 worktree", - "worktreeCount": "{{value0}} worktrees", - "oneFailing": "1 en échec", - "failingCount": "{{value0}} en échec", - "onePending": "1 en attente", - "pendingCount": "{{value0}} en attente" + "worktreeCountLabel_one": "{{count}} worktree", + "worktreeCountLabel_other": "{{count}} worktrees", + "failingCountLabel_one": "{{count}} en échec", + "failingCountLabel_other": "{{count}} en échec", + "pendingCountLabel_one": "{{count}} en attente", + "pendingCountLabel_other": "{{count}} en attente" }, "parentPrChecks": { "rowSummary": { @@ -16905,10 +17177,11 @@ "combobox": { "noProjects": "Aucun projet", "allProjects": "Tous les projets", - "hostCount": "{{value0}} hôtes", "searchProjects": "Rechercher des projets...", "noMatches": "Aucun projet ne correspond à votre recherche.", - "chooseSource": "Choisir la source des tâches" + "chooseSource": "Choisir la source des tâches", + "hostCount_one": "{{count}} hôte", + "hostCount_other": "{{count}} hôtes" } } }, @@ -16945,7 +17218,35 @@ "taskSourceContextSummary": { "sourceUnavailable": "Source {{value0}} indisponible : {{value1}}", "someSourceHostsUnavailable": "Certains hôtes de la source {{value0}} sont indisponibles : {{value1}}", - "reconnectOrUpdateTitle": "Reconnectez ou mettez à jour {{value0}} pour charger cette source." + "reconnectOrUpdateTitle": "Reconnectez ou mettez à jour {{value0}} pour charger cette source.", + "providerSourceTitle": "Source {{provider}}", + "hostTitle": "Hôte : {{hosts}}", + "accountTitle": "Compte : {{accounts}}", + "sourceTitle": "Source : {{source}}", + "sourceHostCount_one": "{{count}} hôte source", + "sourceHostCount_other": "{{count}} hôtes sources", + "noHost": "Aucun hôte", + "projectCount_one": "{{count}} projet", + "projectCount_other": "{{count}} projets", + "selectedProject": "Projet sélectionné", + "selectedProjectCount_one": "{{count}} projet sélectionné", + "selectedProjectCount_other": "{{count}} projets sélectionnés", + "currentAccount": "Compte actuel", + "statusCheckingCapabilities": "vérification des capacités du serveur", + "statusServerUpdateForTaskSources": "mise à jour du serveur requise pour les sources de tâches", + "statusProviderAuthNeeded": "authentification du fournisseur requise", + "statusSourceToolUnavailable": "outil source indisponible", + "statusProviderUnsupported": "fournisseur non pris en charge sur cet hôte", + "statusServerUpdateNeeded": "mise à jour du serveur requise", + "unavailableCount_one": "{{count}} indisponible", + "unavailableCount_other": "{{count}} indisponibles", + "statusConnected": "connecté", + "statusAuthNeeded": "authentification requise", + "statusConnecting": "connexion en cours", + "statusConnectionIssue": "problème de connexion", + "statusDisconnected": "déconnecté", + "hostStatus": "{{host}} {{status}}", + "availabilityTitle": "Disponibilité : {{hosts}}" }, "ShortcutKeyCombo": { "07eb4985a1": "Appuyez deux fois sur {{value0}}" @@ -17212,19 +17513,9 @@ "untitled": "Discussion sans titre", "listLabel": "Des discussions qui reprendraient", "dontAskAgain": "Ne plus demander (reprendre automatiquement)", - "dontAskAgainHint": "Vous pouvez désactiver cette option dans Paramètres → Expérimental → Chat UI.", - "continuedOne": "1 chat a été repris", - "continuedMany": "{{value0}} chats ont été repris", + "dontAskAgainHint": "Vous pouvez désactiver cette option dans Paramètres → Chat → Comportement.", "selectAgent": "Reprendre le chat {{value0}} \"{{value1}}\" dans {{value2}}", - "resumeSelected": "Reprendre les discussions {{value0}}", - "resumeSelectedOne": "Reprendre 1 discussion", "dismissAll": "Tout rejeter", - "notContinuedOne": "1 chat n'a pas pu reprendre", - "notContinuedMany": "{{value0}} chats n'ont pas pu reprendre", - "notConfirmedOne": "Impossible de confirmer qu'1 chat a repris", - "notConfirmedMany": "Impossible de confirmer que {{value0}} chats ont repris", - "notConfirmedOtherOne": "Impossible de confirmer qu'1 autre chat a repris", - "notConfirmedOtherMany": "Impossible de confirmer que {{value0}} autres chats ont repris", "viewChats": "Voir les chats", "review": "Vérifier", "activityUnnamed": "sans nom", @@ -17232,9 +17523,7 @@ "activityQuestion": "En attente de votre réponse : {{value0}}", "activityMidReply": "Réponse en cours", "activitySubagentOne": "Sous-agent en cours : {{value0}}", - "activitySubagentMany": "{{value0}} sous-agents en cours", "activityMonitorOne": "Surveillance : {{value0}}", - "activityMonitorMany": "Surveillance de {{value0}} tâches en arrière-plan", "selectWorkspace": "Sélectionner toutes les discussions dans {{value0}}", "workspaceSelectedCount": "{{value0}} sur {{value1}}", "selectAll": "Sélectionner toutes les discussions", @@ -17251,8 +17540,22 @@ "serverBody": "Ces chats étaient en cours lorsque Orca a redémarré sur {{machine}}. La reprise restaure chacun là où il s'était arrêté et demande à l'agent de continuer. Votre propre prompt n'est pas renvoyé.", "serverDismiss": "Ignorer", "serverResumeAll": "Reprendre les {{count}} sur {{machine}}", - "serverResumeHereOne": "Reprendre 1 chat démarré ici", - "serverResumeHere": "Reprendre {{count}} chats démarrés ici" + "resumeChats_one": "Reprendre {{count}} discussion", + "resumeChats_other": "Reprendre {{count}} discussions", + "serverResumeHereCount_one": "Reprendre {{count}} discussion démarrée ici", + "serverResumeHereCount_other": "Reprendre {{count}} discussions démarrées ici", + "continuedCount_one": "{{count}} discussion reprise", + "continuedCount_other": "{{count}} discussions reprises", + "notContinuedCount_one": "Impossible de reprendre {{count}} discussion", + "notContinuedCount_other": "Impossible de reprendre {{count}} discussions", + "notConfirmedCount_one": "Impossible de confirmer la reprise de {{count}} discussion", + "notConfirmedCount_other": "Impossible de confirmer la reprise de {{count}} discussions", + "notConfirmedOtherCount_one": "Impossible de confirmer la reprise de {{count}} autre discussion", + "notConfirmedOtherCount_other": "Impossible de confirmer la reprise de {{count}} autres discussions", + "activitySubagentCount_one": "{{count}} sous-agent en cours d’exécution", + "activitySubagentCount_other": "{{count}} sous-agents en cours d’exécution", + "activityMonitorCount_one": "Surveillance de {{count}} tâche en arrière-plan", + "activityMonitorCount_other": "Surveillance de {{count}} tâches en arrière-plan" }, "linear-issue-attribute-filter-coverage-notice": { "statusPartialTeamCoverage": "Filtrage des statuts des équipes {{value0}} sur {{value1}} : les problèmes des équipes restantes ne sont pas inclus.", @@ -17388,15 +17691,15 @@ } }, "NativeChatResumeRunPanel": { - "resumedTitle": "{{value0}} discussions sur {{value1}} reprises", - "resumedTitleOne": "{{value0}} discussion sur 1 reprise", - "resumingTitleOne": "Reprise d’une discussion", - "resumingTitle": "Reprise de {{value0}} discussions", "description": "Chaque discussion est restaurée avec tout son contexte, et l’agent vérifie où il s’était arrêté. Vous pouvez fermer cette fenêtre ; la barre d’état suit la progression.", "finished": "Ces discussions étaient en cours quand Orca s’est fermé. Orca a restauré chacune là où elle s’était arrêtée, avec tout son contexte, et a demandé à l’agent de vérifier ce qu’il faisait avant de continuer. Vos propres messages n’ont pas été renvoyés.", "finishedUpdate": "Ces discussions étaient en cours quand Orca a installé une mise à jour. Orca a restauré chacune là où elle s’était arrêtée, avec tout son contexte, et a demandé à l’agent de vérifier ce qu’il faisait avant de continuer. Vos propres messages n’ont pas été renvoyés.", "finishedPartial": "Ces discussions étaient en cours quand Orca s’est fermé. Celles qu’Orca a reprises ont été restaurées là où elles s’étaient arrêtées, avec tout leur contexte, et invitées à vérifier ce qu’elles faisaient avant de continuer. Vos propres messages n’ont pas été renvoyés. Consultez la liste pour voir les discussions qui nécessitent encore votre attention ou qui peuvent être reprises.", - "finishedPartialUpdate": "Ces discussions étaient en cours quand Orca a installé une mise à jour. Celles qu’Orca a reprises ont été restaurées là où elles s’étaient arrêtées, avec tout leur contexte, et invitées à vérifier ce qu’elles faisaient avant de continuer. Vos propres messages n’ont pas été renvoyés. Consultez la liste pour voir les discussions qui nécessitent encore votre attention ou qui peuvent être reprises." + "finishedPartialUpdate": "Ces discussions étaient en cours quand Orca a installé une mise à jour. Celles qu’Orca a reprises ont été restaurées là où elles s’étaient arrêtées, avec tout leur contexte, et invitées à vérifier ce qu’elles faisaient avant de continuer. Vos propres messages n’ont pas été renvoyés. Consultez la liste pour voir les discussions qui nécessitent encore votre attention ou qui peuvent être reprises.", + "resumedOfTotal_one": "Discussions reprises : {{resumed}} sur {{count}}", + "resumedOfTotal_other": "Discussions reprises : {{resumed}} sur {{count}}", + "resumingCount_one": "Reprise de {{count}} discussion", + "resumingCount_other": "Reprise de {{count}} discussions" }, "NativeChatResumeRunStatusIcon": { "waitingForReply": "En attente de réponse", @@ -17446,6 +17749,72 @@ "copyFailed": "Impossible de copier le lien.", "signingIn": "Connexion…", "cancel": "Annuler" + }, + "AgentStateDot": { + "working": "En cours", + "monitoring": "Surveillance des tâches en arrière-plan", + "blocked": "Bloqué", + "waiting": "En attente de saisie", + "interrupted": "Interrompu", + "failed": "Échec", + "done": "Terminé", + "idle": "Inactif", + "unverifiable": "Aucune mise à jour récente", + "unconfirmed": "Confirmation impossible", + "permission": "Attention requise" + }, + "issueComments": { + "you": "Vous" + }, + "ZoomOverlay": { + "uiZoom": "Zoom de l’interface", + "editorZoom": "Zoom de l’éditeur", + "terminalZoom": "Zoom du terminal" + }, + "issueCopy": { + "urlCopied": "URL copiée", + "keyCopied": "Clé copiée", + "identifierCopied": "Identifiant copié", + "branchNameCopied": "Nom de branche copié", + "promptCopied": "Prompt copié", + "urlCopyFailed": "Impossible de copier l’URL", + "keyCopyFailed": "Impossible de copier la clé", + "identifierCopyFailed": "Impossible de copier l’identifiant", + "branchNameCopyFailed": "Impossible de copier le nom de branche", + "promptCopyFailed": "Impossible de copier le prompt" + }, + "prCheckCounts": { + "noChecksFound": "Aucune vérification trouvée", + "checksFailing_one": "{{count}} vérification en échec", + "checksFailing_other": "{{count}} vérifications en échec", + "checksNeedAction_one": "{{count}} vérification nécessite une action", + "checksNeedAction_other": "{{count}} vérifications nécessitent une action", + "checksPending_one": "{{count}} vérification en attente", + "checksPending_other": "{{count}} vérifications en attente", + "allChecksPassing": "Toutes les vérifications réussissent", + "checksPassingOfTotal_one": "Vérifications réussies : {{passing}} sur {{count}}", + "checksPassingOfTotal_other": "Vérifications réussies : {{passing}} sur {{count}}" + }, + "taskPageJiraBoard": { + "changeStatusFailed": "Impossible de modifier le statut." + }, + "jiraIssue": { + "loadStatusChangesFailed": "Impossible de charger les changements de statut.", + "loadCommentsFailed": "Impossible de charger les commentaires." + }, + "taskPageJiraLinkedIssues": { + "someIssuesFailed": "Impossible de charger certaines issues Jira liées à des espaces de travail. Actualisez pour réessayer." + }, + "taskPageJiraLoadState": { + "failedToLoadIssues": "Impossible de charger les issues Jira.", + "authFailed": "Échec de l’authentification Jira. Reconnectez Jira dans les paramètres, puis réessayez.", + "accessDenied": "Jira a refusé l’accès à cette recherche d’issues. Vérifiez les permissions du projet ou essayez une autre requête JQL.", + "rateLimited": "Jira a limité cette recherche d’issues en raison du nombre de requêtes. Réessayez dans un instant.", + "serverError": "Une erreur serveur Jira est survenue lors du chargement des issues. Réessayez dans un instant.", + "jqlFailed": "Jira n’a pas pu exécuter cette requête JQL. Vérifiez la syntaxe et réessayez.", + "unreachable": "Impossible de joindre Jira. Vérifiez votre connexion et réessayez.", + "loadFailed": "Impossible de charger les issues Jira. Réessayez dans un instant.", + "errorWithCode": "Erreur {{code}} : {{summary}}" } }, "i18n": { @@ -17614,6 +17983,7 @@ "agentCommandNotRunnable": "{{agent}} : la Commande dans Paramètres → Agents doit être le chemin ou le nom d'un programme qu'Orca peut trouver, sans arguments ni variables. Modifiez-la ou réinitialisez-la.", "runtimeNotInstalled": "{{agent}} n'est pas installé sur l'ordinateur qui exécute ce chat. Installez-le depuis le chat dans une version récente d'Orca.", "fullAccessAsRoot": "{{agent}} n'utilisera pas l'Accès complet tant qu'il s'exécute en tant que root. Choisissez une autre autorisation pour {{agent}} dans Paramètres → Agents pour l'ordinateur qui exécute ce chat, puis démarrez un nouveau chat.", + "launchPreparationFailed": "Orca n'a pas pu préparer le démarrage de {{agent}} sur l'ordinateur qui exécute ce chat.", "conversationOpenElsewhere": "Codex maintient encore cette conversation ouverte. Réessayez dans un instant ou fermez les autres terminaux Codex.", "conversationOpenInTerminal": "{{agent}} exécute déjà cette conversation dans un autre terminal. Quittez {{agent}} là-bas ou fermez ce terminal pour continuer ici.", "chooseClaudeAccount": "Choisissez-en un ou ajoutez-en un dans les paramètres Comptes Claude.", @@ -17763,7 +18133,8 @@ "compactAfterRetry": "Réessayez votre message précédent, puis lancez /compact.", "clearAfterSending": "Votre message précédent est encore en cours d'envoi. Lancez /clear une fois qu'il est parti.", "compactAfterSending": "Votre message précédent est encore en cours d'envoi. Lancez /compact une fois qu'il est parti.", - "pendingWork": "Attendez la fin du travail et des messages en attente avant d'utiliser cette commande." + "pendingWork": "Attendez la fin du travail et des messages en attente avant d'utiliser cette commande.", + "notDoneGoalChangeIncomplete": "Impossible de terminer la modification de l’objectif. Consultez le chat." }, "composer": { "imageUnavailable": "Aperçu indisponible", @@ -18267,7 +18638,6 @@ "pausedSendFailedWaiting": "Envoi impossible. Quand l'agent aura terminé, appuyez sur Envoyer pour réessayer.", "save": "Enregistrer", "editingMessage": "Modification du message", - "cancelEditing": "Annuler la modification", "editChanged": "Ce message a changé pendant que vous le modifiiez. Votre modification se trouve dans le champ de discussion.", "editChangedPrompt": "Ce message a changé pendant que vous le modifiiez. Votre modification sera dans le champ de discussion une fois que vous aurez répondu à l'agent.", "editChangedNotSaved": "Ce message a changé pendant que vous le modifiiez. Votre modification n'a pas été enregistrée.", @@ -18281,8 +18651,6 @@ "expand": "Développer", "queued": "En file d'attente", "clearAll": "Tout effacer", - "pasteOrDropImages": "Collez ou déposez des images", - "saveNeedsContent": "Ajoutez du texte ou une image pour enregistrer", "moveChanged": "La file d'attente a changé avant ce déplacement. Essayez de faire glisser le message à nouveau.", "reorderHint": "Faites glisser pour réorganiser, ou utilisez les touches fléchées Haut et Bas.", "reorderMessage": "Réorganiser le message" @@ -18435,6 +18803,15 @@ "settings": "Ouvrir les paramètres dans le terminal", "extensions": "Ouvrir le tableau de bord des extensions dans le terminal", "hotkeys": "Afficher les raccourcis clavier dans le terminal" + }, + "modelDescriptions": { + "grok_4_7": "Le dernier modèle de pointe de xAI", + "grok_4_6": "Le précédent modèle de pointe de xAI", + "grok_4_5": "Un ancien modèle de pointe de xAI", + "fable": "Le plus performant pour les tâches les plus difficiles et longues", + "opus": "Idéal pour les tâches complexes du quotidien", + "sonnet": "Efficace pour les tâches courantes", + "haiku": "Le plus rapide pour des réponses immédiates" } }, "tab": { @@ -19012,7 +19389,6 @@ "subagents_other": "{{count}} sous-agents" }, "terminal": { - "closed": "Pas de terminal en direct — le volet de cet agent est fermé.", "focusWorktree": "Ouvrir le worktree", "close": "Fermer", "remotePreviewUnavailable": "Aucun aperçu pour cette session à distance — ouvrez l'espace de travail pour afficher le terminal." @@ -19149,7 +19525,9 @@ }, "quickOpen": { "moreMatchesAvailable": "D'autres correspondances sont peut-être disponibles. Affinez votre recherche pour réduire les résultats.", - "recentValidationFailed": "Impossible de vérifier les fichiers récents : {{error}}" + "recentValidationFailed": "Impossible de vérifier les fichiers récents : {{error}}", + "installRipgrepOnRemote": "Installez ripgrep sur l'hôte distant pour lister rapidement les fichiers en respectant les règles de .gitignore :", + "scanTooLarge": "L'analyse de l'ouverture rapide est trop volumineuse ({{reason}})." }, "notifications": { "agentStatus": { @@ -19192,6 +19570,30 @@ "confirm": "Ajustez les filtres et révélez", "cancel": "Conserver les filtres" }, + "wslMoved": { + "movedToHost": "Déplacé vers l'hôte {{distro}}", + "useHere": "Utiliser à nouveau sur cet ordinateur", + "useHereTitle": "Utiliser à nouveau {{name}} sur cet ordinateur ?", + "useHereDescription": "Orca ouvrira ce projet ici tel qu'il était avant le déplacement. Votre code n'est pas concerné : il n'a jamais été déplacé. Les modifications faites sur l'hôte {{distro}} depuis le déplacement, comme de nouveaux onglets et chats, restent sur l'hôte et ne reviennent pas. Les projets déplacés avec celui-ci reviennent aussi. Le projet reste également sur l'hôte {{distro}} jusqu'à ce que vous l'y supprimiez. Cette fenêtre va se recharger.", + "useHereConfirm": "Utiliser sur cet ordinateur", + "useHereSuperseded": "Un déplacement ultérieur vers l'hôte {{distro}} inclut ce projet. Ramenez d'abord celui-là.", + "useHereRefusedTitle": "Impossible d'utiliser {{name}} ici pour le moment", + "useHereRefusedOk": "OK", + "useHereSupersededBy": "Ces projets ont été déplacés vers l'hôte {{distro}} après celui-ci : {{names}}. Ramenez-les d'abord sur cet ordinateur, puis ce projet.", + "useHereMoveRunning": "Un déplacement vers l'hôte {{distro}} est encore en cours. Réessayez une fois terminé.", + "useHereHostKeptForPeers": "{{project}} a été déplacé vers l'hôte {{distro}}, qui reste actif pour un autre Orca. Ajoutez de nouveau l'hôte pour l'utiliser ici.", + "useHereHostUnreachable": "L'hôte {{distro}} ne répond pas : Orca ne peut pas arrêter sa copie de ce projet, et ses agents y tournent peut-être encore. Connectez l'hôte dans les Paramètres, ou supprimez-le, puis réessayez.", + "useHereHostStillRunning": "La copie de ce projet sur l'hôte {{distro}} a encore des terminaux en cours : ses agents pourraient tourner deux fois. Patientez un instant, puis réessayez.", + "useHereFailed": "Impossible de ramener ce projet sur cet ordinateur.", + "useHereHostRemovalPending": "L'hôte {{distro}} est encore en cours de suppression, Orca n'y touche donc pas. Terminez sa suppression dans les Paramètres, puis réessayez.", + "useHereHostAutomations": "Orca n'a pas pu désactiver les automatisations de ce projet sur l'hôte {{distro}} : elles pourraient s'exécuter deux fois. Connectez l'hôte dans les Paramètres, puis réessayez.", + "useHereUnsavedTitle": "Enregistrez d'abord vos fichiers", + "useHereUnsavedDescription": "Récupérer {{name}} recharge cette fenêtre. Enregistrez ou fermez d'abord ces fichiers : {{files}}", + "automationRunsOnHost": "S'exécute sur l'hôte {{distro}}", + "quitDuringMoveTitle": "Quitter pendant le déplacement d'un projet ?", + "quitDuringMoveDescription": "Un projet est en cours de déplacement vers son hôte WSL. Quitter quand même ? Le déplacement sera annulé au prochain lancement.", + "quitDuringMoveConfirm": "Quitter quand même" + }, "startupWorktreeRefresh": { "loading": "Recherche des espaces de travail…", "description": "D'autres espaces de travail peuvent apparaître pendant le chargement des projets locaux et distants." @@ -19232,11 +19634,20 @@ }, "discard": { "deleteUntrackedFileDescription": "Cela supprimera définitivement ce fichier non suivi. Cette action est irréversible.", - "deleteUntrackedFilesDescription": "Cela supprimera définitivement ces {{count}} fichiers non suivis. Cette action est irréversible.", + "deleteUntrackedFilesDescription_other": "Cela supprimera définitivement ces {{count}} fichiers non suivis. Cette action est irréversible.", "restoreStagedVersionDescription": "Cela restaurera la dernière version intermédiaire et annulera la suppression. Cela ne peut pas être annulé.", "unstagedChangesDescription": "Cela annulera les modifications non planifiées apportées à ce fichier. Cela ne peut pas être annulé.", "unstagedSelectionIncludingUntrackedDescription": "Cela annulera les modifications non indexées et supprimera définitivement tous les fichiers non suivis de cette sélection. Cette action est irréversible.", - "unstagedFilesIncludingUntrackedDescription": "Cela annulera les modifications non indexées et supprimera définitivement tous les fichiers non suivis parmi ces {{count}} fichiers. Cette action est irréversible." + "unstagedFilesIncludingUntrackedDescription_other": "Cela annulera les modifications non indexées et supprimera définitivement tous les fichiers non suivis parmi ces {{count}} fichiers. Cette action est irréversible.", + "delete": "Supprimer", + "restore": "Restaurer", + "discard": "Abandonner", + "discardAll": "Tout abandonner", + "deleteUntrackedTitle_one": "Supprimer {{count}} fichier non suivi ?", + "deleteUntrackedTitle_other": "Supprimer {{count}} fichiers non suivis ?", + "deleteCount": "Supprimer {{count}}", + "deleteUntrackedFilesDescription_one": "Cela supprimera définitivement {{count}} fichier non suivi. Cette action est irréversible.", + "unstagedFilesIncludingUntrackedDescription_one": "Cela annulera les modifications non indexées apportées à {{count}} fichier et le supprimera définitivement s'il n'est pas suivi. Cette action est irréversible." }, "createReviewFailure": { "authRequiredCommand": "{{providerName}} n'est pas authentifié. Étape suivante : exécutez {{command}} dans cet environnement.", @@ -19267,6 +19678,34 @@ "creationUnconfirmed": "La création de {{shortLabel}} est peut-être terminée. Actualisation de l'état de revue de la branche...", "withDetail": "La création de {{shortLabel}} a échoué : {{detail}}", "pushFailed": "Le push a échoué. Résolvez l'erreur de push, puis réessayez." + }, + "thinking": { + "off": "Désactivé", + "low": "Basse", + "medium": "Moyenne", + "high": "Haute", + "minimal": "Minimal", + "xhigh": "Très élevé", + "max": "Maximum" + }, + "variables": { + "basePrompt": "Le prompt intégré d’Orca pour cette action, avec le contexte qu’Orca sait recueillir en toute sécurité.", + "branch": "Le nom de la branche actuelle du contrôle de version.", + "stagedFiles": "La liste des fichiers indexés, séparés par des sauts de ligne, pour générer le message de commit.", + "stagedPatch": "Le patch Git indexé utilisé pour générer le message de commit.", + "baseBranch": "La branche cible sélectionnée dans l’éditeur de création de PR.", + "currentTitle": "Le titre du PR saisi dans l’éditeur avant le début de la génération.", + "currentBody": "La description du PR saisie dans l’éditeur avant le début de la génération.", + "commitSummary": "La liste des commits de la branche par rapport à la base, séparés par des sauts de ligne.", + "changedFiles": "Un résumé des fichiers modifiés entre la branche et sa base.", + "patch": "Le diff de la branche par rapport à sa base utilisé pour générer les détails du PR.", + "firstPrompt": "La première demande de l’utilisateur dans cet espace de travail ou ce chat.", + "assistantMessage": "La réponse initiale de l’agent, lorsqu’Orca en dispose.", + "linkedIssue": "Le numéro de l’issue GitHub liée à cet espace de travail. Vide si aucune issue GitHub n’est liée (y compris pour les espaces liés à GitLab). Préférez les modèles avec instructions : « Fixes #{linkedIssue} » seul devient « Fixes # » sans lien." + }, + "model": { + "configDefault": "Valeur par défaut de la configuration", + "auto": "Automatique" } }, "agentsSidebarIntro": { @@ -19298,8 +19737,6 @@ }, "sessionSearch": { "panel": { - "resultsOne": "résultat {{count}}", - "resultsOther": "Résultats {{count}}", "noMatches": "Aucune session correspondante dans l'historique indexé. Essayez une autre requête ou une autre étendue.", "loadMore": "Charger plus de matchs", "indexedHistory": "Historique indexé", @@ -19320,12 +19757,24 @@ "retry": "Essayer à nouveau", "scopeUnknown": "Cet ordinateur ne dispose pas de cet espace de travail ou de ce projet. Basculez la portée sur Tous pour tout rechercher.", "sortSessionsAriaLabel": "Trier les sessions : {{value0}}", - "sessionsOne": "Séance {{count}}", - "sessionsOther": "{{count}} séances", - "sessionsOfLoaded": "{{value0}} sur {{value1}} séances", "showMoreSessions": "Afficher plus de séances", "loadingMoreSessions": "Chargement de plus de sessions…", - "unsupportedAgent": "Cet ordinateur ne prend pas en charge la recherche dans l'historique de l'agent sélectionné. Mettez à jour Orca sur cet ordinateur ou sélectionnez un autre agent." + "unsupportedAgent": "Cet ordinateur ne prend pas en charge la recherche dans l'historique de l'agent sélectionné. Mettez à jour Orca sur cet ordinateur ou sélectionnez un autre agent.", + "resultCount_one": "{{count}} résultat", + "resultCount_other": "{{count}} résultats", + "sessionCount_one": "{{count}} session", + "sessionCount_other": "{{count}} sessions", + "sessionsShownOfLoaded_one": "{{shown}} sur {{count}} session", + "sessionsShownOfLoaded_other": "{{shown}} sur {{count}} sessions", + "hostSkipReason": { + "indexChanged": "index modifié", + "searchOff": "recherche désactivée", + "notReady": "pas prêt", + "unavailable": "indisponible", + "unreachable": "injoignable", + "scopeNotFound": "périmètre de recherche introuvable sur cet hôte", + "agentNotSupported": "agent non pris en charge" + } } }, "sessionHistory": { @@ -19447,9 +19896,9 @@ "pathAdded": "Added", "openFolder": "Open {{name}}", "findOrTypePath": "Recherchez un dossier ou saisissez n’importe quel chemin…", - "addTypedPath": "Add", "noDirectories": "Aucun dossier ajouté pour l'instant.", - "removePath": "Remove {{name}}" + "removePath": "Remove {{name}}", + "addTypedPathCode": "Ajouter " }, "accounts": { "wslAccountNotApplied": { @@ -19550,10 +19999,7 @@ "title": "Passé à {{account}}", "dontAskAgainHint": "Vous pouvez désactiver cette option dans Paramètres → Comptes de fournisseurs d’IA.", "dontAskAgain": "Ne plus demander (redémarrer automatiquement)", - "bodyOne": "1 session Claude est toujours en cours d'exécution sur {{previous}}. Le redémarrage continue la conversation sur {{next}}. Les sessions occupées attendent d'être inactives avant de redémarrer.", - "bodyOther": "{{count}} sessions Claude sont toujours en cours d’exécution sur {{previous}}. Le redémarrage poursuit chaque conversation sur {{next}}. Les sessions occupées attendent d’être inactives avant de redémarrer.", "restartOne": "Redémarrer la session", - "restartOther": "Redémarrer {{count}} sessions", "session": "Session Claude", "settingTitle": "Lorsque vous changez de compte alors que Claude est en cours d'exécution", "listLabel": "Sessions Claude à redémarrer", @@ -19570,13 +20016,17 @@ "reasonOwnFolder": "Utilise votre propre dossier Claude", "reasonUnknownAccount": "Compte inconnu", "reasonNoSession": "Reprise impossible", - "reviewBodyOne": "1 autre session Claude n'a pas été déplacée vers {{next}}.", - "reviewBodyOther": "{{count}} autres sessions Claude n'ont pas été déplacées vers {{next}}.", "notMovedOne": "1 autre session n'a pas été déplacée.", "notMovedOther": "{{count}} autres sessions n'ont pas été déplacées.", "review": "Vérifier", "uncheckedOne": "Impossible de vérifier la présence de Claude dans 1 terminal. Si Claude y est en cours d’exécution, il reste sur {{previous}} jusqu’à son redémarrage.", - "uncheckedOther": "Impossible de vérifier la présence de Claude dans {{count}} terminaux. Toute instance de Claude qui y tourne reste sur {{previous}} jusqu’à son redémarrage." + "uncheckedOther": "Impossible de vérifier la présence de Claude dans {{count}} terminaux. Toute instance de Claude qui y tourne reste sur {{previous}} jusqu’à son redémarrage.", + "restartCount_one": "Redémarrer {{count}} session", + "restartCount_other": "Redémarrer {{count}} sessions", + "reviewBody_one": "{{count}} autre session Claude n’a pas été déplacée vers {{next}}.", + "reviewBody_other": "{{count}} autres sessions Claude n’ont pas été déplacées vers {{next}}.", + "body_one": "{{count}} session Claude est toujours active sur {{previous}}. Le redémarrage poursuit la conversation sur {{next}}. Les sessions occupées attendent d’être inactives avant de redémarrer.", + "body_other": "{{count}} sessions Claude sont toujours actives sur {{previous}}. Le redémarrage poursuit chaque conversation sur {{next}}. Les sessions occupées attendent d’être inactives avant de redémarrer." } }, "hostSignIn": { @@ -19690,7 +20140,9 @@ "confirmTitle": "Redémarrer le daemon de terminal ?", "confirmBody": "Le redémarrage met fin à tous les processus en cours d'exécution dans {{sessions}}. Les agents qui prennent en charge la reprise peuvent être repris ensuite ; les shells et autres tâches ne le peuvent pas et doivent être redémarrés. Faites-le lorsque vos agents sont inactifs.", "cancel": "Annuler", - "confirm": "Redémarrer et arrêter les processus" + "confirm": "Redémarrer et arrêter les processus", + "count_other": "{{count}} terminaux en cours d'exécution", + "count_one": "{{count}} terminal en cours d’exécution" }, "restartedInputNotSent": "Le terminal a redémarré pendant votre saisie, une partie ne lui est peut-être pas parvenue. Vérifiez le nouveau shell avant de la saisir à nouveau.", "stalledDaemonBanner": { @@ -19865,7 +20317,11 @@ "picker": { "pasteUnparseable": "URL de projet ou owner/number attendu", "ownerLoadFailed": "Impossible de charger les projets de {{owner}}.", - "organizationsLoadFailed": "Certaines organisations n'ont pas été chargées ({{failureCount}})." + "organizationsLoadFailed": "Certaines organisations n'ont pas été chargées ({{failureCount}}).", + "organizations": "Organisations", + "listFailed": "Impossible de lister les projets", + "detailsFailed": "Impossible de charger les détails", + "viewFailed": "Impossible de récupérer la vue du projet" }, "error": { "notFoundState": "Impossible de trouver ce projet ou cette vue.", @@ -19898,8 +20354,12 @@ "rateLimited": "Limite de débit GitHub atteinte. Réessayez dans quelques minutes.", "network": "Erreur réseau — vérifiez votre connexion.", "tooLargeUnknownCount": "Cette vue contient trop d'éléments pour être affichée dans Orca. Restreignez le filtre de la vue sur GitHub.", - "tooLarge": "Cette vue contient {{itemCount}} éléments, trop pour être affichée dans Orca. Restreignez le filtre de la vue sur GitHub.", - "schemaDriftDetail": "Impossible de lire cette vue de projet : {{detail}}." + "schemaDriftDetail": "Impossible de lire cette vue de projet : {{detail}}.", + "tooLargeCount_one": "Cette vue contient {{count}} élément — elle est trop volumineuse pour être affichée dans Orca. Restreignez le filtre de la vue sur GitHub.", + "tooLargeCount_other": "Cette vue contient {{count}} éléments — elle est trop volumineuse pour être affichée dans Orca. Restreignez le filtre de la vue sur GitHub." + }, + "columns": { + "type": "Tapez" } }, "projectField": { @@ -19986,6 +20446,27 @@ "attachments": { "updateRuntime": "Mettez à jour le runtime distant pour modifier les liens de l'espace de travail", "updateRuntimeSafely": "Mettez à jour le runtime distant pour modifier les liens de l'espace de travail en toute sécurité" + }, + "activity": { + "active": "Actif", + "working": "Fonctionnement", + "monitoring": "Surveillance des tâches en arrière-plan", + "failed": "Échec", + "interrupted": "Interrompu", + "unconfirmed": "Impossible de confirmer", + "done": "Terminé", + "inactive": "Inactif", + "permission": "Autorisation requise", + "unreadLabel": "{{status}} · Non lu" + }, + "reviewStatus": { + "checksFailed": "{{review}} : vérifications en échec", + "checksPassing": "{{review}} : vérifications réussies", + "checksPending": "{{review}} : vérifications en attente", + "closed": "{{review}} : fermée", + "draft": "{{review}} : brouillon", + "merged": "{{review}} : fusionnée", + "open": "{{review}} : ouverte" } }, "tabHoverCard": { @@ -20029,13 +20510,13 @@ "optionalEmail": "E-mail Atlassian (facultatif pour les jetons à portée limitée)" }, "workspace": { - "count": "{{count}} espaces de travail liés à {{key}}", "startAnother": "Démarrer un nouvel espace de travail", "empty": "Liez une issue Jira à un espace de travail, ou choisissez une autre vue.", "openFailed": "Impossible d'ouvrir l'espace de travail lié à cette issue Jira.", "mode": "Avec espace de travail", "search": "Rechercher les issues liées", - "single": "1 espace de travail lié à {{key}}" + "linkedCount_one": "{{count}} espace de travail lié à {{key}}", + "linkedCount_other": "{{count}} espaces de travail liés à {{key}}" }, "prompt": { "dialogTitle": "Copier le prompt depuis un modèle", @@ -20128,7 +20609,9 @@ "preparingAriaLabel": "Préparation de la mise à jour. Cliquez pour développer.", "browserSummary": "Le navigateur d'un serveur Orca en arrière-plan utilise toujours cette application.", "browserGuidance": "Terminez le processus ci-dessous, puis réessayez : son serveur continue de fonctionner sans navigateur. Si un autre ordinateur utilise ce Mac comme hôte SSH, la mise à jour d’Orca sur cet ordinateur permet au navigateur de se mettre automatiquement en pause lors des mises à jour." - } + }, + "wslMoveInstallHeld": "Un projet est en cours de déplacement vers son hôte WSL. Installez la mise à jour une fois le déplacement terminé.", + "wslMoveUndoInstallHeld": "Un projet est en train de revenir de son hôte WSL. Installez la mise à jour une fois l'opération terminée." }, "onboarding": { "language": { @@ -20453,7 +20936,8 @@ "email": "Connaître votre adresse e-mail", "allSites": "Lire et modifier toutes vos données sur tous les sites Web", "someSites": "Lire et modifier vos données sur {{hosts}}", - "manySites": "Lire et modifier vos données sur {{hosts}} et {{count}} autres sites" + "manyOtherSites_one": "Lire et modifier vos données sur {{hosts}} et {{count}} autre site", + "manyOtherSites_other": "Lire et modifier vos données sur {{hosts}} et {{count}} autres sites" }, "install": { "title": "Ajouter {{name}} ?", @@ -20483,5 +20967,340 @@ "math": { "scrollDisplayEquation": "Faire défiler l'équation affichée" } + }, + "runtime": { + "health": { + "local": "Local", + "available": "Connecté", + "connecting": "Connexion", + "disconnected": "Déconnecté", + "error": "Demande votre attention", + "mixed": "Mixte", + "repair": "Nouvel appairage requis", + "update": "Mise à jour requise" + }, + "compat": { + "compatible": "Le client et le serveur d’exécution sont compatibles.", + "clientTooOld": "Ce client Orca est trop ancien pour le serveur sélectionné. Mettez Orca à jour sur cette machine. Protocole du client : {{clientProtocol}} ; le serveur exige le protocole client {{requiredProtocol}}.", + "serverTooOld": "Le serveur Orca sélectionné est trop ancien pour ce client. Mettez Orca à jour sur le serveur. Protocole du serveur : {{serverProtocol}} ; le client exige le protocole serveur {{requiredProtocol}}." + } + }, + "native": { + "about": { + "gpu": { + "unknownStatus": "Statut indisponible", + "enabled": "Activé", + "disabled": "Désactivé", + "unavailable": "Indisponible", + "safeMode": "Désactivée (mode graphique sécurisé)", + "software": "Rendu logiciel", + "unknown": "Inconnu ({{status}})", + "summary": "Accélération GPU : {{status}}" + } + }, + "dialog": { + "importCookies": "Importer des cookies", + "spaceTitle": "Espace Orca bêta", + "dashboardTitle": "Tableau de bord des agents Orca", + "cookieFiles": "Fichiers de cookies", + "allFiles": "Tous les fichiers", + "importPetBundle": "Choisir un paquet .codex-pet", + "pickPet": "Choisir une mascotte", + "petImage": "Image de mascotte", + "importWarpTheme": "Importer un thème Warp", + "warpThemeYaml": "YAML de thème Warp", + "importWarpFolder": "Importer un dossier de thèmes Warp", + "images": "Images", + "repoIconImages": "Images d’icône du dépôt", + "audio": "Audio" + } + }, + "taskProviders": { + "linear": { + "updateAccess": "Accès aux mises à jour", + "addAccess": "Ajouter l'accès Linear", + "fetchMore": "Charger plus", + "connectionFailed": "Échec de la connexion", + "listLabel": "Liste Linear", + "projectsLoadFailed": "Impossible de charger les projets.", + "projectNotFound": "Le projet est introuvable.", + "projectLoadFailed": "Impossible de charger le projet.", + "projectIssuesLoadFailed": "Impossible de charger les issues du projet.", + "viewsLoadFailed": "Impossible de charger les vues.", + "viewContentsLoadFailed": "Impossible de charger le contenu de la vue.", + "issuesLoadFailed": "Impossible de charger les issues Linear.", + "apiKeyHint": "Collez une clé API personnelle de l’espace de travail Linear à utiliser dans Orca. Si cet espace est déjà connecté, Orca remplace la clé enregistrée.", + "remoteKeyStorage": "Cette clé est stockée par l’environnement d’exécution distant actif.", + "localKeyStorage": "Les clés de l’environnement d’exécution local sont stockées sur cet appareil avec le stockage chiffré d’Electron lorsqu’il est disponible.", + "commentsLoadFailed": "Impossible de charger les commentaires.", + "updateWorkspaceAccess": "Mettre à jour l’accès Linear pour {{workspace}}", + "workspaceApiKeyHint": "Collez une clé API personnelle pour {{workspace}}. Si cet espace est déjà connecté, Orca remplace la clé enregistrée.", + "connect": "Se connecter", + "descriptionUpdateFailed": "Échec de la mise à jour de la description", + "titleUpdateFailed": "Échec de la mise à jour du titre", + "truncated": { + "issues_one": "Affichage de {{count}} issue en tête de liste. Faites une recherche ou ouvrez Linear pour consulter la liste complète.", + "issues_other": "Affichage des {{count}} premières issues. Faites une recherche ou ouvrez Linear pour consulter la liste complète.", + "projectIssues_one": "Affichage de {{count}} issue du projet en tête de liste. Faites une recherche ou ouvrez Linear pour consulter la liste complète.", + "projectIssues_other": "Affichage des {{count}} premières issues du projet. Faites une recherche ou ouvrez Linear pour consulter la liste complète.", + "projects_one": "Affichage de {{count}} projet en tête de liste. Faites une recherche ou ouvrez Linear pour consulter la liste complète.", + "projects_other": "Affichage des {{count}} premiers projets. Faites une recherche ou ouvrez Linear pour consulter la liste complète.", + "viewIssues_one": "Affichage de {{count}} issue de la vue en tête de liste. Faites une recherche ou ouvrez Linear pour consulter la liste complète.", + "viewIssues_other": "Affichage des {{count}} premières issues de la vue. Faites une recherche ou ouvrez Linear pour consulter la liste complète.", + "views_one": "Affichage de {{count}} vue en tête de liste. Faites une recherche ou ouvrez Linear pour consulter la liste complète.", + "views_other": "Affichage des {{count}} premières vues. Faites une recherche ou ouvrez Linear pour consulter la liste complète." + } + }, + "jira": { + "connectionFailed": "Échec de la connexion", + "remoteTokenStorage": "Votre jeton est envoyé à l’environnement d’exécution distant sélectionné et y est stocké avec le chiffrement pris en charge.", + "localTokenStorage": "Votre jeton est stocké localement et chiffré si le stockage de l’environnement d’exécution local le permet." + }, + "errors": { + "jira": { + "createFailed": "Échec de la création de l'issue.", + "commentFailed": "Échec de l'ajout du commentaire.", + "notConnected": "Non connecté à Jira.", + "titleRequired": "Le titre est requis.", + "labelsConflict": "Fournissez labels ou labelOperations, mais pas les deux.", + "updateFailed": "Impossible de mettre à jour l’issue.", + "credentialsRequired": "L’URL du site, l’adresse e-mail et le jeton API sont requis.", + "projectRequired": "Le projet est requis.", + "issueTypeRequired": "Le type d’issue est requis.", + "issueKeyRequired": "La clé de l’issue est requise.", + "updatesRequired": "L’objet de mise à jour est requis.", + "commentBodyRequired": "Le contenu du commentaire est requis.", + "invalidSiteUrl": "Saisissez une URL de site Jira valide.", + "passwordRequired": "Le mot de passe est requis.", + "personalTokenRequired": "Le jeton d’accès personnel est requis.", + "apiTokenRequired": "Le jeton API est requis.", + "connectionFailed": "Échec de la connexion.", + "invalidSiteIdentity": "Saisissez une URL de site Jira HTTP ou HTTPS sans identifiants.", + "missingProjectIdentity": "Jira a renvoyé un projet sans ID ni clé.", + "invalidIssuePage": "Jira a renvoyé une page d’issues invalide.", + "incompleteIssuePage": "Jira a renvoyé une page d’issues incomplète.", + "repeatedIssueToken": "Jira a renvoyé un jeton de page d’issues invalide ou répété.", + "issueSearchLimit": "La recherche d’issues Jira a dépassé la limite de pages. Sélectionnez plutôt un projet avec JQL.", + "invalidProjectPage": "Jira a renvoyé une page de projets invalide.", + "incompleteProjectPage": "Jira a renvoyé une page de projets incomplète.", + "projectListLimit": "La liste des projets Jira a dépassé la limite de pages. Sélectionnez plutôt un projet avec JQL.", + "invalidCloudId": "Le site n’a pas fourni d’ID Atlassian Cloud valide." + }, + "linear": { + "notConnected": "Non connecté à Linear", + "createFailed": "Échec de la création dans Linear", + "createdButUnavailable": "L’issue a été créée, mais n’a pas pu être récupérée", + "updateFailed": "Échec de la mise à jour dans Linear", + "commentFailed": "Impossible de créer le commentaire", + "projectCreateFailed": "Échec de la création du projet Linear", + "noApiKey": "Aucune clé API n’est enregistrée.", + "workspaceAuthExpired": "L’authentification Linear a expiré pour cet espace de travail.", + "projectNameRequired": "Le nom du projet est requis", + "projectIdRequired": "L’ID du projet est requis", + "projectNotFound": "Le projet est introuvable", + "viewIdRequired": "L’ID de la vue personnalisée est requis", + "viewHasNoIssues": "La vue personnalisée ne contient pas d’issues", + "viewHasNoProjects": "La vue personnalisée ne contient pas de projets" + } + } + }, + "workspaceOptions": { + "activeFilterCount_one": "{{count}} filtre", + "activeFilterCount_other": "{{count}} filtres" + }, + "editorConflicts": { + "kind": { + "addedByUs": "Ajouté chez nous", + "bothAdded": "Ajouté des deux côtés", + "deletedByUs": "Supprimé chez nous", + "addedByThem": "Ajouté chez eux", + "bothDeleted": "Supprimé des deux côtés", + "bothModified": "Modifié des deux côtés", + "deletedByThem": "Supprimé chez eux" + }, + "resolvedBanner": "Conflit résolu localement · {{kind}}", + "hint": { + "addedByUs": "Vérifiez s'il faut conserver le fichier ajouté", + "bothModified": "Résolvez les conflits signalés par les marqueurs", + "addedByThem": "Examinez le fichier ajouté avant de le conserver", + "bothDeleted": "Résolvez le conflit dans Git ou restaurez l'une des versions avant de modifier le fichier", + "deletedByThem": "Décidez s'il faut conserver le fichier ou accepter sa suppression", + "deletedByUs": "Décidez s'il faut restaurer le fichier", + "bothAdded": "Choisissez la version à conserver ou combinez les deux" + }, + "renamedFrom": "Ancien nom : {{path}}", + "snapshotCapturedAt": "Instantané capturé à {{time}}.", + "unresolvedBanner": "Conflit non résolu · {{kind}}" + }, + "stats": { + "usageBreakdown": { + "turns_one": "{{count}} tour", + "events_one": "{{count}} événement", + "sessions_one": "{{count}} session", + "events_other": "{{count}} événements", + "sessions_other": "{{count}} sessions", + "turns_other": "{{count}} tours" + } + }, + "github": { + "viewed": { + "markFile": "Marquer {{path}} comme consulté", + "unmarkFile": "Ne plus marquer {{path}} comme consulté" + } + }, + "wslMove": { + "entry": { + "hostRow": "Déplacer des projets depuis cette distro…", + "projectMenu": "Déplacer vers l'hôte {{distro}}…" + }, + "blockers": { + "title": "Avant que ces projets puissent être déplacés", + "inProjects": "Dans {{names}}", + "skipOne": "Exclure {{name}} de ce déplacement", + "skipMany": "Exclure ces {{n}} projets de ce déplacement" + }, + "title": "Déplacer des projets vers l'hôte {{distro}}", + "loading": "Vérification des projets dans {{distro}}…", + "runningTitle": "Déplacement vers l'hôte {{distro}}", + "preview": { + "counts": "Projets : {{projects}} · Espaces de travail : {{workspaces}} · Terminaux : {{terminals}} · Chats : {{chats}}", + "whatHappens": "Vos fichiers restent où ils sont. Les terminaux redémarrent dans le même dossier ; leur sortie, l'historique du shell et les conversations des agents sont conservés.", + "projects": "Projets dans {{distro}}", + "folderBadge": "Dossier", + "notMoving": "Non déplacé", + "checking": "Vérification des projets sélectionnés…", + "checkAgain": "Revérifier", + "moveOne": "Déplacer 1 projet", + "moveMany": "Déplacer {{n}} projets", + "heldByHost": "Déjà sur l'hôte {{distro}}.", + "changed": "Déplacé auparavant, puis modifié ici par une version plus ancienne d'Orca. Il n'est pas déplacé à nouveau.", + "chatsStay": "Les chats existants restent sur cet ordinateur. Les nouveaux chats de ce projet démarrent sur l'hôte WSL.", + "browserLoginsConflict": "Les connexions du navigateur ne seront pas transférées, car le profil de navigateur de l'hôte est déjà utilisé. Reconnectez-vous dans les onglets de navigateur de l'hôte après le déplacement.", + "browserLoginsNotCarried": "Les connexions du navigateur ne seront pas transférées vers cet hôte. Reconnectez-vous dans ses onglets de navigateur après le déplacement." + }, + "cancel": "Annuler", + "progress": { + "bytes": "{{sent}} sur {{total}}", + "tooLate": "Trop tard pour annuler : l'hôte est déjà en train de basculer. Gardez Orca ouvert jusqu'à la fin.", + "switching": "La bascule ne peut pas être annulée. Gardez Orca ouvert jusqu'à la fin.", + "readOnly": "Ces projets sont en lecture seule pendant leur déplacement. Vous pouvez annuler jusqu'au début de la bascule.", + "cancelUntilSwitch": "Vous pouvez annuler jusqu'au début de la bascule.", + "closeKeepsGoing": "Fermer cette boîte de dialogue n'arrête pas le déplacement ; elle se rouvre à la fin du déplacement.", + "cancelling": "Annulation…", + "cancel": "Annuler le déplacement" + }, + "result": { + "movedTitle": "Projets déplacés vers l'hôte {{distro}}", + "resetTitle": "Rien n'a été déplacé", + "waitingTitle": "En attente de l'hôte {{distro}}", + "earlierMoveTitle": "Un déplacement précédent s'est terminé d'abord", + "refusedTitle": "Projets non déplacés", + "reloadCheckpointRefused": "Orca n'a pas pu sauvegarder les fichiers non enregistrés : la fenêtre ne s'est donc pas rechargée. Fermez cette boîte de dialogue, enregistrez ou fermez ces fichiers, puis utilisez Recharger maintenant dans la notification qui reste ouverte.", + "reloadVetoed": "Quelque chose a empêché le rechargement de la fenêtre. Fermez cette boîte de dialogue, enregistrez votre travail, puis utilisez Recharger maintenant dans la notification qui reste ouverte.", + "reloadFailed": "La fenêtre ne s'est pas rechargée. Réessayez.", + "moved": "Rechargez cette fenêtre pour voir les projets sous l'hôte {{distro}}. Orca sauvegarde les fichiers non enregistrés avant de recharger.", + "automationsPendingOne": "Une automatisation est désactivée sur l'hôte pour l'instant. Orca continue de demander à l'hôte de la réactiver.", + "automationsPendingMany": "{{n}} automatisations sont désactivées sur l'hôte pour l'instant. Orca continue de demander à l'hôte de les réactiver.", + "undoHint": "Vous avez changé d'avis ? Après le rechargement, la barre latérale affiche ces projets comme « Déplacé vers l'hôte {{distro}} ». Choisissez-y « Utiliser à nouveau sur cet ordinateur » pour les ramener tels qu'ils étaient avant le déplacement.", + "reset": "Le déplacement s'est arrêté et tout a été remis en place. Les projets fonctionnent sur cet ordinateur comme avant ; les terminaux en pause redémarrent quand vous les ouvrez.", + "resetReason": "Raison de l'arrêt : {{detail}}", + "waiting": "Le déplacement a peut-être atteint l'hôte {{distro}}, mais l'hôte ne répond pas. Ces projets restent en lecture seule ici jusqu'à ce qu'il réponde. Connectez l'hôte dans les Paramètres, puis rouvrez cette boîte de dialogue et lancez un déplacement : Orca termine ou annule d'abord celui-ci.", + "reloading": "Rechargement…", + "reload": "Recharger maintenant", + "close": "Fermer", + "review": "Retour aux projets", + "browserLoginsHostUnknown": "Les connexions du navigateur n'ont pas été copiées, car Orca n'a pas pu identifier le profil de navigateur de l'hôte. Reconnectez-vous dans les onglets de navigateur de l'hôte.", + "browserLoginsConflict": "Les connexions du navigateur n'ont pas été copiées, car le profil de navigateur de l'hôte est déjà utilisé. Reconnectez-vous dans les onglets de navigateur de l'hôte.", + "browserLoginsNotCopied": "Les connexions du navigateur n'ont pas été copiées vers l'hôte. Reconnectez-vous dans les onglets de navigateur de l'hôte." + }, + "runtime": { + "label": "Runtime du projet", + "description": "Ce projet s'exécute dans {{distro}} via cet ordinateur. Déplacez-le vers l'hôte {{distro}} pour l'y exécuter.", + "move": "Déplacer le projet" + }, + "unfinished": { + "one": "Une automatisation déplacée vers l'hôte {{distro}} est toujours désactivée. Orca continue de demander à l'hôte de la réactiver.", + "many": "{{n}} automatisations déplacées vers l'hôte {{distro}} sont toujours désactivées. Orca continue de demander à l'hôte de les réactiver." + }, + "refusal": { + "previewFailed": "Orca n'a pas pu vérifier ces projets. Réessayez.", + "startFailed": "Orca a perdu le contact avec le déplacement. Rouvrez cette boîte de dialogue pour voir où il en est.", + "unavailable": "Le déplacement de projets vers un hôte WSL n'est pas disponible dans cette fenêtre.", + "alreadyRunning": "Un déplacement vers {{distro}} est déjà en cours. Attendez qu'il se termine, puis réessayez.", + "alreadyInFlightPreview": "Un déplacement de {{distro}} est encore en cours de finalisation. Lancer ce déplacement le termine ou l'annule d'abord, là où Orca le peut.", + "alreadyInFlight": "Un déplacement de {{distro}} est encore en cours de finalisation : celui-ci n'a donc pas démarré. Gardez l'hôte {{distro}} connecté et réessayez plus tard.", + "nothingNew": "Ces projets sont déjà sur l'hôte {{distro}}.", + "destinationChanged": "Des projets de {{distro}} ont déjà été déplacés vers un autre hôte WSL. Connectez cet hôte pour en déplacer d'autres.", + "hostUnavailable": "L'hôte {{distro}} n'est pas connecté. Connectez-le dans les Paramètres, puis réessayez.", + "hostUpdateRequired": "L'hôte {{distro}} exécute une version plus ancienne d'Orca. Mettez-le à jour dans les Paramètres, puis réessayez.", + "terminalsBlocked": "Des terminaux, agents ou automatisations de ces projets sont occupés. Rien n'a été déplacé.", + "exportIncomplete": "Rien n'a été déplacé, car certaines données enregistrées de ces projets ne peuvent pas encore l'être :", + "exportIncompletePreview": "Certaines données enregistrées de ces projets ne peuvent pas encore être déplacées :", + "tooLarge": "Ces projets contiennent trop de données enregistrées pour être déplacés en une seule fois. Déplacez moins de projets à la fois.", + "pauseFailed": "Orca n'a pas pu mettre en pause les terminaux de ces projets : rien n'a donc été déplacé. Les terminaux en pause redémarrent quand vous les ouvrez. Réessayez.", + "scopeChanged": "Un projet a changé pendant la préparation du déplacement : rien n'a donc été déplacé. Vérifiez les projets et réessayez.", + "cancelled": "Déplacement annulé. Rien n'a été déplacé.", + "finishedEarlierMove": "Orca a d'abord terminé un déplacement précédent vers {{distro}}. Rechargez la fenêtre, puis relancez ce déplacement." + }, + "step": { + "preparing": "Préparation", + "pausingTerminals": "Mise en pause des terminaux", + "copying": "Copie", + "switching": "Bascule", + "finishing": "Finalisation", + "done": "Terminé" + }, + "blocker": { + "agentWorkingOne": "Un agent travaille ou attend une réponse", + "agentWorkingMany": "{{n}} agents travaillent ou attendent une réponse", + "processRunningOne": "Un terminal exécute un programme", + "processRunningMany": "{{n}} terminaux exécutent un programme", + "agentNotResumableOne": "Un agent ne pourra pas reprendre après le déplacement", + "agentNotResumableMany": "{{n}} agents ne pourront pas reprendre après le déplacement", + "unverifiableOne": "Orca ne peut pas vérifier un terminal pour le moment", + "unverifiableMany": "Orca ne peut pas vérifier {{n}} terminaux pour le moment", + "automationRunningOne": "Une exécution d'automatisation est en cours", + "automationRunningMany": "{{n}} exécutions d'automatisation sont en cours", + "dispatchRunningOne": "Une tâche d'agent est en cours", + "dispatchRunningMany": "{{n}} tâches d'agent sont en cours", + "scrollbackTooLargeOne": "Un terminal a un historique de sortie trop volumineux pour être déplacé", + "scrollbackTooLargeMany": "{{n}} terminaux ont un historique de sortie trop volumineux pour être déplacés" + }, + "blockerHint": { + "agentWorking": "Laissez-le terminer, ou arrêtez-le dans son terminal, puis revérifiez.", + "processRunning": "Arrêtez le programme (par exemple un serveur de développement ou un éditeur), puis revérifiez.", + "agentNotResumable": "Quittez l'agent dans son terminal, puis revérifiez.", + "unverifiable": "Patientez un instant, puis revérifiez. Rien n'est arrêté pour permettre le déplacement.", + "wait": "Attendez la fin, puis revérifiez.", + "scrollbackTooLarge": "Effacez la sortie de ces terminaux, puis revérifiez." + }, + "scopeRefused": { + "windowsDrive": "Son dossier se trouve sur un lecteur Windows : il reste donc sur cet ordinateur.", + "mixedLocations": "Certains de ses dossiers se trouvent hors de cette distro : il reste donc sur cet ordinateur.", + "notLocal": "Il s'exécute déjà sur un autre hôte.", + "other": "Il ne peut pas être déplacé." + }, + "reloadToast": { + "title": "Rechargez pour terminer le déplacement" + }, + "orchestrator": { + "showTerminal": "Afficher le terminal", + "moveAgain": "Relancer le déplacement", + "checkAgain": "Revérifier", + "deferred": "Finalisation de votre déplacement vers l'hôte {{distro}} : certains terminaux sont encore occupés.", + "stuck": "Un déplacement précédent vers l'hôte {{distro}} n'est pas encore entièrement finalisé.", + "declined": "Le déplacement est en pause, car vous avez ramené ces projets sur cet ordinateur.", + "doneToast": "Projets déplacés vers l'hôte {{distro}}", + "terminalGone": "Ce terminal n'est plus ouvert dans cette fenêtre. Revérifiez pour actualiser.", + "blocker": "{{title}}. {{hint}}", + "paused": "Le déplacement des projets vers l'hôte {{distro}} est en pause : {{reason}}.", + "pausedReason": { + "exportIncomplete": "certaines données enregistrées ne peuvent pas encore être transférées", + "manifestTooLarge": "il y a plus de données enregistrées qu'un seul déplacement ne peut en transférer", + "hostUpdate": "l'hôte doit d'abord être mis à jour", + "attemptsExhausted": "il n'a pas abouti après plusieurs tentatives" + }, + "finishPending": "Un déplacement précédent vers l'hôte {{distro}} est terminé là-bas. Orca le finalise ici au redémarrage, ou dès maintenant avec Revérifier." + } } } diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 4e9f7a934043..3bffc873c5c5 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -110,11 +110,15 @@ "system": "システム", "english": "English", "chinese": "中文(简体)", + "chineseTraditional": "繁體中文(台灣)", "korean": "한국어", "japanese": "日本語", "spanish": "Español", "french": "Français", - "portuguese": "Português (Brasil)" + "portuguese": "Português (Brasil)", + "russian": "Русский", + "turkish": "Türkçe", + "german": "Deutsch" }, "statusBar": { "claudeToggleDescription": "アクティブなワークスペースの Claude トークンとコストの使用状況を表示します。", @@ -346,7 +350,8 @@ "permissionOverrideMore": "ほか {{count}} 件", "permissionOverrideMore_one": "ほか {{count}} 件", "permissionOverrideMore_other": "ほか {{count}} 件", - "permissionOverridesUse": "{{mode}} を使用" + "permissionOverridesUse": "{{mode}} を使用", + "approveForMe": "代わりに承認" }, "followSymlinkedDirectoriesKeywords": { "symlink": "シンボリックリンク", @@ -377,6 +382,34 @@ "actionPermissions": { "sameAsAgent": "{{agent}} と同じ" } + }, + "ssh": { + "status": { + "disconnected": "切断済み", + "connecting": "接続中…", + "auth-failed": "認証に失敗しました", + "connected": "接続済み", + "reconnection-failed": "再接続に失敗しました", + "deploying-relay": "リレーをデプロイ中…", + "reconnecting": "再接続中…" + } + }, + "mcp": { + "workspace": "ワークスペース", + "inspectFailed": "{{directory}} を確認できません。", + "unreadable": "読み取り不可", + "notFound": "見つかりません", + "invalidJson": "無効な JSON", + "noServers": "サーバーなし", + "httpServer": "HTTP サーバー", + "stdioServer": "stdio サーバー", + "invalidServer": "無効なサーバー", + "serverCount_one": "サーバー {{count}} 件", + "serverCount_other": "サーバー {{count}} 件", + "claudeWorkspace": "Claude ワークスペース" + }, + "shortcuts": { + "parseFailed": "ショートカットを解析できません。" } }, "menu": { @@ -1465,9 +1498,6 @@ "3fdf777817": "GitHub で開く", "c43fe79ee0": "GitHub リンクをコピーする", "0caac1a18f": "PR からワークスペースを開始する", - "8223320f8d": "更新されました", - "10ef1afb8e": "· 更新されました", - "55962099bc": "この Issue を作成しました", "0ab4664a8b": "Issue からワークスペースを開始", "36182aa57f": "新規ワークスペースを開始", "fe6ff12dc2": "Issue ワークスペースのその他の操作", @@ -1540,8 +1570,6 @@ "52b20b56f7": "説明", "4d555d3796": "説明の編集", "9df4e74bdf": "保存", - "0ae387d8ca": "による", - "228e2f59d3": "解決済み", "a154ec5224": "GitHub でコメントを開く", "bca8eb39ac": "コメントに返信", "68cb993d61": "解決済み", @@ -1557,13 +1585,11 @@ "d43736d09c": "コードコンテキストコントロール", "bd7be7b1fd": "コメントL", "db61d76cd5": "コードコンテキストを読み込み中…", - "f2d02cdf8c": "閲覧したファイル", "1257d1435d": "ファイルツリーを表示", "a341343303": "レビューコメントを追加しました。", "d1fa2cf888": "PR ヘッドの SHA がないとコメントできません。", "829674460a": "PR commit SHA が欠落しているため、差分は利用できません。", "af924014f8": "閲覧済み", - "2d89a38d9d": "{{value0}} {{value1}} 表示", "70e84e3d0b": "一致するレビュアーがいません。", "1ffce94a8b": "他のみんな", "c2b21818e1": "提案", @@ -1598,8 +1624,6 @@ "ec5c4b3ab2": "PR 再開", "21860b58d0": "PR を閉じる", "5932578f51": "マージには登録済みのローカルリポジトリが必要です", - "e2bf3e41a9": "コメント", - "28d0d3374f": "スレッド", "080d071d48": "@{{value0}} に返信", "86f809e2ce": "このレビュースレッドに返信する", "136542c9ba": ":L{{value0}}", @@ -1629,7 +1653,9 @@ "from": "から", "to": "to", "activity": "アクティビティ", - "noActivity": "まだアクティビティはありません。" + "noActivity": "まだアクティビティはありません。", + "pullRequestReference": "PR #{{number}}", + "issueReference": "Issue #{{number}}" }, "checkActionRequiredHint": "マージのブロックを解除するには、GitHub 上での手動操作(例: 実行の承認)が必要です。", "e15a8b77ef": "このチェックではインライン詳細は利用できません。", @@ -1643,8 +1669,13 @@ "09d67a0f9b": "PR をクローズできませんでした", "88809e79db": "PR の再開に失敗しました", "00f55cc17b": "この PR ではリポジトリにアクセスできません。", - "reactionCountSingular": "{{reaction}} 反応 {{count}} 件", - "reactionCountPlural": "{{reaction}} 反応 {{count}} 件" + "reactionCount_other": "{{reaction}} の反応 {{count}} 件", + "filesViewed_other": "{{viewed}} / {{count}} ファイルを閲覧済み", + "updatedRelativeTime": "{{time}} に更新", + "authorOpenedThisIssue": " がこの Issue を作成しました", + "middotUpdatedRelativeTime": "· {{time}} に更新", + "resolvedThreadBy": "{{author}} の解決済みスレッド", + "resolvedCommentBy": "{{author}} の解決済みコメント" }, "GitLabItemDialog": { "65e784c1f1": "再度開く", @@ -1700,14 +1731,13 @@ "f23ea85341": "解決済み", "6de8ce0cc6": "{{value0}}は必須です", "22511537d2": "承認された", - "00f3bab87b": "{{value0}} 個が必要です", "3a051b8ade": "作業項目", "32f8bef818": "ログは出力されません。", "4168eb2c51": "解決", "commentTooLarge": "コメントが大きすぎるため安全に送信できません。", "gitlabActionFailed": "GitLab 操作が失敗しました。", - "approvalsRemainingSingular": "残り {{count}} 件の承認", - "approvalsRemainingPlural": "残り {{count}} 件の承認" + "approvalsRemainingOfRequired_other": "必要な承認 {{required}} 件のうち残り {{count}} 件", + "approvalsRemaining_other": "残り {{count}} 件の承認" }, "JiraIssueWorkspace": { "b0b92666c9": "コメント", @@ -1732,14 +1762,11 @@ "69da9a208c": "Jira で開く", "fa132c8aed": "コメントの追加に失敗しました。", "ea21952aa3": "Jira Issue を更新できませんでした。", - "6c41a9bcea": "{{value0}} のコピーに失敗しました", - "2ff69a3545": "{{value0}} をコピーしました", "666cfdd835": "不明", "ef21405c6d": "Jira Issue", "commentTooLarge": "コメントが大きすぎるため安全に送信できません。" }, "Landing": { - "76a95f7f47": "作成", "f9eaa9e12d": "プロジェクトを追加", "6ca6ff404e": "ORCA", "520304a067": "Orca のロゴ", @@ -1755,7 +1782,12 @@ "0d0ace8861": "GitHub でスターを付ける", "ec43b38ba7": "GitHub でスター済み", "157bb5ecbb": "GitHub を開く", - "preflightDismiss": "閉じる" + "preflightDismiss": "閉じる", + "moveUpWorkspace": "前のワークスペースを選択", + "moveDownWorkspace": "次のワークスペースを選択", + "installGit": "Git をインストール", + "installGitHubCli": "GitHub CLI をインストール", + "learnMore": "詳しく見る" }, "LinearIssueMarkdownDescriptionEditor": { "d9c47069ef": "Markdown", @@ -1780,14 +1812,12 @@ "LinearIssueTextEditor": { "947ba2d6f4": "保存する", "04d73b72dc": "Issue のタイトル", - "e8ff595db3": "{{value0}} を更新できませんでした", "1e08a1ec80": "タイトルは必須です" }, "LinearIssueWorkspace": { "ad5dec37b7": "選択した Issue をプレビュー・編集し、そこから作業を開始します。", "c23e79e5c0": "操作", "b0eac92d85": "再試行", - "fabbd3f974": "Issue を更新しました ·", "543970c87a": "アクティビティ", "df4c86ed12": "閉じる", "7a4997d8bb": "Linear Issue のプレビューを閉じる", @@ -1811,11 +1841,8 @@ "b25e453c9d": "サブ Issue の作成に失敗しました", "aeed19d003": "{{value0}} を作成しました", "9a1317cdd3": "サブ Issue のロードに失敗しました", - "9bcbaa2737": "{{value0}} のコピーに失敗しました", - "7835483c43": "{{value0}} をコピーしました", "61f424f8ca": "Linear Issue", "ca8778c124": "不明", - "8a33c85e9c": "誰か", "65239a714b": "Linear", "76ffd3c937": "追加するプロジェクトを検索します。", "c11b4e3cc2": "プロジェクトが見つかりませんでした。", @@ -1826,7 +1853,10 @@ "moreWorkspaceActions": "Issue ワークスペースのその他の操作", "startNewWorkspace": "新規ワークスペースを開始", "workspaceSection": "ワークスペース", - "noWorkspaceYet": "まだありません" + "noWorkspaceYet": "まだありません", + "issueDescriptionLabel": "Issue の説明", + "namedUserUpdatedIssue": "{{name}} が Issue を更新 · {{time}}", + "someoneUpdatedIssue": "誰かが Issue を更新 · {{time}}" }, "LinearItemDrawer": { "04008e6c46": "Issue からワークスペースを開始", @@ -1862,7 +1892,9 @@ "openAttachedWorkspace": "Issue にリンクされたワークスペースを開く", "openWorkspace": "ワークスペースを開く", "moreWorkspaceActions": "Issue ワークスペースのその他の操作", - "startNewWorkspace": "新規ワークスペースを開始" + "startNewWorkspace": "新規ワークスペースを開始", + "setEstimate": "見積もりを設定", + "estimateValue": "見積もり {{estimate}}" }, "NewWorkspaceComposerCard": { "cbb47ee0dc": "ローカル Git プロジェクトでのみ使用できます。", @@ -1924,7 +1956,22 @@ "defaultBranchUpdateFailed": "プロジェクトのデフォルトブランチを更新できませんでした。再試行。", "setLocation": "プロジェクトの場所を設定する", "setLocationOnHost": "プロジェクトの場所を {{host}} に設定します", - "setLocationTooltip": "フォルダーを選択するか、このプロジェクトを {{host}} に複製します。" + "setLocationTooltip": "フォルダーを選択するか、このプロジェクトを {{host}} に複製します。", + "connect": "接続", + "reconnect": "再接続", + "setupConfigDefaultTabs": "デフォルトタブのコマンド", + "setupConfigSetupAndDefaultTabs": "セットアップとデフォルトタブのコマンド", + "setupConfigSetupScript": "セットアップスクリプト", + "runDefaultTabCommands": "デフォルトタブのコマンドを実行", + "runSetupAndDefaultTabCommands": "セットアップとデフォルトタブのコマンドを実行", + "runSetupCommand": "セットアップコマンドを実行", + "askRunDefaultTabCommands": "デフォルトタブのコマンドを今すぐ実行しますか?", + "askRunSetupAndDefaultTabCommands": "セットアップとデフォルトタブのコマンドを今すぐ実行しますか?", + "askRunSetup": "今すぐセットアップを実行しますか?", + "runSetupNow": "今すぐセットアップを実行", + "runCommandsNow": "今すぐコマンドを実行", + "skipForNow": "今はスキップ", + "skipCommands": "コマンドをスキップ" }, "NewWorkspaceComposerModal": { "createWorktree": "ワークツリーを作成する", @@ -2014,9 +2061,6 @@ "778683ec84": "説明", "da9aaa8bcf": "説明の編集", "4a337ac05f": "保存", - "169a93b29a": "更新されました", - "3c891789f6": "による", - "f4fe47c2bb": "解決済み", "0ac19bb52e": "GitHub でコメントを開く", "d6c6679de7": "コメントに返信", "76b2a0ac5b": "解決済み", @@ -2024,7 +2068,6 @@ "6885c619e7": "リポジトリパスがないと返信できません。", "d94810f652": "説明の更新に失敗しました。", "9b4190dc98": "説明が更新されました。", - "89e80af1c7": "閲覧したファイル", "319cf2d54b": "ファイルツリーを表示", "eff839f438": "レビューコメントを追加しました。", "d8c3ba91c4": "PR ヘッドの SHA がないとコメントできません。", @@ -2062,8 +2105,6 @@ "9d5425918e": "PR 再開", "96d013ed28": "PR を閉じる", "eca289e593": "マージには登録済みのローカルリポジトリが必要です", - "e01e34f5fa": "コメント", - "345b68254c": "スレッド", "31a7b202f2": "@{{value0}} に返信", "408e634fbb": "このレビュースレッドに返信する", "34b9f7c264": ":L{{value0}}", @@ -2089,7 +2130,18 @@ "diffLoadTimedOut": "この差分の読み込みがタイムアウトしました。", "6b1d5ee3e4": "このチェックではインライン詳細は利用できません。", "e04c027d98": "チェックの詳細をロードできませんでした。", - "5df7c41d2a": "再試行" + "5df7c41d2a": "再試行", + "filesViewed_other": "{{viewed}} / {{count}} ファイルを閲覧済み", + "updatedRelativeTime": "{{time}} に更新", + "resolvedThreadBy": "{{author}} の解決済みスレッド", + "resolvedCommentBy": "{{author}} の解決済みコメント", + "mentionSource": { + "prAuthor": "PR 作成者", + "issueAuthor": "Issue 作成者", + "commenter": "コメント投稿者", + "participant": "参加者", + "teamMember": "チームメンバー" + } }, "QuickOpen": { "1dbd3f59ff": "移動", @@ -2103,13 +2155,11 @@ "9e97f08d0f": "開くファイルを検索する", "ec31e058f7": "ファイルに移動", "73b44e7bde": "インストールコマンドのコピー", - "1cf8561ab4": "リモートで、gitignore 対応の高速リストを有効にします。", - "5d80dc39bb": "ripgrep", - "2ca749c15d": "インストール", - "4725b0e931": "クイックオープンスキャンが大きすぎます (", - "b227d88520": "{{value0}} ファイルが見つかりました", "995be8ea22": "コピー", - "cf144856dc": "コピーしました" + "cf144856dc": "コピーしました", + "filesFound_other": "{{count}} 件のファイルが見つかりました", + "hostCouldNotOpenPath": "ホストがこのファイルパスを開けませんでした。", + "chooseFileNotDirectory": "ディレクトリではなくファイルを選択してください。" }, "SelectedTextCopyMenu": { "9b40d7b018": "コピー" @@ -2127,7 +2177,6 @@ "TaskPage": { "ff69a30681": "キャンセル", "8ff6fdc368": "作成中…", - "fc0d8a1fa4": "提出する。", "919a20dd5b": "{{value0}}と入力", "56cdb413a2": "カンマ区切りの値", "1f0fce91e3": "{{value0}} を選択", @@ -2175,14 +2224,9 @@ "bdebffcbfe": "選択したチームの Linear プロジェクトを作成します。", "1361275ec3": "新規 Linear プロジェクト", "7f3f7b4c18": "説明 (オプション、markdown)", - "9f2b4c03a6": "提出する", "d3d0998b7d": "GitHub の新規 Issue", - "d1e243795c": "Issue", - "be8cf68d9f": "Issue を表示", - "67662ade50": "プロジェクトの Issue", "6244a02f46": "Linear で開く", "606a85c774": "オープン", - "5e8061b088": "{{value0}} {{value1}} からワークスペースを開始します", "592a55611b": "さらにチームを選択するか更新してみてください。チームフィルターは、現在取得されている Issue セットに適用されます。", "618107fab3": "選択したチームと一致する取得済み Issue はありません", "903c7af49f": "Linear Issue が見つかりません", @@ -2191,7 +2235,6 @@ "f362667d55": "更新済み", "b1eaa18ace": "Issue", "37e7ee311e": "キー", - "b7bae28b6a": "示されている", "a26a48252e": "表示プロパティ", "5d2d835467": "並べ替え", "5659da12fc": "グループ化", @@ -2199,11 +2242,9 @@ "af377b13b1": "{{value0}} ビュー", "d47248df4d": "Linear ビューモード", "f397d513e3": "戻る", - "b39fe6511d": "プロジェクト", "8675cd6188": "Linear", "733b8f2421": "Linear / ビュー", "bc06ed0fb0": "ビューに戻る", - "3cb855080f": "ビュー", "b4e10f096e": "オーナー", "a04fe7ba73": "可視性", "0aa8525950": "モデル", @@ -2233,8 +2274,6 @@ "054bf695cc": "下書き", "5b6b2af943": "再試行中…", "0c0de0fc0e": "からの Issue を読み込めませんでした", - "d1766fd62d": "プロジェクトのロードに失敗しました", - "7762f4b03a": "の", "443f7dd928": "マージ", "a7396b05c6": "チェック", "f6fa3c97d0": "レビュアー", @@ -2416,10 +2455,36 @@ "jiraColumnOriginalEstimate": "見積もり", "jiraColumnRemainingEstimate": "残り", "jiraBoardEmptyColumn": "Issue はありません", - "labelCountPlural": "{{count}} 個のラベル", - "labelCountSingular": "{{count}} 個のラベル", - "memberCountPlural": "{{count}} 人のメンバー", - "memberCountSingular": "{{count}} 人のメンバー" + "backToPullRequests": "PR", + "backToGitHubList": "GitHub の一覧", + "noGitHubRepositoryContext": "この Issue の GitHub リポジトリのコンテキストはありません。", + "filingInTarget": "{{target}} に作成", + "filingInThisRepository": "このリポジトリに作成", + "shortcutToSubmit": "{{shortcut}} で送信。", + "projectsFailedToLoad_other": "{{count}} 件中 {{failed}} 件のプロジェクトを読み込めませんでした", + "draftPullRequestNumber": "ドラフトの PR #{{number}}", + "pullRequestNumber": "PR #{{number}}", + "issueNumber": "Issue #{{number}}", + "loadGitHubWorkFailed": "GitHub の作業項目を読み込めませんでした。", + "gitlabViewIssues": "Issue", + "gitlabViewMrs": "MR", + "gitlabViewTodos": "自分の ToDo", + "startWorkspaceFromMr": "MR {{number}} からワークスペースを開始", + "startWorkspaceFromIssue": "Issue {{number}} からワークスペースを開始", + "shownCount_other": "{{count}} 件表示", + "linearProjectPlaceholder": "プロジェクト", + "labelCount_other": "{{count}} 個のラベル", + "memberCount_other": "{{count}} 人のメンバー", + "groupUnassigned": "未割り当て", + "linearProjectContext": "プロジェクト: {{name}}", + "linearViewContext": "ビュー: {{name}}", + "changedFileCount_other": "{{count}} ファイル", + "resumeRestoration": { + "linearProjectNotFound": "保存された Linear プロジェクトが見つかりませんでした。", + "linearProjectRestoreFailed": "保存された Linear プロジェクトを復元できませんでした。", + "linearViewNotFound": "保存された Linear ビューが見つかりませんでした。", + "linearViewRestoreFailed": "保存された Linear ビューを復元できませんでした。" + } }, "Terminal": { "73768427cf": "閉じる", @@ -2494,7 +2559,8 @@ "b1e390250d": "ローカルビルドの切り替えを完了できませんでした。", "d29740d175": "選択したビルドを使用できませんでした。", "37d45c9ec1": "別のビルドを選択", - "7f1a4c9e02": "システムパッケージマネージャーによって Orca がインストールされているため、そこから更新してください。Orca はこのリリース自体をインストールできません。" + "7f1a4c9e02": "システムパッケージマネージャーによって Orca がインストールされているため、そこから更新してください。Orca はこのリリース自体をインストールできません。", + "compatibilityModeFailed": "互換モードを有効にできませんでした。{{message}}" }, "WorktreeJumpPalette": { "ac037cfac2": "移動", @@ -2520,8 +2586,6 @@ "d7d496a451": "ブラウザページはもう存在しません", "50a1d11d5b": "開いているタブ", "088d66d980": "操作と設定", - "20af998bff": "{{value0}}アイテムが利用可能{{value1}}", - "bb72c08e63": "{{value0}} の結果が見つかりました{{value1}}", "34c8fbb46e": "SSH リモート", "63c2be1914": "SSH が切断されました", "95be6587d3": "ワークツリー「{{value0}}」を作成する", @@ -2538,7 +2602,10 @@ "27f10cca63": "チャット、ターミナル、ワークスペース、タスク、設定、操作を検索します…", "2770f02910": "チャット、ターミナル、ワークスペース、タスク、設定、操作を検索します", "recentChatsTerminalsHeader": "最近のチャットとターミナル", - "lastActiveTime": "最後にアクティブになったのは{{value0}}前です" + "lastActiveTime": "最後にアクティブになったのは{{value0}}前です", + "resultsFound_other": "{{count}} 件の結果が見つかりました。", + "itemsAvailable_other": "{{count}} 件の項目が利用可能です。", + "createActionAvailable": "ワークツリーの作成操作が利用可能です。" }, "github": { "pr": { @@ -2579,7 +2646,8 @@ "8f6cb3772f": "要件が満たされると、この PR を自動的にマージします", "def355ff38": "マージ可能", "e42c5bae67": "GitHub によると、この PR はマージ可能で、チェックも成功しています", - "cbf0113af6": "GitHub によると、この PR はマージ可能です" + "cbf0113af6": "GitHub によると、この PR はマージ可能です", + "autoMergeOn": "自動マージ有効" } } }, @@ -2753,10 +2821,10 @@ "imageUrlTooLarge": "画像 URL が大きすぎます。" }, "IssueSourceSelector": { - "d6aeb2012b": "からの Issue を表示しています", "787c970baf": "Issue ソース", "51d1608920": "オリジン", - "30b2c9df91": "upstream" + "30b2c9df91": "upstream", + "showingIssuesFromRepo": " の Issue を表示中" }, "PRFilterDropdowns": { "979be3cf6b": "担当者", @@ -2766,12 +2834,18 @@ "01f3f3d161": "著者", "13b3ac0a84": "状態", "79c54552f7": "フィルター", - "8a2ffbf9b3": "{{value0}} フィルターを解除" + "8a2ffbf9b3": "{{value0}} フィルターを解除", + "anyState": "指定なし", + "currentUser": "現在のユーザー" }, "PRFilterPickers": { - "fdf387297c": "クリア (", "472c12ae03": "クリア", - "2d1f58eda6": "使用" + "pressEnterToUseValue": "Enter を押すと入力した値を使用します。", + "useTypedValue": " を使用", + "clearSelected": "クリア ({{count}})", + "loading": "読み込み中…", + "searchTextTooLarge": "検索テキストが大きすぎます。", + "noMatches": "一致なし" }, "PRFilterSections": { "a00830d3f7": "ユーザーがいません", @@ -2781,7 +2855,6 @@ "458ea3602b": "著者がいません", "b69fa4fa20": "戻る", "30ebb6ca44": "すべてのフィルターをクリア", - "8177eda37e": "フィルター", "ea3416d646": "担当者", "b1d9fdea08": "ラベル", "24754c44ad": "著者", @@ -2793,7 +2866,14 @@ "2b2f019091": "すべての状態", "0fd3249e2e": "クローズ", "d78b60b5c2": "オープン", - "bd162b7d5a": "マージ済み" + "bd162b7d5a": "マージ済み", + "draft": "下書き", + "labelCount_other": "{{count}} 個のラベル", + "allStates": "全て", + "filterPullRequests": "PR を絞り込む", + "filterIssues": "Issue を絞り込む", + "filterOrTypeLogin": "絞り込むかログイン名を入力…", + "filterLabels": "ラベルを絞り込む…" }, "github": { "rate": { @@ -2804,15 +2884,14 @@ "d12d3d6f33": "GitHub API 予算を更新する", "d5e5de9070": "Orca は、GitHub CLI を通じて REST、Search、GraphQL を使用します。", "58c5f88216": "GitHub API の予算", - "6da1858354": "左 · リセット", - "f42790d150": "の", "01f7323e58": "GraphQL API", "1daf0f22a9": "GraphQL", "1f2f28a4de": "検索API", "c377a4f06a": "検索", "c392c749a6": "REST API", "bb227706a6": "REST", - "budget_scope_prefix": "予算スコープ" + "budget_scope_prefix": "予算スコープ", + "remainingOfLimitResetsIn": "残り {{remaining}} / {{limit}} · {{reset}} 後にリセット" } } } @@ -2820,7 +2899,29 @@ "CommentReactions": { "addReaction": "リ操作を追加", "removeNamedReaction": "{{value0}} 反応を削除", - "addNamedReaction": "{{value0}} 反応を追加" + "addNamedReaction": "{{value0}} 反応を追加", + "reaction": { + "thumbsUp": "いいね", + "thumbsDown": "よくないね", + "laugh": "笑い", + "confused": "困惑", + "heart": "ハート", + "hooray": "やったー", + "rocket": "ロケット", + "eyes": "目" + } + }, + "CommentCodeContext": { + "showSurroundingCodeBlock": "周囲のコードブロックを表示", + "showNearbyCodeContext": "近くのコードのコンテキストを表示" + }, + "prCheckPresentation": { + "successful": "成功", + "inProgress": "進行中" + }, + "IssueSourceIndicator": { + "issueFromRepo": " の Issue", + "issuesFromRepo": " の Issue" } }, "linear": { @@ -2840,11 +2941,6 @@ } } }, - "priority": { - "icon": { - "c43d3e065b": "優先度:" - } - }, "project": { "view": { "surfaces": { @@ -2863,7 +2959,6 @@ "c8db98b73b": "リソース", "bb1405eff8": "マイルストーン", "5d99315fb8": "企画", - "3ad562bdf4": "スコープされた Issue", "563501f191": "進捗", "bb5664d456": "プロジェクトの説明はありません。", "7b147907dc": "Linear", @@ -2874,8 +2969,6 @@ "7616c986c6": "{{value0}} Issue を開く", "openInLinear": "Linear で {{value0}} を開く", "93e1f6bfca": "読み込み中", - "98730088a6": "。フルセットについては、Linear を検索するか開きます。", - "06b887d622": "最初に表示しています", "linearLoginUnreadable": "保存された Linear のログイン情報を読み取れません。設定で再接続してください。", "f2cc1e0ff6": "Linear / プロジェクト", "906b5e4cb8": "Linear / プロジェクト / {{value0}}", @@ -2890,7 +2983,9 @@ "df4bd63c1d": "未割り当て", "30402d2c6e": "検索または更新してみてください。", "a2f31c4cd6": "Linear プロジェクトが見つかりません", - "c9b6e9f90d": "Linear プロジェクトをロードできません" + "c9b6e9f90d": "Linear プロジェクトをロードできません", + "scopedIssueCount_other": "対象範囲内の Issue {{count}} 件", + "backlog": "バックログ" } } }, @@ -2903,7 +2998,13 @@ "05baa5ae90": "ワークスペース", "89f6580dbf": "チームを検索…", "b3488fad3c": "チームはフェッチされませんでした。アクセスは、キーのスコープ、プライベートチームのメンバーシップ、アーカイブされたチーム、権限、またはフェッチの失敗によって異なります。", - "405b33c378": "検索に一致する取得チームはありません。" + "405b33c378": "検索に一致する取得チームはありません。", + "teamCount_other": "{{count}} チーム" + } + }, + "priority": { + "icon": { + "priorityValue": "優先度: {{label}}" } } }, @@ -4398,10 +4499,7 @@ }, "UsageBreakdownSection": { "7765a4c3e1": "該当なし", - "247c93ca92": "• 推定価格", - "32176e1d44": "ターン", - "79a69522a5": "イベント", - "02a046792e": "セッション •" + "247c93ca92": "• 推定価格" }, "GrokUsagePane": { "g8h9i0j1k2": "Grok の使用状況", @@ -5909,7 +6007,8 @@ }, "sidebarHostOptions": { "3e102f111c": "すべてのホスト", - "visibleHostsCount": "{{value0}} 台のホスト" + "hosts": "ホスト", + "visibleHosts_other": "{{count}} 台のホスト" }, "HostRemoveDialog": { "1a2b3c4d5e": "{{value0}} を削除しました", @@ -5924,12 +6023,10 @@ "oneWorkspace": "1つのワークスペース", "manyWorkspaces": "{{count}} 個のワークスペース", "hostHasWorkspacesDefault": "このコンピュータから {{value0}} とその認証情報を削除します。{{value1}} は Orca に残ります — リモートファイルは変更されません。", - "alsoDeleteRemote": "また、{{value1}} のこれらの {{value0}} も削除", "alsoForgetLocal": "また、Orca からこれらの {{value0}} も削除", "advanced": "詳細設定", - "alsoDeleteRemoteHint": "リモートの Git ワークツリーとそのブランチを完全に削除します。この操作は取り消せません。", "alsoForgetLocalHint": "Orca からのみ削除します。リモートのファイル、ワークツリー、ブランチはそのまま残ります。", - "wslHostEndsTerminals": "Orca から {{value0}} を削除し、開いているターミナルを終了して、そのディストリビューション内の Orca サーバーを停止します。ディストリビューション内のファイルは変更されません。" + "wslHostEndsTerminalsUnlessShared": "Orca から {{value0}} を削除します。このコンピューターで開いている別の Orca が使用していない場合は、開いているターミナルも終了し、そのディストリビューション内の Orca サーバーを停止します。ディストリビューション内のファイルは変更されません。" }, "HostRenameDialog": { "1a2b3c4d5e": "ホスト名を変更", @@ -6083,14 +6180,9 @@ "sshImportSyncedSingular": "{{count}} 個のホストを Orca に追加しました。" }, "ForgetSshWorkspaceDialog": { - "reconnectFailed": "再接続に失敗しました", - "forgetBody": "このワークスペースを Orca からのみ削除します。ファイル、Git ワークツリー、{{host}}のブランチはそのまま残ります。", - "title": "「{{name}}」を削除しますか?", - "disconnectedBody": "このワークスペースの SSH ホストが接続されていません。再接続してリモートでも削除するか、Orca からのみ削除してください。", "ghostBody": "{{host}} は保存済みの SSH ホストではなくなったため、このワークスペースは稼働中のホストに接続されていません。Orca から削除することのみ可能です。リモート上のファイルとブランチはそのまま残ります。", "cancel": "キャンセル", - "forget": "Orca から削除", - "reconnectAndDelete": "再接続して削除" + "forget": "Orca から削除" }, "MarkdownImageLightbox": { "image": "画像", @@ -6204,7 +6296,7 @@ "running": "実行中", "stopped": "停止中", "title": "WSL ディストリビューションを追加", - "description": "Orca はディストリビューション内でサーバーを実行するため、git、ファイル、ターミナルは Linux 上でネイティブに動作します。新規プロジェクトに使用してください。\\\\wsl.localhost 経由で開いたプロジェクトはそのまま動作し続けます。", + "description": "Orca はディストリビューション内でサーバーを実行するため、git、ファイル、ターミナルは Linux 上でネイティブに動作します。このディストリビューション内で \\\\wsl.localhost 経由で開いたプロジェクトは、ターミナルがアイドル状態になると自動的にこのホストへ移動します。Windows ドライブ (/mnt/…) 上のプロジェクトはこのコンピューターに残ります。移動したプロジェクトはサイドバーから戻せます。", "distro": "ディストリビューション", "loading": "WSL ディストリビューションを探しています…", "placeholder": "ディストリビューションを選択", @@ -6231,6 +6323,7 @@ "removalPending": "削除が完了しませんでした" }, "wslHostRemoval": { + "keptForOthers": "この Orca から削除しました。ホストは {{value0}} のために動作し続けます。", "partial": "ホストは削除されましたが、ディストリビューション内でまだ実行中のものがあります: {{value0}}", "pending": "Orca はまだホストを削除していません: {{value0}} 再試行するにはもう一度削除し、残す場合は接続してください。" }, @@ -6293,7 +6386,11 @@ "e8f25bd903": "ターミナルクリーンアップを完了できませんでした。", "a702d4196e": "これにより、すべてのワークスペースのターミナルタブが閉じられ、現在のターミナルセッションのシャットダウンがリクエストされます。保存されていないターミナル作業は失われます。デーモン自体は実行を続け、新規ターミナルはすぐに開けます。この操作は取り消せません。", "01d6b7c64e": "ターミナルを開くと Agent が再起動します。リモートホスト上のターミナルは影響を受けません。", - "922548bc66": "ターミナルサービスを再起動しますか?" + "922548bc66": "ターミナルサービスを再起動しますか?", + "confirmRestart": "再起動", + "busyRestarting": "再起動中…", + "confirmKillAll": "すべてのセッションを終了", + "busyKilling": "終了中…" }, "MacFolderAccessFixDialog": { "stepAllow": "ファイルとフォルダーで Orca を許可する", @@ -7937,7 +8034,9 @@ "fbb428db98": "選択済み:", "search_terminal_themes": "ターミナルテーマを検索", "cb330ef7f8": "/{{value0}}", - "c822571b2e": " 「{{value0}}」に一致" + "c822571b2e": " 「{{value0}}」に一致", + "plugin_themes": "プラグイン", + "from_plugin": "{{value0}} から" }, "SettingsSidebar": { "e0900f83e7": "SSH", @@ -8223,7 +8322,6 @@ "a016ffbeed": "Auto は現在 Windows PowerShell を使用し、インストールされると PowerShell 7 以降に切り替わります。", "5ed5c95344": "新規ターミナルペインについては、Windows PowerShell と PowerShell 7+ のどちらかを選択します。", "3d88af864d": "PowerShell シェルオプションで、新規ターミナルペインに対して Windows PowerShell を起動するか PowerShell 7+ を起動するかを選択します。", - "8a956cc91e": "文字はダブルクリック選択の単語境界として扱われます。", "4bebcc2b2c": "単語の区切り文字", "12e06178fa": "行", "907b0b9d3e": "カスタム", @@ -10939,7 +11037,7 @@ "mixedTitle": "アクセスとコンテンツを確認", "instructionalTitle": "プラグインコンテンツを確認", "subtitle": "{{value0}} v{{value1}} · {{value2}}", - "reconsent": "前回このプラグインを確認した以降に、権限、ワーカー信頼階層、またはインストラクショナルコンテンツが変更されました。実行する前に再確認してください。", + "reconsent": "承認後にこのプラグインが変更されました。再度実行するには確認してください。", "capabilities": "このプラグインは", "warning": "これらの権限は、プラグインが Orca APIを使用する方法を制限します。ワーカーは引き続きコンピュータで通常のプロセスとして実行され、ファイル、ネットワーク、その他のプロセスへの完全なアクセス権を持ちます。", "instructionalWarning": "このプラグインにはワーカープロセスがありません。それでも、ユーザーや Agent が使用したときに、記載された手順が操作を引き起こす可能性があります。有効にする前に、以下の手順とコマンドを確認してください。", @@ -11728,7 +11826,8 @@ "migration": "未完了: このサーバーへの移動が終わっていません。先に再開してください。", "deferred": "まだ未完了です: サーバーはこの操作の準備ができていません。しばらくしてから、もう一度お試しください。", "failed": "Orca はサーバー上でこれを完了できませんでした。もう一度お試しください。", - "defaultServer": "実行されませんでした: このサーバーは新しいプロジェクトの既定のホストです。停止する前に「新しいプロジェクトを開く場所」で別のものを選んでください。" + "defaultServer": "実行されませんでした: このサーバーは新しいプロジェクトの既定のホストです。停止する前に「新しいプロジェクトを開く場所」で別のものを選んでください。", + "wslMoveRunning": "未完了: このサーバーへプロジェクトを移動中です。移動が完了すると Orca が更新します。" }, "reassurance": "各ホスト上で動作し、あなた自身の SSH 接続を通じて利用します。コードやファイルは今の場所から動きません。ホストに移るのは、Orca のプロジェクト、タブ、ターミナルの一覧だけです。" }, @@ -12066,6 +12165,9 @@ "searchPlaceholder": "ビルドを検索…", "noMatches": "一致するビルドはありません。" }, + "AppearanceThemeControl": { + "useTerminalTheme": "このテーマのターミナル配色を使う" + }, "notification": { "settings": { "copy": { @@ -12113,14 +12215,13 @@ "right": { "sidebar": { "BulkActionBar": { - "79a9f5f712": "アンステージ (", - "ef5f5bd06e": "ステージ(", - "60ed678138": "選択中" + "selectedCount_other": "{{count}} 件選択中", + "stageCount": "ステージ ({{count}})", + "unstageCount": "アンステージ ({{count}})" }, "ChecksPanel": { "2ef90c9819": "失敗したチェックに対して AI Agent を開始しました。", "a0181a8d76": "競合の解決のために AI Agent を開始しました。", - "34464d00b9": "更新されました", "058039787c": "キャンセル", "2ab7fd4b6d": "保存", "dda5924a40": "チェックには Git ブランチとホストされたレビューコンテキストが必要です", @@ -12166,7 +12267,8 @@ "430f1a62d4": "選択したスレッドをホスト上で解決できませんでした。", "updateReactionFailed": "反応を更新できませんでした。", "gitlabMoreActions": "その他の MR 操作", - "gitlabLinkAnother": "別の MR をリンクする" + "gitlabLinkAnother": "別の MR をリンクする", + "reviewUpdatedAt": "{{review}} を {{time}} に更新" }, "CreateHostedReviewComposer": { "741ff8a0d2": "プッシュして{{value0}}を作成" @@ -12323,7 +12425,14 @@ "740aca88ab": "ワークスペースのポートスキャンに失敗しました。", "5be4f7f727": "ポート {{value0}} メニュー", "1004af16ab": "{{value0}}をコピー", - "153d3a8026": "ワークスペースのホストが不明です" + "153d3a8026": "ワークスペースのホストが不明です", + "unknownProcess": "不明なプロセス", + "containerOrForwardedService": "コンテナーまたは転送されたサービス", + "unassigned": "未割り当て", + "remotePortOutOfRange": "リモートポートは 1–65535 の範囲で指定してください", + "localPortOutOfRange": "ローカルポートは 1–65535 の範囲で指定してください", + "localPortInUse": "ポート {{port}} は使用中です。別のローカルポートを選択してください。", + "localPortRequiresPrivileges": "ポート {{port}} には管理者権限が必要です。1024 以上のローカルポートを使用してください。" }, "Search": { "1abfb25a66": "ファイル内を検索するために入力します", @@ -12380,7 +12489,6 @@ "476b77745b": "ベース参照の変更", "ed34038d0d": "ブランチ比較をリフレッシュ", "493f963029": "ベース参照を変更する", - "3278b2767b": "進んでいる", "11b5dd8e41": "と比較する", "a9bf7c171a": "コミット失敗", "011f9713fc": "コミットがブロックされました", @@ -12425,7 +12533,6 @@ "574d2f4413": "ノートをクリア", "05bb8f4a48": "キャンセル", "48db37cca9": "すべて見る", - "78ce2d37ac": "フォークにプッシュ", "c05fe04839": "{{value0}} (原点ではない) のフォークにプッシュします", "c35baf2f1e": "ファイルをフィルタリング…", "2fe2a67580": "その他のメモ操作", @@ -12433,14 +12540,12 @@ "cc474e0b8c": "ノート", "e131cd7128": "ソース管理は Git リポジトリでのみ使用できます", "c07b236287": "変更を表示するワークスペースを選択", - "dc5a6465fc": "{{value0}} (例: {{value1}}{{value2}})", "a5e5a11090": "失敗したすべての破棄 - 破棄する前にファイルをステージング解除できません", "8a5ba6a988": "コミット差分をロードできませんでした", "fe5bd1a610": "{{value0}} を作成しています…", "812cb992ee": "{{value0}} で開く", "eef5446523": "{{value0}} #{{value1}} はすでに開いています", "0453ca3a9a": "{{value0}} が作成されましたが、Orca はまだ更新できませんでした。", - "f99560ab29": "{{value0}} の中止に失敗しました", "eae7a1da5f": "メモを消去できませんでした。", "df5040e3c3": "アンステージ", "8cde1a2fb0": "ステージ", @@ -12468,8 +12573,6 @@ "aaf1451654": "ドラフト {{value0}} を作成する", "26511c22b4": "作成中…", "d7ae61269b": "コミット先のブランチ", - "branchFilesChangedVsBaseOne": "{{ref}} と比べて 1 ファイルが変更されています", - "branchFilesChangedVsBaseOther": "{{ref}} と比べて {{count}} ファイルが変更されています", "48a003c1b1": "ステージ済みの変更", "d4ef4bafc5": "変更点", "9339382454": "すべてのステージを解除する", @@ -12479,7 +12582,6 @@ "72f2bea3f4": "ノートを展開する", "d13edef890": "メモを折りたたむ", "d6fb1df5fe": "{{value0}} はすでに開いています", - "05838cfdeb": "{{value0}} コンフリクト", "0b5b8c234c": "{{value0}} ({{value1}}) を開く", "d97ef8f221": "{{value0}}-{{value1}} 行", "6f8bfa0eb9": "{{value0}} 行", @@ -12492,7 +12594,6 @@ "5b176fa431": "双方で削除", "31f6d46278": "未解決", "2c417432b7": "ローカルで解決済み", - "d206117f90": "{{value0}} コンフリクト ({{value1}})", "f3a8b2c1d0e5": "{{value0}} のタイトルを入力してください。", "e2b7a1c0d9f4": "{{value0}} の作成に失敗しました", "hugeRepoIgnorePrompt": "このリポジトリにはアクティブな変更が多すぎます。「{{value0}}」を .gitignore に追加しますか?", @@ -12533,10 +12634,6 @@ "b3c8f1a902": "ファイル名でフィルター", "d4f8c2a901": "フィルターをクリアして閉じる", "e8a1c4b203": "vs", - "compareBaseCommitsAheadOne": "{{ref}} より 1 コミット進んでいます", - "compareBaseCommitsAheadOther": "{{ref}}より{{count}}コミット進んでいます", - "compareBaseCommitsBehindOne": "{{ref}} より 1 コミット遅れています", - "compareBaseCommitsBehindOther": "{{ref}}より{{count}}コミット遅れています", "4b4a7de138": "ブラウザでレビューページを開く", "createPrIntentCommitBlockedSummary": "コミットがブロックされました:{{value0}} Issue を修正して、PR 作成を再試行してください。", "pushRecovery": { @@ -12567,17 +12664,41 @@ "diffCommentNotesCopyFailed": "メモのコピーに失敗しました", "conflictCount_one": "競合 {{count}} 件", "conflictCount_other": "競合 {{count}} 件", - "discardFailedSingular": "{{count}} 個のファイルを破棄できませんでした", - "discardFailedPlural": "{{count}} 個のファイルを破棄できませんでした", - "noteCountSingular": "メモ {{count}} 件", - "noteCountPlural": "メモ {{count}} 件" + "discardFailedSampleMore_other": "{{paths}}、ほか +{{count}} 件", + "discardFailed_other": "{{count}} 個のファイルの変更を破棄できませんでした", + "discardFailedWithSample": "{{error}} (例: {{paths}})", + "compareBaseCommitsAhead_other": "{{ref}} より {{count}} コミット進んでいます", + "compareBaseCommitsBehind_other": "{{ref}} より {{count}} コミット遅れています", + "branchFilesChangedVsBase_other": "{{ref}} と比べて {{count}} ファイルが変更されています", + "noteCount_other": "メモ {{count}} 件", + "comparingAgainstRef": "{{ref}} と比較中", + "commitsAheadShort_other": "{{count}} 件先行", + "unresolvedConflictOfKind": "未解決の競合 ({{kind}})", + "unresolvedConflict": "未解決の競合", + "locallyResolvedConflictOfKind": "ローカルで解決済みの競合 ({{kind}})", + "locallyResolvedConflict": "ローカルで解決済みの競合", + "pushesToForkTarget": "フォーク {{target}} にプッシュ", + "abortRebaseConfirmTitle": "リベースを中止しますか?", + "abortMergeConfirmTitle": "マージを中止しますか?", + "abortRebaseConfirmDescription": "進行中のリベースを中止します。このリベース中に行った競合の解決が破棄される場合があります。", + "abortMergeConfirmDescription": "進行中のマージを中止します。このマージ中に行った競合の解決が破棄される場合があります。", + "abortRebaseFailedFallback": "リベースを中止できませんでした", + "abortMergeFailedFallback": "マージを中止できませんでした", + "abortRebaseFailed": "リベースの中止に失敗しました", + "abortMergeFailed": "マージの中止に失敗しました", + "clearNotesFromWorkspace_other": "このワークスペースから {{count}} 件のメモを削除しますか?", + "clearNotesFromFile_other": "{{path}} から {{count}} 件のメモを削除しますか?" }, "SourceControlAgentActionDialog": { "8e856842d1": "選択した Agent を開始できませんでした。", "c075d00de1": "ワークスペースの接続を解決できません。", "808cfe0a3b": "このリポジトリのみに保存", "994cddd1f7": "保存しないでください", - "38b899cc02": "すべてのリポジトリ" + "38b899cc02": "すべてのリポジトリ", + "agentNotEnabledOrDetected": "{{agent}} は、このワークスペースのホストで有効になっていないか、検出されませんでした。", + "workspaceConnectionUnresolved": "ワークスペースの接続を解決できません。", + "noEnabledAgentsDetected": "このワークスペースのホストで有効な Agent が検出されませんでした。", + "startAgent": "Agent を起動" }, "SourceControlAgentActionDialogForm": { "7ec6abbf2a": "リセット", @@ -12642,9 +12763,6 @@ "cbcc4ab3db": "最初の 100 件のチェックを表示しています", "0dca6bfab5": "オープンチェックの詳細", "991f50c7e4": "まだチェックは報告されていません", - "9ad98f2a17": "保留中", - "5e52f4ef7f": "失敗", - "02ca4f9074": "合格", "e15a8b77ef": "このチェックではインライン詳細は利用できません。", "679bf2093c": "ログの末尾をコピーする", "d713f500b2": "ログテール (最後の 200 行)", @@ -12661,7 +12779,6 @@ "1f2b980522": "チェックの詳細を読み込んでいます…", "0c96cd25e5": "解決", "3a71a6ed0b": "チェックとマージが完了する前に競合を解決してください。", - "60186d8498": "競合によりこれがブロックされます", "c16762ac8c": "以下のチェックとコメントは、現在取得されているコンテキストを示しています。", "9d0e7bcefc": "PR 操作をブロックしない", "5856874b59": "Orca は、このパネルが開いている間、チェックを更新します。", @@ -12686,7 +12803,6 @@ "084c516efb": "コマンドをコピー", "5dc3af25c0": "コメントを選択", "d7a2f9c401": "未解決の {{value0}} コメントを送信", - "d91f2a6c39": "キュー内の {{value0}} 件のコメントを AI に送信", "a6de3e5a20": "キュー内のコメントをクリア", "f8a2c91d04": "Agent のキューに追加", "b4e8a1c902": "キュー待ち", @@ -12701,7 +12817,6 @@ "b3195cba33": "作成者のボット指定を解除", "f588b46a6c": "作成者をボットとして指定", "e45324fbed": "チェック詳細の読み込みに失敗しました。", - "checksUnresolvedChip": "未解決", "checksUnresolvedStripHint": "これらのチェックは、合格または不合格の判定なしで終了しました。", "dcb3c546fe": "再試行", "commitsBehind_one": "{{count}} コミット遅れ", @@ -12712,7 +12827,23 @@ "pendingChecks_one": "保留中のチェック {{count}} 件", "pendingChecks_other": "保留中のチェック {{count}} 件", "unresolvedChecks_one": "未解決のチェック {{count}} 件", - "unresolvedChecks_other": "未解決のチェック {{count}} 件" + "unresolvedChecks_other": "未解決のチェック {{count}} 件", + "passingCount_other": "{{count}} 件合格", + "failingCount_other": "{{count}} 件失敗", + "pendingCount_other": "{{count}} 件保留中", + "unresolvedCount_other": "{{count}} 件未解決", + "sendQueuedCommentsToAi_other": "キュー内の {{count}} 件のコメントを AI に送信", + "conflictsBlockThisMr": "競合によりこの MR がブロックされています", + "conflictsBlockThisPr": "競合によりこの PR がブロックされています", + "copyComment": "コメントをコピー", + "sendComment": "送信", + "commentingRequiresGitHubPrTarget": "コメントするには、GitHub PR の対象リポジトリが必要です。", + "selectWorkspaceBeforeAiAction": "AI 操作を開始する前に、ワークスペースを選択してください。", + "operation": { + "rebase": "リベース", + "merge": "マージ", + "cherryPick": "チェリーピック" + } }, "empty": { "state": { @@ -12954,10 +13085,10 @@ "dialog": { "3bc61dc989": "キャンセル", "15efa778e3": "破棄", - "42f89dd030": "ファイル", - "e7611dca35": "ファイル", "0d2d88cba5": "これを元に戻すことはできません。", - "1551c14668": "変更を破棄しますか?" + "1551c14668": "変更を破棄しますか?", + "fileCount_one": "{{count}} 個のファイル", + "fileCount_other": "{{count}} 個のファイル" } }, "dropdown": { @@ -13119,8 +13250,7 @@ }, "compare": { "summary": { - "commitsAheadSingular": "{{ref}}より{{count}}コミット進んでいます", - "commitsAheadPlural": "{{ref}}より{{count}}コミット進んでいます" + "commitsAhead_other": "{{ref}} より {{count}} コミット進んでいます" } }, "conflict": { @@ -13184,24 +13314,28 @@ "unresolved": "このワークスペースを所有しているホストを特定できませんでした。接続を確認して、もう一度お試しください。" }, "useFileDeletion": { - "72691dfebc": "{{value0}} '{{value1}}' に失敗しました。", "d979a4fbb5": "「{{value0}}」を完全に削除しますか?", "92276aceb7": "削除", "7fb9435c86": "リモートホスト上のディレクトリとその内容を完全に削除します。この操作は取り消せません。", "23e98f192f": "リモートホスト上のファイルを完全に削除します。この操作は取り消せません。", "8b8ee9d22f": "このファイルを所有しているホストを特定できませんでした。ワークスペースの接続を確認して、もう一度お試しください。", - "af1270b90d": "{{count}}個の項目を完全に削除しますか?", "dd029aa5cd": "選択した項目とディレクトリの内容がリモートホスト上で完全に削除されます。この操作は元に戻せません。", - "77fdc36183": "{{count}} 個の項目を削除しますか?", - "fca915a67a": "リモートの項目は完全に削除され、取り消せません。ローカルの項目は {{value0}} に移動します。" + "deleteFailed": "「{{name}}」を削除できませんでした。", + "deleteItems_other": "{{count}} 件の項目を削除しますか?", + "mixedRecycleBin": "リモートの項目は完全に削除され、元に戻せません。ローカルの項目はごみ箱に移動します。", + "mixedTrash": "リモートの項目は完全に削除され、元に戻せません。ローカルの項目はごみ箱に移動します。", + "permanentlyDeleteItems_other": "{{count}} 件の項目を完全に削除しますか?", + "recycleBinFailed": "「{{name}}」をごみ箱に移動できませんでした。", + "trashFailed": "「{{name}}」をごみ箱に移動できませんでした。" }, "useFileExplorerHandlers": { "32cd9fd991": "シンボリックリンクターゲットを開けません", "folderLinksOutsideProject": "このフォルダーはプロジェクト外へのリンクのため、ここでは開けません。" }, "useFileExplorerImport": { - "25919b2050": "{{value0}} {{value1}} をスキップしました。", - "132fd0e1e9": "{{value0}} {{value1}} のインポートに失敗しました。" + "importFailedCount_other": "{{count}} 個のファイルのインポートに失敗しました。", + "importSkippedCount_other": "{{count}} 個のファイルをスキップしました。", + "importFailed": "ファイルのインポートに失敗しました。" }, "useFileExplorerKeys": { "8adb953095": "操作が失敗しました" @@ -13238,7 +13372,6 @@ "refreshSessionHistory": "セッション履歴を更新", "searchSessions": "セッションを検索", "clearSearch": "検索をクリア", - "transcriptsSkipped": "{{count}} 件のトランスクリプトをスキップしました", "noAgentSessionsFound": "Agent のセッションが見つかりません", "noSessionsMatchFilters": "現在の絞り込み条件に一致するセッションはありません", "noAgentsSelected": "Agent が選択されていません", @@ -13258,7 +13391,8 @@ "resumeInChatFailed": "新規チャットでこのセッションを再開できませんでした。", "resumeInNewCliUnavailable": "このセッションは CLI で開けません。", "resumeInNewCliHostTooOld": "このチャットを新しい CLI で再開するには、チャットを実行しているホストの Orca を更新してください。", - "folderWorkspaceUnavailable": "フォルダーワークスペースは利用できなくなりました。" + "folderWorkspaceUnavailable": "フォルダーワークスペースは利用できなくなりました。", + "transcriptsSkippedCount_other": "{{count}} 件のトランスクリプトをスキップしました" }, "AiVaultPanelControls": { "scanningSessions": "セッションをスキャンしています", @@ -13304,11 +13438,8 @@ "sessionRole": "セッション", "worktree": "ワークツリー", "conversationNotSaved": "会話が保存されていません", - "recoverableEmptyDetail": "このセッションには保存された会話がありませんが、{{value0}} 件の復元可能な項目が残っています。", "recoverableEmptyOpenLogHint": "ログを開いて復元できます。", "emptyConversationDetail": "このセッションには保存された会話がなく、再開できません。", - "queuedMessages": "キュー内のメッセージ {{value0}} 件", - "subagentTranscripts": "サブ Agent の履歴 {{value0}} 件", "prompt": "プロンプト", "firstPrompt": "最初のプロンプト", "recentPrompt": "最近のプロンプト", @@ -13322,7 +13453,10 @@ "noFirstPromptAvailable": "最初のプロンプトはありません", "loadingFirstPrompt": "最初のプロンプトを読み込み中…", "folder": "フォルダー", - "resumeInFolder": "フォルダーで再開" + "resumeInFolder": "フォルダーで再開", + "recoverableEmptyDetailCount_other": "このセッションには保存された会話がありませんが、{{count}} 件の復元可能な項目が残っています。", + "queuedMessageCount_other": "キュー内のメッセージ {{count}} 件", + "subagentTranscriptCount_other": "サブ Agent のトランスクリプト {{count}} 件" }, "AiVaultSessionRow": { "resumeInNewTab": "新規タブで再開", @@ -13456,26 +13590,21 @@ "confirmation": { "84f6f5b9eb": "含まれるもの: {{numbers}}。", "541984b2eb": "#{{pr}} をキューに入れますか?", - "4809f55cdb": "{{included}}GitHub は、{{count}} PR を一緒にマージキューに追加します。キューはマージ方法を選択し、それらを別のグループにマージする場合があります。", - "be8f2621be": "{{included}}GitHub は、{{count}} PR をまとめてマージキューに追加します。キューはマージ方法を選択し、それらを別のグループにマージする場合があります。", - "92ca033e72": "キュー {{count}} PR", - "478a527b15": "{{count}} PR をキューに入れる", "1feef35ca4": "#{{pr}} を介してマージしますか?", - "c3e036c99f": "{{included}}GitHub は、{{method}} を使用して {{count}} PR をアトミックにマージします。マージできない場合は、何もマージされません。", - "369aba4b32": "{{included}}GitHub は、{{method}} を使用して {{count}} PR をアトミックにマージします。どれかがマージできない場合、どれもマージできません。", - "493c78f521": "{{count}} PR をマージ", - "eb7051d268": "{{count}} PR をマージする" + "queueDescription_other": "{{included}}GitHub は {{count}} 件の PR をまとめてマージキューに追加します。キューはマージ方法を選択し、別々のグループに分けてマージする場合があります。", + "queueConfirm_other": "{{count}} 件の PR をキューに入れる", + "mergeDescription_other": "{{included}}GitHub は {{method}} を使用して {{count}} 件の PR をアトミックにマージします。いずれかをマージできない場合、どの PR もマージされません。", + "mergeConfirm_other": "{{count}} 件の PR をマージ" }, "merge": { - "55ae29b907": "#{{pr}} · {{count}} PR を介してマージ", - "b8446f6ec2": "#{{pr}} · {{count}} PR を介してマージ", "189d0ec614": "#{{pr}} はまだ下書きです。", "640fb50d9c": "#{{pr}} は閉店しています。", "46ffcbda75": "#{{pr}} にはマージ競合があります。", "6dabefd63e": "#{{pr}} が変更をリクエストしました。", "2bb21fc326": "#{{pr}} はまだレビューの承認が必要です。", "c23faf74df": "#{{pr}} を更新する必要があります。", - "f561e80968": "#{{pr}} はブロックされています。" + "f561e80968": "#{{pr}} はブロックされています。", + "mergeThroughLabel_other": "#{{pr}} まで含めてマージ · {{count}} 件の PR" } } } @@ -13532,14 +13661,14 @@ "sourceActionsUnavailable": "トランスクリプトのソースが利用できません。" }, "AiVaultScanProgressStrip": { - "agentChecked": "{{agent}}: 履歴候補 {{total}} 件中 {{settled}} 件を確認済み", "fileCount_one": "{{value0}} 個のファイル", "fileCount_other": "{{value0}} 個のファイル", "databaseCount_one": "{{value0}} 個のデータベース", "databaseCount_other": "{{value0}} 個のデータベース", "scanning": "{{value0}}をスキャン中", "checking": "{{value0}} を確認中", - "scanned": "{{value0}}をスキャン済み" + "scanned": "{{value0}}をスキャン済み", + "agentCheckedCount_other": "{{agent}}: 履歴候補 {{total}} 件中 {{settled}} 件を確認済み" }, "run": { "source": { @@ -13568,6 +13697,14 @@ } } } + }, + "fileExplorerMultiDrag": { + "moreItems_other": "ほか +{{count}} 件" + }, + "CreatePullRequest": { + "createInProgress": "PR を作成中…", + "workspaceHostUnresolved": "ワークスペースのホストを特定できません。ワークスペースを更新して再試行してください。", + "branchDiscoveryFailed": "ブランチの検出に失敗しました。" } } }, @@ -14092,11 +14229,11 @@ "a2f68645ac": "GitLab API 予算を更新する", "2f9c16d6c3": "Orca は GitLab CLI を通じて REST を使用します。", "14e144f7a7": "GitLab API の予算", - "3e2c982cfa": "左、リセット", - "ea8ad0bae8": "の", "0a891e8935": "REST API", "953f7c6062": "この GitLab ホストはレート制限ヘッダーを返しませんでした。", - "budget_scope_prefix": "予算スコープ" + "budget_scope_prefix": "予算スコープ", + "resetUnknown": "不明", + "remainingOfLimit": "{{limit}} 中 {{remaining}} 残り、{{reset}} 後にリセット" } } } @@ -14168,13 +14305,13 @@ "9ee54037a4": "カスタムコマンド", "4b2fc4b80c": "考える努力", "be8917699e": "モデル", - "4d9b6d84df": "サポートされていません。Claude、Codex、またはカスタムを選択します。", "560d4feb00": "カスタム", "29d119fe95": "Agent", "f9382b48a1": "AI 著者を有効にする", "1c0cb4fabb": "AI作者", "bd14e9c42a": "未設定", - "1f9468c5c9": "{{value0}} はサポートされていません" + "1f9468c5c9": "{{value0}} はサポートされていません", + "unsupportedAgent": "{{agent}} はサポートされていません。Claude、Codex、カスタムのいずれかを選択してください。" }, "BrowserAnimatedVisual": { "46df009982": "無料トライアルを開始する", @@ -14715,17 +14852,14 @@ "ConflictComponents": { "f338288514": "競合するコンテンツを読み込んでいます…", "90d576adb2": "更新", - "a1ce36f77d": "スナップショットがキャプチャされた場所", "c8ca989aea": "ファイルツリーを表示", "58ad5ad431": "閉じる", "28e7db4a90": "ソース管理", "31931dec46": "このレビュースナップショットには、未解決のライブ競合はなくなりました。", "992145ff5a": "すべての競合が解決されました", - "d5edd81755": "から改名", "6e459867ad": "セッションローカルの継続状態。 Git は、このファイルがマージされていないと報告しなくなりました。", "9c2901ef8a": "次の競合", "41d9af2e7a": "前の競合", - "55d61a0ccd": "競合 ·", "da539359b6": "この競合に対して編集できる作業ツリーファイルはありません。", "unresolvedConflicts_one": "未解決の競合 {{count}} 件", "unresolvedConflicts_other": "未解決の競合 {{count}} 件" @@ -15421,7 +15555,9 @@ "6978871a3d": "オープン", "cce596969e": "メモの削除", "cad3384faa": "メモを編集する", - "508ee678a5": "ブラウザで開く" + "508ee678a5": "ブラウザで開く", + "noteAuthorFallback": "メモ", + "sentMeta": "送信済み" }, "DiffCommentPopover": { "2b3ce6d394": "キャンセル", @@ -15434,6 +15570,9 @@ }, "useDiffCommentDecorator": { "995fa28b50": "このメモ" + }, + "diffCommentZoneCard": { + "noteAlreadySent": "メモは送信済みです" } } }, @@ -16028,7 +16167,18 @@ "b09b2384fd": "一時停止中", "eaa02014f8": "有効", "29baf8f4c2": "ソース", - "lastRunFailed": "前回の実行は失敗しました。" + "lastRunFailed": "前回の実行は失敗しました。", + "noGrace": "猶予なし", + "graceMinutes_other": "{{count}} 分", + "graceHours_other": "{{count}} 時間", + "usageCoverageRuns_other": "{{known}}/{{count}} 回の実行", + "usageUnavailable": "利用不可", + "noRuns": "実行なし", + "projectDefault": "プロジェクトのデフォルト", + "reuseLiveSession": "実行中のセッションを再利用", + "freshEachRun": "実行ごとに新規作成", + "precheckEnabled": "有効、{{timeout}}", + "precheckNone": "なし" }, "AutomationEditorDialog": { "fb1896a5e7": "キャンセル", @@ -16129,11 +16279,8 @@ "2faecab10b": "今すぐ実行", "13118faadf": "不明なプロジェクト", "73f630b49d": "キャンセル", - "1b586f0e2b": "の", - "02a33e3204": "から", "9adfab2596": "外部オートメーションの削除", "1e2e41392f": "今後表示しない", - "b264564427": "そしてその実行履歴。以前の実行で作成されたワークスペースは削除されません。", "080dcb5fbb": "オートメーションの削除", "19a6e30eae": "自動更新", "77c2778945": "自動化", @@ -16168,7 +16315,6 @@ "pendingAutomationRunMissing": "実行履歴は利用できなくなりました。", "paused": "一時停止中", "missingWorkspace": "ワークスペースがありません", - "runUsageSummary": "約 {{cost}} · {{tokens}} tokens", "usageUnavailable": "使用量を利用できません", "noRunUsageYet": "まだ実行の使用量がありません", "noWorkspace": "ワークスペースなし", @@ -16183,7 +16329,10 @@ "rowActions": "自動化の操作", "tableLastRun": "最後の実行", "ownerChanged": "この自動化によりホストが変更されました。更新して再試行してください。", - "runError": "エラー:" + "runError": "エラー:", + "deleteAutomationDescription": " とその実行履歴を削除します。過去の実行で作成されたワークスペースは削除されません。", + "deleteExternalAutomationDescription": " 上の から を削除します。", + "runUsageSummaryTokens_other": "推定 {{cost}} · {{tokens}} トークン" }, "CreateFromPicker": { "f061f49e3f": "リポジトリブランチを検索…", @@ -16210,8 +16359,7 @@ "92405f1431": "利用不可", "dbdcec22bd": "読み取り専用", "0a2d4359a8": "管理可能", - "e2532150ed": "自動化", - "701515f010": "オートメーション" + "automationCount_other": "{{count}} 件のオートメーション" }, "WorkspaceCombobox": { "ee5b280eba": "ワークスペースが見つかりません。", @@ -16263,7 +16411,8 @@ "last": { "run": { "done": "完了", - "failed": "失敗" + "failed": "失敗", + "statusWithRelative": "{{status}} · {{relative}}" } } } @@ -16419,15 +16568,11 @@ }, "externalScope": { "uncheckedHost": "{{hostLabel}} の外部自動化マネージャーをチェックできませんでした。", - "uncheckedHosts": "{{count}} ホスト上の外部自動化マネージャーをチェックできませんでした。" + "uncheckedHostCount_other": "{{count}} 台のホスト上の外部オートメーションマネージャーを確認できませんでした。" }, "enablement": { "paused": "一時停止中" }, - "runHistory": { - "occurrencesWithLatest": "{{times}} 回、最近では {{date}}", - "occurrences": "{{times}}回" - }, "extraAgentArgs": { "advanced": "詳細設定", "clear": "引数をクリア", @@ -16437,6 +16582,67 @@ "useFreshSessions": "新しいセッションを使用", "helper": "新しいセッションごとに、このホストのデフォルト引数に追加されます。", "detailLabel": "追加の引数" + }, + "runHistory": { + "runCountSummary_other": "{{count}} 回実行 · {{completed}} 回完了", + "occurrencesWithLatestCount_other": "{{count}} 回、直近は {{date}}", + "occurrencesCount_other": "{{count}} 回" + }, + "capabilityProbe": { + "createIdempotencyUpdateRequired": "このホストにオートメーションを移動するには、最新の Orca サーバーが必要です。HUB を更新して再試行してください。" + }, + "editDraft": { + "unsupportedSchedule": "このオートメーションには未対応のスケジュールが保存されています。変更を保存する前に、対応するスケジュールを選択してください。" + }, + "hostCatalog": { + "orphanEntryLabel": "未割り当ての旧オートメーション" + }, + "automationPageParts": { + "never": "なし", + "now": "たった今", + "runStatusPending": "キュー待ち", + "runStatusDispatching": "起動中", + "runStatusDispatched": "起動済み", + "runStatusCompleted": "完了", + "runStatusSkippedPrecheck": "事前チェックによりスキップ", + "runStatusSkippedMissed": "スキップ済み", + "runStatusSkippedUnavailable": "利用不可", + "runStatusSkippedNeedsInteractiveAuth": "認証情報が必要", + "runStatusDispatchFailed": "失敗" + }, + "runContent": { + "noOutput": "出力内容はありません。" + }, + "runViewState": { + "viewRun": "実行を表示", + "runOpen": "実行は開いています", + "terminalOnPairedServer": "実行ターミナルはペアリング済みサーバーにあります。", + "terminalUnavailable": "実行ターミナルは利用できません。", + "openWorkspace": "ワークスペースを開く", + "workspaceAvailable": "ワークスペースは利用可能です。", + "snapshotSaved": "スナップショット保存済み", + "showingSnapshot": "保存された実行スナップショットを表示しています。", + "namedWorkspaceGone": "{{name}} は利用できなくなりました", + "workspaceGone": "ワークスペースは利用できなくなりました", + "noWorkspaceLaunched": "ワークスペースは起動されていません" + }, + "runWorkspaceDisplay": { + "notLaunched": "未起動", + "namedWorkspaceGone": "{{name}}(利用できなくなりました)" + }, + "usage": { + "tokensAndCost_other": "{{tokens}} トークン · {{cost}}" + }, + "externalDisplay": { + "sshHost": "SSH ホスト", + "local": "ローカル" + }, + "externalActionDisabled": { + "actionInProgress": "別のオートメーション操作が実行中です。", + "sshConnecting": "この SSH ホストの接続が完了するまでお待ちください。", + "connectSshHost": "{{provider}} のオートメーションを管理する前に、この SSH ホストに接続してください。", + "cannotManageOnSshHost": "{{provider}} はこの SSH ホストでオートメーションを管理できません。", + "cannotManageLocally": "{{provider}} はこのマシンでオートメーションを管理できません。" } }, "agent": { @@ -16577,8 +16783,6 @@ "63ce735809": "接続", "4a2ab52781": "確認中…", "79e7aaed39": "キャンセル", - "fdd26d81cc": "Atlassian のアカウント設定", - "8090504a3e": "でトークンを作成します", "7b3967c12f": "Atlassian API トークン", "3d81bf3ab3": "APIトークン", "e91b9a4073": "you@example.com", @@ -16603,17 +16807,17 @@ "be9eba0a1b": "username", "70035652d7": "パスワード", "c50abbf340": "Jira アカウントのパスワード", - "d8737db691": "Jira Server または Data Center のアカウントのユーザー名とパスワードを使用します。" + "d8737db691": "Jira Server または Data Center のアカウントのユーザー名とパスワードを使用します。", + "createTokenInSettings": "Atlassian アカウント設定でトークンを作成してください。" } } }, "rightSidebar": { "FolderWorkspaceWorktreesPanel": { "unavailable": "ワークスペースは、フォルダーワークスペースの場合にのみ表示されます。", - "countOne": "紐づくワークツリー 1 件", - "countMany": "紐づくワークツリー {{value0}} 件", "emptyTitle": "紐づくワークツリーはまだありません", - "emptyCopy": "このワークスペースから作成したワークツリーが、ここに表示されます。" + "emptyCopy": "このワークスペースから作成したワークツリーが、ここに表示されます。", + "attachedCount_other": "紐づくワークツリー {{count}} 件" }, "FolderWorkspacePrChecksPanel": { "unavailable": "PR チェックはフォルダーワークスペースでのみ表示されます。", @@ -16625,12 +16829,9 @@ "hideDetails": "{{value0}} の PR チェック詳細を非表示", "reviewChecks": "レビューのチェック", "allChecksPassing": "すべてのチェックが成功", - "oneWorktree": "1 件のワークツリー", - "worktreeCount": "{{value0}} 件のワークツリー", - "oneFailing": "1 件失敗", - "failingCount": "{{value0}} 件失敗", - "onePending": "保留中 1 件", - "pendingCount": "{{value0}} 件保留中" + "worktreeCountLabel_other": "{{count}} 件のワークツリー", + "failingCountLabel_other": "{{count}} 件失敗", + "pendingCountLabel_other": "{{count}} 件保留中" }, "parentPrChecks": { "rowSummary": { @@ -16712,10 +16913,10 @@ "combobox": { "noProjects": "プロジェクトがありません", "allProjects": "すべてのプロジェクト", - "hostCount": "{{value0}} 台のホスト", "searchProjects": "プロジェクトを検索…", "noMatches": "検索条件に一致するプロジェクトはありません。", - "chooseSource": "タスクソースを選択" + "chooseSource": "タスクソースを選択", + "hostCount_other": "{{count}} 台のホスト" } } }, @@ -16752,7 +16953,31 @@ "taskSourceContextSummary": { "sourceUnavailable": "{{value0}} のソースを利用できません: {{value1}}", "someSourceHostsUnavailable": "一部の {{value0}} ソースホストを利用できません: {{value1}}", - "reconnectOrUpdateTitle": "このソースを読み込むには、{{value0}} を再接続するか更新してください。" + "reconnectOrUpdateTitle": "このソースを読み込むには、{{value0}} を再接続するか更新してください。", + "providerSourceTitle": "{{provider}} ソース", + "hostTitle": "ホスト: {{hosts}}", + "accountTitle": "アカウント: {{accounts}}", + "sourceTitle": "ソース: {{source}}", + "sourceHostCount_other": "{{count}} 台のソースホスト", + "noHost": "ホストなし", + "projectCount_other": "{{count}} 件のプロジェクト", + "selectedProject": "選択したプロジェクト", + "selectedProjectCount_other": "選択したプロジェクト {{count}} 件", + "currentAccount": "現在のアカウント", + "statusCheckingCapabilities": "サーバーの機能を確認中", + "statusServerUpdateForTaskSources": "タスクソースの利用にはサーバーの更新が必要", + "statusProviderAuthNeeded": "プロバイダー認証が必要", + "statusSourceToolUnavailable": "ソースツールが利用不可", + "statusProviderUnsupported": "このホストではプロバイダー未対応", + "statusServerUpdateNeeded": "サーバーの更新が必要", + "unavailableCount_other": "{{count}} 件が利用不可", + "statusConnected": "接続済み", + "statusAuthNeeded": "認証が必要", + "statusConnecting": "接続中", + "statusConnectionIssue": "接続に問題あり", + "statusDisconnected": "未接続", + "hostStatus": "{{host}} {{status}}", + "availabilityTitle": "利用可否: {{hosts}}" }, "ShortcutKeyCombo": { "07eb4985a1": "{{value0}} を 2 回押す" @@ -17007,19 +17232,9 @@ "untitled": "無題のチャット", "listLabel": "再開されるチャット", "dontAskAgain": "二度と質問しないでください (自動的に再開します)", - "dontAskAgainHint": "これは、「設定」→「実験的機能」→「チャット UI」でオフにできます。", - "continuedOne": "1 件のチャットを再開しました", - "continuedMany": "{{value0}} 件のチャットを再開しました", + "dontAskAgainHint": "設定 → チャット → 動作でオフにできます。", "selectAgent": "{{value0}} チャット「{{value1}}」を {{value2}} で再開します", - "resumeSelected": "{{value0}} チャットを再開", - "resumeSelectedOne": "1 チャットを再開", "dismissAll": "すべて閉じる", - "notContinuedOne": "1 件のチャットを再開できませんでした", - "notContinuedMany": "{{value0}} 件のチャットを再開できませんでした", - "notConfirmedOne": "1 件のチャットが再開されたことを確認できませんでした", - "notConfirmedMany": "{{value0}} 件のチャットが再開されたことを確認できませんでした", - "notConfirmedOtherOne": "他のチャット 1 件が再開されたことを確認できませんでした", - "notConfirmedOtherMany": "他のチャット {{value0}} 件が再開されたことを確認できませんでした", "viewChats": "チャットを表示", "review": "確認", "activityUnnamed": "名前なし", @@ -17027,9 +17242,7 @@ "activityQuestion": "回答待ち: {{value0}}", "activityMidReply": "返信の途中でした", "activitySubagentOne": "サブ Agent 実行中: {{value0}}", - "activitySubagentMany": "{{value0}} 個のサブ Agent が実行中", "activityMonitorOne": "監視中: {{value0}}", - "activityMonitorMany": "{{value0}} 個のバックグラウンドタスクを監視中", "selectWorkspace": "{{value0}} のチャットをすべて選択", "workspaceSelectedCount": "{{value0}}/{{value1}}", "selectAll": "すべてのチャットを選択", @@ -17046,8 +17259,15 @@ "serverBody": "{{machine}} の Orca が再起動したとき、これらのチャットは作業中でした。再開すると、各チャットを停止した位置から復元し、Agent に作業の続行を依頼します。あなたのプロンプトは再送信されません。", "serverDismiss": "閉じる", "serverResumeAll": "{{machine}} の {{count}} 件をすべて再開", - "serverResumeHereOne": "ここで開始したチャット 1 件を再開", - "serverResumeHere": "ここで開始したチャット {{count}} 件を再開" + "resumeChats_one": "{{count}} 件のチャットを再開", + "resumeChats_other": "{{count}} 件のチャットを再開", + "serverResumeHereCount_other": "ここで開始した {{count}} 件のチャットを再開", + "continuedCount_other": "{{count}} 件のチャットを再開しました", + "notContinuedCount_other": "{{count}} 件のチャットを再開できませんでした", + "notConfirmedCount_other": "{{count}} 件のチャットの再開を確認できませんでした", + "notConfirmedOtherCount_other": "ほかの {{count}} 件のチャットの再開を確認できませんでした", + "activitySubagentCount_other": "{{count}} 個のサブ Agent が実行中", + "activityMonitorCount_other": "{{count}} 件のバックグラウンドタスクを監視中" }, "linear-issue-attribute-filter-coverage-notice": { "statusPartialTeamCoverage": "{{value0}}/{{value1}} チームステータスをフィルタリングしています。残りのチームからの問題は含まれません。", @@ -17199,15 +17419,13 @@ } }, "NativeChatResumeRunPanel": { - "resumedTitle": "{{value1}} 件中 {{value0}} 件のチャットを再開しました", - "resumedTitleOne": "1 件中 {{value0}} 件のチャットを再開しました", - "resumingTitleOne": "1 件のチャットを再開中", - "resumingTitle": "{{value0}} 件のチャットを再開中", "description": "各チャットは全コンテキストとともに復元され、中断した箇所を確認するよう依頼されます。このダイアログは閉じても構いません。進行状況はステータスバーで確認できます。", "finished": "これらのチャットは Orca が終了したときに作業中でした。Orca は各チャットを停止した時点から、すべてのコンテキストとともに復元し、続行する前に何をしていたかを確認するよう Agent に依頼しました。あなた自身のプロンプトは再送信されていません。", "finishedUpdate": "これらのチャットは Orca がアップデートをインストールしたときに作業中でした。Orca は各チャットを停止した時点から、すべてのコンテキストとともに復元し、続行する前に何をしていたかを確認するよう Agent に依頼しました。あなた自身のプロンプトは再送信されていません。", "finishedPartial": "これらのチャットは Orca が終了したときに作業中でした。Orca が再開したチャットは停止した時点から、すべてのコンテキストとともに復元され、続行する前に何をしていたかを確認するよう依頼されました。あなた自身のプロンプトは再送信されていません。対応が必要なチャットや再開できるチャットは、この一覧で確認してください。", - "finishedPartialUpdate": "これらのチャットは Orca がアップデートをインストールしたときに作業中でした。Orca が再開したチャットは停止した時点から、すべてのコンテキストとともに復元され、続行する前に何をしていたかを確認するよう依頼されました。あなた自身のプロンプトは再送信されていません。対応が必要なチャットや再開できるチャットは、この一覧で確認してください。" + "finishedPartialUpdate": "これらのチャットは Orca がアップデートをインストールしたときに作業中でした。Orca が再開したチャットは停止した時点から、すべてのコンテキストとともに復元され、続行する前に何をしていたかを確認するよう依頼されました。あなた自身のプロンプトは再送信されていません。対応が必要なチャットや再開できるチャットは、この一覧で確認してください。", + "resumedOfTotal_other": "{{count}} 件中 {{resumed}} 件のチャットを再開しました", + "resumingCount_other": "{{count}} 件のチャットを再開中" }, "NativeChatResumeRunStatusIcon": { "waitingForReply": "返信を待っています", @@ -17272,6 +17490,68 @@ "cancelled": "この通常の SSH ターミナルは開始前に閉じられました。", "terminalUnavailable": "Orca はここでターミナルを開けませんでした。", "openHint": "Orca がホスト上でセットアップできない間も、ホストで作業を続けられます。" + }, + "AgentStateDot": { + "working": "作業中", + "monitoring": "バックグラウンドタスクを監視中", + "blocked": "ブロック中", + "waiting": "入力待ち", + "interrupted": "中断", + "failed": "失敗", + "done": "完了", + "idle": "待機中", + "unverifiable": "最近の更新なし", + "unconfirmed": "確認できませんでした", + "permission": "対応が必要" + }, + "issueComments": { + "you": "あなた" + }, + "ZoomOverlay": { + "uiZoom": "UI ズーム", + "editorZoom": "エディターのズーム", + "terminalZoom": "ターミナルのズーム" + }, + "issueCopy": { + "urlCopied": "URL をコピーしました", + "keyCopied": "キーをコピーしました", + "identifierCopied": "識別子をコピーしました", + "branchNameCopied": "ブランチ名をコピーしました", + "promptCopied": "プロンプトをコピーしました", + "urlCopyFailed": "URL をコピーできませんでした", + "keyCopyFailed": "キーをコピーできませんでした", + "identifierCopyFailed": "識別子をコピーできませんでした", + "branchNameCopyFailed": "ブランチ名をコピーできませんでした", + "promptCopyFailed": "プロンプトをコピーできませんでした" + }, + "prCheckCounts": { + "noChecksFound": "チェックが見つかりません", + "checksFailing_other": "{{count}} 件のチェックが失敗", + "checksNeedAction_other": "{{count}} 件のチェックに対応が必要", + "checksPending_other": "{{count}} 件のチェックが保留中", + "allChecksPassing": "すべてのチェックに成功", + "checksPassingOfTotal_other": "{{count}} 件中 {{passing}} 件のチェックに成功" + }, + "taskPageJiraBoard": { + "changeStatusFailed": "ステータスを変更できませんでした。" + }, + "jiraIssue": { + "loadStatusChangesFailed": "ステータスの変更を読み込めませんでした。", + "loadCommentsFailed": "コメントを読み込めませんでした。" + }, + "taskPageJiraLinkedIssues": { + "someIssuesFailed": "ワークスペースにリンクされた一部の Jira Issue を読み込めませんでした。更新して再試行してください。" + }, + "taskPageJiraLoadState": { + "failedToLoadIssues": "Jira Issue を読み込めませんでした。", + "authFailed": "Jira の認証に失敗しました。設定で Jira に再接続してから再試行してください。", + "accessDenied": "Jira がこの Issue 検索へのアクセスを拒否しました。プロジェクトの権限を確認するか、別の JQL クエリをお試しください。", + "rateLimited": "この Issue 検索は Jira のレート制限に達しました。しばらくしてから再試行してください。", + "serverError": "Issue の読み込み中に Jira のサーバーエラーが発生しました。しばらくしてから再試行してください。", + "jqlFailed": "Jira がこの JQL クエリを実行できませんでした。構文を確認して再試行してください。", + "unreachable": "Jira に接続できませんでした。接続を確認して再試行してください。", + "loadFailed": "Jira Issue を読み込めませんでした。しばらくしてから再試行してください。", + "errorWithCode": "エラー {{code}}: {{summary}}" } }, "i18n": { @@ -17471,6 +17751,7 @@ "agentCommandNotRunnable": "[設定] → [Agent] にある {{agent}} の [コマンド] には、Orca が見つけられるプログラムのパスまたは名前を、引数や変数なしで指定する必要があります。変更するか、[リセット] してください。", "runtimeNotInstalled": "{{agent}} はこのチャットを実行しているコンピューターにインストールされていません。最新バージョンの Orca でチャットからインストールしてください。", "fullAccessAsRoot": "{{agent}} は root として実行されている間はフルアクセスを使用しません。このチャットを実行しているコンピューターの [設定 → Agent] で {{agent}} に別の権限を選択してから、新しいチャットを開始してください。", + "launchPreparationFailed": "Orca は、このチャットを実行しているコンピューターで {{agent}} の起動を準備できませんでした。", "conversationOpenElsewhere": "Codex がまだこの会話を開いたままにしています。少し待ってからもう一度試すか、ほかの Codex ターミナルを閉じてください。", "conversationOpenInTerminal": "{{agent}} は別のターミナルですでにこの会話を実行しています。そちらの {{agent}} を終了するか、そのターミナルを閉じて、ここで続けてください。", "chooseClaudeAccount": "Claude アカウントの設定で選択または追加してください。", @@ -17620,7 +17901,8 @@ "compactAfterRetry": "以前のメッセージを再試行してから、/compact を実行してください。", "clearAfterSending": "以前のメッセージはまだ送信中です。送信が終わったら /clear を実行してください。", "compactAfterSending": "以前のメッセージはまだ送信中です。送信が終わったら /compact を実行してください。", - "pendingWork": "このコマンドを使用する前に、保留中の作業とメッセージが完了するまで待ってください。" + "pendingWork": "このコマンドを使用する前に、保留中の作業とメッセージが完了するまで待ってください。", + "notDoneGoalChangeIncomplete": "目標の変更を完了できませんでした。チャットを確認してください。" }, "composer": { "send": "送信", @@ -18124,7 +18406,6 @@ "pausedSendFailedWaiting": "送信できませんでした。Agent の処理が終わったら「送信」を押して再試行してください。", "save": "保存", "editingMessage": "メッセージを編集中", - "cancelEditing": "編集をキャンセル", "editChanged": "編集中にこのメッセージが変更されました。編集したテキストはチャット入力欄にあります。", "editChangedPrompt": "編集中にこのメッセージが変更されました。Agent に回答すると、編集したテキストがチャット入力欄に表示されます。", "editChangedNotSaved": "編集中にこのメッセージが変更されました。編集内容は保存されていません。", @@ -18138,8 +18419,6 @@ "expand": "展開", "queued": "キュー待ち", "clearAll": "すべてクリア", - "pasteOrDropImages": "画像を貼り付けるかドロップ", - "saveNeedsContent": "保存するにはテキストか画像を追加してください", "moveChanged": "移動の前にキューが変更されました。もう一度メッセージをドラッグしてください。", "reorderHint": "ドラッグするか、上下の矢印キーを使って並べ替えます。", "reorderMessage": "メッセージを並べ替え" @@ -18296,6 +18575,15 @@ "settings": "ターミナルで設定を開く", "extensions": "ターミナルで拡張機能ダッシュボードを開く", "hotkeys": "ターミナルでキーボードショートカットを表示" + }, + "modelDescriptions": { + "grok_4_7": "xAI の最新のフロンティアモデル", + "grok_4_6": "xAI の前世代のフロンティアモデル", + "grok_4_5": "xAI の以前のフロンティアモデル", + "fable": "最も難しく、長時間かかるタスクに最適", + "opus": "日常の複雑なタスクに最適", + "sonnet": "日常のタスクを効率的に処理", + "haiku": "素早い回答に最適" } }, "tab": { @@ -18832,7 +19120,6 @@ "subagents_other": "{{count}} 個のサブ Agent" }, "terminal": { - "closed": "実行中のターミナルがありません。この Agent のペインは閉じられています。", "focusWorktree": "ワークツリーを開く", "close": "閉じる", "remotePreviewUnavailable": "このリモートセッションにはプレビューがありません。ワークスペースを開いてターミナルを表示してください。" @@ -19055,6 +19342,15 @@ "empty": "このプロファイルで有効な拡張機能はありません", "visitWebStore": "Chrome ウェブストアにアクセス", "manage": "拡張機能を管理" + }, + "viewport": { + "mobile-s": "モバイル S — 320 × 568", + "mobile-m": "モバイル M — 375 × 667", + "mobile-l": "モバイル L — 425 × 812", + "tablet": "タブレット — 768 × 1024", + "laptop": "ノートパソコン — 1024 × 768", + "laptop-l": "ノートパソコン L — 1440 × 900", + "desktop": "デスクトップ — 1920 × 1080" } }, "runtimeRpc": { @@ -19121,6 +19417,30 @@ "confirm": "フィルターを調整して明らかにする", "cancel": "フィルタを保持する" }, + "wslMoved": { + "movedToHost": "{{distro}} ホストに移動済み", + "useHere": "このコンピューターで再び使用", + "useHereTitle": "{{name}} をこのコンピューターで再び使用しますか?", + "useHereDescription": "Orca はこのプロジェクトを移動前の状態でここに開きます。コードには影響しません(移動していません)。移動後に {{distro}} ホストで行った変更(新しいタブやチャットなど)はホストに残り、戻りません。一緒に移動したプロジェクトも戻ります。プロジェクトは、{{distro}} ホストで削除するまでそこにも残ります。このウィンドウは再読み込みされます。", + "useHereConfirm": "このコンピューターで使用", + "useHereSuperseded": "{{distro}} ホストへの後の移動にこのプロジェクトが含まれています。先にそちらを戻してください。", + "useHereRefusedTitle": "{{name}} はまだここで使用できません", + "useHereRefusedOk": "OK", + "useHereSupersededBy": "このプロジェクトの後に、{{names}} が {{distro}} ホストに移動しました。先にそれらをこのコンピューターで再び使用してから、このプロジェクトを戻してください。", + "useHereMoveRunning": "{{distro}} ホストへの移動がまだ実行中です。終了してからもう一度お試しください。", + "useHereHostKeptForPeers": "{{project}} は {{distro}} ホストに移動しました。そのホストは別の Orca のために動作中です。ここで再び使うには、ホストを追加し直してください。", + "useHereHostUnreachable": "{{distro}} ホストが応答しないため、Orca はこのプロジェクトのホスト側のコピーを停止できず、そのAgentがまだ実行中の可能性があります。設定でホストに接続するか削除してから、もう一度お試しください。", + "useHereHostStillRunning": "{{distro}} ホスト上のこのプロジェクトのコピーでまだターミナルが実行中のため、Agentが二重に動く可能性があります。少し待ってからもう一度お試しください。", + "useHereFailed": "このプロジェクトをこのコンピューターに戻せませんでした。", + "useHereHostRemovalPending": "{{distro}} ホストはまだ削除中のため、Orca はそのままにしています。設定で削除を完了してから、もう一度お試しください。", + "useHereHostAutomations": "Orca は {{distro}} ホスト上のこのプロジェクトのオートメーションをオフにできなかったため、二重に実行される可能性があります。設定でホストに接続してから、もう一度お試しください。", + "useHereUnsavedTitle": "先にファイルを保存してください", + "useHereUnsavedDescription": "{{name}} を戻すとこのウィンドウが再読み込みされます。先に次のファイルを保存するか閉じてください: {{files}}", + "automationRunsOnHost": "{{distro}} ホストで実行", + "quitDuringMoveTitle": "プロジェクトの移動中に終了しますか?", + "quitDuringMoveDescription": "プロジェクトを WSL ホストへ移動しています。それでも終了しますか?移動は次回の起動時に取り消されます。", + "quitDuringMoveConfirm": "終了する" + }, "startupWorktreeRefresh": { "loading": "ワークスペースを検出中…", "description": "ローカルおよびリモートのプロジェクトを読み込む間に、さらにワークスペースが表示されることがあります。" @@ -19222,7 +19542,9 @@ }, "quickOpen": { "moreMatchesAvailable": "さらに多くの一致が利用可能になる可能性があります。検索を絞り込んで結果を絞り込みます。", - "recentValidationFailed": "最近のファイルを確認できませんでした: {{error}}" + "recentValidationFailed": "最近のファイルを確認できませんでした: {{error}}", + "installRipgrepOnRemote": ".gitignore の設定に従ってファイルを高速に一覧表示するには、リモートホストに ripgrep をインストールしてください:", + "scanTooLarge": "クイックオープンのスキャン対象が大きすぎます({{reason}})。" }, "checksPanel": { "unlinked": { @@ -19238,11 +19560,18 @@ }, "discard": { "deleteUntrackedFileDescription": "この未追跡ファイルは完全に削除されます。この操作は元に戻せません。", - "deleteUntrackedFilesDescription": "これらの {{count}} 個の未追跡ファイルは完全に削除されます。この操作は元に戻せません。", + "deleteUntrackedFilesDescription_other": "これらの {{count}} 個の未追跡ファイルは完全に削除されます。この操作は元に戻せません。", "restoreStagedVersionDescription": "これにより、最後にステージングされたバージョンが復元され、削除が破棄されます。これを元に戻すことはできません。", "unstagedChangesDescription": "これにより、このファイルに対するステージングされていない変更が元に戻ります。これを元に戻すことはできません。", "unstagedSelectionIncludingUntrackedDescription": "ステージングされていない変更を元に戻し、この選択内の未追跡ファイルを完全に削除します。この操作は元に戻せません。", - "unstagedFilesIncludingUntrackedDescription": "ステージングされていない変更を元に戻し、これらの {{count}} 個のファイルに含まれる未追跡ファイルを完全に削除します。この操作は元に戻せません。" + "unstagedFilesIncludingUntrackedDescription_other": "ステージングされていない変更を元に戻し、これらの {{count}} 個のファイルに含まれる未追跡ファイルを完全に削除します。この操作は元に戻せません。", + "delete": "削除", + "restore": "復元", + "discard": "破棄", + "discardAll": "すべて破棄", + "deleteUntrackedTitle_one": "未追跡のファイル {{count}} 個を削除しますか?", + "deleteUntrackedTitle_other": "未追跡のファイル {{count}} 個を削除しますか?", + "deleteCount": "{{count}} 個を削除" }, "createReviewFailure": { "authRequiredCommand": "{{providerName}} が認証されていません。次の手順: この環境で {{command}} を実行してください。", @@ -19273,6 +19602,34 @@ "creationUnconfirmed": "{{shortLabel}} の作成は完了している可能性があります。ブランチのレビュー状態を更新しています…", "withDetail": "{{shortLabel}} の作成に失敗しました: {{detail}}", "pushFailed": "プッシュに失敗しました。プッシュのエラーを解決してから、もう一度お試しください。" + }, + "model": { + "auto": "自動", + "configDefault": "設定のデフォルト" + }, + "thinking": { + "off": "オフ", + "minimal": "最小", + "low": "低", + "medium": "中", + "high": "高", + "max": "最大", + "xhigh": "最高" + }, + "variables": { + "basePrompt": "Orca が安全に収集できるコンテキストを含む、この操作用の組み込みプロンプトです。", + "branch": "現在のソース管理ブランチ名です。", + "stagedFiles": "コミットメッセージの生成に使う、ステージ済みファイルの改行区切りリストです。", + "stagedPatch": "コミットメッセージの生成に使う、ステージ済みの Git パッチです。", + "baseBranch": "PR 作成画面で選択したターゲットブランチです。", + "currentTitle": "生成開始前に入力されている PR のタイトルです。", + "currentBody": "生成開始前に入力されている PR の説明です。", + "commitSummary": "ベースブランチと比較した、このブランチのコミットの改行区切りリストです。", + "changedFiles": "このブランチとベースブランチの間で変更されたファイルの概要です。", + "patch": "PR の詳細の生成に使う、このブランチとベースブランチの差分です。", + "firstPrompt": "このワークスペースまたはチャットでの最初のユーザーの依頼です。", + "assistantMessage": "Orca が取得できる場合の、Agent の最初の応答です。", + "linkedIssue": "このワークスペースにリンクされた GitHub Issue の番号です。GitHub Issue がリンクされていない場合は空です(GitLab にリンクされたワークスペースを含む)。指示を含むテンプレートを使ってください。リンクがない場合、単独の「Fixes #{linkedIssue}」は「Fixes #」になります。" } }, "rendererRecovery": { @@ -19297,8 +19654,6 @@ }, "sessionSearch": { "panel": { - "resultsOne": "{{count}} 結果", - "resultsOther": "{{count}} の結果", "noMatches": "インデックス付けされた履歴に一致するセッションがありません。別のクエリまたはスコープを試してください。", "loadMore": "さらに一致をロードする", "indexedHistory": "インデックス付き履歴", @@ -19319,12 +19674,21 @@ "retry": "再試行", "scopeUnknown": "このコンピュータにはこのワークスペースまたはプロジェクトがありません。範囲を [すべて] に切り替えて、その範囲内のすべてを検索します。", "sortSessionsAriaLabel": "セッションの並べ替え: {{value0}}", - "sessionsOne": "{{count}} セッション", - "sessionsOther": "{{count}} セッション", - "sessionsOfLoaded": "{{value0}}/{{value1}} セッション", "showMoreSessions": "さらにセッションを表示", "loadingMoreSessions": "さらにセッションを読み込んでいます…", - "unsupportedAgent": "このコンピュータは、選択した Agent の履歴検索をサポートしていません。そのコンピュータで Orca を更新するか、別の Agent を選択します。" + "unsupportedAgent": "このコンピュータは、選択した Agent の履歴検索をサポートしていません。そのコンピュータで Orca を更新するか、別の Agent を選択します。", + "resultCount_other": "{{count}} 件の結果", + "sessionCount_other": "{{count}} セッション", + "sessionsShownOfLoaded_other": "{{shown}} / {{count}} セッション", + "hostSkipReason": { + "indexChanged": "インデックスが変更されました", + "searchOff": "検索が無効", + "notReady": "準備未完了", + "unavailable": "利用不可", + "unreachable": "接続不可", + "scopeNotFound": "そのホストに検索範囲が見つかりません", + "agentNotSupported": "Agent 未対応" + } } }, "sessionHistory": { @@ -19446,9 +19810,9 @@ "pathAdded": "Added", "openFolder": "Open {{name}}", "findOrTypePath": "フォルダーを検索するか、パスを直接入力…", - "addTypedPath": "Add", "noDirectories": "まだフォルダーは追加されていません。", - "removePath": "Remove {{name}}" + "removePath": "Remove {{name}}", + "addTypedPathCode": " を追加" }, "accounts": { "wslAccountNotApplied": { @@ -19547,14 +19911,11 @@ "settingAsk": "確認する", "title": "{{account}} に切り替えました", "dontAskAgainHint": "これは、「設定」→「AI プロバイダーアカウント」でオフにできます。", - "bodyOther": "{{previous}} で Claude セッションが {{count}} 件まだ実行中です。再起動すると、{{next}} で各会話が続きます。作業中のセッションは、アイドル状態になってから再起動します。", - "bodyOne": "{{previous}} で Claude セッションが 1 件まだ実行中です。再起動すると、{{next}} で会話が続きます。作業中のセッションは、アイドル状態になってから再起動します。", "dontAskAgain": "今後は確認しない(自動で再起動する)", "listLabel": "再起動する Claude セッション", "restartOne": "セッションを再起動", "keep": "そのままにする", "session": "Claude セッション", - "restartOther": "{{count}} 件のセッションを再起動", "settingDescription": "再起動すると、新規アカウントで実行中の各会話が継続されます。", "settingTitle": "Claude の実行中にアカウントを切り替える場合", "restartingOne": "{{account}} で Claude セッションを 1 件再起動中", @@ -19569,13 +19930,14 @@ "reasonOwnFolder": "独自の Claude フォルダーを使用", "reasonUnknownAccount": "アカウント不明", "reasonNoSession": "再開できません", - "reviewBodyOne": "他の Claude セッション 1 件は {{next}} に移動されませんでした。", - "reviewBodyOther": "他の Claude セッション {{count}} 件は {{next}} に移動されませんでした。", "notMovedOne": "他の 1 件のセッションは移動されませんでした。", "notMovedOther": "他の {{count}} 件のセッションは移動されませんでした。", "review": "確認", "uncheckedOne": "1 つのターミナルで Claude を確認できませんでした。そこで Claude が実行中の場合、再起動するまで {{previous}} のままになります。", - "uncheckedOther": "{{count}} 個のターミナルで Claude を確認できませんでした。そこで実行中の Claude は、再起動するまで {{previous}} のままになります。" + "uncheckedOther": "{{count}} 個のターミナルで Claude を確認できませんでした。そこで実行中の Claude は、再起動するまで {{previous}} のままになります。", + "restartCount_other": "{{count}} 件のセッションを再起動", + "reviewBody_other": "ほかの {{count}} 件の Claude セッションは {{next}} に移動されませんでした。", + "body_other": "{{count}} 件の Claude セッションがまだ {{previous}} で実行中です。再起動すると、各会話が {{next}} で続行されます。処理中のセッションは待機状態になってから再起動します。" } }, "hostSignIn": { @@ -19689,7 +20051,9 @@ "confirmTitle": "ターミナルデーモンを再起動しますか?", "confirmBody": "再起動すると、{{sessions}} で実行中のすべてのプロセスが終了します。再開に対応している Agent は後で再開できますが、シェルなどのジョブは再開できず、再度開始する必要があります。Agent がアイドル状態のときに行ってください。", "cancel": "キャンセル", - "confirm": "再起動してプロセスを終了" + "confirm": "再起動してプロセスを終了", + "count_other": "実行中のターミナル {{count}} 個", + "count_one": "実行中のターミナル {{count}} 個" }, "restartedInputNotSent": "入力中にターミナルが再起動したため、一部の入力が届いていない可能性があります。もう一度入力する前に新しいシェルを確認してください。", "stalledDaemonBanner": { @@ -19806,7 +20170,11 @@ "picker": { "pasteUnparseable": "プロジェクトの URL または owner/number を入力してください", "ownerLoadFailed": "{{owner}} のプロジェクトを読み込めませんでした。", - "organizationsLoadFailed": "一部の組織を読み込めませんでした({{failureCount}})。" + "organizationsLoadFailed": "一部の組織を読み込めませんでした({{failureCount}})。", + "organizations": "組織", + "listFailed": "プロジェクト一覧を取得できませんでした", + "detailsFailed": "詳細を読み込めませんでした", + "viewFailed": "プロジェクトビューを取得できませんでした" }, "error": { "notFoundState": "このプロジェクトまたはビューが見つかりませんでした。", @@ -19839,8 +20207,11 @@ "rateLimited": "GitHub のレート制限に達しました。数分後にもう一度お試しください。", "network": "ネットワークエラー — 接続を確認してください。", "tooLargeUnknownCount": "このビューはアイテムが多すぎて Orca で表示できません。GitHub でビューのフィルターを絞り込んでください。", - "tooLarge": "このビューには {{itemCount}} 件のアイテムがあり、Orca で表示するには多すぎます。GitHub でビューのフィルターを絞り込んでください。", - "schemaDriftDetail": "このプロジェクトビューを読み取れませんでした: {{detail}}。" + "schemaDriftDetail": "このプロジェクトビューを読み取れませんでした: {{detail}}。", + "tooLargeCount_other": "このビューには {{count}} 件のアイテムがあり、Orca で表示するには多すぎます。GitHub でビューのフィルターを絞り込んでください。" + }, + "columns": { + "type": "タイプ" } }, "projectField": { @@ -19927,6 +20298,27 @@ "attachments": { "updateRuntime": "ワークスペースのリンクを変更するには、リモートランタイムを更新してください", "updateRuntimeSafely": "ワークスペースのリンクを安全に変更するには、リモートランタイムを更新してください" + }, + "activity": { + "active": "アクティブ", + "working": "作業中", + "monitoring": "バックグラウンドタスクを監視中", + "failed": "失敗", + "interrupted": "中断", + "unconfirmed": "確認できませんでした", + "done": "完了", + "inactive": "非アクティブ", + "permission": "許可が必要", + "unreadLabel": "{{status}} · 未読" + }, + "reviewStatus": { + "checksFailed": "{{review}} のチェック: 失敗", + "checksPassing": "{{review}} のチェック: 成功", + "checksPending": "{{review}} のチェック: 保留中", + "closed": "{{review}}: クローズ", + "draft": "{{review}}: 下書き", + "merged": "{{review}}: マージ済み", + "open": "{{review}}: オープン" } }, "tabHoverCard": { @@ -19970,13 +20362,12 @@ "optionalEmail": "Atlassian のメールアドレス (スコープ付きトークンではオプション)" }, "workspace": { - "count": "{{key}} にリンクされたワークスペース {{count}} 件", "startAnother": "新規ワークスペースを開始", "empty": "Jira Issue をワークスペースにリンクするか、別のビューを選択してください。", "openFailed": "この Jira Issue にリンクされたワークスペースを開けませんでした。", "mode": "ワークスペースあり", "search": "リンクされた Issue を検索", - "single": "{{key}} にリンクされたワークスペース 1 件" + "linkedCount_other": "{{count}} 件のワークスペースが {{key}} にリンク済み" }, "prompt": { "dialogTitle": "テンプレートからプロンプトをコピー", @@ -20069,7 +20460,9 @@ "preparingAriaLabel": "更新を準備中。クリックして展開します。", "browserGuidance": "以下のプロセスを終了してから再試行してください。サーバーはブラウザなしで実行を続けます。別のコンピュータがこの Mac を SSH ホストとして使用している場合、そのコンピュータの Orca を更新すると、更新時にブラウザが自動的に一時停止するようになります。", "browserSummary": "バックグラウンド Orca サーバーのブラウザはまだこのアプリを使用しています。" - } + }, + "wslMoveInstallHeld": "プロジェクトを WSL ホストへ移動しています。移動が完了してからアップデートをインストールしてください。", + "wslMoveUndoInstallHeld": "プロジェクトを WSL ホストから戻しています。完了してからアップデートをインストールしてください。" }, "onboarding": { "language": { @@ -20452,7 +20845,7 @@ "email": "メールアドレスの取得", "allSites": "すべてのウェブサイト上にある自分のすべてのデータの読み取りと変更", "someSites": "{{hosts}} 上にある自分のデータの読み取りと変更", - "manySites": "{{hosts}} とほか {{count}} 件のサイト上にある自分のデータの読み取りと変更" + "manyOtherSites_other": "{{hosts}} とほかの {{count}} 個のサイト上にある自分のデータの読み取りと変更" }, "install": { "title": "{{name}} を追加しますか?", @@ -20482,5 +20875,340 @@ "math": { "scrollDisplayEquation": "数式ブロックをスクロール" } + }, + "runtime": { + "health": { + "local": "ローカル", + "available": "接続済み", + "connecting": "接続中", + "disconnected": "切断済み", + "error": "対応が必要", + "mixed": "混在", + "repair": "再ペアリングが必要", + "update": "更新が必要" + }, + "compat": { + "compatible": "ランタイムのクライアントとサーバーは互換性があります。", + "clientTooOld": "この Orca クライアントは古すぎるため、選択したサーバーに接続できません。このマシンの Orca を更新してください。クライアントのプロトコルは {{clientProtocol}}、サーバーが要求するクライアントのプロトコルは {{requiredProtocol}} です。", + "serverTooOld": "選択した Orca サーバーは古すぎるため、このクライアントと互換性がありません。サーバーの Orca を更新してください。サーバーのプロトコルは {{serverProtocol}}、クライアントが要求するサーバーのプロトコルは {{requiredProtocol}} です。" + } + }, + "native": { + "about": { + "gpu": { + "unknownStatus": "ステータスを取得できません", + "enabled": "有効", + "disabled": "無効", + "unavailable": "利用不可", + "safeMode": "無効(セーフグラフィックスモード)", + "software": "ソフトウェアレンダリング", + "unknown": "不明({{status}})", + "summary": "GPU アクセラレーション:{{status}}" + } + }, + "dialog": { + "importCookies": "Cookie のインポート", + "spaceTitle": "Orca スペースベータ", + "dashboardTitle": "Orca Agent ダッシュボード", + "cookieFiles": "Cookie ファイル", + "allFiles": "すべてのファイル", + "importPetBundle": ".codex-pet バンドルを選択", + "pickPet": "ペットを選択", + "petImage": "ペットの画像", + "importWarpTheme": "Warp テーマをインポート", + "warpThemeYaml": "Warp テーマ YAML", + "importWarpFolder": "Warp テーマフォルダーをインポート", + "images": "画像", + "repoIconImages": "リポジトリアイコン画像", + "audio": "音声" + } + }, + "taskProviders": { + "linear": { + "updateAccess": "アクセスを更新", + "addAccess": "Linear アクセスを追加", + "fetchMore": "さらに読み込む", + "connectionFailed": "接続に失敗しました", + "listLabel": "Linear リスト", + "projectsLoadFailed": "プロジェクトを読み込めませんでした。", + "projectNotFound": "プロジェクトが見つかりませんでした。", + "projectLoadFailed": "プロジェクトを読み込めませんでした。", + "projectIssuesLoadFailed": "プロジェクトの Issue を読み込めませんでした。", + "viewsLoadFailed": "ビューを読み込めませんでした。", + "viewContentsLoadFailed": "ビューの内容を読み込めませんでした。", + "issuesLoadFailed": "Linear の Issue を読み込めませんでした。", + "apiKeyHint": "Orca で使う Linear ワークスペースの個人 API キーを貼り付けてください。すでに接続済みの場合、保存されたキーを置き換えます。", + "remoteKeyStorage": "このキーは現在のリモートランタイムに保存されます。", + "localKeyStorage": "ローカルランタイムのキーはこのデバイスに保存され、利用可能な場合は Electron の暗号化ストレージを使います。", + "commentsLoadFailed": "コメントを読み込めませんでした。", + "updateWorkspaceAccess": "{{workspace}} の Linear アクセスを更新", + "workspaceApiKeyHint": "{{workspace}} の個人 API キーを貼り付けてください。すでに接続済みの場合、保存されたキーを置き換えます。", + "connect": "接続", + "descriptionUpdateFailed": "説明の更新に失敗しました。", + "titleUpdateFailed": "タイトルの更新に失敗しました。", + "truncated": { + "issues_one": "最初の {{count}} 件の Issue を表示しています。全件を確認するには、検索するか Linear を開いてください。", + "issues_other": "最初の {{count}} 件の Issue を表示しています。全件を確認するには、検索するか Linear を開いてください。", + "projectIssues_one": "プロジェクトの Issue を最初の {{count}} 件表示しています。全件を確認するには、検索するか Linear を開いてください。", + "projectIssues_other": "プロジェクトの Issue を最初の {{count}} 件表示しています。全件を確認するには、検索するか Linear を開いてください。", + "projects_one": "最初の {{count}} 件のプロジェクトを表示しています。全件を確認するには、検索するか Linear を開いてください。", + "projects_other": "最初の {{count}} 件のプロジェクトを表示しています。全件を確認するには、検索するか Linear を開いてください。", + "viewIssues_one": "ビューの Issue を最初の {{count}} 件表示しています。全件を確認するには、検索するか Linear を開いてください。", + "viewIssues_other": "ビューの Issue を最初の {{count}} 件表示しています。全件を確認するには、検索するか Linear を開いてください。", + "views_one": "最初の {{count}} 件のビューを表示しています。全件を確認するには、検索するか Linear を開いてください。", + "views_other": "最初の {{count}} 件のビューを表示しています。全件を確認するには、検索するか Linear を開いてください。" + } + }, + "jira": { + "connectionFailed": "接続に失敗しました", + "remoteTokenStorage": "トークンは選択したリモートランタイムに送信され、そのランタイムがサポートする暗号化方式で保存されます。", + "localTokenStorage": "トークンはローカルに保存され、ローカルランタイムのストレージが対応している場合は暗号化されます。" + }, + "errors": { + "jira": { + "createFailed": "Issue の作成に失敗しました。", + "commentFailed": "コメントの追加に失敗しました。", + "notConnected": "Jira に接続されていません。", + "titleRequired": "タイトルが必要です。", + "labelsConflict": "labels または labelOperations のどちらか一方を指定してください。", + "updateFailed": "Issue を更新できませんでした。", + "credentialsRequired": "サイト URL、メールアドレス、API トークンが必要です。", + "projectRequired": "プロジェクトが必要です。", + "issueTypeRequired": "Issue の種類が必要です。", + "issueKeyRequired": "Issue キーが必要です。", + "updatesRequired": "更新オブジェクトが必要です。", + "commentBodyRequired": "コメント本文が必要です。", + "invalidSiteUrl": "有効な Jira サイト URL を入力してください。", + "passwordRequired": "パスワードが必要です。", + "personalTokenRequired": "個人アクセストークンが必要です。", + "apiTokenRequired": "API トークンが必要です。", + "connectionFailed": "接続に失敗しました。", + "invalidSiteIdentity": "認証情報を含まない HTTP または HTTPS の Jira サイト URL を入力してください。", + "missingProjectIdentity": "Jira が ID またはキーのないプロジェクトを返しました。", + "invalidIssuePage": "Jira が無効な Issue ページを返しました。", + "incompleteIssuePage": "Jira が不完全な Issue ページを返しました。", + "repeatedIssueToken": "Jira が無効または重複した Issue ページトークンを返しました。", + "issueSearchLimit": "Jira の Issue 検索がページ数の上限を超えました。代わりに JQL でプロジェクトを選択してください。", + "invalidProjectPage": "Jira が無効なプロジェクトページを返しました。", + "incompleteProjectPage": "Jira が不完全なプロジェクトページを返しました。", + "projectListLimit": "Jira のプロジェクト一覧がページ数の上限を超えました。代わりに JQL でプロジェクトを選択してください。", + "invalidCloudId": "サイトが有効な Atlassian Cloud ID を返しませんでした。" + }, + "linear": { + "notConnected": "Linear に接続されていません", + "createFailed": "Linear での作成に失敗しました", + "createdButUnavailable": "Issue は作成されましたが、取得できませんでした", + "updateFailed": "Linear での更新に失敗しました", + "commentFailed": "コメントを作成できませんでした", + "projectCreateFailed": "Linear プロジェクトを作成できませんでした", + "noApiKey": "API キーが保存されていません。", + "workspaceAuthExpired": "このワークスペースの Linear 認証は期限切れです。", + "projectNameRequired": "プロジェクト名が必要です", + "projectIdRequired": "プロジェクト ID が必要です", + "projectNotFound": "プロジェクトが見つかりませんでした", + "viewIdRequired": "カスタムビュー ID が必要です", + "viewHasNoIssues": "カスタムビューに Issue が含まれていません", + "viewHasNoProjects": "カスタムビューにプロジェクトが含まれていません" + } + } + }, + "workspaceOptions": { + "activeFilterCount_one": "{{count}} 件のフィルター", + "activeFilterCount_other": "{{count}} 件のフィルター" + }, + "editorConflicts": { + "kind": { + "addedByUs": "こちらで追加", + "bothAdded": "双方で追加", + "deletedByUs": "こちらで削除", + "addedByThem": "相手側で追加", + "bothDeleted": "双方で削除", + "bothModified": "双方で変更", + "deletedByThem": "相手側で削除" + }, + "resolvedBanner": "ローカルで解決済みの競合 · {{kind}}", + "hint": { + "addedByUs": "追加されたファイルを保持するかどうか検討してください", + "bothModified": "競合マーカーがある箇所を修正してください", + "addedByThem": "保持する前に、追加されたファイルの内容を確認してください", + "bothDeleted": "編集する前に、Git で競合を解決するか、どちらか一方のファイルを復元してください", + "deletedByThem": "ファイルを保持するか、削除を受け入れるか判断してください", + "deletedByUs": "ファイルを復元するかどうか判断してください", + "bothAdded": "保持するバージョンを選択するか、統合してください" + }, + "renamedFrom": "{{path}} から名前を変更", + "snapshotCapturedAt": "{{time}} にスナップショットを取得しました。", + "unresolvedBanner": "未解決の競合 · {{kind}}" + }, + "stats": { + "usageBreakdown": { + "turns_one": "{{count}} ターン", + "events_one": "{{count}} イベント", + "sessions_one": "{{count}} セッション", + "events_other": "{{count}} イベント", + "sessions_other": "{{count}} セッション", + "turns_other": "{{count}} ターン" + } + }, + "github": { + "viewed": { + "markFile": "{{path}} を閲覧済みとしてマークする", + "unmarkFile": "{{path}} の閲覧済みのマークを外す" + } + }, + "wslMove": { + "entry": { + "hostRow": "このディストリビューションからプロジェクトを移動…", + "projectMenu": "{{distro}} ホストへ移動…" + }, + "blockers": { + "title": "これらのプロジェクトを移動する前に", + "inProjects": "{{names}} 内", + "skipOne": "{{name}} をこの移動から除外", + "skipMany": "これらの {{n}} 件のプロジェクトをこの移動から除外" + }, + "title": "プロジェクトを {{distro}} ホストへ移動", + "loading": "{{distro}} 内のプロジェクトを確認しています…", + "runningTitle": "{{distro}} ホストへ移動しています", + "preview": { + "counts": "プロジェクト: {{projects}} · ワークスペース: {{workspaces}} · ターミナル: {{terminals}} · チャット: {{chats}}", + "whatHappens": "ファイルは現在の場所に残ります。ターミナルは同じフォルダーで再起動し、出力、シェル履歴、Agent との会話は保持されます。", + "projects": "{{distro}} 内のプロジェクト", + "folderBadge": "フォルダー", + "notMoving": "移動しない", + "checking": "選択したプロジェクトを確認しています…", + "checkAgain": "再確認", + "moveOne": "1 件のプロジェクトを移動", + "moveMany": "{{n}} 件のプロジェクトを移動", + "heldByHost": "すでに {{distro}} ホスト上にあります。", + "changed": "以前に移動した後、古いバージョンの Orca によってここで変更されました。再び移動されることはありません。", + "chatsStay": "既存のチャットはこのコンピューターに残ります。このプロジェクトの新しいチャットは WSL ホストで開始されます。", + "browserLoginsConflict": "ホストのブラウザープロファイルがすでに使用中のため、ブラウザーのサインイン状態は引き継がれません。移動後、ホストのブラウザータブで再度サインインしてください。", + "browserLoginsNotCarried": "ブラウザーのサインイン状態はこのホストに引き継がれません。移動後、そのブラウザータブで再度サインインしてください。" + }, + "cancel": "キャンセル", + "progress": { + "bytes": "{{sent}} / {{total}}", + "tooLate": "ホストがすでに切り替え中のため、キャンセルできません。完了するまで Orca を開いたままにしてください。", + "switching": "切り替えはキャンセルできません。完了するまで Orca を開いたままにしてください。", + "readOnly": "移動中、これらのプロジェクトは読み取り専用です。切り替えが始まるまではキャンセルできます。", + "cancelUntilSwitch": "切り替えが始まるまではキャンセルできます。", + "closeKeepsGoing": "このダイアログを閉じても移動は止まりません。移動が終わると再び開きます。", + "cancelling": "キャンセルしています…", + "cancel": "移動をキャンセル" + }, + "result": { + "movedTitle": "{{distro}} ホストに移動しました", + "resetTitle": "何も移動されませんでした", + "waitingTitle": "{{distro}} ホストを待っています", + "earlierMoveTitle": "以前の移動が先に完了しました", + "refusedTitle": "プロジェクトは移動されませんでした", + "reloadCheckpointRefused": "Orca は未保存のファイルをバックアップできなかったため、ウィンドウを再読み込みしませんでした。このダイアログを閉じ、それらのファイルを保存するか閉じてから、表示されたままの通知で「今すぐ再読み込み」を使用してください。", + "reloadVetoed": "ウィンドウの再読み込みが妨げられました。このダイアログを閉じ、作業を保存してから、表示されたままの通知で「今すぐ再読み込み」を使用してください。", + "reloadFailed": "ウィンドウを再読み込みできませんでした。もう一度お試しください。", + "moved": "このウィンドウを再読み込みすると、プロジェクトが {{distro}} ホストの下に表示されます。Orca は再読み込みの前に未保存のファイルをバックアップします。", + "automationsPendingOne": "1 件のオートメーションがホスト上で一時的にオフになっています。Orca はホストに再びオンにするよう要求し続けます。", + "automationsPendingMany": "{{n}} 件のオートメーションがホスト上で一時的にオフになっています。Orca はホストに再びオンにするよう要求し続けます。", + "undoHint": "気が変わった場合は、再読み込み後、サイドバーにこれらのプロジェクトが「{{distro}} ホストに移動済み」と表示されます。そこで「このコンピューターで再び使用」を選ぶと、移動前の状態に戻せます。", + "reset": "移動は停止し、すべて元に戻されました。プロジェクトは以前と同じようにこのコンピューターで動作します。一時停止したターミナルは、開くと再び開始されます。", + "resetReason": "停止した理由: {{detail}}", + "waiting": "移動は {{distro}} ホストに届いた可能性がありますが、ホストが応答しません。応答するまで、これらのプロジェクトはここで読み取り専用のままです。設定でホストに接続してから、このダイアログを再び開いて移動を開始してください。Orca は先にこの移動を完了するか取り消します。", + "reloading": "再読み込みしています…", + "reload": "今すぐ再読み込み", + "close": "閉じる", + "review": "プロジェクトに戻る", + "browserLoginsHostUnknown": "Orca がホストのブラウザープロファイルを特定できなかったため、ブラウザーのログイン情報はコピーされませんでした。ホストのブラウザータブで再度サインインしてください。", + "browserLoginsConflict": "ホストのブラウザープロファイルがすでに使用中のため、ブラウザーのログイン情報はコピーされませんでした。ホストのブラウザータブで再度サインインしてください。", + "browserLoginsNotCopied": "ブラウザーのログイン情報はホストにコピーされませんでした。ホストのブラウザータブで再度サインインしてください。" + }, + "runtime": { + "label": "プロジェクトのランタイム", + "description": "このプロジェクトは、このコンピューターを経由して {{distro}} で実行されています。{{distro}} ホストに移動すると、そこで実行されます。", + "move": "プロジェクトを移動" + }, + "unfinished": { + "one": "{{distro}} ホストに移動した 1 件のオートメーションがまだオフです。Orca はホストに再びオンにするよう要求し続けます。", + "many": "{{distro}} ホストに移動した {{n}} 件のオートメーションがまだオフです。Orca はホストに再びオンにするよう要求し続けます。" + }, + "refusal": { + "previewFailed": "Orca はこれらのプロジェクトを確認できませんでした。もう一度お試しください。", + "startFailed": "Orca は移動の状況を把握できなくなりました。このダイアログを再び開いて、現在の状況を確認してください。", + "unavailable": "このウィンドウでは、プロジェクトを WSL ホストへ移動できません。", + "alreadyRunning": "{{distro}} への移動がすでに実行中です。完了するのを待ってから、もう一度お試しください。", + "alreadyInFlightPreview": "{{distro}} の移動がまだ完了処理中です。この移動を開始すると、Orca は可能な範囲で先にその移動を完了するか取り消します。", + "alreadyInFlight": "{{distro}} の移動がまだ完了処理中のため、この移動は開始されませんでした。{{distro}} ホストを接続したままにして、後でもう一度お試しください。", + "nothingNew": "これらのプロジェクトはすでに {{distro}} ホスト上にあります。", + "destinationChanged": "{{distro}} から以前に移動したプロジェクトは、別の WSL ホストに移動しています。さらに移動するには、そのホストに接続してください。", + "hostUnavailable": "{{distro}} ホストが接続されていません。設定で接続してから、もう一度お試しください。", + "hostUpdateRequired": "{{distro}} ホストでは古いバージョンの Orca が実行されています。設定で更新してから、もう一度お試しください。", + "terminalsBlocked": "これらのプロジェクト内の一部のターミナル、Agent、またはオートメーションが使用中です。何も移動されませんでした。", + "exportIncomplete": "これらのプロジェクトの一部の保存済み状態はまだ移動できないため、何も移動されませんでした:", + "exportIncompletePreview": "これらのプロジェクトの一部の保存済み状態はまだ移動できません:", + "tooLarge": "これらのプロジェクトは保存済み状態が多すぎて、一度に移動できません。一度に移動するプロジェクトを減らしてください。", + "pauseFailed": "Orca はこれらのプロジェクトのターミナルを一時停止できなかったため、何も移動されませんでした。一時停止したターミナルは、開くと再び開始されます。もう一度お試しください。", + "scopeChanged": "移動の準備中にプロジェクトが変更されたため、何も移動されませんでした。プロジェクトを確認して、もう一度お試しください。", + "cancelled": "移動をキャンセルしました。何も移動されませんでした。", + "finishedEarlierMove": "Orca は先に {{distro}} への以前の移動を完了しました。ウィンドウを再読み込みしてから、この移動をもう一度開始してください。" + }, + "step": { + "preparing": "準備中", + "pausingTerminals": "ターミナルを一時停止中", + "copying": "コピー中", + "switching": "切り替え中", + "finishing": "完了処理中", + "done": "完了" + }, + "blocker": { + "agentWorkingOne": "Agent が作業中か、回答を待っています", + "agentWorkingMany": "{{n}} 個の Agent が作業中か、回答を待っています", + "processRunningOne": "ターミナルでプログラムが実行中です", + "processRunningMany": "{{n}} 個のターミナルでプログラムが実行中です", + "agentNotResumableOne": "移動後に再開できない Agent があります", + "agentNotResumableMany": "移動後に再開できない Agent が {{n}} 個あります", + "unverifiableOne": "Orca は現在ターミナルを確認できません", + "unverifiableMany": "Orca は現在 {{n}} 個のターミナルを確認できません", + "automationRunningOne": "オートメーションの実行が進行中です", + "automationRunningMany": "{{n}} 件のオートメーションの実行が進行中です", + "dispatchRunningOne": "Agent のタスクが進行中です", + "dispatchRunningMany": "{{n}} 件の Agent のタスクが進行中です", + "scrollbackTooLargeOne": "出力履歴が多すぎて移動できないターミナルがあります", + "scrollbackTooLargeMany": "{{n}} 個のターミナルの出力履歴が多すぎて移動できません" + }, + "blockerHint": { + "agentWorking": "完了するのを待つか、ターミナルで停止してから、再確認してください。", + "processRunning": "プログラム(開発サーバーやエディターなど)を停止してから、再確認してください。", + "agentNotResumable": "ターミナルで Agent を終了してから、再確認してください。", + "unverifiable": "少し待ってから、再確認してください。移動のために何かが停止されることはありません。", + "wait": "完了するのを待ってから、再確認してください。", + "scrollbackTooLarge": "それらのターミナルの出力をクリアしてから、再確認してください。" + }, + "scopeRefused": { + "windowsDrive": "フォルダーが Windows ドライブ上にあるため、このコンピューターに残ります。", + "mixedLocations": "一部のフォルダーがこのディストリビューションの外にあるため、このコンピューターに残ります。", + "notLocal": "すでに別のホストで実行されています。", + "other": "移動できません。" + }, + "reloadToast": { + "title": "再読み込みして移動を完了" + }, + "orchestrator": { + "showTerminal": "ターミナルを表示", + "moveAgain": "再度移動", + "checkAgain": "再確認", + "deferred": "{{distro}} ホストへの移動を完了しようとしています。一部のターミナルがまだ使用中です。", + "stuck": "{{distro}} ホストへの以前の移動がまだ完了していません。", + "declined": "これらのプロジェクトをこのコンピューターに戻したため、移動は一時停止しています。", + "doneToast": "プロジェクトを {{distro}} ホストに移動しました", + "terminalGone": "そのターミナルはこのウィンドウで開かれていません。再確認して更新してください。", + "blocker": "{{title}}。{{hint}}", + "paused": "{{distro}} ホストへのプロジェクトの移動は一時停止しています: {{reason}}。", + "pausedReason": { + "exportIncomplete": "一部の保存済み状態をまだ引き継げません", + "manifestTooLarge": "保存済み状態が 1 回の移動で運べる量を超えています", + "hostUpdate": "先にホストを更新する必要があります", + "attemptsExhausted": "何度か試しても完了しませんでした" + }, + "finishPending": "{{distro}} ホストへの以前の移動はホスト側で完了しています。Orca は再起動時、または「再確認」ですぐに、ここでの処理を完了します。" + } } } diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 8f182971557f..ac6a15e6ddce 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -110,11 +110,15 @@ "system": "시스템", "english": "English", "chinese": "中文(简体)", + "chineseTraditional": "繁體中文(台灣)", "korean": "한국어", "japanese": "日本語", "spanish": "Español", "french": "Français", - "portuguese": "Português (Brasil)" + "portuguese": "Português (Brasil)", + "russian": "Русский", + "turkish": "Türkçe", + "german": "Deutsch" }, "statusBar": { "claudeToggleDescription": "활성 워크스페이스에 대한 Claude 토큰 및 비용 사용량을 표시합니다.", @@ -346,7 +350,8 @@ "permissionOverrideMore": "외 {{count}}개", "permissionOverrideMore_one": "외 {{count}}개", "permissionOverrideMore_other": "외 {{count}}개", - "permissionOverridesUse": "{{mode}} 사용" + "permissionOverridesUse": "{{mode}} 사용", + "approveForMe": "대신 승인" }, "followSymlinkedDirectoriesKeywords": { "symlink": "심볼릭 링크", @@ -377,6 +382,34 @@ "actionPermissions": { "sameAsAgent": "{{agent}}와(과) 동일" } + }, + "ssh": { + "status": { + "disconnected": "연결 끊김", + "connecting": "연결 중…", + "auth-failed": "인증 실패", + "connected": "연결됨", + "reconnection-failed": "재연결 실패", + "deploying-relay": "릴레이 배포 중…", + "reconnecting": "다시 연결 중…" + } + }, + "mcp": { + "workspace": "워크스페이스", + "inspectFailed": "{{directory}}을(를) 검사할 수 없습니다.", + "unreadable": "읽을 수 없음", + "notFound": "찾을 수 없음", + "invalidJson": "잘못된 JSON", + "noServers": "서버 없음", + "httpServer": "HTTP 서버", + "stdioServer": "stdio 서버", + "invalidServer": "잘못된 서버", + "serverCount_one": "서버 {{count}}개", + "serverCount_other": "서버 {{count}}개", + "claudeWorkspace": "Claude 워크스페이스" + }, + "shortcuts": { + "parseFailed": "단축키를 해석할 수 없습니다." } }, "menu": { @@ -1465,9 +1498,6 @@ "3fdf777817": "GitHub에서 열기", "c43fe79ee0": "GitHub 링크 복사", "0caac1a18f": "PR에서 워크스페이스 시작", - "8223320f8d": "업데이트됨", - "10ef1afb8e": "· 업데이트됨", - "55962099bc": "이 이슈를 열었습니다", "0ab4664a8b": "이슈에서 워크스페이스 시작", "36182aa57f": "새 워크스페이스 시작", "fe6ff12dc2": "추가 이슈 워크스페이스 작업", @@ -1540,8 +1570,6 @@ "52b20b56f7": "설명", "4d555d3796": "설명 수정", "9df4e74bdf": "저장", - "0ae387d8ca": "작성자", - "228e2f59d3": "해결됨", "a154ec5224": "GitHub에서 댓글 열기", "bca8eb39ac": "댓글에 답장하기", "68cb993d61": "해결됨", @@ -1557,13 +1585,11 @@ "d43736d09c": "코드 컨텍스트 컨트롤", "bd7be7b1fd": "댓글 L", "db61d76cd5": "코드 컨텍스트 로드 중…", - "f2d02cdf8c": "본 파일", "1257d1435d": "파일 트리 표시", "a341343303": "리뷰 댓글이 추가되었습니다.", "d1fa2cf888": "PR 헤드 SHA가 없으면 댓글을 달 수 없습니다.", "829674460a": "PR commit SHA가 누락되어 diff를 사용할 수 없습니다.", "af924014f8": "봤음", - "2d89a38d9d": "{{value0}} {{value1}}을(를) 본 것으로 표시", "70e84e3d0b": "일치하는 리뷰어가 없습니다.", "1ffce94a8b": "다른 사람들", "c2b21818e1": "제안", @@ -1598,8 +1624,6 @@ "ec5c4b3ab2": "PR 다시 열기", "21860b58d0": "PR 닫기", "5932578f51": "병합하려면 등록된 로컬 repo가 필요합니다.", - "e2bf3e41a9": "댓글", - "28d0d3374f": "스레드", "080d071d48": "@{{value0}}에 답장", "86f809e2ce": "이 리뷰 스레드에 답변하기", "136542c9ba": ":L{{value0}}", @@ -1629,7 +1653,9 @@ "from": "from", "to": "to", "activity": "활동", - "noActivity": "아직 활동이 없습니다." + "noActivity": "아직 활동이 없습니다.", + "pullRequestReference": "PR #{{number}}", + "issueReference": "이슈 #{{number}}" }, "checkActionRequiredHint": "머지 차단을 해제하려면 GitHub에서 수동 작업(예: 실행 승인)이 필요합니다.", "e15a8b77ef": "이 검사에는 인라인 세부정보가 없습니다.", @@ -1643,8 +1669,13 @@ "09d67a0f9b": "PR을 닫지 못했습니다.", "88809e79db": "PR을 다시 열지 못했습니다.", "00f55cc17b": "이 PR에는 저장소 액세스를 사용할 수 없습니다.", - "reactionCountSingular": "{{reaction}} 반응 {{count}}개", - "reactionCountPlural": "{{reaction}} 반응 {{count}}개" + "reactionCount_other": "{{reaction}} 반응 {{count}}개", + "filesViewed_other": "파일 {{viewed}} / {{count}}개 확인", + "updatedRelativeTime": "{{time}} 업데이트됨", + "authorOpenedThisIssue": " 님이 이 이슈를 열었습니다", + "middotUpdatedRelativeTime": "· {{time}} 업데이트됨", + "resolvedThreadBy": "{{author}} 님의 해결된 스레드", + "resolvedCommentBy": "{{author}} 님의 해결된 댓글" }, "GitLabItemDialog": { "65e784c1f1": "다시 열기", @@ -1700,14 +1731,13 @@ "f23ea85341": "해결됨", "6de8ce0cc6": "{{value0}} 필요", "22511537d2": "승인됨", - "00f3bab87b": " / 총 {{value0}}개 필요", "3a051b8ade": "작업 항목", "32f8bef818": "로그 출력이 없습니다.", "4168eb2c51": "해결", "commentTooLarge": "댓글이 너무 길어 안전하게 제출할 수 없습니다.", "gitlabActionFailed": "GitLab 작업이 실패했습니다.", - "approvalsRemainingSingular": "승인 {{count}}개 남음", - "approvalsRemainingPlural": "승인 {{count}}개 남음" + "approvalsRemainingOfRequired_other": "필요한 승인 {{required}}개 중 {{count}}개 남음", + "approvalsRemaining_other": "승인 {{count}}개 남음" }, "JiraIssueWorkspace": { "b0b92666c9": "댓글", @@ -1732,14 +1762,11 @@ "69da9a208c": "Jira에서 열기", "fa132c8aed": "댓글을 추가하지 못했습니다.", "ea21952aa3": "Jira 이슈를 업데이트하지 못했습니다.", - "6c41a9bcea": "{{value0}}을(를) 복사하지 못했습니다.", - "2ff69a3545": "{{value0}} 복사됨", "666cfdd835": "알 수 없음", "ef21405c6d": "Jira 이슈", "commentTooLarge": "댓글이 너무 길어 안전하게 제출할 수 없습니다." }, "Landing": { - "76a95f7f47": "생성", "f9eaa9e12d": "프로젝트 추가", "6ca6ff404e": "Orca", "520304a067": "Orca 로고", @@ -1755,7 +1782,12 @@ "0d0ace8861": "GitHub에서 별표 주기", "ec43b38ba7": "GitHub에 별표 표시됨", "157bb5ecbb": "GitHub 열기", - "preflightDismiss": "닫기" + "preflightDismiss": "닫기", + "moveUpWorkspace": "이전 워크스페이스 선택", + "moveDownWorkspace": "다음 워크스페이스 선택", + "installGit": "Git 설치", + "installGitHubCli": "GitHub CLI 설치", + "learnMore": "자세히 알아보기" }, "LinearIssueMarkdownDescriptionEditor": { "d9c47069ef": "Markdown", @@ -1780,14 +1812,12 @@ "LinearIssueTextEditor": { "947ba2d6f4": "저장", "04d73b72dc": "이슈 제목", - "e8ff595db3": "{{value0}}을(를) 업데이트하지 못했습니다.", "1e08a1ec80": "제목은 필수 항목입니다." }, "LinearIssueWorkspace": { "ad5dec37b7": "선택한 이슈를 미리보기하고, 편집하고, 작업을 시작하세요.", "c23e79e5c0": "작업", "b0eac92d85": "다시 시도", - "fabbd3f974": "이슈를 업데이트했습니다 ·", "543970c87a": "활동", "df4c86ed12": "닫기", "7a4997d8bb": "Linear 이슈 미리보기 닫기", @@ -1811,11 +1841,8 @@ "b25e453c9d": "하위 이슈를 생성하지 못했습니다.", "aeed19d003": "{{value0}}을(를) 생성했습니다.", "9a1317cdd3": "하위 이슈를 로드하지 못했습니다.", - "9bcbaa2737": "{{value0}}을(를) 복사하지 못했습니다.", - "7835483c43": "{{value0}} 복사됨", "61f424f8ca": "Linear 이슈", "ca8778c124": "알 수 없음", - "8a33c85e9c": "누군가", "65239a714b": "Linear", "76ffd3c937": "추가할 프로젝트를 검색하세요.", "c11b4e3cc2": "프로젝트를 찾을 수 없습니다.", @@ -1826,7 +1853,10 @@ "moreWorkspaceActions": "이슈 워크스페이스 작업 더 보기", "startNewWorkspace": "새 워크스페이스 시작", "workspaceSection": "워크스페이스", - "noWorkspaceYet": "아직 없음" + "noWorkspaceYet": "아직 없음", + "issueDescriptionLabel": "이슈 설명", + "namedUserUpdatedIssue": "{{name}}님이 이슈를 업데이트함 · {{time}}", + "someoneUpdatedIssue": "누군가 이슈를 업데이트함 · {{time}}" }, "LinearItemDrawer": { "04008e6c46": "이슈에서 워크스페이스 시작", @@ -1862,7 +1892,9 @@ "openAttachedWorkspace": "이슈에 연결된 워크스페이스 열기", "openWorkspace": "워크스페이스 열기", "moreWorkspaceActions": "이슈 워크스페이스 작업 더 보기", - "startNewWorkspace": "새 워크스페이스 시작" + "startNewWorkspace": "새 워크스페이스 시작", + "setEstimate": "추정치 설정", + "estimateValue": "추정치 {{estimate}}" }, "NewWorkspaceComposerCard": { "cbb47ee0dc": "로컬 Git 프로젝트에만 사용할 수 있습니다.", @@ -1924,7 +1956,22 @@ "defaultBranchUpdateFailed": "프로젝트 기본 브랜치를 업데이트할 수 없습니다. 다시 시도해 보세요.", "setLocation": "프로젝트 위치 설정", "setLocationOnHost": "{{host}}에 프로젝트 위치 설정", - "setLocationTooltip": "폴더를 선택하거나 이 프로젝트를 {{host}}에 복제하세요." + "setLocationTooltip": "폴더를 선택하거나 이 프로젝트를 {{host}}에 복제하세요.", + "connect": "연결", + "reconnect": "다시 연결", + "setupConfigDefaultTabs": "기본 탭 명령", + "setupConfigSetupAndDefaultTabs": "설정 및 기본 탭 명령", + "setupConfigSetupScript": "설정 스크립트", + "runDefaultTabCommands": "기본 탭 명령 실행", + "runSetupAndDefaultTabCommands": "설정 및 기본 탭 명령 실행", + "runSetupCommand": "설정 명령 실행", + "askRunDefaultTabCommands": "지금 기본 탭 명령을 실행할까요?", + "askRunSetupAndDefaultTabCommands": "지금 설정 및 기본 탭 명령을 실행할까요?", + "askRunSetup": "지금 설정을 실행할까요?", + "runSetupNow": "지금 설정 실행", + "runCommandsNow": "지금 명령 실행", + "skipForNow": "지금은 건너뛰기", + "skipCommands": "명령 건너뛰기" }, "NewWorkspaceComposerModal": { "createWorktree": "작업 트리 만들기", @@ -2014,9 +2061,6 @@ "778683ec84": "설명", "da9aaa8bcf": "설명 수정", "4a337ac05f": "저장", - "169a93b29a": "업데이트됨", - "3c891789f6": "작성자", - "f4fe47c2bb": "해결됨", "0ac19bb52e": "GitHub에서 댓글 열기", "d6c6679de7": "댓글에 답장하기", "76b2a0ac5b": "해결됨", @@ -2024,7 +2068,6 @@ "6885c619e7": "repos 경로가 없으면 답글을 달 수 없습니다.", "d94810f652": "설명을 업데이트하지 못했습니다.", "9b4190dc98": "설명이 업데이트되었습니다.", - "89e80af1c7": "본 파일", "319cf2d54b": "파일 트리 표시", "eff839f438": "리뷰 댓글이 추가되었습니다.", "d8c3ba91c4": "PR 헤드 SHA가 없으면 댓글을 달 수 없습니다.", @@ -2062,8 +2105,6 @@ "9d5425918e": "PR 다시 열기", "96d013ed28": "PR 닫기", "eca289e593": "병합하려면 등록된 로컬 repo가 필요합니다.", - "e01e34f5fa": "댓글", - "345b68254c": "스레드", "31a7b202f2": "@{{value0}}에 답장", "408e634fbb": "이 리뷰 스레드에 답변하기", "34b9f7c264": ":L{{value0}}", @@ -2089,7 +2130,18 @@ "diffLoadTimedOut": "이 diff를 불러오는 데 시간이 초과되었습니다.", "6b1d5ee3e4": "이 검사에는 인라인 세부정보가 없습니다.", "e04c027d98": "검사 세부정보를 로드하지 못했습니다.", - "5df7c41d2a": "다시 시도" + "5df7c41d2a": "다시 시도", + "filesViewed_other": "파일 {{viewed}} / {{count}}개 확인", + "updatedRelativeTime": "{{time}} 업데이트됨", + "resolvedThreadBy": "{{author}} 님의 해결된 스레드", + "resolvedCommentBy": "{{author}} 님의 해결된 댓글", + "mentionSource": { + "prAuthor": "PR 작성자", + "issueAuthor": "이슈 작성자", + "commenter": "댓글 작성자", + "participant": "참여자", + "teamMember": "팀원" + } }, "QuickOpen": { "1dbd3f59ff": "이동", @@ -2103,13 +2155,11 @@ "9e97f08d0f": "열 파일 검색", "ec31e058f7": "파일로 이동", "73b44e7bde": "설치 명령 복사", - "1cf8561ab4": "빠르고 gitignore를 인식하는 목록을 활성화하려면 원격 호스트에서 다음을 수행하세요:", - "5d80dc39bb": "ripgrep", - "2ca749c15d": "설치", - "4725b0e931": "Quick Open 스캔이 너무 큼(", - "b227d88520": "{{value0}} 파일을 찾았습니다.", "995be8ea22": "복사", - "cf144856dc": "복사됨" + "cf144856dc": "복사됨", + "filesFound_other": "파일 {{count}}개 찾음", + "hostCouldNotOpenPath": "호스트에서 이 파일 경로를 열 수 없습니다.", + "chooseFileNotDirectory": "디렉터리 대신 파일을 선택하세요." }, "SelectedTextCopyMenu": { "9b40d7b018": "복사" @@ -2127,7 +2177,6 @@ "TaskPage": { "ff69a30681": "취소", "8ff6fdc368": "만드는 중…", - "fc0d8a1fa4": "제출.", "919a20dd5b": "{{value0}}을(를) 입력하세요", "56cdb413a2": "쉼표로 구분된 값", "1f0fce91e3": "{{value0}}을(를) 선택하세요", @@ -2175,14 +2224,9 @@ "bdebffcbfe": "선택한 팀에 대한 Linear 프로젝트를 만듭니다.", "1361275ec3": "새로운 Linear 프로젝트", "7f3f7b4c18": "설명(선택사항, markdown)", - "9f2b4c03a6": "등록 위치: ", "d3d0998b7d": "새 GitHub 이슈", - "d1e243795c": "이슈", - "be8cf68d9f": "이슈 보기", - "67662ade50": "프로젝트 이슈", "6244a02f46": "Linear에서 열기", "606a85c774": "열기", - "5e8061b088": "{{value0}} {{value1}}에서 워크스페이스 시작", "592a55611b": "더 많은 팀을 선택하거나 새로고침해 보세요. 팀 필터는 현재 가져온 이슈 세트에 적용됩니다.", "618107fab3": "선택한 팀과 일치하는 가져온 이슈가 없습니다", "903c7af49f": "Linear 이슈를 찾을 수 없습니다.", @@ -2191,7 +2235,6 @@ "f362667d55": "업데이트됨", "b1eaa18ace": "이슈", "37e7ee311e": "키", - "b7bae28b6a": "표시됨", "a26a48252e": "표시 속성", "5d2d835467": "정렬 순서", "5659da12fc": "그룹화", @@ -2199,11 +2242,9 @@ "af377b13b1": "{{value0}} 보기", "d47248df4d": "Linear 보기 모드", "f397d513e3": "뒤로", - "b39fe6511d": "프로젝트", "8675cd6188": "Linear", "733b8f2421": "Linear / 보기", "bc06ed0fb0": "보기로 돌아가기", - "3cb855080f": "보기", "b4e10f096e": "소유자", "a04fe7ba73": "공개 범위", "0aa8525950": "모델", @@ -2233,8 +2274,6 @@ "054bf695cc": "초안", "5b6b2af943": "재시도 중…", "0c0de0fc0e": "다음에서 이슈를 로드할 수 없습니다.", - "d1766fd62d": "프로젝트를 로드하지 못했습니다.", - "7762f4b03a": "/", "443f7dd928": "병합", "a7396b05c6": "체크", "f6fa3c97d0": "리뷰어", @@ -2416,10 +2455,36 @@ "jiraColumnOriginalEstimate": "예상", "jiraColumnRemainingEstimate": "남음", "jiraBoardEmptyColumn": "이슈 없음", - "labelCountPlural": "라벨 {{count}}개", - "labelCountSingular": "라벨 {{count}}개", - "memberCountPlural": "멤버 {{count}}명", - "memberCountSingular": "멤버 {{count}}명" + "backToPullRequests": "PR", + "backToGitHubList": "GitHub 목록", + "noGitHubRepositoryContext": "이 이슈에 사용할 GitHub 저장소 컨텍스트가 없습니다.", + "filingInTarget": "{{target}}에 생성", + "filingInThisRepository": "이 저장소에 생성", + "shortcutToSubmit": "{{shortcut}} 키로 제출하세요.", + "projectsFailedToLoad_other": "프로젝트 {{count}}개 중 {{failed}}개를 불러오지 못했습니다", + "draftPullRequestNumber": "초안 PR #{{number}}", + "pullRequestNumber": "PR #{{number}}", + "issueNumber": "이슈 #{{number}}", + "loadGitHubWorkFailed": "GitHub 작업을 불러오지 못했습니다.", + "gitlabViewIssues": "이슈", + "gitlabViewMrs": "MR", + "gitlabViewTodos": "내 할 일", + "startWorkspaceFromMr": "MR {{number}}에서 워크스페이스 시작", + "startWorkspaceFromIssue": "이슈 {{number}}에서 워크스페이스 시작", + "shownCount_other": "{{count}}개 표시됨", + "linearProjectPlaceholder": "프로젝트", + "labelCount_other": "라벨 {{count}}개", + "memberCount_other": "멤버 {{count}}명", + "groupUnassigned": "할당되지 않음", + "linearProjectContext": "프로젝트: {{name}}", + "linearViewContext": "보기: {{name}}", + "changedFileCount_other": "파일 {{count}}개", + "resumeRestoration": { + "linearProjectNotFound": "저장된 Linear 프로젝트를 찾을 수 없습니다.", + "linearProjectRestoreFailed": "저장된 Linear 프로젝트를 복원하지 못했습니다.", + "linearViewNotFound": "저장된 Linear 보기를 찾을 수 없습니다.", + "linearViewRestoreFailed": "저장된 Linear 보기를 복원하지 못했습니다." + } }, "Terminal": { "73768427cf": "닫기", @@ -2494,7 +2559,8 @@ "b1e390250d": "로컬 빌드 전환을 완료할 수 없었습니다.", "d29740d175": "선택한 빌드를 사용할 수 없었습니다.", "37d45c9ec1": "다른 빌드 선택", - "7f1a4c9e02": "시스템 패키지 관리자가 Orca를 설치했으므로 거기에서 업데이트하십시오. Orca는 이 릴리스 자체를 설치할 수 없습니다." + "7f1a4c9e02": "시스템 패키지 관리자가 Orca를 설치했으므로 거기에서 업데이트하십시오. Orca는 이 릴리스 자체를 설치할 수 없습니다.", + "compatibilityModeFailed": "호환 모드를 활성화할 수 없습니다. {{message}}" }, "WorktreeJumpPalette": { "ac037cfac2": "이동", @@ -2520,8 +2586,6 @@ "d7d496a451": "브라우저 페이지가 더 이상 존재하지 않습니다.", "50a1d11d5b": "열린 탭", "088d66d980": "작업 및 설정", - "20af998bff": "{{value0}} 사용 가능한 항목{{value1}}", - "bb72c08e63": "{{value0}} 결과를 찾았습니다{{value1}}", "34c8fbb46e": "SSH 원격", "63c2be1914": "SSH 연결이 끊어졌습니다.", "95be6587d3": "워크트리 \"{{value0}}\" 만들기", @@ -2538,7 +2602,10 @@ "27f10cca63": "채팅, 터미널, 워크스페이스, 작업, 설정 및 동작 검색...", "2770f02910": "채팅, 터미널, 워크스페이스, 작업, 설정 및 동작 검색", "recentChatsTerminalsHeader": "최근 채팅 및 터미널", - "lastActiveTime": "마지막 활동: {{value0}} 전" + "lastActiveTime": "마지막 활동: {{value0}} 전", + "resultsFound_other": "결과 {{count}}개를 찾았습니다.", + "itemsAvailable_other": "항목 {{count}}개를 사용할 수 있습니다.", + "createActionAvailable": "워크트리 생성 작업을 사용할 수 있습니다." }, "github": { "pr": { @@ -2579,7 +2646,8 @@ "8f6cb3772f": "요구 사항이 충족되면 이 PR을 자동으로 병합합니다", "def355ff38": "병합 가능", "e42c5bae67": "GitHub에서는 이 PR을 병합할 수 있으며 체크를 통과했다고 합니다", - "cbf0113af6": "GitHub에서는 이 PR을 병합할 수 있다고 합니다" + "cbf0113af6": "GitHub에서는 이 PR을 병합할 수 있다고 합니다", + "autoMergeOn": "자동 병합 켜짐" } } }, @@ -2753,10 +2821,10 @@ "imageUrlTooLarge": "이미지 URL이 너무 큽니다." }, "IssueSourceSelector": { - "d6aeb2012b": "다음에서 이슈 표시", "787c970baf": "이슈 소스", "51d1608920": "origin", - "30b2c9df91": "업스트림" + "30b2c9df91": "업스트림", + "showingIssuesFromRepo": "의 이슈 표시 중" }, "PRFilterDropdowns": { "979be3cf6b": "담당자", @@ -2766,12 +2834,18 @@ "01f3f3d161": "작성자", "13b3ac0a84": "상태", "79c54552f7": "필터", - "8a2ffbf9b3": "{{value0}} 필터 제거" + "8a2ffbf9b3": "{{value0}} 필터 제거", + "anyState": "상관없음", + "currentUser": "현재 사용자" }, "PRFilterPickers": { - "fdf387297c": "지우기 (", "472c12ae03": "지우기", - "2d1f58eda6": "사용" + "pressEnterToUseValue": "입력한 값을 사용하려면 Enter를 누르세요.", + "useTypedValue": " 사용", + "clearSelected": "지우기 ({{count}})", + "loading": "로드 중…", + "searchTextTooLarge": "검색 텍스트가 너무 큽니다.", + "noMatches": "일치하는 항목 없음" }, "PRFilterSections": { "a00830d3f7": "사용자 없음", @@ -2781,7 +2855,6 @@ "458ea3602b": "작성자 없음", "b69fa4fa20": "뒤로", "30ebb6ca44": "모든 필터 지우기", - "8177eda37e": "필터", "ea3416d646": "담당자", "b1d9fdea08": "라벨", "24754c44ad": "작성자", @@ -2793,7 +2866,14 @@ "2b2f019091": "모든 상태", "0fd3249e2e": "닫힘", "d78b60b5c2": "열림", - "bd162b7d5a": "병합됨" + "bd162b7d5a": "병합됨", + "draft": "초안", + "labelCount_other": "라벨 {{count}}개", + "allStates": "모두", + "filterPullRequests": "PR 필터링", + "filterIssues": "이슈 필터링", + "filterOrTypeLogin": "필터링하거나 로그인 이름 입력...", + "filterLabels": "라벨 필터링..." }, "github": { "rate": { @@ -2804,15 +2884,14 @@ "d12d3d6f33": "GitHub API 예산 새로 고침", "d5e5de9070": "Orca는 GitHub CLI를 통해 REST, 검색 및 GraphQL을 사용합니다.", "58c5f88216": "GitHub API 예산", - "6da1858354": "남음 · 재설정까지", - "f42790d150": "/", "01f7323e58": "GraphQL API", "1daf0f22a9": "GraphQL", "1f2f28a4de": "검색 API", "c377a4f06a": "검색", "c392c749a6": "REST API", "bb227706a6": "REST", - "budget_scope_prefix": "예산 범위" + "budget_scope_prefix": "예산 범위", + "remainingOfLimitResetsIn": "{{limit}}개 중 {{remaining}}개 남음 · 재설정까지 {{reset}}" } } } @@ -2820,7 +2899,29 @@ "CommentReactions": { "addReaction": "반응 추가", "removeNamedReaction": "{{value0}} 반응 제거", - "addNamedReaction": "{{value0}} 반응 추가" + "addNamedReaction": "{{value0}} 반응 추가", + "reaction": { + "thumbsUp": "좋아요", + "thumbsDown": "싫어요", + "laugh": "웃음", + "confused": "혼란", + "heart": "하트", + "hooray": "만세", + "rocket": "로켓", + "eyes": "눈" + } + }, + "CommentCodeContext": { + "showSurroundingCodeBlock": "주변 코드 블록 표시", + "showNearbyCodeContext": "인접 코드 컨텍스트 표시" + }, + "prCheckPresentation": { + "successful": "성공", + "inProgress": "진행 중" + }, + "IssueSourceIndicator": { + "issueFromRepo": "의 이슈", + "issuesFromRepo": "의 이슈" } }, "linear": { @@ -2840,11 +2941,6 @@ } } }, - "priority": { - "icon": { - "c43d3e065b": "우선순위:" - } - }, "project": { "view": { "surfaces": { @@ -2863,7 +2959,6 @@ "c8db98b73b": "리소스", "bb1405eff8": "마일스톤", "5d99315fb8": "계획", - "3ad562bdf4": "범위 내 이슈", "563501f191": "진행률", "bb5664d456": "프로젝트 설명이 없습니다.", "7b147907dc": "Linear", @@ -2874,8 +2969,6 @@ "7616c986c6": "열린 이슈 {{value0}}개", "openInLinear": "Linear에서 {{value0}} 열기", "93e1f6bfca": "로드 중", - "98730088a6": ". 전체 세트를 보려면 Linear를 검색하거나 엽니다.", - "06b887d622": "처음 표시", "linearLoginUnreadable": "저장된 Linear 로그인을 읽을 수 없습니다. 설정에서 다시 연결하세요.", "f2cc1e0ff6": "Linear / 프로젝트", "906b5e4cb8": "Linear / 프로젝트 / {{value0}}", @@ -2890,7 +2983,9 @@ "df4bd63c1d": "할당되지 않음", "30402d2c6e": "검색하거나 새로고침해 보세요.", "a2f31c4cd6": "Linear 프로젝트를 찾을 수 없습니다.", - "c9b6e9f90d": "Linear 프로젝트를 로드할 수 없습니다." + "c9b6e9f90d": "Linear 프로젝트를 로드할 수 없습니다.", + "scopedIssueCount_other": "선택 범위의 이슈 {{count}}개", + "backlog": "백로그" } } }, @@ -2903,7 +2998,13 @@ "05baa5ae90": "워크스페이스", "89f6580dbf": "팀 검색...", "b3488fad3c": "가져온 팀이 없습니다. 액세스는 키 범위, 비공개 팀 멤버십, 보관된 팀, 권한 또는 가져오기 실패에 따라 달라질 수 있습니다.", - "405b33c378": "가져온 팀이 검색어와 일치하지 않습니다." + "405b33c378": "가져온 팀이 검색어와 일치하지 않습니다.", + "teamCount_other": "팀 {{count}}개" + } + }, + "priority": { + "icon": { + "priorityValue": "우선순위: {{label}}" } } }, @@ -4398,10 +4499,7 @@ }, "UsageBreakdownSection": { "7765a4c3e1": "n/a", - "247c93ca92": "• 추정 가격", - "32176e1d44": "회전", - "79a69522a5": "이벤트", - "02a046792e": "세션 •" + "247c93ca92": "• 추정 가격" }, "GrokUsagePane": { "g8h9i0j1k2": "Grok 사용량", @@ -5909,7 +6007,8 @@ }, "sidebarHostOptions": { "3e102f111c": "모든 호스트", - "visibleHostsCount": "호스트 {{value0}}개" + "hosts": "호스트", + "visibleHosts_other": "호스트 {{count}}개" }, "HostRemoveDialog": { "1a2b3c4d5e": "{{value0}} 제거됨", @@ -5924,12 +6023,10 @@ "oneWorkspace": "워크스페이스 1개", "manyWorkspaces": "워크스페이스 {{count}}개", "hostHasWorkspacesDefault": "이 컴퓨터에서 {{value0}}과(와) 해당 자격 증명을 제거합니다. {{value1}}은(는) Orca에 남아 있습니다 — 원격 파일은 변경되지 않습니다.", - "alsoDeleteRemote": "{{value1}}에서 이러한 {{value0}}도 삭제", "alsoForgetLocal": "Orca에서 이러한 {{value0}}도 제거", "advanced": "고급", - "alsoDeleteRemoteHint": "원격 Git 워크트리와 해당 브랜치를 영구적으로 삭제합니다. 이 작업은 되돌릴 수 없습니다.", "alsoForgetLocalHint": "Orca에서만 제거합니다. 원격 파일, 워크트리, 브랜치는 그대로 남아 있습니다.", - "wslHostEndsTerminals": "Orca에서 {{value0}}을(를) 제거하고, 열려 있는 터미널을 종료하며, 해당 배포판에서 Orca 서버를 중지합니다. 배포판의 파일은 변경되지 않습니다." + "wslHostEndsTerminalsUnlessShared": "Orca에서 {{value0}}을(를) 제거합니다. 이 컴퓨터에서 열려 있는 다른 Orca가 사용 중이지 않다면 열린 터미널도 종료하고 해당 배포판의 Orca 서버를 중지합니다. 배포판의 파일은 변경되지 않습니다." }, "HostRenameDialog": { "1a2b3c4d5e": "호스트 이름 바꾸기", @@ -6083,14 +6180,9 @@ "sshImportSyncedSingular": "호스트 {{count}}개를 Orca에 추가했습니다." }, "ForgetSshWorkspaceDialog": { - "reconnectFailed": "재연결 실패", - "forgetBody": "이 작업 공간을 Orca에서만 제거합니다. 파일, Git 워크트리, {{host}}의 브랜치는 그대로 유지됩니다.", - "title": "Delete “{{name}}”?", - "disconnectedBody": "이 워크스페이스의 SSH 호스트가 연결되어 있지 않습니다. 재연결하여 원격에서도 삭제하거나 Orca에서만 제거하세요.", "ghostBody": "{{host}}은(는) 더 이상 저장된 SSH 호스트가 아니므로 이 워크스페이스는 라이브 호스트에 연결되어 있지 않습니다. Orca에서 제거만 할 수 있으며, 원격의 파일과 브랜치는 그대로 유지됩니다.", "cancel": "취소", - "forget": "Orca에서 제거", - "reconnectAndDelete": "재연결 후 삭제" + "forget": "Orca에서 제거" }, "MarkdownImageLightbox": { "image": "Image", @@ -6204,7 +6296,7 @@ "running": "실행 중", "stopped": "중지됨", "title": "WSL 배포판 추가", - "description": "Orca는 배포판 안에서 서버를 실행하므로 git, 파일, 터미널이 Linux에서 네이티브로 실행됩니다. 새 프로젝트에 사용하세요. \\\\wsl.localhost를 통해 연 프로젝트는 그대로 계속 작동합니다.", + "description": "Orca는 배포판 안에서 서버를 실행하므로 git, 파일, 터미널이 Linux에서 네이티브로 실행됩니다. 이 배포판에서 \\\\wsl.localhost를 통해 연 프로젝트는 터미널이 유휴 상태가 되면 자동으로 이 호스트로 옮겨지며, Windows 드라이브(/mnt/…)에 있는 프로젝트는 이 컴퓨터에 남습니다. 옮겨진 프로젝트는 사이드바에서 다시 가져올 수 있습니다.", "distro": "배포판", "loading": "WSL 배포판 찾는 중…", "placeholder": "배포판 선택", @@ -6231,6 +6323,7 @@ "removalPending": "제거가 완료되지 않음" }, "wslHostRemoval": { + "keptForOthers": "이 Orca에서 제거했습니다. 호스트는 {{value0}}을(를) 위해 계속 실행됩니다.", "partial": "호스트는 제거되었지만 배포판에서 아직 실행 중인 항목이 있습니다: {{value0}}", "pending": "Orca가 아직 호스트를 제거하지 않았습니다: {{value0}} 다시 시도하려면 다시 제거하고, 유지하려면 연결하세요." }, @@ -6293,7 +6386,11 @@ "e8f25bd903": "터미널 정리를 완료할 수 없습니다.", "a702d4196e": "이 작업은 모든 워크스페이스의 모든 터미널 탭을 닫고 현재 터미널 세션의 종료를 요청합니다. 저장되지 않은 터미널 작업은 손실됩니다. 데몬 자체는 계속 실행되며 새 터미널은 즉시 열 수 있습니다. 이 작업은 되돌릴 수 없습니다.", "01d6b7c64e": "열린 터미널과 에이전트가 다시 시작됩니다. 원격 호스트의 터미널은 영향을 받지 않습니다.", - "922548bc66": "터미널 서비스를 다시 시작하시겠습니까?" + "922548bc66": "터미널 서비스를 다시 시작하시겠습니까?", + "confirmRestart": "다시 시작", + "busyRestarting": "다시 시작 중…", + "confirmKillAll": "모든 세션 종료", + "busyKilling": "종료 중…" }, "MacFolderAccessFixDialog": { "stepAllow": "파일 및 폴더에서 Orca 허용", @@ -7900,7 +7997,9 @@ "builtin_themes": "기본 제공", "imported_from": "{{value0}}에서 가져옴", "imported_themes": "가져옴", - "search_terminal_themes": "터미널 테마 검색" + "search_terminal_themes": "터미널 테마 검색", + "plugin_themes": "플러그인", + "from_plugin": "{{value0}}에서" }, "SettingsSidebar": { "e0900f83e7": "SSH", @@ -8186,7 +8285,6 @@ "a016ffbeed": "자동은 현재 Windows PowerShell을 사용하고, PowerShell 7+가 설치되면 전환합니다.", "5ed5c95344": "새 터미널 패널을 위해 Windows PowerShell과 PowerShell 7+ 중에서 선택하세요.", "3d88af864d": "PowerShell 셸 옵션이 새 터미널 패널에 대해 Windows PowerShell을 시작할지 아니면 PowerShell 7+를 시작할지 선택합니다.", - "8a956cc91e": "두 번 클릭 선택 시 단어 경계로 처리되는 문자입니다.", "4bebcc2b2c": "단어 구분 기호", "12e06178fa": "행", "907b0b9d3e": "사용자 지정", @@ -10939,7 +11037,7 @@ "mixedTitle": "접근 및 내용 검토", "instructionalTitle": "플러그인 내용 검토", "subtitle": "{{value0}} v{{value1}} · {{value2}}", - "reconsent": "마지막으로 이 플러그인을 검토한 이후로 권한, 워커 신뢰 등급 또는 지시 내용이 변경되었습니다. 실행하기 전에 다시 검토하세요.", + "reconsent": "승인한 후 이 플러그인이 변경되었습니다. 다시 실행하려면 검토하세요.", "capabilities": "이 플러그인은 다음을 수행할 수 있습니다", "warning": "이러한 권한은 플러그인이 Orca API를 사용하는 방식을 제한합니다. 워커는 여전히 컴퓨터에서 일반 프로세스로 실행되며 파일, 네트워크 및 기타 프로세스에 대한 전체 액세스 권한을 보유합니다.", "instructionalWarning": "이 플러그인에는 워커 프로세스가 없습니다. 지시 내용은 사용자나 에이전트가 사용할 때 여전히 작업을 발생시킬 수 있습니다. 활성화하기 전에 아래 지침과 명령을 검토하세요.", @@ -11728,7 +11826,8 @@ "migration": "완료되지 않음: 이 서버로의 이동이 끝나지 않았습니다. 먼저 재개하세요.", "deferred": "아직 완료되지 않음: 서버가 아직 준비되지 않았습니다. 나중에 다시 시도하세요.", "failed": "Orca가 서버에서 이 작업을 완료하지 못했습니다. 다시 시도하세요.", - "defaultServer": "완료되지 않음: 이 서버는 새 프로젝트의 기본 호스트입니다. 중지하기 전에 '새 프로젝트를 여는 위치'에서 다른 서버를 선택하세요." + "defaultServer": "완료되지 않음: 이 서버는 새 프로젝트의 기본 호스트입니다. 중지하기 전에 '새 프로젝트를 여는 위치'에서 다른 서버를 선택하세요.", + "wslMoveRunning": "완료되지 않음: 프로젝트를 이 서버로 옮기는 중입니다. 이동이 끝나면 Orca가 업데이트합니다." }, "reassurance": "각 호스트에서 실행되며 사용자 본인의 SSH 연결로 접속합니다. 코드와 파일은 지금 있는 곳에 그대로 있습니다. 호스트로 옮겨지는 것은 Orca의 프로젝트, 탭, 터미널 목록뿐입니다." }, @@ -12066,6 +12165,9 @@ "searchPlaceholder": "빌드 검색…", "searchLabel": "빌드 검색" }, + "AppearanceThemeControl": { + "useTerminalTheme": "이 테마의 터미널 색상 사용" + }, "notification": { "settings": { "copy": { @@ -12113,14 +12215,13 @@ "right": { "sidebar": { "BulkActionBar": { - "79a9f5f712": "언스테이지(", - "ef5f5bd06e": "스테이지에 올리기 (", - "60ed678138": "선택됨" + "selectedCount_other": "{{count}}개 선택됨", + "stageCount": "스테이지에 올리기 ({{count}})", + "unstageCount": "언스테이지 ({{count}})" }, "ChecksPanel": { "2ef90c9819": "실패한 검사에 대한 AI agent를 시작했습니다.", "a0181a8d76": "충돌에 대한 AI agent를 시작했습니다.", - "34464d00b9": "업데이트됨", "058039787c": "취소", "2ab7fd4b6d": "저장", "dda5924a40": "체크를 보려면 Git 브랜치와 호스팅 리뷰 컨텍스트가 필요합니다.", @@ -12166,7 +12267,8 @@ "430f1a62d4": "선택한 스레드를 호스트에서 해결하지 못했습니다.", "updateReactionFailed": "반응을 업데이트하지 못했습니다.", "gitlabMoreActions": "더 많은 MR 작업", - "gitlabLinkAnother": "다른 MR 연결" + "gitlabLinkAnother": "다른 MR 연결", + "reviewUpdatedAt": "{{review}} {{time}} 업데이트됨" }, "CreateHostedReviewComposer": { "741ff8a0d2": "푸시 및 생성 {{value0}}" @@ -12323,7 +12425,14 @@ "740aca88ab": "워크스페이스 포트 스캔에 실패했습니다.", "5be4f7f727": "포트 {{value0}} 메뉴", "1004af16ab": "{{value0}} 복사", - "153d3a8026": "워크스페이스 호스트를 알 수 없음" + "153d3a8026": "워크스페이스 호스트를 알 수 없음", + "unknownProcess": "알 수 없는 프로세스", + "containerOrForwardedService": "컨테이너 또는 포워딩된 서비스", + "unassigned": "할당되지 않음", + "remotePortOutOfRange": "원격 포트는 1–65535 범위여야 합니다", + "localPortOutOfRange": "로컬 포트는 1–65535 범위여야 합니다", + "localPortInUse": "포트 {{port}}은(는) 이미 사용 중입니다. 다른 로컬 포트를 선택하세요.", + "localPortRequiresPrivileges": "포트 {{port}}에는 관리자 권한이 필요합니다. 로컬 포트 ≥ 1024를 사용하세요." }, "Search": { "1abfb25a66": "파일에서 검색하려면 입력하세요.", @@ -12380,7 +12489,6 @@ "476b77745b": "기본 참조 변경", "ed34038d0d": "브랜치 비교 새로 고침", "493f963029": "기본 참조 변경", - "3278b2767b": "앞섬", "11b5dd8e41": "비교 대상", "a9bf7c171a": "Commit 실패", "011f9713fc": "Commit이 차단되었습니다.", @@ -12425,7 +12533,6 @@ "574d2f4413": "메모 지우기", "05bb8f4a48": "취소", "48db37cca9": "모두 보기", - "78ce2d37ac": "포크로 푸시", "c05fe04839": "{{value0}}의 포크로 푸시됩니다(origin 아님).", "c35baf2f1e": "파일 필터링…", "2fe2a67580": "더 많은 메모 작업", @@ -12433,14 +12540,12 @@ "cc474e0b8c": "메모", "e131cd7128": "소스 제어는 Git 리포지토리에서만 사용할 수 있습니다.", "c07b236287": "변경사항을 보려면 워크스페이스를 선택하세요.", - "dc5a6465fc": "{{value0}}(예: {{value1}}{{value2}})", "a5e5a11090": "모든 변경 사항 취소 실패 — 취소 전에 파일의 스테이징을 해제하지 못했습니다.", "8a5ba6a988": "commit 차이점을 로드하지 못했습니다.", "fe5bd1a610": "{{value0}} 생성 중...", "812cb992ee": "{{value0}}에서 열기", "eef5446523": "{{value0}} #{{value1}}은(는) 이미 열려 있습니다.", "0453ca3a9a": "{{value0}}이(가) 생성되었지만 Orca가 아직 새로 고칠 수 없습니다.", - "f99560ab29": "중단 {{value0}} 실패", "eae7a1da5f": "메모를 지우지 못했습니다.", "df5040e3c3": "언스테이지", "8cde1a2fb0": "스테이지", @@ -12468,8 +12573,6 @@ "aaf1451654": "초안 {{value0}} 만들기", "26511c22b4": "만드는 중...", "d7ae61269b": "브랜치에 Commit 됨", - "branchFilesChangedVsBaseOne": "{{ref}} 대비 파일 1개 변경됨", - "branchFilesChangedVsBaseOther": "{{ref}} 대비 파일 {{count}}개 변경됨", "48a003c1b1": "스테이징된 변경 사항", "d4ef4bafc5": "변경 사항", "9339382454": "모두 언스테이징", @@ -12479,7 +12582,6 @@ "72f2bea3f4": "메모 펼치기", "d13edef890": "메모 접기", "d6fb1df5fe": "{{value0}}이(가) 이미 열려 있습니다", - "05838cfdeb": "{{value0}} 충돌", "0b5b8c234c": "{{value0}} ({{value1}}) 열기", "d97ef8f221": "{{value0}}-{{value1}}줄", "6f8bfa0eb9": "{{value0}}줄", @@ -12492,7 +12594,6 @@ "5b176fa431": "양쪽에서 삭제됨", "31f6d46278": "미해결", "2c417432b7": "로컬에서 해결됨", - "d206117f90": "{{value0}} 충돌 ({{value1}})", "f3a8b2c1d0e5": "{{value0}} 제목을 입력하세요.", "e2b7a1c0d9f4": "{{value0}} 생성에 실패했습니다", "hugeRepoIgnorePrompt": "이 repos에 활성 변경 사항이 너무 많습니다. \"{{value0}}\"을(를) .gitignore에 추가하시겠습니까?", @@ -12533,10 +12634,6 @@ "b3c8f1a902": "파일 이름으로 필터링", "d4f8c2a901": "필터 지우고 닫기", "e8a1c4b203": "vs", - "compareBaseCommitsAheadOne": "{{ref}}보다 커밋 1개 앞서 있음", - "compareBaseCommitsAheadOther": "{{ref}}보다 커밋 {{count}}개 앞서 있음", - "compareBaseCommitsBehindOne": "{{ref}}보다 커밋 1개 뒤처짐", - "compareBaseCommitsBehindOther": "{{ref}}보다 커밋 {{count}}개 뒤처짐", "4b4a7de138": "브라우저에서 검토 페이지 열기", "createPrIntentCommitBlockedSummary": "커밋이 차단됨: {{value0}} 이슈를 수정한 후 PR 만들기를 다시 시도하세요.", "pushRecovery": { @@ -12567,17 +12664,41 @@ "diffCommentNotesCopyFailed": "메모를 복사하지 못했습니다.", "conflictCount_one": "충돌 {{count}}개", "conflictCount_other": "충돌 {{count}}개", - "discardFailedSingular": "파일 {{count}}개의 변경 사항을 버리지 못했습니다.", - "discardFailedPlural": "파일 {{count}}개의 변경 사항을 버리지 못했습니다.", - "noteCountSingular": "메모 {{count}}개", - "noteCountPlural": "메모 {{count}}개" + "discardFailedSampleMore_other": "{{paths}}, +{{count}}개 더", + "discardFailed_other": "파일 {{count}}개의 변경 사항을 버리지 못했습니다", + "discardFailedWithSample": "{{error}} (예: {{paths}})", + "compareBaseCommitsAhead_other": "{{ref}}보다 커밋 {{count}}개 앞서 있음", + "compareBaseCommitsBehind_other": "{{ref}}보다 커밋 {{count}}개 뒤처짐", + "branchFilesChangedVsBase_other": "{{ref}} 대비 파일 {{count}}개 변경됨", + "noteCount_other": "메모 {{count}}개", + "comparingAgainstRef": "{{ref}}와 비교 중", + "commitsAheadShort_other": "{{count}}개 앞섬", + "unresolvedConflictOfKind": "해결되지 않은 충돌 ({{kind}})", + "unresolvedConflict": "해결되지 않은 충돌", + "locallyResolvedConflictOfKind": "로컬에서 해결된 충돌 ({{kind}})", + "locallyResolvedConflict": "로컬에서 해결된 충돌", + "pushesToForkTarget": "포크 {{target}}에 푸시", + "abortRebaseConfirmTitle": "리베이스를 중단할까요?", + "abortMergeConfirmTitle": "병합을 중단할까요?", + "abortRebaseConfirmDescription": "진행 중인 리베이스를 취소하며, 이번 리베이스에서 수행한 충돌 해결 작업이 삭제될 수 있습니다.", + "abortMergeConfirmDescription": "진행 중인 병합을 취소하며, 이번 병합에서 수행한 충돌 해결 작업이 삭제될 수 있습니다.", + "abortRebaseFailedFallback": "리베이스를 중단하지 못했습니다", + "abortMergeFailedFallback": "병합을 중단하지 못했습니다", + "abortRebaseFailed": "리베이스 중단 실패", + "abortMergeFailed": "병합 중단 실패", + "clearNotesFromWorkspace_other": "이 워크스페이스에서 메모 {{count}}개를 지울까요?", + "clearNotesFromFile_other": "{{path}}에서 메모 {{count}}개를 지울까요?" }, "SourceControlAgentActionDialog": { "8e856842d1": "선택한 agent를 시작할 수 없습니다.", "c075d00de1": "워크스페이스 연결을 확인할 수 없습니다.", "808cfe0a3b": "이 repos", "994cddd1f7": "저장하지 않음", - "38b899cc02": "모든 리포지토리" + "38b899cc02": "모든 리포지토리", + "agentNotEnabledOrDetected": "{{agent}}: 이 워크스페이스 호스트에서 활성화되지 않았거나 감지되지 않았습니다.", + "workspaceConnectionUnresolved": "워크스페이스 연결을 확인할 수 없습니다.", + "noEnabledAgentsDetected": "이 워크스페이스 호스트에서 활성화된 에이전트가 감지되지 않았습니다.", + "startAgent": "에이전트 시작" }, "SourceControlAgentActionDialogForm": { "7ec6abbf2a": "재설정", @@ -12642,9 +12763,6 @@ "cbcc4ab3db": "처음 100개 검사 표시", "0dca6bfab5": "검사 세부 정보 열기", "991f50c7e4": "아직 보고된 체크가 없습니다.", - "9ad98f2a17": "보류 중", - "5e52f4ef7f": "실패", - "02ca4f9074": "통과", "e15a8b77ef": "이 검사에는 인라인 세부정보가 없습니다.", "679bf2093c": "로그 테일 복사", "d713f500b2": "로그 테일(마지막 200줄)", @@ -12661,7 +12779,6 @@ "1f2b980522": "검사 세부 정보 로드 중…", "0c96cd25e5": "해결", "3a71a6ed0b": "체크와 병합을 완료하려면 먼저 충돌을 해결하세요.", - "60186d8498": "충돌로 인해 차단됨", "c16762ac8c": "아래 체크와 댓글은 현재 가져온 컨텍스트를 보여줍니다.", "9d0e7bcefc": "차단 PR 조치 없음", "5856874b59": "Orca는 이 패널이 열려 있는 동안 검사를 새로 고칩니다.", @@ -12686,7 +12803,6 @@ "084c516efb": "Copy commands", "5dc3af25c0": "댓글 선택", "d7a2f9c401": "해결되지 않은 댓글 {{value0}}개 보내기", - "d91f2a6c39": "대기 중인 댓글 {{value0}}개를 AI로 보내기", "a6de3e5a20": "대기 중인 댓글 지우기", "f8a2c91d04": "에이전트 대기열에 추가", "b4e8a1c902": "Queued", @@ -12701,7 +12817,6 @@ "b3195cba33": "작성자의 봇 지정 해제", "f588b46a6c": "작성자를 봇으로 지정", "e45324fbed": "체크 세부 정보를 불러오지 못했습니다.", - "checksUnresolvedChip": "해결되지 않은", "checksUnresolvedStripHint": "이러한 검사는 통과 또는 실패 판정 없이 완료되었습니다.", "dcb3c546fe": "다시 시도", "commitsBehind_one": "커밋 {{count}}개 뒤처짐", @@ -12712,7 +12827,23 @@ "pendingChecks_one": "대기 중인 검사 {{count}}개", "pendingChecks_other": "대기 중인 검사 {{count}}개", "unresolvedChecks_one": "미해결 검사 {{count}}개", - "unresolvedChecks_other": "미해결 검사 {{count}}개" + "unresolvedChecks_other": "미해결 검사 {{count}}개", + "passingCount_other": "{{count}}개 통과", + "failingCount_other": "{{count}}개 실패", + "pendingCount_other": "{{count}}개 대기 중", + "unresolvedCount_other": "{{count}}개 미해결", + "sendQueuedCommentsToAi_other": "대기 중인 댓글 {{count}}개를 AI로 보내기", + "conflictsBlockThisMr": "충돌로 인해 이 MR이 차단됨", + "conflictsBlockThisPr": "충돌로 인해 이 PR이 차단됨", + "copyComment": "댓글 복사", + "sendComment": "보내기", + "commentingRequiresGitHubPrTarget": "댓글을 작성하려면 GitHub PR의 대상 저장소가 필요합니다.", + "selectWorkspaceBeforeAiAction": "AI 작업을 실행하기 전에 워크스페이스를 선택하세요.", + "operation": { + "rebase": "리베이스", + "merge": "병합", + "cherryPick": "체리픽" + } }, "empty": { "state": { @@ -12954,10 +13085,10 @@ "dialog": { "3bc61dc989": "취소", "15efa778e3": "버리기", - "42f89dd030": "파일", - "e7611dca35": "파일", "0d2d88cba5": "이 작업은 취소할 수 없습니다.", - "1551c14668": "변경사항을 삭제하시겠습니까?" + "1551c14668": "변경사항을 삭제하시겠습니까?", + "fileCount_one": "파일 {{count}}개", + "fileCount_other": "파일 {{count}}개" } }, "dropdown": { @@ -13119,8 +13250,7 @@ }, "compare": { "summary": { - "commitsAheadSingular": "{{ref}}보다 커밋 {{count}}개 앞서 있음", - "commitsAheadPlural": "{{ref}}보다 커밋 {{count}}개 앞서 있음" + "commitsAhead_other": "{{ref}}보다 커밋 {{count}}개 앞서 있음" } }, "conflict": { @@ -13184,24 +13314,28 @@ "unresolved": "이 워크스페이스를 소유한 호스트를 확인할 수 없습니다. 연결을 확인한 후 다시 시도하세요." }, "useFileDeletion": { - "72691dfebc": "{{value0}} '{{value1}}'에 실패했습니다.", "d979a4fbb5": "'{{value0}}'을(를) 영구적으로 삭제하시겠습니까?", "92276aceb7": "삭제", "7fb9435c86": "원격 호스트의 디렉터리와 그 안의 내용을 영구적으로 삭제합니다. 이 작업은 되돌릴 수 없습니다.", "23e98f192f": "원격 호스트의 파일을 영구적으로 삭제합니다. 이 작업은 되돌릴 수 없습니다.", "8b8ee9d22f": "이 파일을 소유한 호스트를 확인할 수 없습니다. 워크스페이스 연결을 확인한 후 다시 시도하세요.", - "af1270b90d": "{{count}}개 항목을 영구적으로 삭제하시겠습니까?", "dd029aa5cd": "원격 호스트의 선택한 항목과 디렉터리 내용을 영구적으로 삭제합니다. 이 작업은 되돌릴 수 없습니다.", - "77fdc36183": "{{count}}개 항목을 삭제하시겠습니까?", - "fca915a67a": "원격 항목은 영구적으로 삭제되며 되돌릴 수 없습니다. 로컬 항목은 {{value0}}(으)로 이동합니다." + "deleteFailed": "'{{name}}'을(를) 삭제하지 못했습니다.", + "deleteItems_other": "항목 {{count}}개를 삭제하시겠습니까?", + "mixedRecycleBin": "원격 항목은 영구적으로 삭제되며 되돌릴 수 없습니다. 로컬 항목은 휴지통으로 이동합니다.", + "mixedTrash": "원격 항목은 영구적으로 삭제되며 되돌릴 수 없습니다. 로컬 항목은 휴지통으로 이동합니다.", + "permanentlyDeleteItems_other": "항목 {{count}}개를 영구적으로 삭제하시겠습니까?", + "recycleBinFailed": "'{{name}}'을(를) 휴지통으로 이동하지 못했습니다.", + "trashFailed": "'{{name}}'을(를) 휴지통으로 이동하지 못했습니다." }, "useFileExplorerHandlers": { "32cd9fd991": "심볼릭 링크 대상을 열 수 없습니다", "folderLinksOutsideProject": "이 폴더는 프로젝트 외부로 연결되어 있어 여기에서 열 수 없습니다." }, "useFileExplorerImport": { - "25919b2050": "{{value0}} {{value1}}을(를) 건너뛰었습니다.", - "132fd0e1e9": "{{value0}} {{value1}}을(를) 가져오지 못했습니다." + "importFailedCount_other": "파일 {{count}}개를 가져오지 못했습니다.", + "importSkippedCount_other": "파일 {{count}}개를 건너뛰었습니다.", + "importFailed": "파일을 가져오지 못했습니다." }, "useFileExplorerKeys": { "8adb953095": "작업 실패" @@ -13238,7 +13372,6 @@ "refreshSessionHistory": "세션 기록 새로고침", "searchSessions": "세션 검색", "clearSearch": "검색 지우기", - "transcriptsSkipped": "대화 기록 {{count}}개 건너뜀", "noAgentSessionsFound": "agent 세션을 찾을 수 없습니다", "noSessionsMatchFilters": "현재 필터와 일치하는 세션이 없습니다", "noAgentsSelected": "선택된 에이전트가 없습니다", @@ -13258,7 +13391,8 @@ "resumeInChatFailed": "새 채팅에서 이 세션을 재개할 수 없습니다.", "resumeInNewCliUnavailable": "이 세션은 CLI에서 열 수 없습니다.", "resumeInNewCliHostTooOld": "이 채팅을 새 CLI에서 재개하려면 채팅을 실행하는 호스트의 Orca를 업데이트하세요.", - "folderWorkspaceUnavailable": "폴더 워크스페이스는 더 이상 사용할 수 없습니다." + "folderWorkspaceUnavailable": "폴더 워크스페이스는 더 이상 사용할 수 없습니다.", + "transcriptsSkippedCount_other": "대화 기록 {{count}}개 건너뜀" }, "AiVaultPanelControls": { "scanningSessions": "세션 스캔 중", @@ -13304,11 +13438,8 @@ "sessionRole": "세션", "worktree": "작업 트리", "conversationNotSaved": "대화가 저장되지 않음", - "recoverableEmptyDetail": "이 세션에는 저장된 대화가 없지만 복구 가능한 항목이 {{value0}}개 남아 있습니다.", "recoverableEmptyOpenLogHint": "로그를 열어 복구하세요.", "emptyConversationDetail": "이 세션에는 저장된 대화가 없어 재개할 수 없습니다.", - "queuedMessages": "대기 중인 메시지 {{value0}}개", - "subagentTranscripts": "서브에이전트 대화 기록 {{value0}}개", "prompt": "프롬프트", "firstPrompt": "첫 프롬프트", "recentPrompt": "최근 프롬프트", @@ -13322,7 +13453,10 @@ "noFirstPromptAvailable": "첫 프롬프트를 사용할 수 없습니다", "loadingFirstPrompt": "첫 프롬프트를 불러오는 중…", "folder": "폴더", - "resumeInFolder": "폴더에서 재개" + "resumeInFolder": "폴더에서 재개", + "recoverableEmptyDetailCount_other": "이 세션에는 저장된 대화가 없지만 복구 가능한 항목이 {{count}}개 남아 있습니다.", + "queuedMessageCount_other": "대기 중인 메시지 {{count}}개", + "subagentTranscriptCount_other": "서브에이전트 대화 기록 {{count}}개" }, "AiVaultSessionRow": { "resumeInNewTab": "새 탭에서 재개", @@ -13456,26 +13590,21 @@ "confirmation": { "84f6f5b9eb": "포함됨: {{numbers}}.", "541984b2eb": "#{{pr}}을(를) 통해 대기열에 등록하시겠습니까?", - "4809f55cdb": "{{included}}GitHub는 병합 대기열에 {{count}} PR을 함께 추가합니다. 대기열은 병합 방법을 선택하고 이를 별도의 그룹으로 병합할 수 있습니다.", - "be8f2621be": "{{included}}GitHub는 병합 대기열에 {{count}} PR을 함께 추가합니다. 대기열은 병합 방법을 선택하고 이를 별도의 그룹으로 병합할 수 있습니다.", - "92ca033e72": "대기열 {{count}} PR", - "478a527b15": "대기열 {{count}} PR", "1feef35ca4": "#{{pr}}을(를) 통해 병합하시겠습니까?", - "c3e036c99f": "{{included}}GitHub는 {{method}}를 사용하여 {{count}} PR을 원자적으로 병합합니다. 병합할 수 없으면 아무것도 병합되지 않습니다.", - "369aba4b32": "{{included}}GitHub는 {{method}}를 사용하여 {{count}} PR을 원자적으로 병합합니다. 병합할 수 없는 경우에는 병합할 수 없습니다.", - "493c78f521": "{{count}} PR 병합", - "eb7051d268": "{{count}} PR 병합" + "queueDescription_other": "{{included}}GitHub는 PR {{count}}개를 병합 대기열에 함께 추가합니다. 대기열은 병합 방법을 선택하며 여러 그룹으로 나누어 병합할 수 있습니다.", + "queueConfirm_other": "PR {{count}}개를 대기열에 추가", + "mergeDescription_other": "{{included}}GitHub는 {{method}}를 사용하여 PR {{count}}개를 원자적으로 병합합니다. 하나라도 병합할 수 없으면 아무것도 병합되지 않습니다.", + "mergeConfirm_other": "PR {{count}}개 병합" }, "merge": { - "55ae29b907": "#{{pr}} · {{count}} PR을 통해 병합", - "b8446f6ec2": "#{{pr}} · {{count}} PR을 통해 병합", "189d0ec614": "#{{pr}}은 아직 초안입니다.", "640fb50d9c": "#{{pr}}이(가) 닫혔습니다.", "46ffcbda75": "#{{pr}}에 병합 충돌이 있습니다.", "6dabefd63e": "#{{pr}}님이 변경 사항을 요청했습니다.", "2bb21fc326": "#{{pr}}에는 아직 검토 승인이 필요합니다.", "c23faf74df": "#{{pr}}을(를) 업데이트해야 합니다.", - "f561e80968": "#{{pr}}이(가) 차단되었습니다." + "f561e80968": "#{{pr}}이(가) 차단되었습니다.", + "mergeThroughLabel_other": "#{{pr}}까지 포함하여 병합 · PR {{count}}개" } } } @@ -13532,14 +13661,14 @@ "sourceActionsUnavailable": "스크립트 소스를 사용할 수 없습니다." }, "AiVaultScanProgressStrip": { - "agentChecked": "{{agent}}: 기록 후보 {{total}}개 중 {{settled}}개 확인됨", "fileCount_one": "파일 {{value0}}개", "fileCount_other": "파일 {{value0}}개", "databaseCount_one": "데이터베이스 {{value0}}개", "databaseCount_other": "데이터베이스 {{value0}}개", "scanning": "{{value0}} 스캔 중", "checking": "{{value0}} 확인 중", - "scanned": "{{value0}} 스캔함" + "scanned": "{{value0}} 스캔함", + "agentCheckedCount_other": "{{agent}}: 기록 후보 {{total}}개 중 {{settled}}개 확인됨" }, "run": { "source": { @@ -13568,6 +13697,14 @@ } } } + }, + "fileExplorerMultiDrag": { + "moreItems_other": "+{{count}}개 더" + }, + "CreatePullRequest": { + "createInProgress": "PR 생성 중...", + "workspaceHostUnresolved": "워크스페이스 호스트를 확인할 수 없습니다. 워크스페이스를 새로 고친 후 다시 시도하세요.", + "branchDiscoveryFailed": "브랜치를 감지하지 못했습니다." } } }, @@ -14092,11 +14229,11 @@ "a2f68645ac": "GitLab API 예산 새로 고침", "2f9c16d6c3": "Orca는 GitLab CLI를 통해 REST를 사용합니다.", "14e144f7a7": "GitLab API 예산", - "3e2c982cfa": "남음, 재설정까지", - "ea8ad0bae8": "/", "0a891e8935": "REST API", "953f7c6062": "이 GitLab 호스트는 속도 제한 헤더를 반환하지 않았습니다.", - "budget_scope_prefix": "예산 범위" + "budget_scope_prefix": "예산 범위", + "resetUnknown": "알 수 없음", + "remainingOfLimit": "{{limit}}개 중 {{remaining}}개 남음, {{reset}} 후 초기화" } } } @@ -14168,13 +14305,13 @@ "9ee54037a4": "사용자 지정 명령", "4b2fc4b80c": "사고 강도", "be8917699e": "모델", - "4d9b6d84df": "지원되지 않습니다. Claude, Codex 또는 Custom을 선택하세요.", "560d4feb00": "사용자 정의", "29d119fe95": "에이전트", "f9382b48a1": "AI author 활성화", "1c0cb4fabb": "AI 작성자", "bd14e9c42a": "구성되지 않음", - "1f9468c5c9": "{{value0}} 지원되지 않음" + "1f9468c5c9": "{{value0}} 지원되지 않음", + "unsupportedAgent": "{{agent}}은(는) 지원되지 않습니다. Claude, Codex 또는 사용자 정의를 선택하세요." }, "BrowserAnimatedVisual": { "46df009982": "무료 평가판을 시작하세요", @@ -14715,17 +14852,14 @@ "ConflictComponents": { "f338288514": "충돌 콘텐츠 로드 중...", "90d576adb2": "새로고침", - "a1ce36f77d": "스냅샷 캡처 시간:", "c8ca989aea": "파일 트리 표시", "58ad5ad431": "닫기", "28e7db4a90": "소스 제어", "31931dec46": "이 리뷰 스냅샷에는 더 이상 실시간으로 해결되지 않은 충돌이 없습니다.", "992145ff5a": "모든 충돌이 해결되었습니다.", - "d5edd81755": "다음에서 이름 변경됨", "6e459867ad": "세션-로컬 연속성 상태. Git은 더 이상 이 파일을 병합되지 않은 것으로 보고하지 않습니다.", "9c2901ef8a": "다음 충돌", "41d9af2e7a": "이전 충돌", - "55d61a0ccd": "충돌 ·", "da539359b6": "이 충돌에 대해 편집할 수 있는 작업 트리 파일이 없습니다.", "unresolvedConflicts_one": "미해결 충돌 {{count}}개", "unresolvedConflicts_other": "미해결 충돌 {{count}}개" @@ -15421,7 +15555,9 @@ "6978871a3d": "열기", "cce596969e": "메모 삭제", "cad3384faa": "메모 수정", - "508ee678a5": "브라우저에서 열기" + "508ee678a5": "브라우저에서 열기", + "noteAuthorFallback": "메모", + "sentMeta": "전송됨" }, "DiffCommentPopover": { "2b3ce6d394": "취소", @@ -15434,6 +15570,9 @@ }, "useDiffCommentDecorator": { "995fa28b50": "이 메모" + }, + "diffCommentZoneCard": { + "noteAlreadySent": "이미 보낸 메모" } } }, @@ -16028,7 +16167,18 @@ "b09b2384fd": "일시중지됨", "eaa02014f8": "활성화됨", "29baf8f4c2": "소스", - "lastRunFailed": "마지막 실행이 실패했습니다." + "lastRunFailed": "마지막 실행이 실패했습니다.", + "noGrace": "유예 없음", + "graceMinutes_other": "{{count}}분", + "graceHours_other": "{{count}}시간", + "usageCoverageRuns_other": "실행 {{known}}/{{count}}회", + "usageUnavailable": "사용할 수 없음", + "noRuns": "실행 없음", + "projectDefault": "프로젝트 기본값", + "reuseLiveSession": "활성 세션 재사용", + "freshEachRun": "실행마다 새로 시작", + "precheckEnabled": "활성화됨, {{timeout}}", + "precheckNone": "없음" }, "AutomationEditorDialog": { "fb1896a5e7": "취소", @@ -16129,11 +16279,8 @@ "2faecab10b": "지금 실행", "13118faadf": "알 수 없는 프로젝트", "73f630b49d": "취소", - "1b586f0e2b": "~에", - "02a33e3204": "~에서", "9adfab2596": "외부 자동화 삭제", "1e2e41392f": "다시 묻지 마세요", - "b264564427": "및 실행 기록. 이전 실행으로 생성된 워크스페이스는 삭제되지 않습니다.", "080dcb5fbb": "자동화 삭제", "19a6e30eae": "자동화 새로 고침", "77c2778945": "자동화", @@ -16168,7 +16315,6 @@ "pendingAutomationRunMissing": "실행 기록을 더 이상 사용할 수 없습니다.", "paused": "일시 중지됨", "missingWorkspace": "워크스페이스 없음", - "runUsageSummary": "약 {{cost}} · {{tokens}} tokens", "usageUnavailable": "사용량을 사용할 수 없음", "noRunUsageYet": "아직 실행 사용량 없음", "noWorkspace": "워크스페이스 없음", @@ -16183,7 +16329,10 @@ "rowActions": "자동화 작업", "tableLastRun": "마지막 실행", "ownerChanged": "이 자동화로 인해 호스트가 변경되었습니다. 새로고침하고 다시 시도하세요.", - "runError": "오류:" + "runError": "오류:", + "deleteAutomationDescription": " 및 실행 기록을 삭제합니다. 이전 실행에서 생성된 워크스페이스는 삭제되지 않습니다.", + "deleteExternalAutomationDescription": "의 에서 을(를) 삭제합니다.", + "runUsageSummaryTokens_other": "예상 {{cost}} · {{tokens}} 토큰" }, "CreateFromPicker": { "f061f49e3f": "repo 브랜치 검색...", @@ -16210,8 +16359,7 @@ "92405f1431": "사용 불가", "dbdcec22bd": "읽기 전용", "0a2d4359a8": "관리 가능", - "e2532150ed": "자동화", - "701515f010": "자동화" + "automationCount_other": "자동화 {{count}}개" }, "WorkspaceCombobox": { "ee5b280eba": "워크스페이스를 찾을 수 없습니다.", @@ -16263,7 +16411,8 @@ "last": { "run": { "done": "완료", - "failed": "실패" + "failed": "실패", + "statusWithRelative": "{{status}} · {{relative}}" } } } @@ -16419,15 +16568,11 @@ }, "externalScope": { "uncheckedHost": "{{hostLabel}}의 외부 자동화 관리자를 확인할 수 없습니다.", - "uncheckedHosts": "{{count}} 호스트의 외부 자동화 관리자를 확인할 수 없습니다." + "uncheckedHostCount_other": "호스트 {{count}}개의 외부 자동화 관리자를 확인할 수 없습니다." }, "enablement": { "paused": "일시중지됨" }, - "runHistory": { - "occurrencesWithLatest": "{{times}}회, 가장 최근에는 {{date}}", - "occurrences": "{{times}}회" - }, "extraAgentArgs": { "advanced": "고급", "clear": "인수 지우기", @@ -16437,6 +16582,67 @@ "useFreshSessions": "새 세션 사용", "helper": "새 세션마다 이 호스트의 기본 인수 뒤에 추가됩니다.", "detailLabel": "추가 인수" + }, + "runHistory": { + "runCountSummary_other": "실행 {{count}}회 · 완료 {{completed}}회", + "occurrencesWithLatestCount_other": "{{count}}회, 최근 {{date}}", + "occurrencesCount_other": "{{count}}회" + }, + "capabilityProbe": { + "createIdempotencyUpdateRequired": "이 호스트로 자동화를 이동하려면 더 최신 Orca 서버가 필요합니다. HUB를 업데이트하고 다시 시도하세요." + }, + "editDraft": { + "unsupportedSchedule": "이 자동화에 지원되지 않는 일정이 저장되어 있습니다. 변경 사항을 저장하기 전에 지원되는 일정을 선택하세요." + }, + "hostCatalog": { + "orphanEntryLabel": "할당되지 않은 기존 자동화" + }, + "automationPageParts": { + "never": "없음", + "now": "방금", + "runStatusPending": "대기 중", + "runStatusDispatching": "시작 중", + "runStatusDispatched": "시작됨", + "runStatusCompleted": "완료", + "runStatusSkippedPrecheck": "사전 확인으로 건너뜀", + "runStatusSkippedMissed": "건너뜀", + "runStatusSkippedUnavailable": "사용할 수 없음", + "runStatusSkippedNeedsInteractiveAuth": "인증 정보 필요", + "runStatusDispatchFailed": "실패" + }, + "runContent": { + "noOutput": "사용 가능한 출력 내용이 없습니다." + }, + "runViewState": { + "viewRun": "실행 보기", + "runOpen": "실행이 열려 있습니다", + "terminalOnPairedServer": "실행 터미널이 페어링된 서버에 있습니다.", + "terminalUnavailable": "실행 터미널을 사용할 수 없습니다.", + "openWorkspace": "워크스페이스 열기", + "workspaceAvailable": "워크스페이스를 사용할 수 있습니다.", + "snapshotSaved": "스냅샷 저장됨", + "showingSnapshot": "저장된 실행 스냅샷을 표시합니다.", + "namedWorkspaceGone": "{{name}}을(를) 더 이상 사용할 수 없습니다", + "workspaceGone": "워크스페이스를 더 이상 사용할 수 없습니다", + "noWorkspaceLaunched": "시작된 워크스페이스 없음" + }, + "runWorkspaceDisplay": { + "notLaunched": "시작되지 않음", + "namedWorkspaceGone": "{{name}} (더 이상 사용할 수 없음)" + }, + "usage": { + "tokensAndCost_other": "{{tokens}} 토큰 · {{cost}}" + }, + "externalDisplay": { + "sshHost": "SSH 호스트", + "local": "로컬" + }, + "externalActionDisabled": { + "actionInProgress": "다른 자동화 작업이 아직 실행 중입니다.", + "sshConnecting": "이 SSH 호스트의 연결이 완료될 때까지 기다리세요.", + "connectSshHost": "{{provider}} 자동화를 관리하기 전에 이 SSH 호스트에 연결하세요.", + "cannotManageOnSshHost": "{{provider}}에서 이 SSH 호스트의 자동화를 관리할 수 없습니다.", + "cannotManageLocally": "{{provider}}에서 이 컴퓨터의 자동화를 관리할 수 없습니다." } }, "agent": { @@ -16577,8 +16783,6 @@ "63ce735809": "연결", "4a2ab52781": "확인 중…", "79e7aaed39": "취소", - "fdd26d81cc": "Atlassian 계정 설정", - "8090504a3e": "다음에서 토큰 생성:", "7b3967c12f": "Atlassian API 토큰", "3d81bf3ab3": "API 토큰", "e91b9a4073": "you@example.com", @@ -16603,17 +16807,17 @@ "be9eba0a1b": "username", "70035652d7": "Password", "c50abbf340": "Jira 계정 비밀번호", - "d8737db691": "Jira Server 또는 Data Center 계정의 사용자 이름과 비밀번호를 사용하세요." + "d8737db691": "Jira Server 또는 Data Center 계정의 사용자 이름과 비밀번호를 사용하세요.", + "createTokenInSettings": "Atlassian 계정 설정에서 토큰을 만드세요." } } }, "rightSidebar": { "FolderWorkspaceWorktreesPanel": { "unavailable": "폴더 워크스페이스에서만 워크스페이스가 표시됩니다.", - "countOne": "연결된 워크트리 1개", - "countMany": "연결된 워크트리 {{value0}}개", "emptyTitle": "아직 연결된 워크트리가 없습니다", - "emptyCopy": "이 워크스페이스에서 만든 워크트리가 여기에 표시됩니다." + "emptyCopy": "이 워크스페이스에서 만든 워크트리가 여기에 표시됩니다.", + "attachedCount_other": "연결된 워크트리 {{count}}개" }, "FolderWorkspacePrChecksPanel": { "unavailable": "PR 검사는 폴더 워크스페이스에서만 표시됩니다.", @@ -16625,12 +16829,9 @@ "hideDetails": "{{value0}} PR 검사 세부 정보 숨기기", "reviewChecks": "리뷰 검사", "allChecksPassing": "모든 검사 통과", - "oneWorktree": "워크트리 1개", - "worktreeCount": "워크트리 {{value0}}개", - "oneFailing": "1개 실패", - "failingCount": "{{value0}}개 실패", - "onePending": "1개 대기 중", - "pendingCount": "{{value0}}개 대기 중" + "worktreeCountLabel_other": "워크트리 {{count}}개", + "failingCountLabel_other": "{{count}}개 실패", + "pendingCountLabel_other": "{{count}}개 대기 중" }, "parentPrChecks": { "rowSummary": { @@ -16712,10 +16913,10 @@ "combobox": { "noProjects": "프로젝트 없음", "allProjects": "모든 프로젝트", - "hostCount": "호스트 {{value0}}개", "searchProjects": "프로젝트 검색...", "noMatches": "검색과 일치하는 프로젝트가 없습니다.", - "chooseSource": "작업 소스 선택" + "chooseSource": "작업 소스 선택", + "hostCount_other": "호스트 {{count}}개" } } }, @@ -16752,7 +16953,31 @@ "taskSourceContextSummary": { "sourceUnavailable": "{{value0}} 소스를 사용할 수 없음: {{value1}}", "someSourceHostsUnavailable": "일부 {{value0}} 소스 호스트를 사용할 수 없음: {{value1}}", - "reconnectOrUpdateTitle": "이 소스를 불러오려면 {{value0}}을(를) 다시 연결하거나 업데이트하세요." + "reconnectOrUpdateTitle": "이 소스를 불러오려면 {{value0}}을(를) 다시 연결하거나 업데이트하세요.", + "providerSourceTitle": "{{provider}} 소스", + "hostTitle": "호스트: {{hosts}}", + "accountTitle": "계정: {{accounts}}", + "sourceTitle": "소스: {{source}}", + "sourceHostCount_other": "소스 호스트 {{count}}개", + "noHost": "호스트 없음", + "projectCount_other": "프로젝트 {{count}}개", + "selectedProject": "선택한 프로젝트", + "selectedProjectCount_other": "선택한 프로젝트 {{count}}개", + "currentAccount": "현재 계정", + "statusCheckingCapabilities": "서버 기능 확인 중", + "statusServerUpdateForTaskSources": "작업 소스에 서버 업데이트 필요", + "statusProviderAuthNeeded": "공급자 인증 필요", + "statusSourceToolUnavailable": "소스 도구 사용 불가", + "statusProviderUnsupported": "이 호스트에서 공급자 미지원", + "statusServerUpdateNeeded": "서버 업데이트 필요", + "unavailableCount_other": "{{count}}개 사용 불가", + "statusConnected": "연결됨", + "statusAuthNeeded": "인증 필요", + "statusConnecting": "연결 중", + "statusConnectionIssue": "연결 문제", + "statusDisconnected": "연결 끊김", + "hostStatus": "{{host}} {{status}}", + "availabilityTitle": "가용성: {{hosts}}" }, "ShortcutKeyCombo": { "07eb4985a1": "{{value0}} 두 번 누르기" @@ -17007,19 +17232,9 @@ "untitled": "제목 없는 채팅", "listLabel": "재개될 채팅", "dontAskAgain": "다시 묻지 않음(자동으로 재개)", - "dontAskAgainHint": "설정 → 실험적 → 채팅 UI에서 이 기능을 끌 수 있습니다.", - "continuedOne": "채팅 1개를 재개했습니다", - "continuedMany": "{{value0}}개의 채팅을 재개했습니다", + "dontAskAgainHint": "설정 → 채팅 → 동작에서 이 기능을 끌 수 있습니다.", "selectAgent": "{{value2}}에서 {{value0}} 채팅 \"{{value1}}\" 재개", - "resumeSelected": "{{value0}} 채팅 재개", - "resumeSelectedOne": "채팅 1개 재개", "dismissAll": "모두 닫기", - "notContinuedOne": "채팅 1개를 재개하지 못했습니다", - "notContinuedMany": "{{value0}}개의 채팅을 재개하지 못했습니다", - "notConfirmedOne": "채팅 1개가 재개되었는지 확인하지 못했습니다", - "notConfirmedMany": "{{value0}}개의 채팅이 재개되었는지 확인하지 못했습니다", - "notConfirmedOtherOne": "다른 채팅 1개가 재개되었는지 확인하지 못했습니다", - "notConfirmedOtherMany": "다른 채팅 {{value0}}개가 재개되었는지 확인하지 못했습니다", "viewChats": "채팅 보기", "review": "확인", "activityUnnamed": "이름 없음", @@ -17027,9 +17242,7 @@ "activityQuestion": "답변 대기 중: {{value0}}", "activityMidReply": "응답 중이었음", "activitySubagentOne": "하위 에이전트 실행 중: {{value0}}", - "activitySubagentMany": "하위 에이전트 {{value0}}개 실행 중", "activityMonitorOne": "모니터링 중: {{value0}}", - "activityMonitorMany": "백그라운드 작업 {{value0}}개 모니터링 중", "selectWorkspace": "{{value0}}의 채팅 모두 선택", "workspaceSelectedCount": "{{value0}}/{{value1}}", "selectAll": "모든 채팅 선택", @@ -17046,8 +17259,15 @@ "serverBody": "{{machine}}의 Orca가 다시 시작될 때 이 채팅들은 작업 중이었습니다. 재개하면 각 채팅이 중단된 위치에서 복원되고 에이전트에게 계속 진행하도록 요청합니다. 사용자의 프롬프트는 다시 전송되지 않습니다.", "serverDismiss": "닫기", "serverResumeAll": "{{machine}}에서 {{count}}개 모두 재개", - "serverResumeHereOne": "여기에서 시작한 채팅 1개 재개", - "serverResumeHere": "여기에서 시작한 채팅 {{count}}개 재개" + "resumeChats_one": "채팅 {{count}}개 재개", + "resumeChats_other": "채팅 {{count}}개 재개", + "serverResumeHereCount_other": "여기서 시작한 채팅 {{count}}개 재개", + "continuedCount_other": "채팅 {{count}}개 재개됨", + "notContinuedCount_other": "채팅 {{count}}개를 재개할 수 없습니다", + "notConfirmedCount_other": "채팅 {{count}}개의 재개 여부를 확인할 수 없습니다", + "notConfirmedOtherCount_other": "다른 채팅 {{count}}개의 재개 여부를 확인할 수 없습니다", + "activitySubagentCount_other": "하위 에이전트 {{count}}개 실행 중", + "activityMonitorCount_other": "백그라운드 작업 {{count}}개 모니터링 중" }, "linear-issue-attribute-filter-coverage-notice": { "statusPartialTeamCoverage": "{{value1}} 팀 상태 중 {{value0}} 필터링 중 - 나머지 팀의 문제는 포함되지 않습니다.", @@ -17199,15 +17419,13 @@ } }, "NativeChatResumeRunPanel": { - "resumedTitle": "채팅 {{value1}}개 중 {{value0}}개를 재개했습니다", - "resumedTitleOne": "채팅 1개 중 {{value0}}개를 재개했습니다", - "resumingTitleOne": "채팅 1개 재개 중", - "resumingTitle": "채팅 {{value0}}개 재개 중", "description": "각 채팅은 전체 컨텍스트와 함께 복원되며, 멈춘 지점을 확인하도록 요청됩니다. 이 창을 닫아도 상태 표시줄에서 진행 상황을 계속 볼 수 있습니다.", "finished": "이 채팅들은 Orca가 종료될 때 작업 중이었습니다. Orca는 각 채팅을 멈춘 지점에서 전체 컨텍스트와 함께 복원하고, 계속하기 전에 하던 작업을 확인하도록 에이전트에게 요청했습니다. 사용자의 프롬프트는 다시 전송되지 않았습니다.", "finishedUpdate": "이 채팅들은 Orca가 업데이트를 설치할 때 작업 중이었습니다. Orca는 각 채팅을 멈춘 지점에서 전체 컨텍스트와 함께 복원하고, 계속하기 전에 하던 작업을 확인하도록 에이전트에게 요청했습니다. 사용자의 프롬프트는 다시 전송되지 않았습니다.", "finishedPartial": "이 채팅들은 Orca가 종료될 때 작업 중이었습니다. Orca가 재개한 채팅은 멈춘 지점에서 전체 컨텍스트와 함께 복원되었고, 계속하기 전에 하던 작업을 확인하도록 요청받았습니다. 사용자의 프롬프트는 다시 전송되지 않았습니다. 아직 확인이 필요하거나 재개할 수 있는 채팅은 목록에서 확인하세요.", - "finishedPartialUpdate": "이 채팅들은 Orca가 업데이트를 설치할 때 작업 중이었습니다. Orca가 재개한 채팅은 멈춘 지점에서 전체 컨텍스트와 함께 복원되었고, 계속하기 전에 하던 작업을 확인하도록 요청받았습니다. 사용자의 프롬프트는 다시 전송되지 않았습니다. 아직 확인이 필요하거나 재개할 수 있는 채팅은 목록에서 확인하세요." + "finishedPartialUpdate": "이 채팅들은 Orca가 업데이트를 설치할 때 작업 중이었습니다. Orca가 재개한 채팅은 멈춘 지점에서 전체 컨텍스트와 함께 복원되었고, 계속하기 전에 하던 작업을 확인하도록 요청받았습니다. 사용자의 프롬프트는 다시 전송되지 않았습니다. 아직 확인이 필요하거나 재개할 수 있는 채팅은 목록에서 확인하세요.", + "resumedOfTotal_other": "채팅 {{count}}개 중 {{resumed}}개 재개됨", + "resumingCount_other": "채팅 {{count}}개 재개 중" }, "NativeChatResumeRunStatusIcon": { "waitingForReply": "응답 대기 중", @@ -17272,6 +17490,68 @@ "cancelled": "이 일반 SSH 터미널은 시작되기 전에 닫혔습니다.", "terminalUnavailable": "Orca에서 여기의 터미널을 열 수 없습니다.", "openHint": "Orca가 호스트에서 설정할 수 없는 동안에도 호스트에서 계속 작업할 수 있습니다." + }, + "AgentStateDot": { + "working": "작업 중", + "monitoring": "백그라운드 작업 모니터링 중", + "blocked": "차단됨", + "waiting": "입력 대기 중", + "interrupted": "중단됨", + "failed": "실패", + "done": "완료", + "idle": "유휴 상태", + "unverifiable": "최근 업데이트 없음", + "unconfirmed": "확인할 수 없음", + "permission": "주의 필요" + }, + "issueComments": { + "you": "나" + }, + "ZoomOverlay": { + "uiZoom": "UI 확대/축소", + "editorZoom": "편집기 확대/축소", + "terminalZoom": "터미널 확대/축소" + }, + "issueCopy": { + "urlCopied": "URL 복사됨", + "keyCopied": "키 복사됨", + "identifierCopied": "식별자 복사됨", + "branchNameCopied": "브랜치 이름 복사됨", + "promptCopied": "프롬프트 복사됨", + "urlCopyFailed": "URL을 복사하지 못했습니다", + "keyCopyFailed": "키를 복사하지 못했습니다", + "identifierCopyFailed": "식별자를 복사하지 못했습니다", + "branchNameCopyFailed": "브랜치 이름을 복사하지 못했습니다", + "promptCopyFailed": "프롬프트를 복사하지 못했습니다" + }, + "prCheckCounts": { + "noChecksFound": "검사를 찾을 수 없음", + "checksFailing_other": "검사 {{count}}개 실패", + "checksNeedAction_other": "검사 {{count}}개에 조치 필요", + "checksPending_other": "검사 {{count}}개 대기 중", + "allChecksPassing": "모든 검사 통과", + "checksPassingOfTotal_other": "검사 {{count}}개 중 {{passing}}개 통과" + }, + "taskPageJiraBoard": { + "changeStatusFailed": "상태를 변경하지 못했습니다." + }, + "jiraIssue": { + "loadStatusChangesFailed": "상태 변경 내역을 불러오지 못했습니다.", + "loadCommentsFailed": "댓글을 불러오지 못했습니다." + }, + "taskPageJiraLinkedIssues": { + "someIssuesFailed": "워크스페이스에 연결된 일부 Jira 이슈를 불러올 수 없습니다. 새로고침하여 다시 시도하세요." + }, + "taskPageJiraLoadState": { + "failedToLoadIssues": "Jira 이슈를 불러오지 못했습니다.", + "authFailed": "Jira 인증에 실패했습니다. 설정에서 Jira를 다시 연결한 후 다시 시도하세요.", + "accessDenied": "Jira에서 이 이슈 검색에 대한 접근을 거부했습니다. 프로젝트 권한을 확인하거나 다른 JQL 쿼리를 사용해 보세요.", + "rateLimited": "이 이슈 검색이 Jira 요청 한도에 도달했습니다. 잠시 후 다시 시도하세요.", + "serverError": "이슈를 불러오는 중 Jira 서버 오류가 발생했습니다. 잠시 후 다시 시도하세요.", + "jqlFailed": "Jira에서 이 JQL 쿼리를 실행할 수 없습니다. 구문을 확인하고 다시 시도하세요.", + "unreachable": "Jira에 연결할 수 없습니다. 연결을 확인하고 다시 시도하세요.", + "loadFailed": "Jira 이슈를 불러올 수 없습니다. 잠시 후 다시 시도하세요.", + "errorWithCode": "오류 {{code}}: {{summary}}" } }, "i18n": { @@ -17471,6 +17751,7 @@ "agentCommandNotRunnable": "{{agent}}의 설정 → 에이전트 → 명령은 Orca가 찾을 수 있는 프로그램 경로나 이름이어야 하며, 인수나 변수를 포함할 수 없습니다. 변경하거나 재설정하세요.", "runtimeNotInstalled": "{{agent}}이(가) 이 채팅을 실행하는 컴퓨터에 설치되어 있지 않습니다. 최신 버전의 Orca에서 채팅을 통해 설치하세요.", "fullAccessAsRoot": "{{agent}}은(는) root로 실행되는 동안 전체 액세스를 사용하지 않습니다. 이 채팅을 실행하는 컴퓨터의 설정 → 에이전트에서 {{agent}}에 다른 권한을 선택한 다음 새 채팅을 시작하세요.", + "launchPreparationFailed": "Orca가 이 채팅을 실행하는 컴퓨터에서 {{agent}} 시작을 준비하지 못했습니다.", "conversationOpenElsewhere": "Codex가 아직 이 대화를 열어 두고 있습니다. 잠시 후 다시 시도하거나 다른 Codex 터미널을 닫으세요.", "conversationOpenInTerminal": "{{agent}}이(가) 다른 터미널에서 이미 이 대화를 실행 중입니다. 그곳에서 {{agent}}을(를) 종료하거나 해당 터미널을 닫은 후 여기서 계속하세요.", "chooseClaudeAccount": "Claude 계정 설정에서 선택하거나 추가하세요.", @@ -17620,7 +17901,8 @@ "compactAfterRetry": "이전 메시지를 다시 시도한 다음 /compact를 실행하세요.", "clearAfterSending": "이전 메시지를 아직 보내는 중입니다. 전송이 끝나면 /clear를 실행하세요.", "compactAfterSending": "이전 메시지를 아직 보내는 중입니다. 전송이 끝나면 /compact를 실행하세요.", - "pendingWork": "이 명령을 사용하기 전에 보류 중인 작업과 메시지가 완료될 때까지 기다리십시오." + "pendingWork": "이 명령을 사용하기 전에 보류 중인 작업과 메시지가 완료될 때까지 기다리십시오.", + "notDoneGoalChangeIncomplete": "목표 변경을 완료하지 못했습니다. 채팅을 확인하세요." }, "composer": { "send": "보내기", @@ -18124,7 +18406,6 @@ "pausedSendFailedWaiting": "보낼 수 없습니다. 에이전트가 끝나면 보내기를 눌러 다시 시도하세요.", "save": "저장", "editingMessage": "메시지 편집 중", - "cancelEditing": "편집 취소", "editChanged": "편집하는 동안 이 메시지가 변경되었습니다. 편집한 내용은 채팅 입력란에 있습니다.", "editChangedPrompt": "편집하는 동안 이 메시지가 변경되었습니다. 에이전트에 답하면 편집한 내용이 채팅 입력란에 표시됩니다.", "editChangedNotSaved": "편집하는 동안 이 메시지가 변경되었습니다. 편집한 내용은 저장되지 않았습니다.", @@ -18138,8 +18419,6 @@ "expand": "펼치기", "queued": "대기 중", "clearAll": "모두 지우기", - "pasteOrDropImages": "이미지를 붙여넣거나 끌어다 놓기", - "saveNeedsContent": "저장하려면 텍스트나 이미지를 추가하세요", "moveChanged": "이동하기 전에 대기열이 변경되었습니다. 메시지를 다시 드래그해 보세요.", "reorderHint": "드래그하거나 위쪽 및 아래쪽 화살표 키를 사용하여 순서를 변경하세요.", "reorderMessage": "메시지 순서 변경" @@ -18296,6 +18575,15 @@ "settings": "터미널에서 설정 열기", "extensions": "터미널에서 확장 대시보드 열기", "hotkeys": "터미널에서 키보드 단축키 표시" + }, + "modelDescriptions": { + "grok_4_7": "xAI의 최신 프런티어 모델", + "grok_4_6": "xAI의 이전 프런티어 모델", + "grok_4_5": "xAI의 초기 프런티어 모델", + "fable": "가장 어렵고 오래 걸리는 작업에 가장 적합", + "opus": "일상적인 복잡한 작업에 가장 적합", + "sonnet": "일상 작업에 효율적", + "haiku": "빠른 답변에 가장 빠름" } }, "tab": { @@ -18832,7 +19120,6 @@ "subagents_other": "서브에이전트 {{count}}개" }, "terminal": { - "closed": "실시간 터미널이 없습니다 — 이 에이전트의 창이 닫혔습니다.", "focusWorktree": "워크트리 열기", "close": "닫기", "remotePreviewUnavailable": "이 원격 세션에 대한 미리 보기가 없습니다. 터미널을 보려면 워크스페이스를 엽니다." @@ -19055,6 +19342,15 @@ "empty": "이 프로필에 켜진 확장 프로그램이 없습니다", "visitWebStore": "Chrome 웹 스토어 방문", "manage": "확장 프로그램 관리" + }, + "viewport": { + "mobile-s": "소형 모바일 — 320 × 568", + "mobile-m": "중형 모바일 — 375 × 667", + "mobile-l": "대형 모바일 — 425 × 812", + "tablet": "태블릿 — 768 × 1024", + "laptop": "노트북 — 1024 × 768", + "laptop-l": "대형 노트북 — 1440 × 900", + "desktop": "데스크톱 — 1920 × 1080" } }, "runtimeRpc": { @@ -19121,6 +19417,30 @@ "confirm": "필터 조정 및 공개", "cancel": "필터 유지" }, + "wslMoved": { + "movedToHost": "{{distro}} 호스트로 이동됨", + "useHere": "이 컴퓨터에서 다시 사용", + "useHereTitle": "{{name}}을(를) 이 컴퓨터에서 다시 사용할까요?", + "useHereDescription": "Orca가 이 프로젝트를 이동 전 상태 그대로 여기에서 엽니다. 코드에는 영향이 없습니다. 코드는 이동되지 않았습니다. 이동 후 {{distro}} 호스트에서 만든 새 탭이나 채팅 같은 변경 사항은 호스트에 남고 돌아오지 않습니다. 함께 이동한 프로젝트도 함께 돌아옵니다. 프로젝트는 {{distro}} 호스트에서 제거할 때까지 그곳에도 남아 있습니다. 이 창이 다시 로드됩니다.", + "useHereConfirm": "이 컴퓨터에서 사용", + "useHereSuperseded": "이후 {{distro}} 호스트로의 이동에 이 프로젝트가 포함되어 있습니다. 그 이동을 먼저 되돌리세요.", + "useHereRefusedTitle": "아직 여기에서 {{name}}을(를) 사용할 수 없습니다", + "useHereRefusedOk": "확인", + "useHereSupersededBy": "이 프로젝트 이후에 {{names}}이(가) {{distro}} 호스트로 이동했습니다. 먼저 해당 프로젝트를 이 컴퓨터에서 다시 사용한 다음 이 프로젝트를 되돌리세요.", + "useHereMoveRunning": "{{distro}} 호스트로의 이동이 아직 진행 중입니다. 끝난 후 다시 시도하세요.", + "useHereHostKeptForPeers": "{{project}}이(가) {{distro}} 호스트로 이동했으며, 해당 호스트는 다른 Orca를 위해 계속 실행 중입니다. 여기서 다시 사용하려면 호스트를 다시 추가하세요.", + "useHereHostUnreachable": "{{distro}} 호스트가 응답하지 않아 Orca가 이 프로젝트의 호스트 사본을 중지할 수 없으며, 그 에이전트가 아직 실행 중일 수 있습니다. 설정에서 호스트를 연결하거나 제거한 후 다시 시도하세요.", + "useHereHostStillRunning": "{{distro}} 호스트에 있는 이 프로젝트의 사본에서 아직 터미널이 실행 중이라 에이전트가 두 번 실행될 수 있습니다. 잠시 후 다시 시도하세요.", + "useHereFailed": "이 프로젝트를 이 컴퓨터로 되돌리지 못했습니다.", + "useHereHostRemovalPending": "{{distro}} 호스트가 아직 제거되는 중이므로 Orca가 그대로 둡니다. 설정에서 제거를 완료한 후 다시 시도하세요.", + "useHereHostAutomations": "Orca가 {{distro}} 호스트에서 이 프로젝트의 자동화를 끄지 못해 자동화가 두 번 실행될 수 있습니다. 설정에서 호스트를 연결한 후 다시 시도하세요.", + "useHereUnsavedTitle": "먼저 파일을 저장하세요", + "useHereUnsavedDescription": "{{name}}을(를) 다시 가져오면 이 창이 새로고침됩니다. 먼저 다음 파일을 저장하거나 닫으세요: {{files}}", + "automationRunsOnHost": "{{distro}} 호스트에서 실행", + "quitDuringMoveTitle": "프로젝트를 이동하는 중에 종료할까요?", + "quitDuringMoveDescription": "프로젝트를 WSL 호스트로 옮기는 중입니다. 그래도 종료할까요? 이동은 다음 실행 시 취소됩니다.", + "quitDuringMoveConfirm": "그래도 종료" + }, "startupWorktreeRefresh": { "loading": "워크스페이스를 찾는 중…", "description": "로컬 및 원격 프로젝트를 불러오는 동안 워크스페이스가 더 표시될 수 있습니다." @@ -19222,7 +19542,9 @@ }, "quickOpen": { "moreMatchesAvailable": "더 많은 일치 항목을 사용할 수 있습니다. 검색 결과를 좁히려면 검색을 구체화하세요.", - "recentValidationFailed": "최근 파일을 확인할 수 없습니다: {{error}}" + "recentValidationFailed": "최근 파일을 확인할 수 없습니다: {{error}}", + "installRipgrepOnRemote": "gitignore 규칙을 반영한 파일 목록을 빠르게 표시하려면 원격 호스트에 ripgrep을 설치하세요:", + "scanTooLarge": "Quick Open 스캔 범위가 너무 큽니다({{reason}})." }, "checksPanel": { "unlinked": { @@ -19238,11 +19560,18 @@ }, "discard": { "deleteUntrackedFileDescription": "이 추적되지 않은 파일은 영구적으로 삭제됩니다. 이 작업은 취소할 수 없습니다.", - "deleteUntrackedFilesDescription": "이 {{count}}개의 추적되지 않은 파일은 영구적으로 삭제됩니다. 이 작업은 취소할 수 없습니다.", + "deleteUntrackedFilesDescription_other": "이 {{count}}개의 추적되지 않은 파일은 영구적으로 삭제됩니다. 이 작업은 취소할 수 없습니다.", "restoreStagedVersionDescription": "이렇게 하면 마지막 단계 버전이 복원되고 삭제가 취소됩니다. 이 작업은 취소할 수 없습니다.", "unstagedChangesDescription": "이렇게 하면 단계가 지정되지 않은 변경 사항이 이 파일로 되돌아갑니다. 이 작업은 취소할 수 없습니다.", "unstagedSelectionIncludingUntrackedDescription": "스테이징되지 않은 변경 사항을 되돌리고 이 선택 항목의 추적되지 않은 파일을 영구적으로 삭제합니다. 이 작업은 취소할 수 없습니다.", - "unstagedFilesIncludingUntrackedDescription": "스테이징되지 않은 변경 사항을 되돌리고 이 {{count}}개 파일 중 추적되지 않은 파일을 영구적으로 삭제합니다. 이 작업은 취소할 수 없습니다." + "unstagedFilesIncludingUntrackedDescription_other": "스테이징되지 않은 변경 사항을 되돌리고 이 {{count}}개 파일 중 추적되지 않은 파일을 영구적으로 삭제합니다. 이 작업은 취소할 수 없습니다.", + "delete": "삭제", + "restore": "복원", + "discard": "버리기", + "discardAll": "모두 폐기", + "deleteUntrackedTitle_one": "추적되지 않은 파일 {{count}}개를 삭제할까요?", + "deleteUntrackedTitle_other": "추적되지 않은 파일 {{count}}개를 삭제할까요?", + "deleteCount": "{{count}}개 삭제" }, "createReviewFailure": { "authRequiredCommand": "{{providerName}}이(가) 인증되지 않았습니다. 다음 단계: 이 환경에서 {{command}}을(를) 실행하세요.", @@ -19273,6 +19602,34 @@ "creationUnconfirmed": "{{shortLabel}} 생성이 완료되었을 수 있습니다. 브랜치 리뷰 상태를 새로고침하는 중...", "withDetail": "{{shortLabel}} 생성에 실패했습니다: {{detail}}", "pushFailed": "푸시에 실패했습니다. 푸시 오류를 해결한 후 다시 시도하세요." + }, + "model": { + "auto": "자동", + "configDefault": "설정 기본값" + }, + "thinking": { + "off": "꺼짐", + "minimal": "최소", + "low": "낮음", + "medium": "중간", + "high": "높음", + "max": "최대", + "xhigh": "매우 높음" + }, + "variables": { + "basePrompt": "Orca가 안전하게 수집할 수 있는 컨텍스트를 포함한 이 작업의 기본 프롬프트입니다.", + "branch": "현재 소스 제어 브랜치 이름입니다.", + "stagedFiles": "커밋 메시지 생성에 사용할 스테이징된 파일 목록입니다. 파일은 줄바꿈으로 구분됩니다.", + "stagedPatch": "커밋 메시지 생성에 사용할 스테이징된 Git 패치입니다.", + "baseBranch": "PR 생성 편집기에서 선택한 대상 브랜치입니다.", + "currentTitle": "생성을 시작하기 전에 편집기에 입력한 현재 PR 제목입니다.", + "currentBody": "생성을 시작하기 전에 편집기에 입력한 현재 PR 설명입니다.", + "commitSummary": "기준 브랜치와 비교한 현재 브랜치의 커밋 목록입니다. 커밋은 줄바꿈으로 구분됩니다.", + "changedFiles": "현재 브랜치와 기준 브랜치 간에 변경된 파일의 요약입니다.", + "patch": "PR 세부 정보 생성에 사용할 현재 브랜치와 기준 브랜치 간의 diff입니다.", + "firstPrompt": "이 워크스페이스 또는 채팅의 첫 번째 사용자 요청입니다.", + "assistantMessage": "Orca에서 사용할 수 있는 경우 에이전트의 첫 번째 응답입니다.", + "linkedIssue": "이 워크스페이스에 연결된 GitHub 이슈 번호입니다. GitHub 이슈가 연결되지 않으면 비어 있습니다(GitLab에 연결된 워크스페이스 포함). 지시문이 있는 템플릿을 사용하세요. 연결이 없으면 단독 \"Fixes #{linkedIssue}\"는 \"Fixes #\"가 됩니다." } }, "rendererRecovery": { @@ -19297,8 +19654,6 @@ }, "sessionSearch": { "panel": { - "resultsOne": "{{count}} 결과", - "resultsOther": "{{count}} 결과", "noMatches": "색인화된 기록에 일치하는 세션이 없습니다. 다른 쿼리나 범위를 시도해 보세요.", "loadMore": "더 많은 경기 로드", "indexedHistory": "색인된 기록", @@ -19319,12 +19674,21 @@ "retry": "다시 시도하세요", "scopeUnknown": "이 컴퓨터에는 이 워크스페이스가나 프로젝트가 없습니다. 모든 항목을 검색하려면 범위를 모두로 전환하세요.", "sortSessionsAriaLabel": "세션 정렬: {{value0}}", - "sessionsOne": "{{count}} 세션", - "sessionsOther": "{{count}} 세션", - "sessionsOfLoaded": "{{value1}} 세션 중 {{value0}}", "showMoreSessions": "더 많은 세션 보기", "loadingMoreSessions": "추가 세션 로드 중…", - "unsupportedAgent": "이 컴퓨터는 선택한 에이전트에 대한 이력 검색을 지원하지 않습니다. 해당 컴퓨터에서 ORCA를 업데이트하거나 다른 에이전트를 선택하십시오." + "unsupportedAgent": "이 컴퓨터는 선택한 에이전트에 대한 이력 검색을 지원하지 않습니다. 해당 컴퓨터에서 ORCA를 업데이트하거나 다른 에이전트를 선택하십시오.", + "resultCount_other": "결과 {{count}}개", + "sessionCount_other": "세션 {{count}}개", + "sessionsShownOfLoaded_other": "세션 {{count}}개 중 {{shown}}개", + "hostSkipReason": { + "indexChanged": "인덱스 변경됨", + "searchOff": "검색 꺼짐", + "notReady": "준비되지 않음", + "unavailable": "사용할 수 없음", + "unreachable": "연결할 수 없음", + "scopeNotFound": "해당 호스트에서 검색 범위를 찾을 수 없음", + "agentNotSupported": "지원되지 않는 에이전트" + } } }, "sessionHistory": { @@ -19446,9 +19810,9 @@ "pathAdded": "Added", "openFolder": "Open {{name}}", "findOrTypePath": "폴더를 찾거나 경로를 입력하세요...", - "addTypedPath": "Add", "noDirectories": "아직 추가된 폴더가 없습니다.", - "removePath": "Remove {{name}}" + "removePath": "Remove {{name}}", + "addTypedPathCode": " 추가" }, "accounts": { "wslAccountNotApplied": { @@ -19547,12 +19911,9 @@ "settingAsk": "묻기", "dontAskAgain": "다시 묻지 않음(자동으로 다시 시작)", "title": "{{account}}(으)로 전환됨", - "bodyOther": "{{previous}} 계정에서 Claude 세션 {{count}}개가 아직 실행 중입니다. 다시 시작하면 {{next}} 계정에서 각 대화가 이어집니다. 작업 중인 세션은 작업이 끝난 후 다시 시작됩니다.", "dontAskAgainHint": "설정 → AI 공급자 계정에서 이 기능을 끌 수 있습니다.", - "bodyOne": "{{previous}} 계정에서 Claude 세션 1개가 아직 실행 중입니다. 다시 시작하면 {{next}} 계정에서 대화가 이어집니다. 작업 중인 세션은 작업이 끝난 후 다시 시작됩니다.", "session": "Claude 세션", "restartOne": "세션 다시 시작", - "restartOther": "{{count}} 세션 다시 시작", "keep": "그대로 유지", "listLabel": "다시 시작할 Claude 세션", "settingTitle": "Claude가 실행되는 동안 계정을 전환하는 경우", @@ -19569,13 +19930,14 @@ "reasonOwnFolder": "자체 Claude 폴더 사용", "reasonUnknownAccount": "계정 알 수 없음", "reasonNoSession": "재개할 수 없음", - "reviewBodyOne": "다른 Claude 세션 1개가 {{next}}(으)로 옮겨지지 않았습니다.", - "reviewBodyOther": "다른 Claude 세션 {{count}}개가 {{next}}(으)로 옮겨지지 않았습니다.", "notMovedOne": "다른 세션 1개는 옮겨지지 않았습니다.", "notMovedOther": "다른 세션 {{count}}개는 옮겨지지 않았습니다.", "review": "검토", "uncheckedOne": "터미널 1개에서 Claude 실행 여부를 확인할 수 없습니다. 그곳에서 Claude가 실행 중이면 다시 시작할 때까지 {{previous}}을(를) 계속 사용합니다.", - "uncheckedOther": "터미널 {{count}}개에서 Claude 실행 여부를 확인할 수 없습니다. 그곳에서 실행 중인 Claude는 다시 시작할 때까지 {{previous}}을(를) 계속 사용합니다." + "uncheckedOther": "터미널 {{count}}개에서 Claude 실행 여부를 확인할 수 없습니다. 그곳에서 실행 중인 Claude는 다시 시작할 때까지 {{previous}}을(를) 계속 사용합니다.", + "restartCount_other": "세션 {{count}}개 다시 시작", + "reviewBody_other": "다른 Claude 세션 {{count}}개가 {{next}}(으)로 이동되지 않았습니다.", + "body_other": "Claude 세션 {{count}}개가 아직 {{previous}}에서 실행 중입니다. 다시 시작하면 각 대화가 {{next}}에서 계속됩니다. 작업 중인 세션은 유휴 상태가 된 후 다시 시작됩니다." } }, "hostSignIn": { @@ -19689,7 +20051,9 @@ "confirmTitle": "터미널 데몬을 다시 시작하시겠습니까?", "confirmBody": "다시 시작하면 {{sessions}}에서 실행 중인 모든 프로세스가 종료됩니다. 재개를 지원하는 에이전트는 나중에 재개할 수 있지만, 셸과 기타 작업은 재개할 수 없으므로 다시 시작해야 합니다. 에이전트가 유휴 상태일 때 실행하세요.", "cancel": "취소", - "confirm": "다시 시작하고 프로세스 종료" + "confirm": "다시 시작하고 프로세스 종료", + "count_other": "실행 중인 터미널 {{count}}개", + "count_one": "실행 중인 터미널 {{count}}개" }, "restartedInputNotSent": "입력하는 동안 터미널이 다시 시작되어 일부 입력이 전달되지 않았을 수 있습니다. 다시 입력하기 전에 새 셸을 확인하세요.", "stalledDaemonBanner": { @@ -19806,7 +20170,11 @@ "picker": { "pasteUnparseable": "프로젝트 URL 또는 owner/number 형식이어야 합니다", "ownerLoadFailed": "{{owner}}의 프로젝트를 불러올 수 없습니다.", - "organizationsLoadFailed": "일부 조직을 불러오지 못했습니다({{failureCount}})." + "organizationsLoadFailed": "일부 조직을 불러오지 못했습니다({{failureCount}}).", + "organizations": "조직", + "listFailed": "프로젝트 목록을 가져오지 못했습니다", + "detailsFailed": "세부 정보를 불러오지 못했습니다", + "viewFailed": "프로젝트 보기를 가져오지 못했습니다" }, "error": { "notFoundState": "이 프로젝트 또는 보기를 찾을 수 없습니다.", @@ -19839,8 +20207,11 @@ "rateLimited": "GitHub 속도 제한에 도달했습니다. 몇 분 후 다시 시도하세요.", "network": "네트워크 오류 — 연결을 확인하세요.", "tooLargeUnknownCount": "이 보기는 항목이 너무 많아 Orca에서 렌더링할 수 없습니다. GitHub에서 보기 필터를 좁히세요.", - "tooLarge": "이 보기에는 항목이 {{itemCount}}개 있어 Orca에서 렌더링하기에는 너무 많습니다. GitHub에서 보기 필터를 좁히세요.", - "schemaDriftDetail": "이 프로젝트 보기를 읽을 수 없습니다: {{detail}}." + "schemaDriftDetail": "이 프로젝트 보기를 읽을 수 없습니다: {{detail}}.", + "tooLargeCount_other": "이 보기에는 항목이 {{count}}개 있어 Orca에서 표시하기에는 너무 많습니다. GitHub에서 보기 필터를 좁히세요." + }, + "columns": { + "type": "유형" } }, "projectField": { @@ -19927,6 +20298,27 @@ "attachments": { "updateRuntime": "워크스페이스 링크를 변경하려면 원격 런타임을 업데이트하세요", "updateRuntimeSafely": "워크스페이스 링크를 안전하게 변경하려면 원격 런타임을 업데이트하세요" + }, + "activity": { + "active": "활성", + "working": "작업 중", + "monitoring": "백그라운드 작업 모니터링 중", + "failed": "실패", + "interrupted": "중단됨", + "unconfirmed": "확인하지 못함", + "done": "완료", + "inactive": "비활성", + "permission": "권한 필요", + "unreadLabel": "{{status}} · 읽지 않음" + }, + "reviewStatus": { + "checksFailed": "{{review}} 체크: 실패", + "checksPassing": "{{review}} 체크: 통과", + "checksPending": "{{review}} 체크: 대기 중", + "closed": "{{review}}: 닫힘", + "draft": "{{review}}: 초안", + "merged": "{{review}}: 병합됨", + "open": "{{review}}: 열림" } }, "tabHoverCard": { @@ -19970,13 +20362,12 @@ "optionalEmail": "Atlassian 이메일(범위가 지정된 토큰은 선택 사항)" }, "workspace": { - "count": "{{key}}에 연결된 워크스페이스 {{count}}개", "startAnother": "새 워크스페이스 시작", "empty": "Jira 이슈를 워크스페이스에 연결하거나 다른 보기를 선택하세요.", "openFailed": "이 Jira 이슈에 연결된 워크스페이스를 열 수 없습니다.", "mode": "워크스페이스 있음", "search": "연결된 이슈 검색", - "single": "{{key}}에 연결된 워크스페이스 1개" + "linkedCount_other": "워크스페이스 {{count}}개가 {{key}}에 연결됨" }, "prompt": { "dialogTitle": "템플릿에서 프롬프트 복사", @@ -20069,7 +20460,9 @@ "preparingAriaLabel": "업데이트 준비 중입니다. 클릭하여 펼치세요.", "browserSummary": "백그라운드 Orca 서버의 브라우저가 아직 이 앱을 사용하고 있습니다.", "browserGuidance": "아래 프로세스를 종료한 후 다시 시도하세요. 서버는 브라우저 없이 계속 실행됩니다. 다른 컴퓨터가 이 Mac을 SSH 호스트로 사용하는 경우 해당 컴퓨터의 Orca를 업데이트하면 업데이트 시 브라우저가 자동으로 일시 중지됩니다." - } + }, + "wslMoveInstallHeld": "프로젝트를 WSL 호스트로 옮기는 중입니다. 이동이 끝난 후 업데이트를 설치하세요.", + "wslMoveUndoInstallHeld": "프로젝트를 WSL 호스트에서 다시 가져오는 중입니다. 완료된 후 업데이트를 설치하세요." }, "onboarding": { "language": { @@ -20452,7 +20845,7 @@ "email": "이메일 주소 확인", "allSites": "모든 웹사이트의 모든 데이터 읽기 및 변경", "someSites": "{{hosts}}에 있는 데이터 읽기 및 변경", - "manySites": "{{hosts}} 및 다른 사이트 {{count}}개에 있는 데이터 읽기 및 변경" + "manyOtherSites_other": "{{hosts}} 및 다른 사이트 {{count}}개에서 데이터 읽기 및 변경" }, "install": { "title": "{{name}}을(를) 추가하시겠습니까?", @@ -20482,5 +20875,340 @@ "math": { "scrollDisplayEquation": "수식 블록 스크롤" } + }, + "runtime": { + "health": { + "local": "로컬", + "available": "연결됨", + "connecting": "연결 중", + "disconnected": "연결 끊김", + "error": "확인 필요", + "mixed": "혼합 상태", + "repair": "다시 페어링 필요", + "update": "업데이트 필요" + }, + "compat": { + "compatible": "런타임 클라이언트와 서버가 호환됩니다.", + "clientTooOld": "이 Orca 클라이언트가 너무 오래되어 선택한 서버와 호환되지 않습니다. 이 기기의 Orca를 업데이트하세요. 클라이언트 프로토콜은 {{clientProtocol}}이며 서버에는 클라이언트 프로토콜 {{requiredProtocol}}이(가) 필요합니다.", + "serverTooOld": "선택한 Orca 서버가 너무 오래되어 이 클라이언트와 호환되지 않습니다. 서버의 Orca를 업데이트하세요. 서버 프로토콜은 {{serverProtocol}}이며 클라이언트에는 서버 프로토콜 {{requiredProtocol}}이(가) 필요합니다." + } + }, + "native": { + "about": { + "gpu": { + "unknownStatus": "상태를 사용할 수 없음", + "enabled": "활성", + "disabled": "비활성", + "unavailable": "사용할 수 없음", + "safeMode": "비활성화됨(안전 그래픽 모드)", + "software": "소프트웨어 렌더링", + "unknown": "알 수 없음({{status}})", + "summary": "GPU 가속: {{status}}" + } + }, + "dialog": { + "importCookies": "쿠키 가져오기", + "spaceTitle": "Orca 스페이스 베타", + "dashboardTitle": "Orca 에이전트 대시보드", + "cookieFiles": "쿠키 파일", + "allFiles": "모든 파일", + "importPetBundle": ".codex-pet 번들 선택", + "pickPet": "펫 선택", + "petImage": "펫 이미지", + "importWarpTheme": "Warp 테마 가져오기", + "warpThemeYaml": "Warp 테마 YAML", + "importWarpFolder": "Warp 테마 폴더 가져오기", + "images": "이미지", + "repoIconImages": "저장소 아이콘 이미지", + "audio": "오디오" + } + }, + "taskProviders": { + "linear": { + "updateAccess": "액세스 업데이트", + "addAccess": "Linear 액세스 추가", + "fetchMore": "더 불러오기", + "connectionFailed": "연결 실패", + "listLabel": "Linear 목록", + "projectsLoadFailed": "프로젝트를 불러오지 못했습니다.", + "projectNotFound": "프로젝트를 찾을 수 없습니다.", + "projectLoadFailed": "프로젝트를 불러오지 못했습니다.", + "projectIssuesLoadFailed": "프로젝트 이슈를 불러오지 못했습니다.", + "viewsLoadFailed": "보기를 불러오지 못했습니다.", + "viewContentsLoadFailed": "보기 내용을 불러오지 못했습니다.", + "issuesLoadFailed": "Linear 이슈를 불러오지 못했습니다.", + "apiKeyHint": "Orca에서 사용할 Linear 워크스페이스의 개인 API 키를 붙여넣으세요. 이미 연결된 워크스페이스라면 저장된 키가 교체됩니다.", + "remoteKeyStorage": "이 키는 활성 원격 런타임에 저장됩니다.", + "localKeyStorage": "로컬 런타임 키는 이 기기에 저장되며, 사용 가능한 경우 Electron 암호화 저장소를 사용합니다.", + "commentsLoadFailed": "댓글을 불러오지 못했습니다.", + "updateWorkspaceAccess": "{{workspace}}의 Linear 액세스 업데이트", + "workspaceApiKeyHint": "{{workspace}}의 개인 API 키를 붙여넣으세요. 이미 연결된 워크스페이스라면 저장된 키가 교체됩니다.", + "connect": "연결", + "descriptionUpdateFailed": "설명을 업데이트하지 못했습니다.", + "titleUpdateFailed": "제목을 업데이트하지 못했습니다.", + "truncated": { + "issues_one": "처음 {{count}}개의 이슈를 표시합니다. 전체 목록을 보려면 검색하거나 Linear를 여세요.", + "issues_other": "처음 {{count}}개의 이슈를 표시합니다. 전체 목록을 보려면 검색하거나 Linear를 여세요.", + "projectIssues_one": "프로젝트의 이슈 중 처음 {{count}}개를 표시합니다. 전체 목록을 보려면 검색하거나 Linear를 여세요.", + "projectIssues_other": "프로젝트의 이슈 중 처음 {{count}}개를 표시합니다. 전체 목록을 보려면 검색하거나 Linear를 여세요.", + "projects_one": "처음 {{count}}개의 프로젝트를 표시합니다. 전체 목록을 보려면 검색하거나 Linear를 여세요.", + "projects_other": "처음 {{count}}개의 프로젝트를 표시합니다. 전체 목록을 보려면 검색하거나 Linear를 여세요.", + "viewIssues_one": "보기에 포함된 이슈 중 처음 {{count}}개를 표시합니다. 전체 목록을 보려면 검색하거나 Linear를 여세요.", + "viewIssues_other": "보기에 포함된 이슈 중 처음 {{count}}개를 표시합니다. 전체 목록을 보려면 검색하거나 Linear를 여세요.", + "views_one": "처음 {{count}}개의 보기를 표시합니다. 전체 목록을 보려면 검색하거나 Linear를 여세요.", + "views_other": "처음 {{count}}개의 보기를 표시합니다. 전체 목록을 보려면 검색하거나 Linear를 여세요." + } + }, + "jira": { + "connectionFailed": "연결 실패", + "remoteTokenStorage": "토큰은 선택한 원격 런타임으로 전송되며 런타임에서 지원하는 암호화 방식으로 저장됩니다.", + "localTokenStorage": "토큰은 로컬에 저장되며 로컬 런타임 저장소에서 지원하는 경우 암호화됩니다." + }, + "errors": { + "jira": { + "createFailed": "이슈를 생성하지 못했습니다.", + "commentFailed": "댓글을 추가하지 못했습니다.", + "notConnected": "Jira에 연결되지 않았습니다.", + "titleRequired": "제목이 필요합니다.", + "labelsConflict": "labels 또는 labelOperations 중 하나만 전달하세요.", + "updateFailed": "이슈를 업데이트하지 못했습니다.", + "credentialsRequired": "사이트 URL, 이메일 및 API 토큰이 필요합니다.", + "projectRequired": "프로젝트가 필요합니다.", + "issueTypeRequired": "이슈 유형이 필요합니다.", + "issueKeyRequired": "이슈 키가 필요합니다.", + "updatesRequired": "업데이트 객체가 필요합니다.", + "commentBodyRequired": "댓글 내용이 필요합니다.", + "invalidSiteUrl": "올바른 Jira 사이트 URL을 입력하세요.", + "passwordRequired": "비밀번호가 필요합니다.", + "personalTokenRequired": "개인 액세스 토큰이 필요합니다.", + "apiTokenRequired": "API 토큰이 필요합니다.", + "connectionFailed": "연결하지 못했습니다.", + "invalidSiteIdentity": "인증 정보가 포함되지 않은 HTTP 또는 HTTPS Jira 사이트 URL을 입력하세요.", + "missingProjectIdentity": "Jira가 ID 또는 키가 없는 프로젝트를 반환했습니다.", + "invalidIssuePage": "Jira가 잘못된 이슈 페이지를 반환했습니다.", + "incompleteIssuePage": "Jira가 불완전한 이슈 페이지를 반환했습니다.", + "repeatedIssueToken": "Jira가 잘못되었거나 반복된 이슈 페이지 토큰을 반환했습니다.", + "issueSearchLimit": "Jira 이슈 검색이 페이지 제한을 초과했습니다. JQL로 프로젝트를 선택하세요.", + "invalidProjectPage": "Jira가 잘못된 프로젝트 페이지를 반환했습니다.", + "incompleteProjectPage": "Jira가 불완전한 프로젝트 페이지를 반환했습니다.", + "projectListLimit": "Jira 프로젝트 목록이 페이지 제한을 초과했습니다. JQL로 프로젝트를 선택하세요.", + "invalidCloudId": "사이트에서 올바른 Atlassian 클라우드 ID를 제공하지 않았습니다." + }, + "linear": { + "notConnected": "Linear에 연결되지 않음", + "createFailed": "Linear 생성 실패", + "createdButUnavailable": "이슈가 생성되었지만 가져올 수 없습니다", + "updateFailed": "Linear 업데이트 실패", + "commentFailed": "댓글을 작성하지 못했습니다", + "projectCreateFailed": "Linear 프로젝트 생성 실패", + "noApiKey": "저장된 API 키가 없습니다.", + "workspaceAuthExpired": "이 워크스페이스의 Linear 인증이 만료되었습니다.", + "projectNameRequired": "프로젝트 이름이 필요합니다", + "projectIdRequired": "프로젝트 ID가 필요합니다", + "projectNotFound": "프로젝트를 찾을 수 없습니다", + "viewIdRequired": "사용자 지정 보기 ID가 필요합니다", + "viewHasNoIssues": "사용자 지정 보기에 이슈가 없습니다", + "viewHasNoProjects": "사용자 지정 보기에 프로젝트가 없습니다" + } + } + }, + "workspaceOptions": { + "activeFilterCount_one": "필터 {{count}}개", + "activeFilterCount_other": "필터 {{count}}개" + }, + "editorConflicts": { + "kind": { + "addedByUs": "우리 쪽에서 추가됨", + "bothAdded": "양쪽에서 추가됨", + "deletedByUs": "우리 쪽에서 삭제됨", + "addedByThem": "상대 쪽에서 추가됨", + "bothDeleted": "양쪽에서 삭제됨", + "bothModified": "양쪽에서 수정됨", + "deletedByThem": "상대 쪽에서 삭제됨" + }, + "resolvedBanner": "로컬에서 충돌 해결됨 · {{kind}}", + "hint": { + "addedByUs": "추가된 파일을 유지할지 검토하세요", + "bothModified": "충돌 마커가 있는 부분을 수정해 충돌을 해결하세요", + "addedByThem": "추가된 파일을 유지하기 전에 검토하세요", + "bothDeleted": "편집하기 전에 Git에서 충돌을 해결하거나 한쪽 버전의 파일을 복원하세요", + "deletedByThem": "파일을 유지할지 삭제를 받아들일지 결정하세요", + "deletedByUs": "파일을 복원할지 결정하세요", + "bothAdded": "유지할 버전을 선택하거나 두 버전을 합치세요" + }, + "renamedFrom": "이름 변경 전: {{path}}", + "snapshotCapturedAt": "{{time}}에 스냅샷을 캡처했습니다.", + "unresolvedBanner": "해결되지 않은 충돌 · {{kind}}" + }, + "stats": { + "usageBreakdown": { + "turns_one": "{{count}}턴", + "events_one": "이벤트 {{count}}개", + "sessions_one": "세션 {{count}}개", + "events_other": "이벤트 {{count}}개", + "sessions_other": "세션 {{count}}개", + "turns_other": "{{count}}턴" + } + }, + "github": { + "viewed": { + "markFile": "{{path}}을(를) 본 것으로 표시", + "unmarkFile": "{{path}}을(를) 본 것으로 표시 해제" + } + }, + "wslMove": { + "entry": { + "hostRow": "이 배포판에서 프로젝트 이동…", + "projectMenu": "{{distro}} 호스트로 이동…" + }, + "blockers": { + "title": "이 프로젝트를 이동하기 전에", + "inProjects": "{{names}}에서", + "skipOne": "이번 이동에서 {{name}} 제외", + "skipMany": "이번 이동에서 이 프로젝트 {{n}}개 제외" + }, + "title": "프로젝트를 {{distro}} 호스트로 이동", + "loading": "{{distro}}의 프로젝트를 확인하는 중…", + "runningTitle": "{{distro}} 호스트로 이동하는 중", + "preview": { + "counts": "프로젝트: {{projects}} · 워크스페이스: {{workspaces}} · 터미널: {{terminals}} · 채팅: {{chats}}", + "whatHappens": "파일은 현재 위치에 그대로 남습니다. 터미널은 같은 폴더에서 다시 시작되며, 출력, 셸 기록, 에이전트 대화는 유지됩니다.", + "projects": "{{distro}}의 프로젝트", + "folderBadge": "폴더", + "notMoving": "이동하지 않음", + "checking": "선택한 프로젝트를 확인하는 중…", + "checkAgain": "다시 확인", + "moveOne": "프로젝트 1개 이동", + "moveMany": "프로젝트 {{n}}개 이동", + "heldByHost": "이미 {{distro}} 호스트에 있습니다.", + "changed": "이전에 이동된 후 이전 버전의 Orca가 여기에서 변경했습니다. 다시 이동하지 않습니다.", + "chatsStay": "기존 채팅은 이 컴퓨터에 남습니다. 이 프로젝트의 새 채팅은 WSL 호스트에서 시작됩니다.", + "browserLoginsConflict": "호스트의 브라우저 프로필이 이미 사용 중이므로 브라우저 로그인은 옮겨지지 않습니다. 이동 후 호스트의 브라우저 탭에서 다시 로그인하세요.", + "browserLoginsNotCarried": "브라우저 로그인은 이 호스트로 옮겨지지 않습니다. 이동 후 호스트의 브라우저 탭에서 다시 로그인하세요." + }, + "cancel": "취소", + "progress": { + "bytes": "{{sent}} / {{total}}", + "tooLate": "호스트가 이미 전환 중이라 취소할 수 없습니다. 완료될 때까지 Orca를 열어 두세요.", + "switching": "전환은 취소할 수 없습니다. 완료될 때까지 Orca를 열어 두세요.", + "readOnly": "이동하는 동안 이 프로젝트는 읽기 전용입니다. 전환이 시작되기 전까지 취소할 수 있습니다.", + "cancelUntilSwitch": "전환이 시작되기 전까지 취소할 수 있습니다.", + "closeKeepsGoing": "이 대화 상자를 닫아도 이동은 멈추지 않으며, 이동이 끝나면 다시 열립니다.", + "cancelling": "취소하는 중…", + "cancel": "이동 취소" + }, + "result": { + "movedTitle": "{{distro}} 호스트로 이동됨", + "resetTitle": "이동된 항목이 없습니다", + "waitingTitle": "{{distro}} 호스트를 기다리는 중", + "earlierMoveTitle": "이전 이동이 먼저 완료되었습니다", + "refusedTitle": "프로젝트가 이동되지 않았습니다", + "reloadCheckpointRefused": "Orca가 저장되지 않은 파일을 백업하지 못해 창을 다시 로드하지 않았습니다. 이 대화 상자를 닫고 해당 파일을 저장하거나 닫은 다음, 계속 표시되는 알림에서 지금 다시 로드를 사용하세요.", + "reloadVetoed": "창을 다시 로드하지 못하게 하는 항목이 있습니다. 이 대화 상자를 닫고 작업을 저장한 다음, 계속 표시되는 알림에서 지금 다시 로드를 사용하세요.", + "reloadFailed": "창이 다시 로드되지 않았습니다. 다시 시도하세요.", + "moved": "이 창을 다시 로드하면 {{distro}} 호스트 아래에 프로젝트가 표시됩니다. Orca는 다시 로드하기 전에 저장되지 않은 파일을 백업합니다.", + "automationsPendingOne": "자동화 1개가 호스트에서 일시적으로 꺼져 있습니다. Orca가 호스트에 다시 켜도록 계속 요청합니다.", + "automationsPendingMany": "자동화 {{n}}개가 호스트에서 일시적으로 꺼져 있습니다. Orca가 호스트에 다시 켜도록 계속 요청합니다.", + "undoHint": "마음이 바뀌었나요? 다시 로드한 후 사이드바에 이 프로젝트가 “{{distro}} 호스트로 이동됨”으로 표시됩니다. 거기에서 “이 컴퓨터에서 다시 사용”을 선택하면 이동 전 상태로 되돌릴 수 있습니다.", + "reset": "이동이 중지되었고 모든 항목이 원래대로 되돌려졌습니다. 프로젝트는 이전처럼 이 컴퓨터에서 작동하며, 일시 중지된 터미널은 열면 다시 시작됩니다.", + "resetReason": "중지된 이유: {{detail}}", + "waiting": "이동이 {{distro}} 호스트에 도달했을 수 있지만 호스트가 응답하지 않습니다. 응답할 때까지 이 프로젝트는 여기에서 읽기 전용으로 유지됩니다. 설정에서 호스트를 연결한 다음 이 대화 상자를 다시 열고 이동을 시작하세요. Orca가 먼저 이 이동을 완료하거나 취소합니다.", + "reloading": "다시 로드하는 중…", + "reload": "지금 다시 로드", + "close": "닫기", + "review": "프로젝트로 돌아가기", + "browserLoginsHostUnknown": "Orca가 호스트의 브라우저 프로필을 확인하지 못해 브라우저 로그인이 복사되지 않았습니다. 호스트의 브라우저 탭에서 다시 로그인하세요.", + "browserLoginsConflict": "호스트의 브라우저 프로필이 이미 사용 중이라 브라우저 로그인이 복사되지 않았습니다. 호스트의 브라우저 탭에서 다시 로그인하세요.", + "browserLoginsNotCopied": "브라우저 로그인이 호스트로 복사되지 않았습니다. 호스트의 브라우저 탭에서 다시 로그인하세요." + }, + "runtime": { + "label": "프로젝트 런타임", + "description": "이 프로젝트는 이 컴퓨터를 통해 {{distro}}에서 실행됩니다. {{distro}} 호스트로 이동하면 그곳에서 실행됩니다.", + "move": "프로젝트 이동" + }, + "unfinished": { + "one": "{{distro}} 호스트로 이동한 자동화 1개가 아직 꺼져 있습니다. Orca가 호스트에 다시 켜도록 계속 요청합니다.", + "many": "{{distro}} 호스트로 이동한 자동화 {{n}}개가 아직 꺼져 있습니다. Orca가 호스트에 다시 켜도록 계속 요청합니다." + }, + "refusal": { + "previewFailed": "Orca가 이 프로젝트를 확인하지 못했습니다. 다시 시도하세요.", + "startFailed": "Orca가 이동 상태를 확인할 수 없게 되었습니다. 이 대화 상자를 다시 열어 진행 상황을 확인하세요.", + "unavailable": "이 창에서는 프로젝트를 WSL 호스트로 이동할 수 없습니다.", + "alreadyRunning": "{{distro}}(으)로의 이동이 이미 진행 중입니다. 끝날 때까지 기다린 후 다시 시도하세요.", + "alreadyInFlightPreview": "{{distro}}의 이동이 아직 마무리되는 중입니다. 이 이동을 시작하면 Orca가 가능한 경우 먼저 그 이동을 완료하거나 취소합니다.", + "alreadyInFlight": "{{distro}}의 이동이 아직 마무리되는 중이라 이 이동은 시작되지 않았습니다. {{distro}} 호스트를 연결된 상태로 두고 나중에 다시 시도하세요.", + "nothingNew": "이 프로젝트는 이미 {{distro}} 호스트에 있습니다.", + "destinationChanged": "이전에 {{distro}}에서 이동한 프로젝트는 다른 WSL 호스트로 이동했습니다. 더 이동하려면 해당 호스트를 연결하세요.", + "hostUnavailable": "{{distro}} 호스트가 연결되어 있지 않습니다. 설정에서 연결한 후 다시 시도하세요.", + "hostUpdateRequired": "{{distro}} 호스트에서 이전 버전의 Orca가 실행 중입니다. 설정에서 업데이트한 후 다시 시도하세요.", + "terminalsBlocked": "이 프로젝트의 일부 터미널, 에이전트 또는 자동화가 사용 중입니다. 이동된 항목이 없습니다.", + "exportIncomplete": "이 프로젝트의 일부 저장된 상태를 아직 이동할 수 없어 아무것도 이동하지 않았습니다:", + "exportIncompletePreview": "이 프로젝트의 일부 저장된 상태를 아직 이동할 수 없습니다:", + "tooLarge": "이 프로젝트에 저장된 상태가 너무 많아 한 번에 이동할 수 없습니다. 한 번에 더 적은 프로젝트를 이동하세요.", + "pauseFailed": "Orca가 이 프로젝트의 터미널을 일시 중지하지 못해 아무것도 이동하지 않았습니다. 일시 중지된 터미널은 열면 다시 시작됩니다. 다시 시도하세요.", + "scopeChanged": "이동을 준비하는 동안 프로젝트가 변경되어 아무것도 이동하지 않았습니다. 프로젝트를 확인한 후 다시 시도하세요.", + "cancelled": "이동이 취소되었습니다. 이동된 항목이 없습니다.", + "finishedEarlierMove": "Orca가 먼저 {{distro}}(으)로의 이전 이동을 완료했습니다. 창을 다시 로드한 후 이 이동을 다시 시작하세요." + }, + "step": { + "preparing": "준비 중", + "pausingTerminals": "터미널 일시 중지 중", + "copying": "복사 중", + "switching": "전환 중", + "finishing": "마무리 중", + "done": "완료" + }, + "blocker": { + "agentWorkingOne": "에이전트가 작업 중이거나 응답을 기다리고 있습니다", + "agentWorkingMany": "에이전트 {{n}}개가 작업 중이거나 응답을 기다리고 있습니다", + "processRunningOne": "터미널에서 프로그램이 실행 중입니다", + "processRunningMany": "터미널 {{n}}개에서 프로그램이 실행 중입니다", + "agentNotResumableOne": "이동 후 재개할 수 없는 에이전트가 있습니다", + "agentNotResumableMany": "이동 후 재개할 수 없는 에이전트가 {{n}}개 있습니다", + "unverifiableOne": "Orca가 지금 터미널을 확인할 수 없습니다", + "unverifiableMany": "Orca가 지금 터미널 {{n}}개를 확인할 수 없습니다", + "automationRunningOne": "자동화 실행이 진행 중입니다", + "automationRunningMany": "자동화 실행 {{n}}개가 진행 중입니다", + "dispatchRunningOne": "에이전트 작업이 진행 중입니다", + "dispatchRunningMany": "에이전트 작업 {{n}}개가 진행 중입니다", + "scrollbackTooLargeOne": "출력 기록이 너무 많아 이동할 수 없는 터미널이 있습니다", + "scrollbackTooLargeMany": "터미널 {{n}}개의 출력 기록이 너무 많아 이동할 수 없습니다" + }, + "blockerHint": { + "agentWorking": "완료될 때까지 기다리거나 해당 터미널에서 중지한 후 다시 확인하세요.", + "processRunning": "프로그램(예: 개발 서버나 편집기)을 중지한 후 다시 확인하세요.", + "agentNotResumable": "해당 터미널에서 에이전트를 종료한 후 다시 확인하세요.", + "unverifiable": "잠시 기다린 후 다시 확인하세요. 이동을 위해 중지되는 것은 없습니다.", + "wait": "완료될 때까지 기다린 후 다시 확인하세요.", + "scrollbackTooLarge": "해당 터미널의 출력을 지운 후 다시 확인하세요." + }, + "scopeRefused": { + "windowsDrive": "폴더가 Windows 드라이브에 있어 이 컴퓨터에 남습니다.", + "mixedLocations": "일부 폴더가 이 배포판 밖에 있어 이 컴퓨터에 남습니다.", + "notLocal": "이미 다른 호스트에서 실행 중입니다.", + "other": "이동할 수 없습니다." + }, + "reloadToast": { + "title": "이동을 완료하려면 다시 로드하세요" + }, + "orchestrator": { + "showTerminal": "터미널 표시", + "moveAgain": "다시 이동", + "checkAgain": "다시 확인", + "deferred": "{{distro}} 호스트로의 이동을 마무리하는 중입니다. 일부 터미널이 아직 사용 중입니다.", + "stuck": "{{distro}} 호스트로의 이전 이동이 아직 마무리되지 않았습니다.", + "declined": "이 프로젝트를 이 컴퓨터로 되돌렸기 때문에 이동이 일시 중지되었습니다.", + "doneToast": "프로젝트가 {{distro}} 호스트로 이동됨", + "terminalGone": "해당 터미널이 이 창에 더 이상 열려 있지 않습니다. 새로 고치려면 다시 확인하세요.", + "blocker": "{{title}}. {{hint}}", + "paused": "{{distro}} 호스트로의 프로젝트 이동이 일시 중지되었습니다: {{reason}}.", + "pausedReason": { + "exportIncomplete": "일부 저장된 상태를 아직 옮길 수 없습니다", + "manifestTooLarge": "저장된 상태가 한 번의 이동으로 옮길 수 있는 양보다 많습니다", + "hostUpdate": "먼저 호스트를 업데이트해야 합니다", + "attemptsExhausted": "여러 번 시도했지만 완료되지 않았습니다" + }, + "finishPending": "{{distro}} 호스트로의 이전 이동은 호스트에서 완료되었습니다. Orca가 다시 시작할 때 또는 지금 다시 확인을 누르면 여기에서 마무리합니다." + } } } diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 5709bfab87f4..5cc327786d75 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -12,7 +12,9 @@ }, "quickOpen": { "moreMatchesAvailable": "Mais resultados podem estar disponíveis. Refine sua busca para reduzir os resultados.", - "recentValidationFailed": "Não foi possível verificar os arquivos recentes: {{error}}" + "recentValidationFailed": "Não foi possível verificar os arquivos recentes: {{error}}", + "installRipgrepOnRemote": "Instale ripgrep no host remoto para listar arquivos rapidamente, respeitando as regras do .gitignore:", + "scanTooLarge": "A varredura da Abertura rápida é grande demais ({{reason}})." }, "sourceControl": { "unlinkedPr": { @@ -20,11 +22,20 @@ }, "discard": { "deleteUntrackedFileDescription": "Isso excluirá permanentemente este arquivo não rastreado. Essa ação não pode ser desfeita.", - "deleteUntrackedFilesDescription": "Isso excluirá permanentemente estes {{count}} arquivos não rastreados. Essa ação não pode ser desfeita.", + "deleteUntrackedFilesDescription_other": "Isso excluirá permanentemente estes {{count}} arquivos não rastreados. Essa ação não pode ser desfeita.", "restoreStagedVersionDescription": "Isso restaurará a última versão preparada e descartará a exclusão. Essa ação não pode ser desfeita.", "unstagedChangesDescription": "Isso reverterá as alterações não preparadas neste arquivo. Essa ação não pode ser desfeita.", "unstagedSelectionIncludingUntrackedDescription": "Isso reverterá as alterações não preparadas e excluirá permanentemente quaisquer arquivos não rastreados nesta seleção. Essa ação não pode ser desfeita.", - "unstagedFilesIncludingUntrackedDescription": "Isso reverterá as alterações não preparadas e excluirá permanentemente quaisquer arquivos não rastreados entre estes {{count}} arquivos. Essa ação não pode ser desfeita." + "unstagedFilesIncludingUntrackedDescription_other": "Isso reverterá as alterações não preparadas e excluirá permanentemente quaisquer arquivos não rastreados entre estes {{count}} arquivos. Essa ação não pode ser desfeita.", + "delete": "Excluir", + "restore": "Restaurar", + "discard": "Descartar", + "discardAll": "Descartar tudo", + "deleteUntrackedTitle_one": "Excluir {{count}} arquivo não rastreado?", + "deleteUntrackedTitle_other": "Excluir {{count}} arquivos não rastreados?", + "deleteCount": "Excluir {{count}}", + "deleteUntrackedFilesDescription_one": "Isso excluirá permanentemente {{count}} arquivo não rastreado. Essa ação não pode ser desfeita.", + "unstagedFilesIncludingUntrackedDescription_one": "Isso reverterá as alterações não preparadas em {{count}} arquivo e o excluirá permanentemente se ele não for rastreado. Essa ação não pode ser desfeita." }, "createReviewFailure": { "authRequiredCommand": "{{providerName}} não está autenticado. Próximo passo: execute {{command}} neste ambiente.", @@ -56,7 +67,35 @@ "withDetail": "Falha ao criar {{shortLabel}}: {{detail}}", "pushFailed": "O push falhou. Resolva o erro de push e tente novamente." }, - "actionSaveFailed": "Não foi possível salvar esta ação. Tente salvá-la novamente em Configurações." + "actionSaveFailed": "Não foi possível salvar esta ação. Tente salvá-la novamente em Configurações.", + "model": { + "auto": "Automático", + "configDefault": "Padrão da configuração" + }, + "thinking": { + "off": "Desativado", + "minimal": "Mínimo", + "low": "Baixa", + "medium": "Média", + "high": "Alta", + "max": "Máximo", + "xhigh": "Muito alto" + }, + "variables": { + "basePrompt": "O prompt integrado do Orca para esta ação, incluindo o contexto que o Orca sabe coletar com segurança.", + "branch": "O nome da branch atual do controle de versão.", + "stagedFiles": "Uma lista de arquivos em staging, separados por quebras de linha, para gerar a mensagem de commit.", + "stagedPatch": "O patch do Git em staging usado para gerar a mensagem de commit.", + "baseBranch": "A branch de destino selecionada no editor de criação de PR.", + "currentTitle": "O título do PR digitado no editor antes do início da geração.", + "currentBody": "A descrição do PR digitada no editor antes do início da geração.", + "commitSummary": "Uma lista de commits da branch em relação à base, separados por quebras de linha.", + "changedFiles": "Um resumo dos arquivos alterados entre a branch e sua base.", + "patch": "O diff da branch em relação à base usado para gerar os detalhes do PR.", + "firstPrompt": "A primeira solicitação do usuário neste espaço de trabalho ou chat.", + "assistantMessage": "A resposta inicial do agente, quando disponível no Orca.", + "linkedIssue": "O número da issue do GitHub vinculada a este espaço de trabalho. Fica vazio quando não há issue do GitHub vinculada (incluindo espaços vinculados ao GitLab). Prefira modelos com instruções: \"Fixes #{linkedIssue}\" isolado vira \"Fixes #\" quando não há vínculo." + } }, "githubChecks": { "retrying": "Tentando novamente…", @@ -165,6 +204,30 @@ "startupWorktreeRefresh": { "loading": "Descobrindo espaços de trabalho…", "description": "Mais espaços de trabalho podem aparecer enquanto os projetos locais e remotos são carregados." + }, + "wslMoved": { + "movedToHost": "Movido para o host {{distro}}", + "useHere": "Usar novamente neste computador", + "useHereTitle": "Usar {{name}} novamente neste computador?", + "useHereDescription": "O Orca vai abrir este projeto aqui como ele estava antes da movimentação. Seu código não é afetado: ele nunca foi movido. As alterações feitas no host {{distro}} desde a movimentação, como novas abas e chats, ficam no host e não voltam. Os projetos movidos junto com este também voltam. O projeto também continua no host {{distro}} até você removê-lo de lá. Esta janela será recarregada.", + "useHereConfirm": "Usar neste computador", + "useHereSuperseded": "Uma movimentação posterior para o host {{distro}} inclui este projeto. Traga aquela de volta primeiro.", + "useHereRefusedTitle": "Ainda não é possível usar {{name}} aqui", + "useHereRefusedOk": "OK", + "useHereSupersededBy": "{{names}} foram movidos para o host {{distro}} depois deste projeto. Use-os novamente neste computador primeiro e depois este projeto.", + "useHereMoveRunning": "Uma movimentação para o host {{distro}} ainda está em andamento. Tente novamente quando ela terminar.", + "useHereHostKeptForPeers": "{{project}} foi movido para o host {{distro}}, que continua em execução para outro Orca. Adicione o host novamente para usá-lo aqui de novo.", + "useHereHostUnreachable": "O host {{distro}} não está respondendo, então o Orca não consegue parar a cópia deste projeto lá, e os agentes dele ainda podem estar em execução. Conecte o host em Configurações, ou remova-o, e tente novamente.", + "useHereHostStillRunning": "A cópia deste projeto no host {{distro}} ainda tem terminais em execução, então os agentes dele podem ser executados duas vezes. Aguarde um momento e tente novamente.", + "useHereFailed": "Não foi possível trazer este projeto de volta para este computador.", + "useHereHostRemovalPending": "O host {{distro}} ainda está sendo removido, então o Orca não mexe nele. Conclua a remoção em Configurações e tente novamente.", + "useHereHostAutomations": "O Orca não conseguiu desativar as automações deste projeto no host {{distro}}, então elas podem ser executadas duas vezes. Conecte o host em Configurações e tente novamente.", + "useHereUnsavedTitle": "Salve seus arquivos primeiro", + "useHereUnsavedDescription": "Trazer {{name}} de volta recarrega esta janela. Salve ou feche estes arquivos primeiro: {{files}}", + "automationRunsOnHost": "É executada no host {{distro}}", + "quitDuringMoveTitle": "Sair enquanto um projeto está sendo movido?", + "quitDuringMoveDescription": "Um projeto está sendo movido para o host WSL dele. Sair mesmo assim? A movimentação será desfeita na próxima inicialização.", + "quitDuringMoveConfirm": "Sair mesmo assim" } }, "tray": { @@ -318,19 +381,29 @@ "enable": "Ativar", "retry": "Tentar novamente", "scopeUnknown": "Este computador não tem este espaço de trabalho ou projeto. Mude o escopo para Tudo para pesquisar tudo nele.", - "resultsOne": "{{count}} resultado", - "resultsOther": "{{count}} resultados", "sortRelevance": "Mais relevantes", "sortNewest": "Mais recentes", "sortResultsAriaLabel": "Ordenar resultados: {{value0}}", "titleOnly": "A busca no texto completo está desativada neste computador, então apenas os títulos das sessões são pesquisados.", "unsupportedAgent": "Este computador não oferece busca no histórico do agente selecionado. Atualize o Orca nesse computador ou selecione outro agente.", "sortSessionsAriaLabel": "Ordenar sessões: {{value0}}", - "sessionsOne": "{{count}} sessão", - "sessionsOther": "{{count}} sessões", - "sessionsOfLoaded": "{{value0}} de {{value1}} sessões", "showMoreSessions": "Mostrar mais sessões", - "loadingMoreSessions": "Carregando mais sessões…" + "loadingMoreSessions": "Carregando mais sessões…", + "resultCount_one": "{{count}} resultado", + "resultCount_other": "{{count}} resultados", + "sessionCount_one": "{{count}} sessão", + "sessionCount_other": "{{count}} sessões", + "sessionsShownOfLoaded_one": "{{shown}} de {{count}} sessão", + "sessionsShownOfLoaded_other": "{{shown}} de {{count}} sessões", + "hostSkipReason": { + "indexChanged": "índice alterado", + "searchOff": "busca desativada", + "notReady": "não está pronto", + "unavailable": "indisponível", + "unreachable": "inacessível", + "scopeNotFound": "escopo de busca não encontrado nesse host", + "agentNotSupported": "agente não compatível" + } } }, "menu": { @@ -509,7 +582,6 @@ "subagents_other": "{{count}} subagentes" }, "terminal": { - "closed": "Nenhum terminal ativo — o painel deste agente foi encerrado.", "remotePreviewUnavailable": "Nenhuma pré-visualização para esta sessão remota — abra o espaço de trabalho para ver o terminal.", "focusWorktree": "Abrir worktree", "close": "Fechar" @@ -717,6 +789,15 @@ "empty": "Nenhuma extensão está ativada para este perfil", "visitWebStore": "Visitar a Chrome Web Store", "manage": "Gerenciar extensões" + }, + "viewport": { + "mobile-s": "Celular P — 320 × 568", + "mobile-m": "Celular M — 375 × 667", + "mobile-l": "Celular G — 425 × 812", + "tablet": "Tablet — 768 × 1024", + "laptop": "Notebook — 1024 × 768", + "laptop-l": "Notebook G — 1440 × 900", + "desktop": "Desktop — 1920 × 1080" } }, "settings": { @@ -727,11 +808,15 @@ "system": "Sistema", "english": "Inglês", "chinese": "中文(简体)", + "chineseTraditional": "繁體中文(台灣)", "korean": "한국어", "japanese": "日本語", "spanish": "Español", "french": "Français", - "portuguese": "Português (Brasil)" + "portuguese": "Português (Brasil)", + "russian": "Русский", + "turkish": "Türkçe", + "german": "Deutsch" }, "statusBar": { "claudeToggleDescription": "Mostra o uso de tokens e custo do Claude para o espaço de trabalho ativo.", @@ -1037,7 +1122,8 @@ "permissionOverrideMore": "e mais {{count}}", "permissionOverrideMore_one": "e mais {{count}}", "permissionOverrideMore_other": "e mais {{count}}", - "permissionOverridesUse": "Usar {{mode}}" + "permissionOverridesUse": "Usar {{mode}}", + "approveForMe": "aprovar por mim" }, "followSymlinkedDirectoriesKeywords": { "symlink": "link simbólico", @@ -1068,6 +1154,34 @@ "actionPermissions": { "sameAsAgent": "Igual a {{agent}}" } + }, + "ssh": { + "status": { + "disconnected": "Desconectado", + "connecting": "Conectando…", + "auth-failed": "Falha na autenticação", + "connected": "Conectado", + "reconnection-failed": "Falha na reconexão", + "deploying-relay": "Implantando relay…", + "reconnecting": "Reconectando…" + } + }, + "mcp": { + "workspace": "Espaço de Trabalho", + "inspectFailed": "Não foi possível inspecionar {{directory}}.", + "unreadable": "Não foi possível ler", + "notFound": "Não encontrado", + "invalidJson": "JSON inválido", + "noServers": "Nenhum servidor", + "httpServer": "Servidor HTTP", + "stdioServer": "Servidor stdio", + "invalidServer": "Servidor inválido", + "serverCount_one": "{{count}} servidor", + "serverCount_other": "{{count}} servidores", + "claudeWorkspace": "Espaço de trabalho do Claude" + }, + "shortcuts": { + "parseFailed": "Não foi possível interpretar o atalho." } }, "auto": { @@ -4021,7 +4135,6 @@ "a016ffbeed": "Auto usa o Windows PowerShell agora e alterna para o PowerShell 7+ quando instalado.", "5ed5c95344": "Escolha entre Windows PowerShell e PowerShell 7+ para novos painéis de terminal.", "3d88af864d": "Escolha se a opção de shell PowerShell inicia o Windows PowerShell ou o PowerShell 7+ para novos painéis de terminal.", - "8a956cc91e": "Caracteres tratados como limites de palavra para seleção por clique duplo.", "4bebcc2b2c": "Separadores de Palavra", "12e06178fa": "linhas", "907b0b9d3e": "Personalizado", @@ -8134,7 +8247,8 @@ "migration": "Não concluído: há uma movimentação para este servidor pendente. Retome-a primeiro.", "deferred": "Ainda não concluído: o servidor não está pronto para isso. Tente novamente mais tarde.", "failed": "O Orca não conseguiu concluir esta ação no servidor. Tente novamente.", - "defaultServer": "Não concluído: este servidor é o host padrão para novos projetos. Escolha outro em Novos projetos são abertos em antes de pará-lo." + "defaultServer": "Não concluído: este servidor é o host padrão para novos projetos. Escolha outro em Novos projetos são abertos em antes de pará-lo.", + "wslMoveRunning": "Não concluído: um projeto está sendo movido para este servidor. O Orca o atualiza quando a movimentação terminar." }, "reassurance": "É executado em cada host, acessado pela sua própria conexão SSH. Seu código e seus arquivos permanecem onde estão. Apenas a lista de projetos, abas e terminais do Orca é movida para o host." }, @@ -8589,7 +8703,6 @@ "476b77745b": "Alterar Ref Base", "ed34038d0d": "Atualizar comparação de branch", "493f963029": "Alterar ref base", - "3278b2767b": "adiante", "11b5dd8e41": "Comparando com", "a9bf7c171a": "Falha no Commit", "011f9713fc": "Commit bloqueado", @@ -8634,7 +8747,6 @@ "574d2f4413": "Limpar Notas", "05bb8f4a48": "Cancelar", "48db37cca9": "Ver tudo", - "78ce2d37ac": "Envia (push) para o fork", "c05fe04839": "Envia (push) para o fork em {{value0}} (não o origin)", "c35baf2f1e": "Filtrar arquivos…", "2fe2a67580": "Mais ações de nota", @@ -8642,14 +8754,12 @@ "cc474e0b8c": "Notas", "e131cd7128": "O Controle de Versão está disponível somente para repositórios Git", "c07b236287": "Selecione um espaço de trabalho para ver as alterações", - "dc5a6465fc": "{{value0}} (e.g. {{value1}}{{value2}})", "a5e5a11090": "Falha ao descartar tudo — não foi possível remover os arquivos do stage antes de descartar", "8a5ba6a988": "Falha ao carregar o diff do commit", "fe5bd1a610": "Criando {{value0}}...", "812cb992ee": "Abrir em {{value0}}", "eef5446523": "{{value0}} #{{value1}} já está aberto", "0453ca3a9a": "{{value0}} criado, mas o Orca ainda não conseguiu atualizá-lo.", - "f99560ab29": "Falha ao abortar {{value0}}", "eae7a1da5f": "Falha ao limpar as notas.", "df5040e3c3": "Remover do stage", "8cde1a2fb0": "Adicionar ao stage", @@ -8677,8 +8787,6 @@ "aaf1451654": "Criar {{value0}} em rascunho", "26511c22b4": "Criando...", "d7ae61269b": "Commitado na Branch", - "branchFilesChangedVsBaseOne": "1 arquivo alterado em relação a {{ref}}", - "branchFilesChangedVsBaseOther": "{{count}} arquivos alterados em relação a {{ref}}", "48a003c1b1": "Alterações no Stage", "d4ef4bafc5": "Alterações", "9339382454": "Remover tudo do stage", @@ -8688,8 +8796,6 @@ "72f2bea3f4": "Expandir notas", "d13edef890": "Recolher notas", "d6fb1df5fe": "{{value0}} já está aberto", - "05838cfdeb": "{{value0}} conflito", - "d206117f90": "{{value0}} conflito ({{value1}})", "0b5b8c234c": "Abrir {{value0}} ({{value1}})", "d97ef8f221": "linhas {{value0}}-{{value1}}", "6f8bfa0eb9": "linha {{value0}}", @@ -8742,10 +8848,6 @@ "b3c8f1a902": "Filtrar arquivos por nome", "d4f8c2a901": "Limpar e fechar filtro", "e8a1c4b203": "vs", - "compareBaseCommitsAheadOne": "1 commit adiante de {{ref}}", - "compareBaseCommitsAheadOther": "{{count}} commits adiante de {{ref}}", - "compareBaseCommitsBehindOne": "1 commit atrás de {{ref}}", - "compareBaseCommitsBehindOther": "{{count}} commits atrás de {{ref}}", "4b4a7de138": "Abrir página de revisão no navegador", "createPrIntentCommitBlockedSummary": "Commit bloqueado: {{value0}} Corrija o problema e tente novamente Criar PR.", "pushRecovery": { @@ -8776,10 +8878,39 @@ "diffCommentNotesCopyFailed": "Falha ao copiar as notas", "conflictCount_one": "{{count}} conflito", "conflictCount_other": "{{count}} conflitos", - "discardFailedSingular": "Falha ao descartar {{count}} arquivo", - "discardFailedPlural": "Falha ao descartar {{count}} arquivos", - "noteCountSingular": "{{count}} nota", - "noteCountPlural": "{{count}} notas" + "discardFailedSampleMore_one": "{{paths}}, +{{count}} outro", + "discardFailedSampleMore_other": "{{paths}}, +{{count}} outros", + "discardFailed_one": "Falha ao descartar {{count}} arquivo", + "discardFailed_other": "Falha ao descartar {{count}} arquivos", + "discardFailedWithSample": "{{error}} (por exemplo, {{paths}})", + "compareBaseCommitsAhead_one": "{{count}} commit adiante de {{ref}}", + "compareBaseCommitsAhead_other": "{{count}} commits adiante de {{ref}}", + "compareBaseCommitsBehind_one": "{{count}} commit atrás de {{ref}}", + "compareBaseCommitsBehind_other": "{{count}} commits atrás de {{ref}}", + "branchFilesChangedVsBase_one": "{{count}} arquivo alterado em relação a {{ref}}", + "branchFilesChangedVsBase_other": "{{count}} arquivos alterados em relação a {{ref}}", + "noteCount_one": "{{count}} nota", + "noteCount_other": "{{count}} notas", + "comparingAgainstRef": "Comparando com {{ref}}", + "commitsAheadShort_one": "{{count}} adiante", + "commitsAheadShort_other": "{{count}} adiante", + "unresolvedConflictOfKind": "Conflito não resolvido ({{kind}})", + "unresolvedConflict": "Conflito não resolvido", + "locallyResolvedConflictOfKind": "Conflito resolvido localmente ({{kind}})", + "locallyResolvedConflict": "Conflito resolvido localmente", + "pushesToForkTarget": "Envia (push) para o fork {{target}}", + "abortRebaseConfirmTitle": "Abortar rebase?", + "abortMergeConfirmTitle": "Abortar merge?", + "abortRebaseConfirmDescription": "Isso cancela o rebase em andamento e pode descartar as resoluções de conflitos feitas durante este rebase.", + "abortMergeConfirmDescription": "Isso cancela o merge em andamento e pode descartar as resoluções de conflitos feitas durante este merge.", + "abortRebaseFailedFallback": "Não foi possível abortar o rebase", + "abortMergeFailedFallback": "Não foi possível abortar o merge", + "abortRebaseFailed": "Falha ao abortar o rebase", + "abortMergeFailed": "Falha ao abortar o merge", + "clearNotesFromWorkspace_one": "Limpar {{count}} nota deste espaço de trabalho?", + "clearNotesFromWorkspace_other": "Limpar {{count}} notas deste espaço de trabalho?", + "clearNotesFromFile_one": "Limpar {{count}} nota de {{path}}?", + "clearNotesFromFile_other": "Limpar {{count}} notas de {{path}}?" }, "checks": { "panel": { @@ -8803,10 +8934,6 @@ "cbcc4ab3db": "Mostrando as primeiras 100 verificações", "0dca6bfab5": "Abrir detalhes da verificação", "991f50c7e4": "Nenhuma verificação configurada", - "9ad98f2a17": "pendente", - "5e52f4ef7f": "com falha", - "02ca4f9074": "aprovada", - "checksUnresolvedChip": "não resolvido", "checksUnresolvedStripHint": "Estas verificações terminaram sem um veredito de aprovação ou falha.", "e15a8b77ef": "Nenhum detalhe inline está disponível para esta verificação.", "dcb3c546fe": "Tentar novamente", @@ -8825,7 +8952,6 @@ "1f2b980522": "Carregando detalhes da verificação…", "0c96cd25e5": "Resolver", "3a71a6ed0b": "Resolva os conflitos antes que as verificações e o merge possam ser concluídos.", - "60186d8498": "Conflitos bloqueiam isto", "c16762ac8c": "As verificações e comentários abaixo mostram o contexto obtido atual.", "9d0e7bcefc": "Nenhuma ação bloqueante de PR", "5856874b59": "O Orca vai atualizar as verificações enquanto este painel estiver aberto.", @@ -8850,7 +8976,6 @@ "084c516efb": "Copiar comandos", "5dc3af25c0": "Selecionar comentário", "d7a2f9c401": "Enviar {{value0}} comentários não resolvidos", - "d91f2a6c39": "Enviar {{value0}} comentários na fila para a IA", "a6de3e5a20": "Limpar comentários na fila", "f8a2c91d04": "Colocar na fila para o agente", "b4e8a1c902": "Na fila", @@ -8873,7 +8998,28 @@ "pendingChecks_one": "{{count}} verificação pendente", "pendingChecks_other": "{{count}} verificações pendentes", "unresolvedChecks_one": "{{count}} verificação não resolvida", - "unresolvedChecks_other": "{{count}} verificações não resolvidas" + "unresolvedChecks_other": "{{count}} verificações não resolvidas", + "passingCount_one": "{{count}} com sucesso", + "passingCount_other": "{{count}} com sucesso", + "failingCount_one": "{{count}} com falha", + "failingCount_other": "{{count}} com falha", + "pendingCount_one": "{{count}} pendente", + "pendingCount_other": "{{count}} pendentes", + "unresolvedCount_one": "{{count}} não resolvido", + "unresolvedCount_other": "{{count}} não resolvidos", + "sendQueuedCommentsToAi_one": "Enviar {{count}} comentário na fila para a IA", + "sendQueuedCommentsToAi_other": "Enviar {{count}} comentários na fila para a IA", + "conflictsBlockThisMr": "Conflitos bloqueiam este MR", + "conflictsBlockThisPr": "Conflitos bloqueiam este PR", + "copyComment": "Copiar comentário", + "sendComment": "Enviar", + "commentingRequiresGitHubPrTarget": "Para comentar, é necessário um repositório de destino para o PR do GitHub.", + "selectWorkspaceBeforeAiAction": "Selecione um espaço de trabalho antes de iniciar uma ação de IA.", + "operation": { + "rebase": "Rebase", + "merge": "Merge", + "cherryPick": "Cherry-pick" + } }, "empty": { "state": { @@ -9047,10 +9193,10 @@ "dialog": { "3bc61dc989": "Cancelar", "15efa778e3": "Descartar", - "42f89dd030": "arquivos", - "e7611dca35": "arquivo", "0d2d88cba5": "Isso não pode ser desfeito.", - "1551c14668": "Descartar alterações?" + "1551c14668": "Descartar alterações?", + "fileCount_one": "{{count}} arquivo", + "fileCount_other": "{{count}} arquivos" } }, "dropdown": { @@ -9212,8 +9358,8 @@ }, "compare": { "summary": { - "commitsAheadSingular": "{{count}} commit adiante de {{ref}}", - "commitsAheadPlural": "{{count}} commits adiante de {{ref}}" + "commitsAhead_one": "{{count}} commit adiante de {{ref}}", + "commitsAhead_other": "{{count}} commits adiante de {{ref}}" } }, "conflict": { @@ -9263,11 +9409,8 @@ "latestTurns": "Últimos turnos", "noPreviewAvailable": "Nenhuma pré-visualização de conversa disponível", "conversationNotSaved": "Conversa não salva", - "recoverableEmptyDetail": "Esta sessão não tem conversa salva, mas {{value0}} item(ns) recuperável(is) sobrevive(m).", "recoverableEmptyOpenLogHint": "Abra o log para recuperá-los.", "emptyConversationDetail": "Esta sessão não tem conversa salva e não pode ser retomada.", - "queuedMessages": "{{value0}} mensagem(ns) na fila", - "subagentTranscripts": "{{value0}} transcrição(ões) de subagente", "resumeInWorktree": "Retomar em Worktree", "viewLog": "Ver Registro", "unknownTime": "Hora desconhecida", @@ -9296,7 +9439,13 @@ "noFirstPromptAvailable": "Nenhum primeiro prompt disponível", "loadingFirstPrompt": "Carregando primeiro prompt…", "folder": "Pasta", - "resumeInFolder": "Retomar na pasta" + "resumeInFolder": "Retomar na pasta", + "recoverableEmptyDetailCount_one": "Esta sessão não tem conversa salva, mas ainda resta {{count}} item recuperável.", + "recoverableEmptyDetailCount_other": "Esta sessão não tem conversa salva, mas ainda restam {{count}} itens recuperáveis.", + "queuedMessageCount_one": "{{count}} mensagem na fila", + "queuedMessageCount_other": "{{count}} mensagens na fila", + "subagentTranscriptCount_one": "{{count}} transcrição de subagente", + "subagentTranscriptCount_other": "{{count}} transcrições de subagentes" }, "PortsPanel": { "3ea4a02a8f": "Cancelar", @@ -9361,12 +9510,18 @@ "740aca88ab": "Falha na varredura de portas do espaço de trabalho.", "5be4f7f727": "Menu da porta {{value0}}", "1004af16ab": "Copiar {{value0}}", - "153d3a8026": "Host do espaço de trabalho desconhecido" + "153d3a8026": "Host do espaço de trabalho desconhecido", + "unknownProcess": "Processo desconhecido", + "containerOrForwardedService": "Contêiner ou serviço encaminhado", + "unassigned": "Não atribuído", + "remotePortOutOfRange": "A porta remota deve estar no intervalo 1–65535", + "localPortOutOfRange": "A porta local deve estar no intervalo 1–65535", + "localPortInUse": "A porta {{port}} já está em uso. Escolha outra porta local.", + "localPortRequiresPrivileges": "A porta {{port}} exige privilégios elevados. Use uma porta local ≥ 1024." }, "ChecksPanel": { "2ef90c9819": "Foi iniciado um agente de IA para as verificações com falha.", "a0181a8d76": "Foi iniciado um agente de IA para os conflitos.", - "34464d00b9": "atualizado", "058039787c": "Cancelar", "2ab7fd4b6d": "Salvar", "dda5924a40": "As verificações exigem uma branch Git e um contexto de review hospedado", @@ -9412,7 +9567,8 @@ "430f1a62d4": "Não foi possível resolver a thread selecionada no host.", "updateReactionFailed": "Falha ao atualizar a reação.", "gitlabMoreActions": "Mais ações de MR", - "gitlabLinkAnother": "Vincular outro MR" + "gitlabLinkAnother": "Vincular outro MR", + "reviewUpdatedAt": "{{review}} atualizado {{time}}" }, "FileExplorerRow": { "addc01145f": "Excluir", @@ -9458,7 +9614,6 @@ "refreshSessionHistory": "Atualizar Histórico de Sessões", "searchSessions": "Buscar sessões", "clearSearch": "Limpar busca", - "transcriptsSkipped": "{{count}} transcrição ignorada", "noAgentSessionsFound": "Nenhuma sessão de agente encontrada", "noSessionsMatchFilters": "Nenhuma sessão corresponde aos filtros atuais", "noAgentsSelected": "Nenhum agente selecionado", @@ -9477,7 +9632,9 @@ "resumeInChatFailed": "Não foi possível retomar esta sessão em um novo chat.", "resumeInNewCliUnavailable": "Esta sessão não pode ser aberta na CLI.", "resumeInNewCliHostTooOld": "Atualize o Orca no host que executa este chat para retomá-lo em uma nova CLI.", - "folderWorkspaceUnavailable": "O espaço de trabalho de pasta não está mais disponível." + "folderWorkspaceUnavailable": "O espaço de trabalho de pasta não está mais disponível.", + "transcriptsSkippedCount_one": "{{count}} transcrição ignorada", + "transcriptsSkippedCount_other": "{{count}} transcrições ignoradas" }, "AiVaultSessionRow": { "noPreviewAvailable": "Nenhuma pré-visualização de conversa disponível", @@ -9600,26 +9757,26 @@ "confirmation": { "84f6f5b9eb": "Incluídos: {{numbers}}. ", "541984b2eb": "Colocar na fila até #{{pr}}?", - "4809f55cdb": "{{included}}O GitHub vai adicionar {{count}} pull request à fila de merge junto. A fila escolhe o método de merge e pode mergeá-los em grupos separados.", - "be8f2621be": "{{included}}O GitHub vai adicionar {{count}} pull requests à fila de merge juntos. A fila escolhe o método de merge e pode mergeá-los em grupos separados.", - "92ca033e72": "Colocar {{count}} PR na Fila", - "478a527b15": "Colocar {{count}} PRs na Fila", "1feef35ca4": "Fazer merge até #{{pr}}?", - "c3e036c99f": "{{included}}O GitHub vai mergear {{count}} pull request atomicamente usando {{method}}. Se não conseguir mergear, nada será mergeado.", - "369aba4b32": "{{included}}O GitHub vai mergear {{count}} pull requests atomicamente usando {{method}}. Se algum não conseguir mergear, nenhum será mergeado.", - "493c78f521": "Mergear {{count}} PR", - "eb7051d268": "Mergear {{count}} PRs" + "queueDescription_one": "{{included}}O GitHub vai adicionar {{count}} pull request à fila de merge. A fila escolhe o método de merge e pode mergear os pull requests em grupos separados.", + "queueDescription_other": "{{included}}O GitHub vai adicionar {{count}} pull requests juntos à fila de merge. A fila escolhe o método de merge e pode mergeá-los em grupos separados.", + "queueConfirm_one": "Colocar {{count}} PR na fila", + "queueConfirm_other": "Colocar {{count}} PRs na fila", + "mergeDescription_one": "{{included}}O GitHub vai mergear {{count}} pull request atomicamente usando {{method}}. Se não for possível mergeá-lo, nada será mergeado.", + "mergeDescription_other": "{{included}}O GitHub vai mergear {{count}} pull requests atomicamente usando {{method}}. Se algum não puder ser mergeado, nenhum será mergeado.", + "mergeConfirm_one": "Mergear {{count}} PR", + "mergeConfirm_other": "Mergear {{count}} PRs" }, "merge": { - "55ae29b907": "Merge até #{{pr}} · {{count}} PR", - "b8446f6ec2": "Merge até #{{pr}} · {{count}} PRs", "189d0ec614": "#{{pr}} ainda é um rascunho.", "640fb50d9c": "#{{pr}} está fechado.", "46ffcbda75": "#{{pr}} tem conflitos de merge.", "6dabefd63e": "#{{pr}} tem alterações solicitadas.", "2bb21fc326": "#{{pr}} ainda precisa de aprovação de review.", "c23faf74df": "#{{pr}} precisa ser atualizado.", - "f561e80968": "#{{pr}} está bloqueado." + "f561e80968": "#{{pr}} está bloqueado.", + "mergeThroughLabel_one": "Mergear até #{{pr}} inclusive · {{count}} PR", + "mergeThroughLabel_other": "Mergear até #{{pr}} inclusive · {{count}} PRs" } } } @@ -9699,16 +9856,21 @@ "525259fa17": "Os detalhes da pilha estão temporariamente indisponíveis." }, "useFileDeletion": { - "72691dfebc": "Falha ao {{value0}} '{{value1}}'.", "d979a4fbb5": "Excluir '{{value0}}' permanentemente?", "92276aceb7": "Excluir", "7fb9435c86": "Isso exclui permanentemente o diretório e seu conteúdo no host remoto. Isso não pode ser desfeito.", "23e98f192f": "Isso exclui permanentemente o arquivo no host remoto. Isso não pode ser desfeito.", "8b8ee9d22f": "Não foi possível determinar qual host possui este arquivo. Verifique a conexão do espaço de trabalho e tente novamente.", - "af1270b90d": "Excluir {{count}} itens permanentemente?", "dd029aa5cd": "Isso exclui permanentemente os itens selecionados e qualquer conteúdo de diretório no host remoto. Isso não pode ser desfeito.", - "77fdc36183": "Excluir {{count}} itens?", - "fca915a67a": "Itens remotos são excluídos permanentemente e não podem ser desfeitos. Itens locais são movidos para {{value0}}." + "deleteFailed": "Falha ao excluir '{{name}}'.", + "deleteItems_one": "Excluir {{count}} item?", + "deleteItems_other": "Excluir {{count}} itens?", + "mixedRecycleBin": "Os itens remotos são excluídos permanentemente, e isso não pode ser desfeito. Os itens locais são movidos para a Lixeira.", + "mixedTrash": "Os itens remotos são excluídos permanentemente, e isso não pode ser desfeito. Os itens locais são movidos para a Lixeira.", + "permanentlyDeleteItems_one": "Excluir {{count}} item permanentemente?", + "permanentlyDeleteItems_other": "Excluir {{count}} itens permanentemente?", + "recycleBinFailed": "Não foi possível mover '{{name}}' para a Lixeira.", + "trashFailed": "Não foi possível mover '{{name}}' para a Lixeira." }, "GitHistoryPanel": { "cf7cad58d2": "Ainda sem commits", @@ -9813,7 +9975,11 @@ "c075d00de1": "Não foi possível resolver a conexão do espaço de trabalho.", "38b899cc02": "Todos os repositórios", "808cfe0a3b": "Este repositório", - "994cddd1f7": "Não salvar" + "994cddd1f7": "Não salvar", + "agentNotEnabledOrDetected": "{{agent}} não está habilitado ou não foi detectado no host deste espaço de trabalho.", + "workspaceConnectionUnresolved": "Não foi possível identificar a conexão do espaço de trabalho.", + "noEnabledAgentsDetected": "Nenhum agente habilitado foi detectado no host deste espaço de trabalho.", + "startAgent": "Iniciar agente" }, "FileExplorer": { "79b1537dd3": "Selecione um espaço de trabalho para navegar pelos arquivos", @@ -9884,9 +10050,10 @@ "sourceActionsUnavailable": "A fonte da transcrição não está disponível." }, "BulkActionBar": { - "79a9f5f712": "Remover do Stage (", - "ef5f5bd06e": "Stage (", - "60ed678138": "selecionado(s)" + "selectedCount_one": "{{count}} selecionado", + "selectedCount_other": "{{count}} selecionados", + "stageCount": "Adicionar ao stage ({{count}})", + "unstageCount": "Remover do stage ({{count}})" }, "AiVaultSessionDeleteDialog": { "title": "Excluir esta sessão?", @@ -9961,8 +10128,11 @@ } }, "useFileExplorerImport": { - "25919b2050": "{{value0}} {{value1}} ignorado(s).", - "132fd0e1e9": "Falha ao importar {{value0}} {{value1}}." + "importFailedCount_one": "Falha ao importar {{count}} arquivo.", + "importFailedCount_other": "Falha ao importar {{count}} arquivos.", + "importSkippedCount_one": "{{count}} arquivo ignorado.", + "importSkippedCount_other": "{{count}} arquivos ignorados.", + "importFailed": "Falha ao importar arquivos." }, "GitHistoryRow": { "2f9c41ab07": "Mostrar arquivos no commit {{value0}}: {{value1}}", @@ -9994,8 +10164,9 @@ "databaseCount_other": "{{value0}} bancos de dados", "scanning": "Verificando {{value0}}", "scanned": "Verificação concluída: {{value0}}", - "agentChecked": "{{agent}}: {{settled}} de {{total}} candidatos do histórico verificados", - "checking": "Verificando {{value0}}" + "checking": "Verificando {{value0}}", + "agentCheckedCount_one": "{{agent}}: {{settled}} de {{total}} candidato do histórico verificado", + "agentCheckedCount_other": "{{agent}}: {{settled}} de {{total}} candidatos do histórico verificados" }, "run": { "source": { @@ -10024,6 +10195,15 @@ } } } + }, + "fileExplorerMultiDrag": { + "moreItems_one": "+{{count}} outro", + "moreItems_other": "+{{count}} outros" + }, + "CreatePullRequest": { + "createInProgress": "Criação do PR em andamento...", + "workspaceHostUnresolved": "Não foi possível resolver o host do espaço de trabalho. Atualize o espaço de trabalho e tente novamente.", + "branchDiscoveryFailed": "Falha na detecção de branches." } } }, @@ -10618,12 +10798,10 @@ "oneWorkspace": "1 espaço de trabalho", "manyWorkspaces": "{{count}} espaços de trabalho", "hostHasWorkspacesDefault": "Remove {{value0}} e suas credenciais deste computador. Seus(Suas) {{value1}} permanecem no Orca — os arquivos remotos não são tocados.", - "alsoDeleteRemote": "Também excluir estes(as) {{value0}} em {{value1}}", "alsoForgetLocal": "Também remover estes(as) {{value0}} do Orca", "advanced": "Avançado", - "alsoDeleteRemoteHint": "Exclui permanentemente as worktrees Git remotas e suas branches. Não pode ser desfeito.", "alsoForgetLocalHint": "Limpa-os apenas do Orca. Os arquivos, worktrees e branches remotos permanecem intocados.", - "wslHostEndsTerminals": "Remove {{value0}} do Orca, encerra os terminais abertos e interrompe o servidor Orca nessa distribuição. Os arquivos da distribuição não são alterados." + "wslHostEndsTerminalsUnlessShared": "Remove {{value0}} do Orca. A menos que outro Orca aberto neste computador o esteja usando, também encerra seus terminais abertos e para o servidor do Orca nessa distro. Os arquivos da distro não são alterados." }, "AddRepoSteps": { "569326d9cc": "Escolher pasta", @@ -10934,14 +11112,9 @@ "6c07f3a91e": "{{value0}} em {{value1}}" }, "ForgetSshWorkspaceDialog": { - "reconnectFailed": "Falha na reconexão", - "forgetBody": "Remove este espaço de trabalho apenas do Orca. Os arquivos, a worktree Git e as branches em {{host}} permanecem intocados.", - "title": "Excluir “{{name}}”?", - "disconnectedBody": "O host SSH deste espaço de trabalho não está conectado. Reconecte para excluí-lo também no remoto, ou remova-o somente do Orca.", "ghostBody": "{{host}} não é mais um host SSH salvo, então este espaço de trabalho não está mais conectado a um host ativo. Ele só pode ser removido do Orca — os arquivos e branches no remoto permanecem intocados.", "cancel": "Cancelar", - "forget": "Remover do Orca", - "reconnectAndDelete": "Reconectar e Excluir" + "forget": "Remover do Orca" }, "RepoScanUnavailableIndicator": { "title": "Falha na varredura de worktree para {{value0}}", @@ -11221,7 +11394,9 @@ }, "sidebarHostOptions": { "3e102f111c": "Todos os hosts", - "visibleHostsCount": "{{value0}} hosts" + "hosts": "Hosts", + "visibleHosts_one": "{{count}} host", + "visibleHosts_other": "{{count}} hosts" }, "SshTargetRow": { "4677394048": "Conectando…", @@ -11336,7 +11511,7 @@ "running": "Em execução", "stopped": "Parada", "title": "Adicionar distribuição WSL", - "description": "O Orca executa seu servidor dentro da distribuição, para que git, arquivos e terminais funcionem nativamente no Linux. Use para novos projetos; os projetos que você abriu por \\\\wsl.localhost continuam funcionando como estão.", + "description": "O Orca executa seu servidor dentro da distribuição, para que git, arquivos e terminais funcionem nativamente no Linux. Os projetos desta distribuição que você abriu por \\\\wsl.localhost são movidos automaticamente para este host quando seus terminais ficam ociosos; projetos em uma unidade do Windows (/mnt/…) permanecem neste computador. Você pode trazer de volta um projeto movido pela barra lateral.", "distro": "Distribuição", "loading": "Procurando distribuições WSL…", "placeholder": "Escolha uma distribuição", @@ -11363,6 +11538,7 @@ "removalPending": "A remoção não foi concluída" }, "wslHostRemoval": { + "keptForOthers": "Removido deste Orca. O host continua em execução para {{value0}}.", "partial": "O host foi removido, mas algo na distribuição ainda está em execução: {{value0}}", "pending": "O Orca ainda não removeu o host: {{value0}} Remova-o novamente para tentar de novo, ou conecte-o para mantê-lo." }, @@ -11740,17 +11916,14 @@ "ConflictComponents": { "f338288514": "Carregando conteúdo do conflito...", "90d576adb2": "Atualizar", - "a1ce36f77d": "Snapshot capturado em", "c8ca989aea": "Mostrar árvore de arquivos", "58ad5ad431": "Descartar", "28e7db4a90": "Controle de Código-Fonte", "31931dec46": "Este snapshot de revisão não tem mais conflitos não resolvidos ativos.", "992145ff5a": "Todos os conflitos resolvidos", - "d5edd81755": "Renomeado de", "6e459867ad": "Estado de continuidade local da sessão. O Git não está mais reportando este arquivo como não mesclado.", "9c2901ef8a": "Próximo conflito", "41d9af2e7a": "Conflito anterior", - "55d61a0ccd": "conflito ·", "da539359b6": "Nenhum arquivo da working tree está disponível para edição neste conflito.", "unresolvedConflicts_one": "{{count}} conflito não resolvido", "unresolvedConflicts_other": "{{count}} conflitos não resolvidos" @@ -12631,11 +12804,8 @@ "2faecab10b": "Executar Agora", "13118faadf": "Projeto desconhecido", "73f630b49d": "Cancelar", - "1b586f0e2b": "em", - "02a33e3204": "de", "9adfab2596": "Excluir Automação Externa", "1e2e41392f": "Não perguntar novamente", - "b264564427": "e seu histórico de execução. Espaços de trabalho criados por execuções anteriores não são excluídos.", "080dcb5fbb": "Excluir Automação", "19a6e30eae": "Atualizar automações", "77c2778945": "Automações", @@ -12670,7 +12840,6 @@ "pendingAutomationRunMissing": "Histórico de execução não está mais disponível.", "paused": "Pausada", "missingWorkspace": "Espaço de trabalho faltando", - "runUsageSummary": "{{cost}} estimados · {{tokens}} tokens", "usageUnavailable": "Uso indisponível", "noRunUsageYet": "Ainda sem uso de execução", "noWorkspace": "Nenhum espaço de trabalho", @@ -12685,7 +12854,11 @@ "rowActions": "Ações da automação", "tableLastRun": "Última execução", "ownerChanged": "Esta automação mudou de host. Atualize e tente novamente.", - "runError": "Erro:" + "runError": "Erro:", + "deleteAutomationDescription": "Excluir e seu histórico de execuções. Os espaços de trabalho criados por execuções anteriores não serão excluídos.", + "deleteExternalAutomationDescription": "Excluir de em .", + "runUsageSummaryTokens_one": "{{cost}} (est.) · {{tokens}} token", + "runUsageSummaryTokens_other": "{{cost}} (est.) · {{tokens}} tokens" }, "hostStatus": { "authority": { @@ -12764,7 +12937,8 @@ "last": { "run": { "done": "Concluído", - "failed": "Falhou" + "failed": "Falhou", + "statusWithRelative": "{{status}} · {{relative}}" } } }, @@ -12803,7 +12977,21 @@ "b09b2384fd": "Pausada", "eaa02014f8": "Habilitada", "29baf8f4c2": "Origem", - "lastRunFailed": "A última execução falhou." + "lastRunFailed": "A última execução falhou.", + "noGrace": "Sem tolerância", + "graceMinutes_one": "{{count}} minuto", + "graceMinutes_other": "{{count}} minutos", + "graceHours_one": "{{count}} hora", + "graceHours_other": "{{count}} horas", + "usageCoverageRuns_one": "{{known}}/{{count}} execução", + "usageCoverageRuns_other": "{{known}}/{{count}} execuções", + "usageUnavailable": "Indisponível", + "noRuns": "Nenhuma execução", + "projectDefault": "Padrão do projeto", + "reuseLiveSession": "Reutilizar sessão ativa", + "freshEachRun": "Nova a cada execução", + "precheckEnabled": "Ativada, {{timeout}}", + "precheckNone": "Nenhuma" }, "ExternalAutomationManagers": { "e02f970595": "Nenhum gerenciador de automação externa encontrado.", @@ -12822,8 +13010,8 @@ "92405f1431": "Indisponível", "dbdcec22bd": "Somente leitura", "0a2d4359a8": "Gerenciável", - "e2532150ed": "automações", - "701515f010": "automação" + "automationCount_one": "{{count}} automação", + "automationCount_other": "{{count}} automações" }, "AutomationRunsDashboard": { "search": "Buscar execuções…", @@ -13024,7 +13212,8 @@ }, "externalScope": { "uncheckedHost": "Os gerenciadores de automação externa em {{hostLabel}} não puderam ser verificados.", - "uncheckedHosts": "Os gerenciadores de automação externa em {{count}} hosts não puderam ser verificados." + "uncheckedHostCount_one": "Não foi possível verificar os gerenciadores de automações externos em {{count}} host.", + "uncheckedHostCount_other": "Não foi possível verificar os gerenciadores de automações externos em {{count}} hosts." }, "AutomationPromptDisclosure": { "showLess": "Mostrar menos", @@ -13046,10 +13235,6 @@ "orphan": "Esta automação não tem host para ser executada. Exclua-a, ou adicione novamente o host ao qual ela pertence.", "unfenced": "O Orca neste host precisa de uma atualização antes que você possa ver o histórico de execução ou gerenciar esta automação. As execuções programadas podem continuar no host." }, - "runHistory": { - "occurrencesWithLatest": "{{times}} vezes, mais recentemente {{date}}", - "occurrences": "{{times}} vezes" - }, "AutomationsPageBreadcrumb": { "ariaLabel": "Trilha de navegação de automações", "runDetails": "Detalhes da execução" @@ -13096,12 +13281,76 @@ "useFreshSessions": "Usar novas sessões", "helper": "Adicionados aos argumentos padrão deste host a cada nova sessão.", "detailLabel": "Argumentos extras" + }, + "runHistory": { + "runCountSummary_one": "{{count}} execução · concluídas: {{completed}}", + "runCountSummary_other": "{{count}} execuções · concluídas: {{completed}}", + "occurrencesWithLatestCount_one": "{{count}} vez, mais recentemente em {{date}}", + "occurrencesWithLatestCount_other": "{{count}} vezes, mais recentemente em {{date}}", + "occurrencesCount_one": "{{count}} vez", + "occurrencesCount_other": "{{count}} vezes" + }, + "capabilityProbe": { + "createIdempotencyUpdateRequired": "Mover automações para este host exige um servidor Orca mais recente. Atualize o HUB e tente novamente." + }, + "editDraft": { + "unsupportedSchedule": "Esta automação tem um agendamento salvo não compatível. Escolha um agendamento compatível antes de salvar as alterações." + }, + "hostCatalog": { + "orphanEntryLabel": "Automações antigas não atribuídas" + }, + "automationPageParts": { + "never": "Nunca", + "now": "agora mesmo", + "runStatusPending": "Na fila", + "runStatusDispatching": "Iniciando", + "runStatusDispatched": "Iniciada", + "runStatusCompleted": "Concluída", + "runStatusSkippedPrecheck": "Ignorada pela pré-verificação", + "runStatusSkippedMissed": "Ignorada", + "runStatusSkippedUnavailable": "Indisponível", + "runStatusSkippedNeedsInteractiveAuth": "Requer credenciais", + "runStatusDispatchFailed": "Falhou" + }, + "runContent": { + "noOutput": "Nenhum conteúdo de saída disponível." + }, + "runViewState": { + "viewRun": "Ver execução", + "runOpen": "A execução está aberta", + "terminalOnPairedServer": "O terminal da execução está no servidor pareado.", + "terminalUnavailable": "O terminal da execução está indisponível.", + "openWorkspace": "Abrir espaço de trabalho", + "workspaceAvailable": "O espaço de trabalho está disponível.", + "snapshotSaved": "Snapshot salvo", + "showingSnapshot": "Exibindo o snapshot salvo da execução.", + "namedWorkspaceGone": "{{name}} não está mais disponível", + "workspaceGone": "O espaço de trabalho não está mais disponível", + "noWorkspaceLaunched": "Nenhum espaço de trabalho iniciado" + }, + "runWorkspaceDisplay": { + "notLaunched": "Não iniciado", + "namedWorkspaceGone": "{{name}} (não está mais disponível)" + }, + "usage": { + "tokensAndCost_one": "{{tokens}} token · {{cost}}", + "tokensAndCost_other": "{{tokens}} tokens · {{cost}}" + }, + "externalDisplay": { + "sshHost": "Host SSH", + "local": "Local" + }, + "externalActionDisabled": { + "actionInProgress": "Outra ação de automação ainda está em execução.", + "sshConnecting": "Aguarde a conclusão da conexão deste host SSH.", + "connectSshHost": "Conecte este host SSH antes de gerenciar automações de {{provider}}.", + "cannotManageOnSshHost": "{{provider}} não pode gerenciar automações neste host SSH.", + "cannotManageLocally": "{{provider}} não pode gerenciar automações nesta máquina." } }, "TaskPage": { "ff69a30681": "Cancelar", "8ff6fdc368": "Criando…", - "fc0d8a1fa4": "para enviar.", "919a20dd5b": "Digite {{value0}}", "56cdb413a2": "Valores separados por vírgula", "1f0fce91e3": "Selecione {{value0}}", @@ -13149,14 +13398,9 @@ "bdebffcbfe": "Crie um projeto do Linear para a equipe selecionada.", "1361275ec3": "Novo projeto do Linear", "7f3f7b4c18": "Descrição (opcional, markdown)", - "9f2b4c03a6": "Registrando em", "d3d0998b7d": "Nova issue do GitHub", - "d1e243795c": "issues", - "be8cf68d9f": "ver issues", - "67662ade50": "issues do projeto", "6244a02f46": "Abrir no Linear", "606a85c774": "Abrir", - "5e8061b088": "Iniciar espaço de trabalho a partir de {{value0}} {{value1}}", "592a55611b": "Tente selecionar mais equipes ou atualizar; os filtros de equipe se aplicam ao conjunto de issues já buscado.", "618107fab3": "Nenhuma issue buscada corresponde às equipes selecionadas", "903c7af49f": "Nenhuma issue do Linear encontrada", @@ -13165,7 +13409,6 @@ "f362667d55": "Atualizado", "b1eaa18ace": "Issue", "37e7ee311e": "Chave", - "b7bae28b6a": "exibido(s)", "a26a48252e": "Propriedades de exibição", "5d2d835467": "Ordenação", "5659da12fc": "Agrupamento", @@ -13173,11 +13416,9 @@ "af377b13b1": "Visualização de {{value0}}", "d47248df4d": "Modo de visualização do Linear", "f397d513e3": "Voltar", - "b39fe6511d": "projetos", "8675cd6188": "Linear", "733b8f2421": "Linear / Visualizações", "bc06ed0fb0": "Voltar para visualizações", - "3cb855080f": "visualizações", "b4e10f096e": "Proprietário", "a04fe7ba73": "Visibilidade", "0aa8525950": "Modelo", @@ -13205,8 +13446,6 @@ "054bf695cc": "Rascunho", "5b6b2af943": "Tentando novamente…", "0c0de0fc0e": "Não foi possível carregar issues de", - "d1766fd62d": "projetos falharam ao carregar", - "7762f4b03a": "de", "443f7dd928": "Merge", "a7396b05c6": "Verificações", "f6fa3c97d0": "Revisores", @@ -13390,10 +13629,41 @@ "jiraColumnOriginalEstimate": "Estimativa", "jiraColumnRemainingEstimate": "Restante", "jiraBoardEmptyColumn": "Nenhuma issue", - "labelCountPlural": "{{count}} rótulos", - "labelCountSingular": "{{count}} rótulo", - "memberCountPlural": "{{count}} membros", - "memberCountSingular": "{{count}} membro" + "backToPullRequests": "Pull requests", + "backToGitHubList": "Lista do GitHub", + "noGitHubRepositoryContext": "Nenhum contexto de repositório do GitHub disponível para esta issue.", + "filingInTarget": "Será criada em {{target}}", + "filingInThisRepository": "Será criada neste repositório", + "shortcutToSubmit": "{{shortcut}} para enviar.", + "projectsFailedToLoad_one": "Falha ao carregar {{failed}} de {{count}} projeto", + "projectsFailedToLoad_other": "Falha ao carregar {{failed}} de {{count}} projetos", + "draftPullRequestNumber": "Rascunho de pull request #{{number}}", + "pullRequestNumber": "Pull request #{{number}}", + "issueNumber": "Issue #{{number}}", + "loadGitHubWorkFailed": "Falha ao carregar o trabalho do GitHub.", + "gitlabViewIssues": "Issues", + "gitlabViewMrs": "MRs", + "gitlabViewTodos": "Minhas tarefas", + "startWorkspaceFromMr": "Iniciar espaço de trabalho a partir da MR {{number}}", + "startWorkspaceFromIssue": "Iniciar espaço de trabalho a partir da issue {{number}}", + "shownCount_one": "{{count}} exibido", + "shownCount_other": "{{count}} exibidos", + "linearProjectPlaceholder": "Projeto", + "labelCount_one": "{{count}} rótulo", + "labelCount_other": "{{count}} rótulos", + "memberCount_one": "{{count}} membro", + "memberCount_other": "{{count}} membros", + "groupUnassigned": "Não atribuído", + "linearProjectContext": "Projeto: {{name}}", + "linearViewContext": "Visualização: {{name}}", + "changedFileCount_one": "{{count}} arquivo", + "changedFileCount_other": "{{count}} arquivos", + "resumeRestoration": { + "linearProjectNotFound": "O projeto do Linear salvo não foi encontrado.", + "linearProjectRestoreFailed": "Falha ao restaurar o projeto do Linear salvo.", + "linearViewNotFound": "A visualização do Linear salva não foi encontrada.", + "linearViewRestoreFailed": "Falha ao restaurar a visualização do Linear salva." + } }, "feature": { "wall": { @@ -13598,13 +13868,13 @@ "9ee54037a4": "Comando personalizado", "4b2fc4b80c": "Esforço de raciocínio", "be8917699e": "Modelo", - "4d9b6d84df": "não suportado. Escolha Claude, Codex, ou Personalizado.", "560d4feb00": "Personalizado", "29d119fe95": "Agente", "f9382b48a1": "Ativar autor de IA", "1c0cb4fabb": "Autor de IA", "bd14e9c42a": "Não configurado", - "1f9468c5c9": "{{value0}} não suportado" + "1f9468c5c9": "{{value0}} não suportado", + "unsupportedAgent": "{{agent}} não é suportado. Escolha Claude, Codex ou Personalizado." }, "ConnectIntegrationsList": { "3dddb2d565": "conectado para tarefas", @@ -14072,10 +14342,7 @@ }, "UsageBreakdownSection": { "7765a4c3e1": "n/d", - "247c93ca92": "• preço inferido", - "32176e1d44": "turnos", - "79a69522a5": "eventos", - "02a046792e": "sessões •" + "247c93ca92": "• preço inferido" }, "MuseUsagePane": { "title": "Acompanhamento de uso do Muse", @@ -14286,7 +14553,8 @@ "8f6cb3772f": "Mergear este pull request automaticamente quando os requisitos forem atendidos", "def355ff38": "Pode ser mergeado", "e42c5bae67": "O GitHub diz que este PR pode ser mergeado e as verificações passaram", - "cbf0113af6": "O GitHub diz que este PR pode ser mergeado" + "cbf0113af6": "O GitHub diz que este PR pode ser mergeado", + "autoMergeOn": "Merge automático ativado" } } }, @@ -14298,7 +14566,6 @@ "458ea3602b": "Nenhum autor", "b69fa4fa20": "Voltar", "30ebb6ca44": "Limpar todos os filtros", - "8177eda37e": "Filtro", "ea3416d646": "Responsável", "b1d9fdea08": "Rótulo", "24754c44ad": "Autor", @@ -14310,7 +14577,15 @@ "2b2f019091": "Qualquer estado", "0fd3249e2e": "Fechado", "d78b60b5c2": "Aberto", - "bd162b7d5a": "Mergeado" + "bd162b7d5a": "Mergeado", + "draft": "Rascunho", + "labelCount_one": "{{count}} rótulo", + "labelCount_other": "{{count}} rótulos", + "allStates": "Todos", + "filterPullRequests": "Filtrar pull requests", + "filterIssues": "Filtrar issues", + "filterOrTypeLogin": "Filtrar ou digitar um login...", + "filterLabels": "Filtrar rótulos..." }, "github": { "rate": { @@ -14321,15 +14596,14 @@ "d12d3d6f33": "Atualizar orçamento da API do GitHub", "d5e5de9070": "O Orca usa REST, Search e GraphQL através da CLI do GitHub.", "58c5f88216": "Orçamento da API do GitHub", - "6da1858354": "restante · redefine em", - "f42790d150": "de", "01f7323e58": "API GraphQL", "1daf0f22a9": "GraphQL", "1f2f28a4de": "API Search", "c377a4f06a": "Search", "c392c749a6": "API REST", "bb227706a6": "REST", - "budget_scope_prefix": "Escopo do orçamento" + "budget_scope_prefix": "Escopo do orçamento", + "remainingOfLimitResetsIn": "Restante: {{remaining}} de {{limit}} · redefinição em {{reset}}" } } } @@ -14353,23 +14627,51 @@ "01f3f3d161": "Autor", "13b3ac0a84": "Status", "79c54552f7": "Filtros", - "8a2ffbf9b3": "Remover filtro de {{value0}}" + "8a2ffbf9b3": "Remover filtro de {{value0}}", + "anyState": "Qualquer", + "currentUser": "Usuário atual" }, "IssueSourceSelector": { - "d6aeb2012b": "Mostrando issues de", "787c970baf": "Origem da issue", "51d1608920": "Origin", - "30b2c9df91": "Upstream" + "30b2c9df91": "Upstream", + "showingIssuesFromRepo": "Mostrando issues de " }, "PRFilterPickers": { - "fdf387297c": "Limpar (", "472c12ae03": "Limpar", - "2d1f58eda6": "Usar" + "pressEnterToUseValue": "Pressione Enter para usar o valor digitado.", + "useTypedValue": "Usar ", + "clearSelected": "Limpar ({{count}})", + "loading": "Carregando…", + "searchTextTooLarge": "O texto de busca é muito grande.", + "noMatches": "Nenhuma correspondência" }, "CommentReactions": { "addReaction": "Adicionar reação", "removeNamedReaction": "Remover reação {{value0}}", - "addNamedReaction": "Adicionar reação {{value0}}" + "addNamedReaction": "Adicionar reação {{value0}}", + "reaction": { + "thumbsUp": "polegar para cima", + "thumbsDown": "polegar para baixo", + "laugh": "risada", + "confused": "confusão", + "heart": "coração", + "hooray": "viva", + "rocket": "foguete", + "eyes": "olhos" + } + }, + "CommentCodeContext": { + "showSurroundingCodeBlock": "Mostrar bloco de código ao redor", + "showNearbyCodeContext": "Mostrar contexto de código próximo" + }, + "prCheckPresentation": { + "successful": "Bem-sucedido", + "inProgress": "Em andamento" + }, + "IssueSourceIndicator": { + "issueFromRepo": "Issue de ", + "issuesFromRepo": "Issues de " } }, "GitHubItemDialog": { @@ -14382,9 +14684,6 @@ "3fdf777817": "Abrir no GitHub", "c43fe79ee0": "Copiar link do GitHub", "0caac1a18f": "Iniciar espaço de trabalho a partir do PR", - "8223320f8d": "atualizado", - "10ef1afb8e": "· atualizado", - "55962099bc": "abriu esta issue", "0ab4664a8b": "Iniciar espaço de trabalho a partir da issue", "36182aa57f": "Iniciar novo espaço de trabalho", "fe6ff12dc2": "Mais ações de espaço de trabalho da issue", @@ -14457,8 +14756,6 @@ "52b20b56f7": "Descrição", "4d555d3796": "Editar descrição", "9df4e74bdf": "Salvar", - "0ae387d8ca": "por", - "228e2f59d3": "Resolvido", "a154ec5224": "Abrir comentário no GitHub", "bca8eb39ac": "Responder ao comentário", "68cb993d61": "resolvido", @@ -14474,13 +14771,11 @@ "d43736d09c": "Controles de contexto do código", "bd7be7b1fd": "comentário L", "db61d76cd5": "Carregando contexto do código…", - "f2d02cdf8c": "arquivos visualizados", "1257d1435d": "Mostrar árvore de arquivos", "a341343303": "Comentário de revisão adicionado.", "d1fa2cf888": "Não é possível comentar sem o SHA head do PR.", "829674460a": "O diff não está disponível porque os SHAs de commit do PR estão faltando.", "af924014f8": "Visualizado", - "2d89a38d9d": "{{value0}} {{value1}} como visualizado", "70e84e3d0b": "Nenhum revisor correspondente.", "1ffce94a8b": "Todos os outros", "c2b21818e1": "Sugestões", @@ -14515,8 +14810,6 @@ "ec5c4b3ab2": "Reabrir PR", "21860b58d0": "Fechar pull request", "5932578f51": "O merge requer um repositório local registrado", - "e2bf3e41a9": "comentário", - "28d0d3374f": "thread", "080d071d48": "Responder a @{{value0}}", "86f809e2ce": "Responder nesta thread de revisão", "136542c9ba": ":L{{value0}}", @@ -14546,7 +14839,9 @@ "from": "de", "to": "para", "activity": "Atividade", - "noActivity": "Ainda sem atividade." + "noActivity": "Ainda sem atividade.", + "pullRequestReference": "PR #{{number}}", + "issueReference": "issue #{{number}}" }, "checkActionRequiredHint": "Precisa de uma ação manual no GitHub (por exemplo, aprovar a execução) para liberar o merge.", "e15a8b77ef": "Nenhum detalhe inline está disponível para esta verificação.", @@ -14560,8 +14855,15 @@ "09d67a0f9b": "Falha ao fechar o pull request", "88809e79db": "Falha ao reabrir o pull request", "00f55cc17b": "O acesso ao repositório não está disponível para este pull request.", - "reactionCountSingular": "{{count}} {{reaction}} reação", - "reactionCountPlural": "{{count}} {{reaction}} reações" + "reactionCount_one": "{{count}} reação de {{reaction}}", + "reactionCount_other": "{{count}} reações de {{reaction}}", + "filesViewed_one": "{{viewed}} / {{count}} arquivo visualizado", + "filesViewed_other": "{{viewed}} / {{count}} arquivos visualizados", + "updatedRelativeTime": "atualizado {{time}}", + "authorOpenedThisIssue": " abriu esta issue", + "middotUpdatedRelativeTime": "· atualizado {{time}}", + "resolvedThreadBy": "Thread resolvida de {{author}}", + "resolvedCommentBy": "Comentário resolvido de {{author}}" }, "terminal": { "pane": { @@ -15225,9 +15527,6 @@ "778683ec84": "Descrição", "da9aaa8bcf": "Editar descrição", "4a337ac05f": "Salvar", - "169a93b29a": "atualizado", - "3c891789f6": "por", - "f4fe47c2bb": "Resolvido", "0ac19bb52e": "Abrir comentário no GitHub", "d6c6679de7": "Responder ao comentário", "76b2a0ac5b": "resolvido", @@ -15235,7 +15534,6 @@ "6885c619e7": "Não é possível responder sem um caminho de repositório.", "d94810f652": "Falha ao atualizar a descrição.", "9b4190dc98": "Descrição atualizada.", - "89e80af1c7": "arquivos visualizados", "319cf2d54b": "Mostrar árvore de arquivos", "eff839f438": "Comentário de revisão adicionado.", "d8c3ba91c4": "Não é possível comentar sem o SHA head do PR.", @@ -15273,8 +15571,6 @@ "9d5425918e": "Reabrir PR", "96d013ed28": "Fechar pull request", "eca289e593": "O merge requer um repositório local registrado", - "e01e34f5fa": "comentário", - "345b68254c": "thread", "31a7b202f2": "Responder a @{{value0}}", "408e634fbb": "Responder nesta thread de revisão", "34b9f7c264": ":L{{value0}}", @@ -15296,7 +15592,19 @@ "4b8ae7303f": "Falha ao carregar o diff.", "closePullRequestFailed": "Falha ao fechar o pull request", "reopenPullRequestFailed": "Falha ao reabrir o pull request", - "diffLoadTimedOut": "Tempo esgotado ao carregar este diff." + "diffLoadTimedOut": "Tempo esgotado ao carregar este diff.", + "filesViewed_one": "{{viewed}} / {{count}} arquivo visualizado", + "filesViewed_other": "{{viewed}} / {{count}} arquivos visualizados", + "updatedRelativeTime": "atualizado {{time}}", + "resolvedThreadBy": "Thread resolvida de {{author}}", + "resolvedCommentBy": "Comentário resolvido de {{author}}", + "mentionSource": { + "prAuthor": "Autor do PR", + "issueAuthor": "Autor da issue", + "commenter": "Autor de comentário", + "participant": "Participante", + "teamMember": "Membro da equipe" + } }, "tab": { "bar": { @@ -16018,7 +16326,22 @@ "addSshHostHint": "Use uma máquina existente via SSH", "addRemoteOrcaServer": "Adicionar Servidor Orca Remoto", "addRemoteOrcaServerHint": "Pareie outro runtime do Orca", - "hostConnectionFailed": "Falha na conexão" + "hostConnectionFailed": "Falha na conexão", + "connect": "Conectar", + "reconnect": "Reconectar", + "setupConfigDefaultTabs": "Comandos das abas padrão", + "setupConfigSetupAndDefaultTabs": "Configuração e comandos das abas padrão", + "setupConfigSetupScript": "Script de configuração", + "runDefaultTabCommands": "Executar comandos das abas padrão", + "runSetupAndDefaultTabCommands": "Executar configuração e comandos das abas padrão", + "runSetupCommand": "Executar comando de configuração", + "askRunDefaultTabCommands": "Executar os comandos das abas padrão agora?", + "askRunSetupAndDefaultTabCommands": "Executar a configuração e os comandos das abas padrão agora?", + "askRunSetup": "Executar a configuração agora?", + "runSetupNow": "Executar configuração agora", + "runCommandsNow": "Executar comandos agora", + "skipForNow": "Pular por enquanto", + "skipCommands": "Pular comandos" }, "new": { "workspace": { @@ -16161,14 +16484,15 @@ "f23ea85341": "resolvido", "6de8ce0cc6": "{{value0}} necessário(s)", "22511537d2": "Aprovado", - "00f3bab87b": " de {{value0}} necessário(s)", "3a051b8ade": "Item de trabalho", "32f8bef818": "Nenhuma saída de log.", "4168eb2c51": "Resolver", "commentTooLarge": "O comentário é muito grande para ser enviado com segurança.", "gitlabActionFailed": "Falha na ação do GitLab.", - "approvalsRemainingSingular": "{{count}} aprovação restante", - "approvalsRemainingPlural": "{{count}} aprovações restantes" + "approvalsRemainingOfRequired_one": "Falta {{count}} aprovação das {{required}} necessárias", + "approvalsRemainingOfRequired_other": "Faltam {{count}} aprovações das {{required}} necessárias", + "approvalsRemaining_one": "{{count}} aprovação restante", + "approvalsRemaining_other": "{{count}} aprovações restantes" }, "linear": { "api": { @@ -16187,11 +16511,6 @@ } } }, - "priority": { - "icon": { - "c43d3e065b": "Prioridade:" - } - }, "project": { "view": { "surfaces": { @@ -16210,7 +16529,6 @@ "c8db98b73b": "Recursos", "bb1405eff8": "Marcos", "5d99315fb8": "Planejamento", - "3ad562bdf4": "issues com escopo", "563501f191": "Progresso", "bb5664d456": "Sem descrição do projeto.", "7b147907dc": "Linear", @@ -16221,8 +16539,6 @@ "7616c986c6": "Abrir {{value0}} issues", "openInLinear": "Abrir {{value0}} no Linear", "93e1f6bfca": "Carregando", - "98730088a6": ". Busque ou abra o Linear para o conjunto completo.", - "06b887d622": "Mostrando os primeiros", "f2cc1e0ff6": "Linear / Projetos", "906b5e4cb8": "Linear / Projetos / {{value0}}", "85607ff793": "Projeto", @@ -16237,7 +16553,10 @@ "30402d2c6e": "Tente buscar ou atualizar.", "a2f31c4cd6": "Nenhum projeto do Linear encontrado", "c9b6e9f90d": "Não foi possível carregar os projetos do Linear", - "linearLoginUnreadable": "Não foi possível ler o login salvo do Linear. Reconecte-o nas Configurações." + "linearLoginUnreadable": "Não foi possível ler o login salvo do Linear. Reconecte-o nas Configurações.", + "scopedIssueCount_one": "{{count}} issue no escopo", + "scopedIssueCount_other": "{{count}} issues no escopo", + "backlog": "Backlog" } } }, @@ -16250,7 +16569,14 @@ "05baa5ae90": "Espaço de Trabalho", "89f6580dbf": "Buscar equipes...", "b3488fad3c": "Nenhuma equipe foi buscada. O acesso pode depender do escopo da chave, membresia em equipe privada, equipes arquivadas, permissões, ou uma falha na busca.", - "405b33c378": "Nenhuma equipe buscada corresponde à sua busca." + "405b33c378": "Nenhuma equipe buscada corresponde à sua busca.", + "teamCount_one": "{{count}} equipe", + "teamCount_other": "{{count}} equipes" + } + }, + "priority": { + "icon": { + "priorityValue": "Prioridade: {{label}}" } } }, @@ -16461,10 +16787,10 @@ "rightSidebar": { "FolderWorkspaceWorktreesPanel": { "unavailable": "Os espaços de trabalho só são exibidos para espaços de trabalho de pasta.", - "countOne": "1 worktree anexada", - "countMany": "{{value0}} worktrees anexadas", "emptyTitle": "Ainda sem worktrees anexadas", - "emptyCopy": "Worktrees criadas a partir deste espaço de trabalho vão aparecer aqui." + "emptyCopy": "Worktrees criadas a partir deste espaço de trabalho vão aparecer aqui.", + "attachedCount_one": "{{count}} worktree anexada", + "attachedCount_other": "{{count}} worktrees anexadas" }, "FolderWorkspacePrChecksPanel": { "unavailable": "As verificações de PR só são exibidas para espaços de trabalho de pasta.", @@ -16476,12 +16802,12 @@ "hideDetails": "Ocultar detalhes de verificação de PR de {{value0}}", "reviewChecks": "Verificações de review", "allChecksPassing": "todas as verificações aprovadas", - "oneWorktree": "1 worktree", - "worktreeCount": "{{value0}} worktrees", - "oneFailing": "1 com falha", - "failingCount": "{{value0}} com falha", - "onePending": "1 pendente", - "pendingCount": "{{value0}} pendentes" + "worktreeCountLabel_one": "{{count}} worktree", + "worktreeCountLabel_other": "{{count}} worktrees", + "failingCountLabel_one": "{{count}} com falha", + "failingCountLabel_other": "{{count}} com falha", + "pendingCountLabel_one": "{{count}} pendente", + "pendingCountLabel_other": "{{count}} pendentes" }, "parentPrChecks": { "rowSummary": { @@ -16629,13 +16955,13 @@ "b1e390250d": "Não foi possível completar a mudança de build local.", "d29740d175": "O build selecionado não pôde ser usado.", "37d45c9ec1": "Escolher Outro Build", - "7f1a4c9e02": "O gerenciador de pacotes do seu sistema instalou o Orca, então atualize-o por lá — o Orca não pode instalar este release por si mesmo." + "7f1a4c9e02": "O gerenciador de pacotes do seu sistema instalou o Orca, então atualize-o por lá — o Orca não pode instalar este release por si mesmo.", + "compatibilityModeFailed": "Não foi possível ativar o modo de compatibilidade. {{message}}" }, "LinearIssueWorkspace": { "ad5dec37b7": "Pré-visualize, edite e comece a trabalhar a partir da issue selecionada.", "c23e79e5c0": "Ações", "b0eac92d85": "Tentar novamente", - "fabbd3f974": "atualizou a issue ·", "543970c87a": "Atividade", "df4c86ed12": "Fechar", "7a4997d8bb": "Fechar pré-visualização de issue do Linear", @@ -16659,11 +16985,8 @@ "b25e453c9d": "Falha ao criar a sub-issue", "aeed19d003": "{{value0}} criada", "9a1317cdd3": "Falha ao carregar a sub-issue", - "9bcbaa2737": "Falha ao copiar {{value0}}", - "7835483c43": "{{value0}} copiado(a)", "61f424f8ca": "Issue do Linear", "ca8778c124": "Desconhecido", - "8a33c85e9c": "Alguém", "65239a714b": "Linear", "76ffd3c937": "Busque um projeto para adicionar.", "c11b4e3cc2": "Nenhum projeto encontrado.", @@ -16674,7 +16997,10 @@ "moreWorkspaceActions": "Mais ações de espaço de trabalho da issue", "startNewWorkspace": "Iniciar novo espaço de trabalho", "workspaceSection": "Espaço de Trabalho", - "noWorkspaceYet": "Nenhum ainda" + "noWorkspaceYet": "Nenhum ainda", + "issueDescriptionLabel": "Descrição da issue", + "namedUserUpdatedIssue": "{{name}} atualizou a issue · {{time}}", + "someoneUpdatedIssue": "Alguém atualizou a issue · {{time}}" }, "WorktreeJumpPalette": { "ac037cfac2": "Mover", @@ -16700,8 +17026,6 @@ "d7d496a451": "A página do navegador não existe mais", "50a1d11d5b": "Abas Abertas", "088d66d980": "Ações e Configurações", - "20af998bff": "{{value0}} itens disponíveis{{value1}}", - "bb72c08e63": "{{value0}} resultados encontrados{{value1}}", "34c8fbb46e": "SSH remoto", "63c2be1914": "SSH desconectado", "95be6587d3": "Criar worktree \"{{value0}}\"", @@ -16718,7 +17042,12 @@ "recentChatsTerminalsHeader": "Chats e Terminais Recentes", "27f10cca63": "Buscar chats, terminais, worktrees, configurações e ações...", "2770f02910": "Buscar chats, terminais, worktrees, configurações e ações", - "lastActiveTime": "Última atividade há {{value0}}" + "lastActiveTime": "Última atividade há {{value0}}", + "resultsFound_one": "{{count}} resultado encontrado.", + "resultsFound_other": "{{count}} resultados encontrados.", + "itemsAvailable_one": "{{count}} item disponível.", + "itemsAvailable_other": "{{count}} itens disponíveis.", + "createActionAvailable": "Ação de criar worktree disponível." }, "floating": { "terminal": { @@ -16774,19 +17103,9 @@ "untitled": "Chat sem título", "listLabel": "Chats que seriam reconectados", "dontAskAgain": "Não perguntar novamente — reconectar automaticamente na próxima vez", - "dontAskAgainHint": "Os chats qualificados serão reconectados automaticamente após uma reinicialização, e o Orca vai avisar você quando isso acontecer. Você pode desativar isso em Configurações → Experimental → Interface de Chat.", - "continuedOne": "1 chat reconectado e solicitado a continuar", - "continuedMany": "{{value0}} chats reconectados e solicitados a continuar", + "dontAskAgainHint": "Você pode desativar isso em Configurações → Chat → Comportamento.", "selectAgent": "Reconectar chat de {{value0}} \"{{value1}}\" em {{value2}}", - "resumeSelected": "Reconectar {{value0}}", - "resumeSelectedOne": "Retomar 1 chat", "dismissAll": "Dispensar todos", - "notContinuedOne": "Não foi possível retomar 1 chat", - "notContinuedMany": "Não foi possível retomar {{value0}} chats", - "notConfirmedOne": "Não foi possível confirmar que 1 chat foi retomado", - "notConfirmedMany": "Não foi possível confirmar que {{value0}} chats foram retomados", - "notConfirmedOtherOne": "Não foi possível confirmar que 1 outro chat foi retomado", - "notConfirmedOtherMany": "Não foi possível confirmar que {{value0}} outros chats foram retomados", "viewChats": "Ver chats", "review": "Revisar", "activityUnnamed": "sem nome", @@ -16794,9 +17113,7 @@ "activityQuestion": "Aguardando sua resposta: {{value0}}", "activityMidReply": "Estava no meio de uma resposta", "activitySubagentOne": "Subagente em execução: {{value0}}", - "activitySubagentMany": "{{value0}} subagentes em execução", "activityMonitorOne": "Monitorando: {{value0}}", - "activityMonitorMany": "Monitorando {{value0}} tarefas em segundo plano", "selectWorkspace": "Selecionar todos os chats em {{value0}}", "workspaceSelectedCount": "{{value0}} de {{value1}}", "selectAll": "Selecionar todos os chats", @@ -16813,8 +17130,22 @@ "serverBody": "Estes chats estavam em andamento quando o Orca em {{machine}} reiniciou. Retomar restaura cada um de onde parou e pede ao agente que continue. Seu próprio prompt não é reenviado.", "serverDismiss": "Descartar", "serverResumeAll": "Retomar todos os {{count}} em {{machine}}", - "serverResumeHereOne": "Retomar 1 chat iniciado aqui", - "serverResumeHere": "Retomar {{count}} chats iniciados aqui" + "resumeChats_one": "Retomar {{count}} chat", + "resumeChats_other": "Retomar {{count}} chats", + "serverResumeHereCount_one": "Retomar {{count}} chat iniciado aqui", + "serverResumeHereCount_other": "Retomar {{count}} chats iniciados aqui", + "continuedCount_one": "{{count}} chat retomado", + "continuedCount_other": "{{count}} chats retomados", + "notContinuedCount_one": "Não foi possível retomar {{count}} chat", + "notContinuedCount_other": "Não foi possível retomar {{count}} chats", + "notConfirmedCount_one": "Não foi possível confirmar a retomada de {{count}} chat", + "notConfirmedCount_other": "Não foi possível confirmar a retomada de {{count}} chats", + "notConfirmedOtherCount_one": "Não foi possível confirmar a retomada de {{count}} outro chat", + "notConfirmedOtherCount_other": "Não foi possível confirmar a retomada de {{count}} outros chats", + "activitySubagentCount_one": "{{count}} subagente em execução", + "activitySubagentCount_other": "{{count}} subagentes em execução", + "activityMonitorCount_one": "Monitorando {{count}} tarefa em segundo plano", + "activityMonitorCount_other": "Monitorando {{count}} tarefas em segundo plano" }, "LinearItemDrawer": { "04008e6c46": "Iniciar espaço de trabalho a partir da issue", @@ -16850,7 +17181,9 @@ "openAttachedWorkspace": "Abrir espaço de trabalho anexado à issue", "openWorkspace": "Abrir espaço de trabalho", "moreWorkspaceActions": "Mais ações de espaço de trabalho da issue", - "startNewWorkspace": "Iniciar novo espaço de trabalho" + "startNewWorkspace": "Iniciar novo espaço de trabalho", + "setEstimate": "Definir estimativa", + "estimateValue": "Estimativa {{estimate}}" }, "JiraIssueWorkspace": { "b0b92666c9": "Comentário", @@ -16875,8 +17208,6 @@ "69da9a208c": "Abrir no Jira", "fa132c8aed": "Falha ao adicionar o comentário.", "ea21952aa3": "Falha ao atualizar a issue do Jira.", - "6c41a9bcea": "Falha ao copiar {{value0}}", - "2ff69a3545": "{{value0}} copiado(a)", "666cfdd835": "Desconhecido", "ef21405c6d": "Issue do Jira", "commentTooLarge": "O comentário é muito grande para ser enviado com segurança." @@ -16932,8 +17263,6 @@ "63ce735809": "Conectar", "4a2ab52781": "Verificando…", "79e7aaed39": "Cancelar", - "fdd26d81cc": "Configurações da conta Atlassian", - "8090504a3e": "Crie um token em", "7b3967c12f": "Token de API do Atlassian", "3d81bf3ab3": "Token de API", "e91b9a4073": "you@example.com", @@ -16958,7 +17287,8 @@ "be9eba0a1b": "nome de usuário", "70035652d7": "Senha", "c50abbf340": "Senha da conta do Jira", - "d8737db691": "Use o nome de usuário e a senha da sua conta do Jira Server ou Data Center." + "d8737db691": "Use o nome de usuário e a senha da sua conta do Jira Server ou Data Center.", + "createTokenInSettings": "Crie um token nas configurações da conta Atlassian." } } }, @@ -17018,7 +17348,11 @@ "c34fb1098d": "Abas de terminal fechadas e encerramento solicitado.", "d9657ac204": "Encerramento da sessão de terminal solicitado.", "e8f25bd903": "Não foi possível concluir a limpeza do terminal.", - "a702d4196e": "Isso fecha todas as abas de terminal em todos os espaços de trabalho e solicita o encerramento de suas sessões de terminal atuais. Qualquer trabalho de terminal não salvo será perdido. O daemon continua em execução, e novos terminais podem ser abertos imediatamente. Isso não pode ser desfeito." + "a702d4196e": "Isso fecha todas as abas de terminal em todos os espaços de trabalho e solicita o encerramento de suas sessões de terminal atuais. Qualquer trabalho de terminal não salvo será perdido. O daemon continua em execução, e novos terminais podem ser abertos imediatamente. Isso não pode ser desfeito.", + "confirmRestart": "Reiniciar", + "busyRestarting": "Reiniciando…", + "confirmKillAll": "Encerrar todas as sessões", + "busyKilling": "Encerrando…" }, "MacFolderAccessFixDialog": { "stepAllow": "Permita o Orca em Arquivos e Pastas", @@ -17053,10 +17387,11 @@ "combobox": { "noProjects": "Nenhum projeto", "allProjects": "Todos os projetos", - "hostCount": "{{value0}} hosts", "searchProjects": "Buscar projetos...", "noMatches": "Nenhum projeto corresponde à sua busca.", - "chooseSource": "Escolher origem da tarefa" + "chooseSource": "Escolher origem da tarefa", + "hostCount_one": "{{count}} host", + "hostCount_other": "{{count}} hosts" } } }, @@ -17122,7 +17457,6 @@ } }, "Landing": { - "76a95f7f47": "Criar", "f9eaa9e12d": "Adicionar projeto", "6ca6ff404e": "ORCA", "520304a067": "Logo do Orca", @@ -17138,7 +17472,12 @@ "0d0ace8861": "Dar estrela no GitHub", "ec43b38ba7": "Com estrela no GitHub", "157bb5ecbb": "Abrir GitHub", - "preflightDismiss": "Descartar" + "preflightDismiss": "Descartar", + "moveUpWorkspace": "Selecionar espaço de trabalho anterior", + "moveDownWorkspace": "Selecionar próximo espaço de trabalho", + "installGit": "Instalar Git", + "installGitHubCli": "Instalar GitHub CLI", + "learnMore": "Saiba mais" }, "QuickOpen": { "1dbd3f59ff": "Mover", @@ -17152,13 +17491,12 @@ "9e97f08d0f": "Busque um arquivo para abrir", "ec31e058f7": "Ir para o arquivo", "73b44e7bde": "Copiar comando de instalação", - "1cf8561ab4": "no remoto para ativar a listagem rápida com reconhecimento de gitignore:", - "5d80dc39bb": "ripgrep", - "2ca749c15d": "Instalar", - "4725b0e931": "Varredura do Quick Open muito grande (", - "b227d88520": "{{value0}} arquivos encontrados", "995be8ea22": "Copiar", - "cf144856dc": "Copiado" + "cf144856dc": "Copiado", + "filesFound_one": "{{count}} arquivo encontrado", + "filesFound_other": "{{count}} arquivos encontrados", + "hostCouldNotOpenPath": "O host não conseguiu abrir este caminho de arquivo.", + "chooseFileNotDirectory": "Escolha um arquivo em vez de um diretório." }, "LinearIssueMarkdownDescriptionEditor": { "d9c47069ef": "Markdown", @@ -17439,7 +17777,9 @@ "6978871a3d": "Abrir", "cce596969e": "Excluir nota", "cad3384faa": "Editar nota", - "508ee678a5": "Abrir no navegador" + "508ee678a5": "Abrir no navegador", + "noteAuthorFallback": "Nota", + "sentMeta": "enviado" }, "DiffCommentPopover": { "2b3ce6d394": "Cancelar", @@ -17452,6 +17792,9 @@ }, "useDiffCommentDecorator": { "995fa28b50": "Esta nota" + }, + "diffCommentZoneCard": { + "noteAlreadySent": "Nota já enviada" } } }, @@ -17545,11 +17888,11 @@ "a2f68645ac": "Atualizar orçamento da API do GitLab", "2f9c16d6c3": "O Orca usa REST através da CLI do GitLab.", "14e144f7a7": "Orçamento da API do GitLab", - "3e2c982cfa": "restante, redefine em", - "ea8ad0bae8": "de", "0a891e8935": "API REST", "953f7c6062": "Este host do GitLab não retornou cabeçalhos de limite de taxa.", - "budget_scope_prefix": "Escopo do orçamento" + "budget_scope_prefix": "Escopo do orçamento", + "resetUnknown": "desconhecido", + "remainingOfLimit": "{{remaining}} de {{limit}} restantes, redefine em {{reset}}" } } } @@ -17669,7 +18012,6 @@ "LinearIssueTextEditor": { "947ba2d6f4": "para salvar", "04d73b72dc": "Título da issue", - "e8ff595db3": "Falha ao atualizar {{value0}}", "1e08a1ec80": "O título é obrigatório" }, "pluginCatalog": { @@ -17783,7 +18125,35 @@ "taskSourceContextSummary": { "sourceUnavailable": "Origem de {{value0}} indisponível: {{value1}}", "someSourceHostsUnavailable": "Alguns hosts de origem de {{value0}} indisponíveis: {{value1}}", - "reconnectOrUpdateTitle": "Reconecte ou atualize {{value0}} para carregar esta origem." + "reconnectOrUpdateTitle": "Reconecte ou atualize {{value0}} para carregar esta origem.", + "providerSourceTitle": "Origem {{provider}}", + "hostTitle": "Host: {{hosts}}", + "accountTitle": "Conta: {{accounts}}", + "sourceTitle": "Origem: {{source}}", + "sourceHostCount_one": "{{count}} host de origem", + "sourceHostCount_other": "{{count}} hosts de origem", + "noHost": "Nenhum host", + "projectCount_one": "{{count}} projeto", + "projectCount_other": "{{count}} projetos", + "selectedProject": "Projeto selecionado", + "selectedProjectCount_one": "{{count}} projeto selecionado", + "selectedProjectCount_other": "{{count}} projetos selecionados", + "currentAccount": "Conta atual", + "statusCheckingCapabilities": "verificando recursos do servidor", + "statusServerUpdateForTaskSources": "requer atualização do servidor para origens de tarefas", + "statusProviderAuthNeeded": "requer autenticação do provedor", + "statusSourceToolUnavailable": "ferramenta de origem indisponível", + "statusProviderUnsupported": "provedor não compatível com este host", + "statusServerUpdateNeeded": "requer atualização do servidor", + "unavailableCount_one": "{{count}} indisponível", + "unavailableCount_other": "{{count}} indisponíveis", + "statusConnected": "conectado", + "statusAuthNeeded": "requer autenticação", + "statusConnecting": "conectando", + "statusConnectionIssue": "problema de conexão", + "statusDisconnected": "desconectado", + "hostStatus": "{{host}} {{status}}", + "availabilityTitle": "Disponibilidade: {{hosts}}" }, "WorktreeBaseFallbackDialog": { "title": "Espaço de trabalho criado a partir de uma base local", @@ -17908,15 +18278,15 @@ } }, "NativeChatResumeRunPanel": { - "resumedTitle": "{{value0}} de {{value1}} chats retomados", - "resumingTitleOne": "Retomando 1 chat", - "resumingTitle": "Retomando {{value0}} chats", "description": "Cada chat é restaurado com seu contexto completo e recebe um pedido para verificar onde parou. Você pode fechar isto; a barra de status acompanha o progresso.", - "resumedTitleOne": "{{value0}} de 1 chat retomado", "finished": "Estes chats estavam trabalhando quando o Orca fechou. O Orca restaurou cada um de onde parou, com seu contexto completo, e pediu ao agente que verificasse o que estava fazendo antes de continuar. Suas próprias instruções não foram reenviadas.", "finishedUpdate": "Estes chats estavam trabalhando quando o Orca instalou uma atualização. O Orca restaurou cada um de onde parou, com seu contexto completo, e pediu ao agente que verificasse o que estava fazendo antes de continuar. Suas próprias instruções não foram reenviadas.", "finishedPartial": "Estes chats estavam trabalhando quando o Orca fechou. Os chats retomados pelo Orca foram restaurados de onde pararam, com seu contexto completo, e receberam um pedido para verificar o que estavam fazendo antes de continuar. Suas próprias instruções não foram reenviadas. Confira na lista os chats que ainda precisam de atenção ou podem ser retomados.", - "finishedPartialUpdate": "Estes chats estavam trabalhando quando o Orca instalou uma atualização. Os chats retomados pelo Orca foram restaurados de onde pararam, com seu contexto completo, e receberam um pedido para verificar o que estavam fazendo antes de continuar. Suas próprias instruções não foram reenviadas. Confira na lista os chats que ainda precisam de atenção ou podem ser retomados." + "finishedPartialUpdate": "Estes chats estavam trabalhando quando o Orca instalou uma atualização. Os chats retomados pelo Orca foram restaurados de onde pararam, com seu contexto completo, e receberam um pedido para verificar o que estavam fazendo antes de continuar. Suas próprias instruções não foram reenviadas. Confira na lista os chats que ainda precisam de atenção ou podem ser retomados.", + "resumedOfTotal_one": "Chats retomados: {{resumed}} de {{count}}", + "resumedOfTotal_other": "Chats retomados: {{resumed}} de {{count}}", + "resumingCount_one": "Retomando {{count}} chat", + "resumingCount_other": "Retomando {{count}} chats" }, "NativeChatResumeRunStatusIcon": { "waitingForReply": "Aguardando resposta", @@ -17981,6 +18351,72 @@ "cancelled": "Este terminal SSH simples foi fechado antes de iniciar.", "terminalUnavailable": "O Orca não conseguiu abrir um terminal aqui.", "openHint": "Permite continuar trabalhando no host enquanto o Orca não consegue se configurar nele." + }, + "AgentStateDot": { + "working": "Trabalhando", + "monitoring": "Monitorando tarefas em segundo plano", + "blocked": "Bloqueado", + "waiting": "Aguardando entrada", + "interrupted": "Interrompido", + "failed": "Falhou", + "done": "Concluído", + "idle": "Ocioso", + "unverifiable": "Sem atualização recente", + "unconfirmed": "Não foi possível confirmar", + "permission": "Requer atenção" + }, + "issueComments": { + "you": "Você" + }, + "ZoomOverlay": { + "uiZoom": "Zoom da interface", + "editorZoom": "Zoom do editor", + "terminalZoom": "Zoom do terminal" + }, + "issueCopy": { + "urlCopied": "URL copiada", + "keyCopied": "Chave copiada", + "identifierCopied": "Identificador copiado", + "branchNameCopied": "Nome da branch copiado", + "promptCopied": "Prompt copiado", + "urlCopyFailed": "Falha ao copiar URL", + "keyCopyFailed": "Falha ao copiar chave", + "identifierCopyFailed": "Falha ao copiar identificador", + "branchNameCopyFailed": "Falha ao copiar nome da branch", + "promptCopyFailed": "Falha ao copiar prompt" + }, + "prCheckCounts": { + "noChecksFound": "Nenhuma verificação encontrada", + "checksFailing_one": "{{count}} verificação falhando", + "checksFailing_other": "{{count}} verificações falhando", + "checksNeedAction_one": "{{count}} verificação requer ação", + "checksNeedAction_other": "{{count}} verificações requerem ação", + "checksPending_one": "{{count}} verificação pendente", + "checksPending_other": "{{count}} verificações pendentes", + "allChecksPassing": "Todas as verificações passaram", + "checksPassingOfTotal_one": "Verificações bem-sucedidas: {{passing}} de {{count}}", + "checksPassingOfTotal_other": "Verificações bem-sucedidas: {{passing}} de {{count}}" + }, + "taskPageJiraBoard": { + "changeStatusFailed": "Falha ao alterar o status." + }, + "jiraIssue": { + "loadStatusChangesFailed": "Falha ao carregar as alterações de status.", + "loadCommentsFailed": "Falha ao carregar os comentários." + }, + "taskPageJiraLinkedIssues": { + "someIssuesFailed": "Não foi possível carregar algumas issues do Jira vinculadas a espaços de trabalho. Atualize para tentar novamente." + }, + "taskPageJiraLoadState": { + "failedToLoadIssues": "Falha ao carregar as issues do Jira.", + "authFailed": "Falha na autenticação do Jira. Reconecte o Jira nas configurações e tente novamente.", + "accessDenied": "O Jira negou acesso a esta busca de issues. Verifique as permissões do projeto ou tente outra consulta JQL.", + "rateLimited": "O Jira limitou esta busca de issues por excesso de solicitações. Tente novamente em instantes.", + "serverError": "O Jira teve um erro de servidor ao carregar as issues. Tente novamente em instantes.", + "jqlFailed": "O Jira não conseguiu executar esta consulta JQL. Verifique a sintaxe e tente novamente.", + "unreachable": "Não foi possível acessar o Jira. Verifique sua conexão e tente novamente.", + "loadFailed": "Não foi possível carregar as issues do Jira. Tente novamente em instantes.", + "errorWithCode": "Erro {{code}}: {{summary}}" } }, "startup": { @@ -18484,6 +18920,7 @@ "agentCommandNotRunnable": "O Comando de {{agent}} em Configurações → Agentes deve ser o caminho ou nome de um programa que o Orca possa encontrar, sem argumentos nem variáveis. Altere-o ou redefina-o.", "runtimeNotInstalled": "{{agent}} não está instalado no computador que executa este chat. Instale-o pelo chat em uma versão atual do Orca.", "fullAccessAsRoot": "{{agent}} não usará Acesso total enquanto for executado como root. Escolha outra permissão para {{agent}} em Configurações → Agentes para o computador que executa este chat e inicie um novo chat.", + "launchPreparationFailed": "O Orca não conseguiu preparar a inicialização de {{agent}} no computador que executa este chat.", "chooseClaudeAccount": "Escolha ou adicione uma nas configurações de Contas do Claude.", "chooseClaudeAccountThenRunCommand": "Escolha ou adicione uma nas configurações de Contas do Claude e execute /{{command}} novamente.", "chooseClaudeAccountThenSend": "Escolha ou adicione uma nas configurações de Contas do Claude e envie sua mensagem novamente.", @@ -18635,7 +19072,8 @@ "compactAfterRetry": "Tente enviar sua mensagem anterior novamente e execute /compact.", "clearAfterSending": "Sua mensagem anterior ainda está sendo enviada. Execute /clear após o envio.", "compactAfterSending": "Sua mensagem anterior ainda está sendo enviada. Execute /compact após o envio.", - "pendingWork": "Aguarde a conclusão do trabalho e das mensagens pendentes antes de usar este comando." + "pendingWork": "Aguarde a conclusão do trabalho e das mensagens pendentes antes de usar este comando.", + "notDoneGoalChangeIncomplete": "Não foi possível concluir a alteração do objetivo. Verifique o chat." }, "newRowsAnnouncement": "Novas mensagens chegaram enquanto você estava ausente", "newRowsMarker": "Novas", @@ -18758,7 +19196,6 @@ "pausedSendFailedWaiting": "Não foi possível enviar — pressione Enviar para tentar novamente quando o agente terminar.", "save": "Salvar", "editingMessage": "Editando mensagem", - "cancelEditing": "Cancelar edição", "editChanged": "Esta mensagem mudou durante a edição. Sua versão está no campo de texto do chat.", "editChangedPrompt": "Esta mensagem mudou durante a edição. Sua versão estará no campo de texto do chat depois que você responder ao agente.", "editChangedNotSaved": "Esta mensagem mudou durante a edição. Sua versão não foi salva.", @@ -18772,8 +19209,6 @@ "expand": "Expandir", "queued": "Na fila", "clearAll": "Limpar tudo", - "pasteOrDropImages": "Cole ou solte imagens", - "saveNeedsContent": "Adicione texto ou uma imagem para salvar", "moveChanged": "A fila mudou antes desta movimentação. Tente arrastar a mensagem novamente.", "reorderHint": "Arraste para reordenar ou use as teclas de seta para cima e para baixo.", "reorderMessage": "Reordenar mensagem" @@ -18906,6 +19341,15 @@ "settings": "Abrir as configurações no terminal", "extensions": "Abrir o painel de extensões no terminal", "hotkeys": "Mostrar os atalhos de teclado no terminal" + }, + "modelDescriptions": { + "grok_4_7": "O modelo de ponta mais recente da xAI", + "grok_4_6": "O modelo de ponta anterior da xAI", + "grok_4_5": "Um modelo de ponta mais antigo da xAI", + "fable": "O mais capaz para as tarefas mais difíceis e demoradas", + "opus": "Ideal para tarefas complexas do dia a dia", + "sonnet": "Eficiente para tarefas rotineiras", + "haiku": "O mais rápido para respostas rápidas" } }, "tab": { @@ -19541,7 +19985,9 @@ "confirmTitle": "Reiniciar o daemon de terminais?", "confirmBody": "Reiniciar encerra todos os processos em execução em {{sessions}}. Agentes que permitem retomar sessões poderão ser retomados depois; shells e outras tarefas precisarão ser iniciados novamente. Faça isso quando seus agentes estiverem ociosos.", "cancel": "Cancelar", - "confirm": "Reiniciar e encerrar processos" + "confirm": "Reiniciar e encerrar processos", + "count_other": "{{count}} terminais em execução", + "count_one": "{{count}} terminal em execução" }, "restartedInputNotSent": "O terminal reiniciou enquanto você digitava, então parte da entrada pode não ter chegado a ele. Verifique o novo shell antes de digitar novamente." }, @@ -19598,9 +20044,9 @@ "pathAdded": "Adicionado", "openFolder": "Abrir {{name}}", "findOrTypePath": "Busque uma pasta ou digite qualquer caminho…", - "addTypedPath": "Adicionar", "noDirectories": "Nenhuma pasta adicionada ainda.", - "removePath": "Remover {{name}}" + "removePath": "Remover {{name}}", + "addTypedPathCode": "Adicionar " }, "accounts": { "wslAccountNotApplied": { @@ -19677,13 +20123,10 @@ "signInLinkCopyFailed": "Não foi possível copiar o link.", "switchSessions": { "title": "Conta alterada para {{account}}", - "bodyOne": "1 sessão do Claude ainda está em execução em {{previous}}. Reiniciar continua a conversa em {{next}}. Sessões ocupadas aguardam ficar ociosas antes de reiniciar.", - "bodyOther": "{{count}} sessões do Claude ainda estão em execução em {{previous}}. Reiniciar continua cada conversa em {{next}}. Sessões ocupadas aguardam ficar ociosas antes de reiniciar.", "dontAskAgain": "Não perguntar novamente (reiniciar automaticamente)", "dontAskAgainHint": "Você pode desativar isso em Configurações → Contas de provedores de IA.", "keep": "Manter como está", "restartOne": "Reiniciar sessão", - "restartOther": "Reiniciar {{count}} sessões", "listLabel": "Sessões do Claude para reiniciar", "session": "Sessão do Claude", "busy": "Trabalhando", @@ -19707,13 +20150,17 @@ "reasonOwnFolder": "Usa sua própria pasta do Claude", "reasonUnknownAccount": "Conta desconhecida", "reasonNoSession": "Não é possível retomar", - "reviewBodyOne": "1 outra sessão do Claude não foi movida para {{next}}.", - "reviewBodyOther": "{{count}} outras sessões do Claude não foram movidas para {{next}}.", "notMovedOne": "1 outra sessão não foi movida.", "notMovedOther": "{{count}} outras sessões não foram movidas.", "review": "Revisar", "uncheckedOne": "Não foi possível verificar o Claude em 1 terminal. Se o Claude estiver em execução nele, ele continuará em {{previous}} até ser reiniciado.", - "uncheckedOther": "Não foi possível verificar o Claude em {{count}} terminais. Qualquer Claude em execução neles continuará em {{previous}} até ser reiniciado." + "uncheckedOther": "Não foi possível verificar o Claude em {{count}} terminais. Qualquer Claude em execução neles continuará em {{previous}} até ser reiniciado.", + "restartCount_one": "Reiniciar {{count}} sessão", + "restartCount_other": "Reiniciar {{count}} sessões", + "reviewBody_one": "{{count}} outra sessão do Claude não foi movida para {{next}}.", + "reviewBody_other": "{{count}} outras sessões do Claude não foram movidas para {{next}}.", + "body_one": "{{count}} sessão do Claude ainda está em execução em {{previous}}. Ao reiniciar, a conversa continua em {{next}}. As sessões ocupadas aguardam ficar ociosas antes de reiniciar.", + "body_other": "{{count}} sessões do Claude ainda estão em execução em {{previous}}. Ao reiniciar, cada conversa continua em {{next}}. As sessões ocupadas aguardam ficar ociosas antes de reiniciar." } }, "managedData": { @@ -19821,7 +20268,11 @@ "picker": { "pasteUnparseable": "Esperava-se uma URL de projeto ou owner/number", "ownerLoadFailed": "Não foi possível carregar os projetos de {{owner}}.", - "organizationsLoadFailed": "Algumas organizações não foram carregadas ({{failureCount}})." + "organizationsLoadFailed": "Algumas organizações não foram carregadas ({{failureCount}}).", + "organizations": "Organizações", + "listFailed": "Não foi possível listar os projetos", + "detailsFailed": "Não foi possível carregar os detalhes", + "viewFailed": "Não foi possível buscar a visualização do projeto" }, "error": { "notFoundState": "Não foi possível encontrar este projeto ou visualização.", @@ -19854,8 +20305,12 @@ "rateLimited": "Limite de taxa do GitHub atingido. Tente novamente em alguns minutos.", "network": "Erro de rede — verifique sua conexão.", "tooLargeUnknownCount": "Esta visualização tem itens demais para ser exibida no Orca. Restrinja o filtro da visualização no GitHub.", - "tooLarge": "Esta visualização tem {{itemCount}} itens, demais para ser exibida no Orca. Restrinja o filtro da visualização no GitHub.", - "schemaDriftDetail": "Não foi possível ler esta visualização do projeto: {{detail}}." + "schemaDriftDetail": "Não foi possível ler esta visualização do projeto: {{detail}}.", + "tooLargeCount_one": "Esta visualização tem {{count}} item — é grande demais para ser exibida no Orca. Restrinja o filtro da visualização no GitHub.", + "tooLargeCount_other": "Esta visualização tem {{count}} itens — é grande demais para ser exibida no Orca. Restrinja o filtro da visualização no GitHub." + }, + "columns": { + "type": "Digite" } }, "projectField": { @@ -19938,6 +20393,27 @@ "attachments": { "updateRuntime": "Atualize o runtime remoto para alterar os links do espaço de trabalho", "updateRuntimeSafely": "Atualize o runtime remoto para alterar com segurança os links do espaço de trabalho" + }, + "activity": { + "active": "Ativo", + "working": "Trabalhando", + "monitoring": "Monitorando tarefas em segundo plano", + "failed": "Falhou", + "interrupted": "Interrompido", + "unconfirmed": "Não foi possível confirmar", + "done": "Concluído", + "inactive": "Inativo", + "permission": "Precisa de permissão", + "unreadLabel": "{{status}} · Não lido" + }, + "reviewStatus": { + "checksFailed": "Verificações do {{review}}: com falha", + "checksPassing": "Verificações do {{review}}: aprovadas", + "checksPending": "Verificações do {{review}}: pendentes", + "closed": "{{review}}: Fechado", + "draft": "{{review}}: Rascunho", + "merged": "{{review}}: Mergeado", + "open": "{{review}}: Aberto" } }, "tabHoverCard": { @@ -19987,7 +20463,9 @@ "waitingAriaLabel": "Atualização aguardando outras instâncias do Orca. Clique para expandir.", "preparingLabel": "Preparando atualização", "preparingAriaLabel": "Preparando atualização. Clique para expandir." - } + }, + "wslMoveInstallHeld": "Um projeto está sendo movido para o host WSL dele. Instale a atualização quando a movimentação terminar.", + "wslMoveUndoInstallHeld": "Um projeto está voltando do host WSL dele. Instale a atualização quando isso terminar." }, "jira": { "connect": { @@ -19997,13 +20475,13 @@ "optionalEmail": "E-mail da Atlassian (opcional para tokens com escopo)" }, "workspace": { - "count": "{{count}} espaços de trabalho vinculados a {{key}}", "startAnother": "Iniciar novo espaço de trabalho", "empty": "Vincule uma issue do Jira a um espaço de trabalho ou escolha outra visualização.", "openFailed": "Não foi possível abrir o espaço de trabalho vinculado a esta issue do Jira.", "mode": "Tem espaço de trabalho", "search": "Buscar issues vinculadas", - "single": "1 espaço de trabalho vinculado a {{key}}" + "linkedCount_one": "{{count}} espaço de trabalho vinculado a {{key}}", + "linkedCount_other": "{{count}} espaços de trabalho vinculados a {{key}}" }, "prompt": { "dialogTitle": "Copiar prompt de um modelo", @@ -20463,7 +20941,8 @@ "email": "Saber seu endereço de e-mail", "allSites": "Ler e alterar todos os seus dados em todos os sites", "someSites": "Ler e alterar seus dados em {{hosts}}", - "manySites": "Ler e alterar seus dados em {{hosts}} e em outros {{count}} sites" + "manyOtherSites_one": "Ler e alterar seus dados em {{hosts}} e {{count}} outro site", + "manyOtherSites_other": "Ler e alterar seus dados em {{hosts}} e {{count}} outros sites" }, "install": { "title": "Adicionar {{name}}?", @@ -20493,5 +20972,340 @@ "math": { "scrollDisplayEquation": "Rolar equação em bloco" } + }, + "runtime": { + "health": { + "available": "Conectado", + "connecting": "Conectando", + "disconnected": "Desconectado", + "error": "Precisa de atenção", + "mixed": "Misto", + "local": "Local", + "repair": "Precisa parear novamente", + "update": "Precisa de atualização" + }, + "compat": { + "compatible": "O cliente e o servidor do ambiente de execução são compatíveis.", + "clientTooOld": "Este cliente Orca é antigo demais para o servidor selecionado. Atualize o Orca nesta máquina. Protocolo do cliente: {{clientProtocol}}; o servidor exige o protocolo de cliente {{requiredProtocol}}.", + "serverTooOld": "O servidor Orca selecionado é antigo demais para este cliente. Atualize o Orca no servidor. Protocolo do servidor: {{serverProtocol}}; o cliente exige o protocolo de servidor {{requiredProtocol}}." + } + }, + "native": { + "about": { + "gpu": { + "unknownStatus": "Status indisponível", + "enabled": "Ativado", + "disabled": "Desativado", + "unavailable": "Indisponível", + "safeMode": "Desativada (modo gráfico seguro)", + "software": "Renderização por software", + "unknown": "Desconhecido ({{status}})", + "summary": "Aceleração de GPU: {{status}}" + } + }, + "dialog": { + "importCookies": "Importar Cookies", + "spaceTitle": "Espaço Orca Beta", + "dashboardTitle": "Painel de agentes do Orca", + "cookieFiles": "Arquivos de cookies", + "allFiles": "Todos os arquivos", + "importPetBundle": "Selecionar um pacote .codex-pet", + "pickPet": "Selecionar mascote", + "petImage": "Imagem do mascote", + "importWarpTheme": "Importar tema do Warp", + "warpThemeYaml": "YAML de tema do Warp", + "importWarpFolder": "Importar pasta de temas do Warp", + "images": "Imagens", + "repoIconImages": "Imagens de ícone do repositório", + "audio": "Áudio" + } + }, + "taskProviders": { + "linear": { + "updateAccess": "Atualizar acesso", + "addAccess": "Adicionar acesso ao Linear", + "fetchMore": "Buscar mais", + "connectionFailed": "Falha na conexão", + "listLabel": "Lista do Linear", + "projectsLoadFailed": "Não foi possível carregar os projetos.", + "projectNotFound": "O projeto não foi encontrado.", + "projectLoadFailed": "Não foi possível carregar o projeto.", + "projectIssuesLoadFailed": "Não foi possível carregar as issues do projeto.", + "viewsLoadFailed": "Não foi possível carregar as visualizações.", + "viewContentsLoadFailed": "Não foi possível carregar o conteúdo da visualização.", + "issuesLoadFailed": "Não foi possível carregar as issues do Linear.", + "apiKeyHint": "Cole uma chave de API pessoal do espaço de trabalho do Linear que deseja usar no Orca. Se ele já estiver conectado, o Orca substituirá a chave armazenada.", + "remoteKeyStorage": "Esta chave é armazenada pelo ambiente de execução remoto ativo.", + "localKeyStorage": "As chaves do ambiente de execução local são armazenadas neste dispositivo com o armazenamento criptografado do Electron quando disponível.", + "commentsLoadFailed": "Não foi possível carregar os comentários.", + "updateWorkspaceAccess": "Atualizar acesso ao Linear para {{workspace}}", + "workspaceApiKeyHint": "Cole uma chave de API pessoal de {{workspace}}. Se ele já estiver conectado, o Orca substituirá a chave armazenada.", + "connect": "Conectar", + "descriptionUpdateFailed": "Falha ao atualizar a descrição", + "titleUpdateFailed": "Falha ao atualizar o título", + "truncated": { + "issues_one": "Mostrando {{count}} issue do início da lista. Pesquise ou abra o Linear para ver a lista completa.", + "issues_other": "Mostrando as primeiras {{count}} issues. Pesquise ou abra o Linear para ver a lista completa.", + "projectIssues_one": "Mostrando {{count}} issue do início da lista do projeto. Pesquise ou abra o Linear para ver a lista completa.", + "projectIssues_other": "Mostrando as primeiras {{count}} issues do projeto. Pesquise ou abra o Linear para ver a lista completa.", + "projects_one": "Mostrando {{count}} projeto do início da lista. Pesquise ou abra o Linear para ver a lista completa.", + "projects_other": "Mostrando os primeiros {{count}} projetos. Pesquise ou abra o Linear para ver a lista completa.", + "viewIssues_one": "Mostrando {{count}} issue do início da lista da visualização. Pesquise ou abra o Linear para ver a lista completa.", + "viewIssues_other": "Mostrando as primeiras {{count}} issues da visualização. Pesquise ou abra o Linear para ver a lista completa.", + "views_one": "Mostrando {{count}} visualização do início da lista. Pesquise ou abra o Linear para ver a lista completa.", + "views_other": "Mostrando as primeiras {{count}} visualizações. Pesquise ou abra o Linear para ver a lista completa." + } + }, + "jira": { + "connectionFailed": "Falha na conexão", + "remoteTokenStorage": "Seu token é enviado ao ambiente de execução remoto selecionado e armazenado lá com a criptografia compatível com esse ambiente.", + "localTokenStorage": "Seu token é armazenado localmente e criptografado quando o armazenamento do ambiente de execução local oferece suporte." + }, + "errors": { + "jira": { + "createFailed": "Falha ao criar a issue.", + "commentFailed": "Falha ao adicionar o comentário.", + "notConnected": "Não conectado ao Jira.", + "titleRequired": "O título é obrigatório.", + "labelsConflict": "Forneça labels ou labelOperations, não ambos.", + "updateFailed": "Não foi possível atualizar a issue.", + "credentialsRequired": "A URL do site, o e-mail e o token de API são obrigatórios.", + "projectRequired": "O projeto é obrigatório.", + "issueTypeRequired": "O tipo de issue é obrigatório.", + "issueKeyRequired": "A chave da issue é obrigatória.", + "updatesRequired": "O objeto de atualização é obrigatório.", + "commentBodyRequired": "O conteúdo do comentário é obrigatório.", + "invalidSiteUrl": "Insira uma URL válida do site do Jira.", + "passwordRequired": "A senha é obrigatória.", + "personalTokenRequired": "O token de acesso pessoal é obrigatório.", + "apiTokenRequired": "O token de API é obrigatório.", + "connectionFailed": "Falha na conexão.", + "invalidSiteIdentity": "Insira uma URL HTTP ou HTTPS do site do Jira sem credenciais.", + "missingProjectIdentity": "O Jira retornou um projeto sem ID ou chave.", + "invalidIssuePage": "O Jira retornou uma página de issues inválida.", + "incompleteIssuePage": "O Jira retornou uma página de issues incompleta.", + "repeatedIssueToken": "O Jira retornou um token de página de issues inválido ou repetido.", + "issueSearchLimit": "A busca de issues do Jira excedeu o limite de páginas. Selecione um projeto usando JQL.", + "invalidProjectPage": "O Jira retornou uma página de projetos inválida.", + "incompleteProjectPage": "O Jira retornou uma página de projetos incompleta.", + "projectListLimit": "A lista de projetos do Jira excedeu o limite de páginas. Selecione um projeto usando JQL.", + "invalidCloudId": "O site não informou um ID válido do Atlassian Cloud." + }, + "linear": { + "notConnected": "Não conectado ao Linear", + "createFailed": "Falha ao criar no Linear", + "createdButUnavailable": "A issue foi criada, mas não foi possível recuperá-la", + "updateFailed": "Falha ao atualizar no Linear", + "commentFailed": "Não foi possível criar o comentário", + "projectCreateFailed": "Falha ao criar o projeto do Linear", + "noApiKey": "Nenhuma chave de API armazenada.", + "workspaceAuthExpired": "A autenticação do Linear expirou para este espaço de trabalho.", + "projectNameRequired": "O nome do projeto é obrigatório", + "projectIdRequired": "O ID do projeto é obrigatório", + "projectNotFound": "O projeto não foi encontrado", + "viewIdRequired": "O ID da visualização personalizada é obrigatório", + "viewHasNoIssues": "A visualização personalizada não contém issues", + "viewHasNoProjects": "A visualização personalizada não contém projetos" + } + } + }, + "workspaceOptions": { + "activeFilterCount_one": "{{count}} filtro", + "activeFilterCount_other": "{{count}} filtros" + }, + "editorConflicts": { + "kind": { + "addedByUs": "Adicionado por nós", + "bothAdded": "Adicionado por ambos", + "deletedByUs": "Excluído por nós", + "addedByThem": "Adicionado por eles", + "bothDeleted": "Excluído por ambos", + "bothModified": "Modificado por ambos", + "deletedByThem": "Excluído por eles" + }, + "resolvedBanner": "Conflito resolvido localmente · {{kind}}", + "hint": { + "addedByUs": "Avalie se deve manter o arquivo adicionado", + "bothModified": "Resolva os conflitos indicados pelos marcadores", + "addedByThem": "Revise o arquivo adicionado antes de mantê-lo", + "bothDeleted": "Resolva o conflito no Git ou restaure uma das versões antes de editar", + "deletedByThem": "Decida se deve manter o arquivo ou aceitar a exclusão", + "deletedByUs": "Decida se deve restaurar o arquivo", + "bothAdded": "Escolha qual versão manter ou combine as duas" + }, + "renamedFrom": "Renomeado de {{path}}", + "snapshotCapturedAt": "Snapshot capturado às {{time}}.", + "unresolvedBanner": "Conflito não resolvido · {{kind}}" + }, + "stats": { + "usageBreakdown": { + "turns_one": "{{count}} turno", + "events_one": "{{count}} evento", + "sessions_one": "{{count}} sessão", + "events_other": "{{count}} eventos", + "sessions_other": "{{count}} sessões", + "turns_other": "{{count}} turnos" + } + }, + "github": { + "viewed": { + "markFile": "Marcar {{path}} como visualizado", + "unmarkFile": "Desmarcar {{path}} como visualizado" + } + }, + "wslMove": { + "entry": { + "hostRow": "Mover projetos desta distro…", + "projectMenu": "Mover para o host {{distro}}…" + }, + "blockers": { + "title": "Antes que estes projetos possam ser movidos", + "inProjects": "Em {{names}}", + "skipOne": "Deixar {{name}} fora desta movimentação", + "skipMany": "Deixar estes {{n}} projetos fora desta movimentação" + }, + "title": "Mover projetos para o host {{distro}}", + "loading": "Verificando os projetos em {{distro}}…", + "runningTitle": "Movendo para o host {{distro}}", + "preview": { + "counts": "Projetos: {{projects}} · Espaços de trabalho: {{workspaces}} · Terminais: {{terminals}} · Chats: {{chats}}", + "whatHappens": "Seus arquivos permanecem onde estão. Os terminais reiniciam na mesma pasta; a saída, o histórico do shell e as conversas com agentes são mantidos.", + "projects": "Projetos em {{distro}}", + "folderBadge": "Pasta", + "notMoving": "Não será movido", + "checking": "Verificando os projetos selecionados…", + "checkAgain": "Verificar novamente", + "moveOne": "Mover 1 projeto", + "moveMany": "Mover {{n}} projetos", + "heldByHost": "Já está no host {{distro}}.", + "changed": "Foi movido antes e depois alterado aqui por uma versão anterior do Orca. Não será movido novamente.", + "chatsStay": "Os chats existentes ficam neste computador. Novos chats neste projeto começam no host WSL.", + "browserLoginsConflict": "Os logins do navegador não serão levados, porque o perfil do navegador do host já está em uso. Entre novamente nas abas do navegador do host após a movimentação.", + "browserLoginsNotCarried": "Os logins do navegador não serão levados para este host. Entre novamente nas abas do navegador dele após a movimentação." + }, + "cancel": "Cancelar", + "progress": { + "bytes": "{{sent}} de {{total}}", + "tooLate": "Tarde demais para cancelar: o host já está fazendo a troca. Mantenha o Orca aberto até terminar.", + "switching": "A troca não pode ser cancelada. Mantenha o Orca aberto até terminar.", + "readOnly": "Estes projetos ficam somente leitura enquanto são movidos. Você pode cancelar até a troca começar.", + "cancelUntilSwitch": "Você pode cancelar até a troca começar.", + "closeKeepsGoing": "Fechar esta caixa de diálogo não interrompe a movimentação; ela abre de novo quando a movimentação terminar.", + "cancelling": "Cancelando…", + "cancel": "Cancelar movimentação" + }, + "result": { + "movedTitle": "Movido para o host {{distro}}", + "resetTitle": "Nada foi movido", + "waitingTitle": "Aguardando o host {{distro}}", + "earlierMoveTitle": "Uma movimentação anterior terminou primeiro", + "refusedTitle": "Projetos não movidos", + "reloadCheckpointRefused": "O Orca não conseguiu fazer backup dos arquivos não salvos, então a janela não foi recarregada. Feche esta caixa de diálogo, salve ou feche esses arquivos e use Recarregar agora no aviso que continua aberto.", + "reloadVetoed": "Algo impediu a janela de recarregar. Feche esta caixa de diálogo, salve seu trabalho e use Recarregar agora no aviso que continua aberto.", + "reloadFailed": "A janela não foi recarregada. Tente novamente.", + "moved": "Recarregue esta janela para ver os projetos no host {{distro}}. O Orca faz backup dos arquivos não salvos antes de recarregar.", + "automationsPendingOne": "Uma automação está desativada no host por enquanto. O Orca continua pedindo ao host para reativá-la.", + "automationsPendingMany": "{{n}} automações estão desativadas no host por enquanto. O Orca continua pedindo ao host para reativá-las.", + "undoHint": "Mudou de ideia? Depois de recarregar, a barra lateral mostra estes projetos como “Movido para o host {{distro}}”. Escolha “Usar novamente neste computador” ali para trazê-los de volta como estavam antes da movimentação.", + "reset": "A movimentação parou e tudo foi restaurado. Os projetos funcionam neste computador como antes; os terminais pausados reiniciam quando você os abre.", + "resetReason": "Por que parou: {{detail}}", + "waiting": "A movimentação pode ter chegado ao host {{distro}}, mas o host não está respondendo. Estes projetos ficam somente leitura aqui até ele responder. Conecte o host em Configurações, abra esta caixa de diálogo novamente e inicie uma movimentação: o Orca conclui ou desfaz esta primeiro.", + "reloading": "Recarregando…", + "reload": "Recarregar agora", + "close": "Fechar", + "review": "Voltar aos projetos", + "browserLoginsHostUnknown": "Os logins do navegador não foram copiados, porque o Orca não conseguiu identificar o perfil do navegador do host. Entre novamente nas abas do navegador do host.", + "browserLoginsConflict": "Os logins do navegador não foram copiados, porque o perfil do navegador do host já está em uso. Entre novamente nas abas do navegador do host.", + "browserLoginsNotCopied": "Os logins do navegador não foram copiados para o host. Entre novamente nas abas do navegador do host." + }, + "runtime": { + "label": "Ambiente de execução do projeto", + "description": "Este projeto é executado em {{distro}} por meio deste computador. Mova-o para o host {{distro}} para executá-lo lá.", + "move": "Mover projeto" + }, + "unfinished": { + "one": "Uma automação movida para o host {{distro}} ainda está desativada. O Orca continua pedindo ao host para reativá-la.", + "many": "{{n}} automações movidas para o host {{distro}} ainda estão desativadas. O Orca continua pedindo ao host para reativá-las." + }, + "refusal": { + "previewFailed": "O Orca não conseguiu verificar estes projetos. Tente novamente.", + "startFailed": "O Orca perdeu o contato com a movimentação. Abra esta caixa de diálogo novamente para ver em que ponto ela está.", + "unavailable": "Mover projetos para um host WSL não está disponível nesta janela.", + "alreadyRunning": "Uma movimentação para {{distro}} já está em andamento. Aguarde até que termine e tente novamente.", + "alreadyInFlightPreview": "Uma movimentação de {{distro}} ainda está terminando. Ao iniciar esta movimentação, o Orca primeiro conclui ou desfaz aquela, quando possível.", + "alreadyInFlight": "Uma movimentação de {{distro}} ainda está terminando, então esta não foi iniciada. Mantenha o host {{distro}} conectado e tente novamente mais tarde.", + "nothingNew": "Estes projetos já estão no host {{distro}}.", + "destinationChanged": "Projetos anteriores de {{distro}} foram movidos para outro host WSL. Conecte esse host para mover mais.", + "hostUnavailable": "O host {{distro}} não está conectado. Conecte-o em Configurações e tente novamente.", + "hostUpdateRequired": "O host {{distro}} usa uma versão anterior do Orca. Atualize-o em Configurações e tente novamente.", + "terminalsBlocked": "Alguns terminais, agentes ou automações nestes projetos estão ocupados. Nada foi movido.", + "exportIncomplete": "Parte do estado salvo destes projetos ainda não pode ser movida, então nada foi movido:", + "exportIncompletePreview": "Parte do estado salvo destes projetos ainda não pode ser movida:", + "tooLarge": "Estes projetos têm estado salvo demais para mover de uma vez. Mova menos projetos por vez.", + "pauseFailed": "O Orca não conseguiu pausar os terminais destes projetos, então nada foi movido. Os terminais pausados reiniciam quando você os abre. Tente novamente.", + "scopeChanged": "Um projeto mudou enquanto a movimentação era preparada, então nada foi movido. Confira os projetos e tente novamente.", + "cancelled": "Movimentação cancelada. Nada foi movido.", + "finishedEarlierMove": "O Orca concluiu primeiro uma movimentação anterior para {{distro}}. Recarregue a janela e inicie esta movimentação novamente." + }, + "step": { + "preparing": "Preparando", + "pausingTerminals": "Pausando terminais", + "copying": "Copiando", + "switching": "Trocando", + "finishing": "Finalizando", + "done": "Concluído" + }, + "blocker": { + "agentWorkingOne": "Um agente está trabalhando ou aguardando uma resposta", + "agentWorkingMany": "{{n}} agentes estão trabalhando ou aguardando uma resposta", + "processRunningOne": "Um terminal está executando um programa", + "processRunningMany": "{{n}} terminais estão executando um programa", + "agentNotResumableOne": "Um agente não poderá ser retomado após a movimentação", + "agentNotResumableMany": "{{n}} agentes não poderão ser retomados após a movimentação", + "unverifiableOne": "O Orca não consegue verificar um terminal agora", + "unverifiableMany": "O Orca não consegue verificar {{n}} terminais agora", + "automationRunningOne": "Uma execução de automação está ativa", + "automationRunningMany": "{{n}} execuções de automação estão ativas", + "dispatchRunningOne": "Uma tarefa de agente está em andamento", + "dispatchRunningMany": "{{n}} tarefas de agente estão em andamento", + "scrollbackTooLargeOne": "Um terminal tem histórico de saída demais para ser movido", + "scrollbackTooLargeMany": "{{n}} terminais têm histórico de saída demais para serem movidos" + }, + "blockerHint": { + "agentWorking": "Deixe-o terminar, ou pare-o no terminal dele, e verifique novamente.", + "processRunning": "Pare o programa (por exemplo, um servidor de desenvolvimento ou editor) e verifique novamente.", + "agentNotResumable": "Saia do agente no terminal dele e verifique novamente.", + "unverifiable": "Aguarde um momento e verifique novamente. Nada é interrompido para que a movimentação aconteça.", + "wait": "Aguarde até que termine e verifique novamente.", + "scrollbackTooLarge": "Limpe a saída desses terminais e verifique novamente." + }, + "scopeRefused": { + "windowsDrive": "A pasta dele está em uma unidade do Windows, então ele fica neste computador.", + "mixedLocations": "Algumas das pastas dele estão fora desta distro, então ele fica neste computador.", + "notLocal": "Ele já é executado em outro host.", + "other": "Ele não pode ser movido." + }, + "reloadToast": { + "title": "Recarregue para concluir a movimentação" + }, + "orchestrator": { + "showTerminal": "Mostrar terminal", + "moveAgain": "Mover novamente", + "checkAgain": "Verificar novamente", + "deferred": "Concluindo sua movimentação para o host {{distro}}: alguns terminais ainda estão ocupados.", + "stuck": "Uma movimentação anterior para o host {{distro}} ainda não terminou de se acomodar.", + "declined": "A movimentação está pausada porque você trouxe estes projetos de volta para este computador.", + "doneToast": "Projetos movidos para o host {{distro}}", + "terminalGone": "Esse terminal não está mais aberto nesta janela. Verifique novamente para atualizar.", + "blocker": "{{title}}. {{hint}}", + "paused": "A movimentação de projetos para o host {{distro}} está pausada: {{reason}}.", + "pausedReason": { + "exportIncomplete": "parte do estado salvo ainda não pode ser levada", + "manifestTooLarge": "há mais estado salvo do que uma movimentação comporta", + "hostUpdate": "o host precisa ser atualizado primeiro", + "attemptsExhausted": "ela não foi concluída após várias tentativas" + }, + "finishPending": "Uma movimentação anterior para o host {{distro}} já foi concluída lá. O Orca a conclui aqui quando reiniciar, ou agora com Verificar novamente." + } } } diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 8d7e62b0279a..09eb68c346b2 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -110,11 +110,15 @@ "system": "系统", "english": "English", "chinese": "中文(简体)", + "chineseTraditional": "繁體中文(台灣)", "korean": "한국어", "japanese": "日本語", "spanish": "Español", "french": "Français", - "portuguese": "Português (Brasil)" + "portuguese": "Português (Brasil)", + "russian": "Русский", + "turkish": "Türkçe", + "german": "Deutsch" }, "statusBar": { "claudeToggleDescription": "显示当前工作区的 Claude Token 与费用消耗情况。", @@ -346,7 +350,8 @@ "permissionOverridesUse": "使用 {{mode}}", "customPermissions": "自定义参数", "rowPermissionsLabel": "{{agent}} 权限", - "replaceWithPermissionMode": "替换为 {{mode}}" + "replaceWithPermissionMode": "替换为 {{mode}}", + "approveForMe": "代我批准" }, "followSymlinkedDirectoriesKeywords": { "symlink": "符号链接", @@ -377,6 +382,34 @@ "actionPermissions": { "sameAsAgent": "与 {{agent}} 相同" } + }, + "ssh": { + "status": { + "disconnected": "已断开", + "connecting": "正在连接…", + "auth-failed": "验证失败", + "connected": "已连接", + "reconnection-failed": "重新连接失败", + "deploying-relay": "正在部署中继…", + "reconnecting": "正在重新连接…" + } + }, + "mcp": { + "workspace": "工作区", + "inspectFailed": "无法检查 {{directory}}。", + "unreadable": "无法读取", + "notFound": "未找到", + "invalidJson": "无效的 JSON", + "noServers": "没有服务器", + "httpServer": "HTTP 服务器", + "stdioServer": "stdio 服务器", + "invalidServer": "无效的服务器", + "serverCount_one": "{{count}} 个服务器", + "serverCount_other": "{{count}} 个服务器", + "claudeWorkspace": "Claude 工作区" + }, + "shortcuts": { + "parseFailed": "无法解析快捷键。" } }, "menu": { @@ -1465,9 +1498,6 @@ "3fdf777817": "在 GitHub 上打开", "c43fe79ee0": "复制 GitHub 链接", "0caac1a18f": "从 PR 启动工作区", - "8223320f8d": "已更新", - "10ef1afb8e": "· 已更新", - "55962099bc": "创建了此议题", "0ab4664a8b": "从议题开始工作区", "36182aa57f": "启动新工作区", "fe6ff12dc2": "更多议题工作区操作", @@ -1540,8 +1570,6 @@ "52b20b56f7": "描述", "4d555d3796": "编辑描述", "9df4e74bdf": "保存", - "0ae387d8ca": "由", - "228e2f59d3": "已解决", "a154ec5224": "在 GitHub 上打开评论", "bca8eb39ac": "回复评论", "68cb993d61": "已解决", @@ -1557,13 +1585,11 @@ "d43736d09c": "代码上下文控制", "bd7be7b1fd": "comment L", "db61d76cd5": "正在加载代码上下文...", - "f2d02cdf8c": "已查看文件", "1257d1435d": "显示文件树", "a341343303": "已添加评审评论。", "d1fa2cf888": "没有 PR head SHA 就无法发表评论。", "829674460a": "Diff 不可用,因为 PR commit SHA 丢失。", "af924014f8": "已查看", - "2d89a38d9d": "{{value0}} {{value1}} 为已查看", "70e84e3d0b": "没有匹配的评审人。", "1ffce94a8b": "其他人", "c2b21818e1": "建议", @@ -1598,8 +1624,6 @@ "ec5c4b3ab2": "重新打开 PR", "21860b58d0": "关闭PR", "5932578f51": "合并需要注册本地仓库", - "e2bf3e41a9": "评论", - "28d0d3374f": "帖子串", "080d071d48": "回复@{{value0}}", "86f809e2ce": "在此评审线程中回复", "136542c9ba": ":L{{value0}}", @@ -1629,7 +1653,9 @@ "from": "从", "to": "到", "activity": "活动", - "noActivity": "暂无活动。" + "noActivity": "暂无活动。", + "pullRequestReference": "PR #{{number}}", + "issueReference": "议题 #{{number}}" }, "checkActionRequiredHint": "需要在 GitHub 上执行手动操作(例如批准运行)才能解除合并阻止。", "e15a8b77ef": "此检查没有可用的内联详细信息。", @@ -1643,8 +1669,13 @@ "09d67a0f9b": "无法关闭拉取请求", "88809e79db": "无法重新提交拉取请求", "00f55cc17b": "此拉取请求无法访问仓库。", - "reactionCountSingular": "{{count}} 个 {{reaction}} 反应", - "reactionCountPlural": "{{count}} 个 {{reaction}} 反应" + "reactionCount_other": "{{count}} 个“{{reaction}}”反应", + "filesViewed_other": "已查看 {{viewed}} / {{count}} 个文件", + "updatedRelativeTime": "更新于 {{time}}", + "authorOpenedThisIssue": " 创建了此议题", + "middotUpdatedRelativeTime": "· 更新于 {{time}}", + "resolvedThreadBy": "{{author}} 发起的已解决讨论串", + "resolvedCommentBy": "{{author}} 发表的已解决评论" }, "GitLabItemDialog": { "65e784c1f1": "重新打开", @@ -1700,14 +1731,13 @@ "f23ea85341": "已解决", "6de8ce0cc6": "需要 {{value0}}", "22511537d2": "已批准", - "00f3bab87b": "需要 {{value0}}", "3a051b8ade": "工作项目", "32f8bef818": "无日志输出。", "4168eb2c51": "解决", "commentTooLarge": "评论过长,无法安全提交。", "gitlabActionFailed": "GitLab 操作失败。", - "approvalsRemainingSingular": "还需 {{count}} 个批准", - "approvalsRemainingPlural": "还需 {{count}} 个批准" + "approvalsRemainingOfRequired_other": "共需 {{required}} 个批准,还差 {{count}} 个", + "approvalsRemaining_other": "还需 {{count}} 个批准" }, "JiraIssueWorkspace": { "b0b92666c9": "评论", @@ -1732,14 +1762,11 @@ "69da9a208c": "在 Jira 中打开", "fa132c8aed": "添加评论失败。", "ea21952aa3": "无法更新 Jira 议题。", - "6c41a9bcea": "复制 {{value0}} 失败", - "2ff69a3545": "{{value0}} 已复制", "666cfdd835": "未知", "ef21405c6d": "Jira 议题", "commentTooLarge": "评论过长,无法安全提交。" }, "Landing": { - "76a95f7f47": "创建", "f9eaa9e12d": "添加项目", "6ca6ff404e": "ORCA", "520304a067": "Orca 标志", @@ -1755,7 +1782,12 @@ "0d0ace8861": "在 GitHub 上加星标", "ec43b38ba7": "已在 GitHub 上加星标", "157bb5ecbb": "打开 GitHub", - "preflightDismiss": "关闭" + "preflightDismiss": "关闭", + "moveUpWorkspace": "选择上一个工作区", + "moveDownWorkspace": "选择下一个工作区", + "installGit": "安装 Git", + "installGitHubCli": "安装 GitHub CLI", + "learnMore": "了解更多" }, "LinearIssueMarkdownDescriptionEditor": { "d9c47069ef": "Markdown", @@ -1780,14 +1812,12 @@ "LinearIssueTextEditor": { "947ba2d6f4": "保存", "04d73b72dc": "议题标题", - "e8ff595db3": "更新 {{value0}} 失败", "1e08a1ec80": "标题为必填项" }, "LinearIssueWorkspace": { "ad5dec37b7": "预览、编辑并从选定的议题开始工作。", "c23e79e5c0": "操作", "b0eac92d85": "重试", - "fabbd3f974": "更新了议题·", "543970c87a": "活动", "df4c86ed12": "关闭", "7a4997d8bb": "关闭 Linear 议题预览", @@ -1811,11 +1841,8 @@ "b25e453c9d": "创建子议题失败", "aeed19d003": "创建 {{value0}}", "9a1317cdd3": "无法加载子议题", - "9bcbaa2737": "复制 {{value0}} 失败", - "7835483c43": "{{value0}} 已复制", "61f424f8ca": "Linear 议题", "ca8778c124": "未知", - "8a33c85e9c": "有人", "65239a714b": "Linear", "76ffd3c937": "搜索要添加的项目。", "c11b4e3cc2": "没有找到项目。", @@ -1826,7 +1853,10 @@ "moreWorkspaceActions": "更多议题工作区操作", "startNewWorkspace": "启动新工作区", "workspaceSection": "工作区", - "noWorkspaceYet": "暂无" + "noWorkspaceYet": "暂无", + "issueDescriptionLabel": "议题描述", + "namedUserUpdatedIssue": "{{name}} 更新了议题 · {{time}}", + "someoneUpdatedIssue": "有人更新了议题 · {{time}}" }, "LinearItemDrawer": { "04008e6c46": "从议题开始工作区", @@ -1862,7 +1892,9 @@ "openAttachedWorkspace": "打开关联到议题的工作区", "openWorkspace": "打开工作区", "moreWorkspaceActions": "更多议题工作区操作", - "startNewWorkspace": "启动新工作区" + "startNewWorkspace": "启动新工作区", + "setEstimate": "设置估计值", + "estimateValue": "估计值 {{estimate}}" }, "NewWorkspaceComposerCard": { "cbb47ee0dc": "仅适用于本地 Git 项目。", @@ -1924,7 +1956,22 @@ "defaultBranchUpdateFailed": "无法更新项目默认分支。再试一次。", "setLocation": "设置项目位置", "setLocationOnHost": "将项目位置设置为 {{host}}", - "setLocationTooltip": "选择一个文件夹或将此项目克隆到 {{host}} 上。" + "setLocationTooltip": "选择一个文件夹或将此项目克隆到 {{host}} 上。", + "connect": "连接", + "reconnect": "重新连接", + "setupConfigDefaultTabs": "默认标签页命令", + "setupConfigSetupAndDefaultTabs": "设置及默认标签页命令", + "setupConfigSetupScript": "设置脚本", + "runDefaultTabCommands": "运行默认标签页命令", + "runSetupAndDefaultTabCommands": "运行设置及默认标签页命令", + "runSetupCommand": "运行设置命令", + "askRunDefaultTabCommands": "立即运行默认标签页命令?", + "askRunSetupAndDefaultTabCommands": "立即运行设置及默认标签页命令?", + "askRunSetup": "立即运行设置?", + "runSetupNow": "立即运行设置", + "runCommandsNow": "立即运行命令", + "skipForNow": "暂时跳过", + "skipCommands": "跳过命令" }, "NewWorkspaceComposerModal": { "createWorktree": "创建工作树", @@ -2014,9 +2061,6 @@ "778683ec84": "描述", "da9aaa8bcf": "编辑描述", "4a337ac05f": "保存", - "169a93b29a": "已更新", - "3c891789f6": "由", - "f4fe47c2bb": "已解决", "0ac19bb52e": "在 GitHub 上打开评论", "d6c6679de7": "回复评论", "76b2a0ac5b": "已解决", @@ -2024,7 +2068,6 @@ "6885c619e7": "如果没有仓库路径,则无法回复。", "d94810f652": "无法更新描述。", "9b4190dc98": "描述已更新。", - "89e80af1c7": "已查看文件", "319cf2d54b": "显示文件树", "eff839f438": "已添加评审评论。", "d8c3ba91c4": "没有 PR head SHA 就无法发表评论。", @@ -2062,8 +2105,6 @@ "9d5425918e": "重新打开 PR", "96d013ed28": "关闭PR", "eca289e593": "合并需要注册本地仓库", - "e01e34f5fa": "评论", - "345b68254c": "帖子串", "31a7b202f2": "回复@{{value0}}", "408e634fbb": "在此评审线程中回复", "34b9f7c264": ":L{{value0}}", @@ -2089,7 +2130,18 @@ "diffLoadTimedOut": "加载此差异超时。", "6b1d5ee3e4": "此检查没有可用的内联详细信息。", "e04c027d98": "无法加载检查详细信息。", - "5df7c41d2a": "重试" + "5df7c41d2a": "重试", + "filesViewed_other": "已查看 {{viewed}} / {{count}} 个文件", + "updatedRelativeTime": "更新于 {{time}}", + "resolvedThreadBy": "{{author}} 发起的已解决讨论串", + "resolvedCommentBy": "{{author}} 发表的已解决评论", + "mentionSource": { + "prAuthor": "PR 作者", + "issueAuthor": "议题作者", + "commenter": "评论者", + "participant": "参与者", + "teamMember": "团队成员" + } }, "QuickOpen": { "1dbd3f59ff": "移动", @@ -2103,13 +2155,11 @@ "9e97f08d0f": "搜索要打开的文件", "ec31e058f7": "转到文件", "73b44e7bde": "复制安装命令", - "1cf8561ab4": "在远程启用快速、gitignore 感知列表:", - "5d80dc39bb": "ripgrep", - "2ca749c15d": "安装", - "4725b0e931": "快速打开扫描太大(", - "b227d88520": "找到 {{value0}} 文件", "995be8ea22": "复制", - "cf144856dc": "已复制" + "cf144856dc": "已复制", + "filesFound_other": "找到 {{count}} 个文件", + "hostCouldNotOpenPath": "主机无法打开此文件路径。", + "chooseFileNotDirectory": "请选择文件,而非目录。" }, "SelectedTextCopyMenu": { "9b40d7b018": "复制" @@ -2127,7 +2177,6 @@ "TaskPage": { "ff69a30681": "取消", "8ff6fdc368": "创建中…", - "fc0d8a1fa4": "提交。", "919a20dd5b": "输入 {{value0}}", "56cdb413a2": "逗号分隔值", "1f0fce91e3": "选择{{value0}}", @@ -2175,14 +2224,9 @@ "bdebffcbfe": "为所选团队创建 Linear 项目。", "1361275ec3": "新建 Linear 项目", "7f3f7b4c18": "描述(可选,markdown)", - "9f2b4c03a6": "提交", "d3d0998b7d": "新的 GitHub 议题", - "d1e243795c": "议题", - "be8cf68d9f": "查看议题", - "67662ade50": "项目议题", "6244a02f46": "在 Linear 中打开", "606a85c774": "开放", - "5e8061b088": "从 {{value0}} {{value1}} 开始工作区", "592a55611b": "尝试选择更多的团队或者刷新;团队筛选条件适用于当前获取的议题集。", "618107fab3": "没有获取到与所选团队匹配的议题", "903c7af49f": "未找到 Linear 议题", @@ -2191,7 +2235,6 @@ "f362667d55": "已更新", "b1eaa18ace": "议题", "37e7ee311e": "标识", - "b7bae28b6a": "显示", "a26a48252e": "显示属性", "5d2d835467": "排序", "5659da12fc": "分组", @@ -2199,11 +2242,9 @@ "af377b13b1": "{{value0}} 视图", "d47248df4d": "Linear 视图模式", "f397d513e3": "返回", - "b39fe6511d": "项目", "8675cd6188": "Linear", "733b8f2421": "Linear/视图", "bc06ed0fb0": "返回视图", - "3cb855080f": "视图", "b4e10f096e": "所有者", "a04fe7ba73": "可见性", "0aa8525950": "模型", @@ -2233,8 +2274,6 @@ "054bf695cc": "草稿", "5b6b2af943": "正在重试...", "0c0de0fc0e": "无法加载议题,来源", - "d1766fd62d": "项目加载失败", - "7762f4b03a": "的", "443f7dd928": "合并", "a7396b05c6": "检查项", "f6fa3c97d0": "评审人", @@ -2416,10 +2455,36 @@ "jiraColumnOriginalEstimate": "预估", "jiraColumnRemainingEstimate": "剩余", "jiraBoardEmptyColumn": "没有议题", - "labelCountPlural": "{{count}} 个标签", - "labelCountSingular": "{{count}} 个标签", - "memberCountPlural": "{{count}} 名成员", - "memberCountSingular": "{{count}} 名成员" + "backToPullRequests": "拉取请求", + "backToGitHubList": "GitHub 列表", + "noGitHubRepositoryContext": "此议题没有可用的 GitHub 仓库上下文。", + "filingInTarget": "将在 {{target}} 中创建", + "filingInThisRepository": "将在此仓库中创建", + "shortcutToSubmit": "按 {{shortcut}} 提交。", + "projectsFailedToLoad_other": "{{count}} 个项目中有 {{failed}} 个加载失败", + "draftPullRequestNumber": "草稿拉取请求 #{{number}}", + "pullRequestNumber": "拉取请求 #{{number}}", + "issueNumber": "议题 #{{number}}", + "loadGitHubWorkFailed": "加载 GitHub 工作项失败。", + "gitlabViewIssues": "议题", + "gitlabViewMrs": "MR", + "gitlabViewTodos": "我的待办", + "startWorkspaceFromMr": "从 MR {{number}} 启动工作区", + "startWorkspaceFromIssue": "从议题 {{number}} 启动工作区", + "shownCount_other": "已显示 {{count}} 项", + "linearProjectPlaceholder": "项目", + "labelCount_other": "{{count}} 个标签", + "memberCount_other": "{{count}} 位成员", + "groupUnassigned": "未分配", + "linearProjectContext": "项目:{{name}}", + "linearViewContext": "视图:{{name}}", + "changedFileCount_other": "{{count}} 个文件", + "resumeRestoration": { + "linearProjectNotFound": "未找到已保存的 Linear 项目。", + "linearProjectRestoreFailed": "恢复已保存的 Linear 项目失败。", + "linearViewNotFound": "未找到已保存的 Linear 视图。", + "linearViewRestoreFailed": "恢复已保存的 Linear 视图失败。" + } }, "Terminal": { "73768427cf": "关闭", @@ -2494,7 +2559,8 @@ "b1e390250d": "无法完成本地构建切换。", "d29740d175": "无法使用所选的构建。", "37d45c9ec1": "选择其他构建", - "7f1a4c9e02": "您的系统包管理器安装了 Orca,因此请从那里更新它 — Orca 本身无法安装此版本。" + "7f1a4c9e02": "您的系统包管理器安装了 Orca,因此请从那里更新它 — Orca 本身无法安装此版本。", + "compatibilityModeFailed": "无法启用兼容模式。{{message}}" }, "WorktreeJumpPalette": { "ac037cfac2": "移动", @@ -2520,8 +2586,6 @@ "d7d496a451": "浏览器页面不再存在", "50a1d11d5b": "打开标签页", "088d66d980": "操作与设置", - "20af998bff": "{{value0}} 可用项{{value1}}", - "bb72c08e63": "找到 {{value0}} 结果{{value1}}", "34c8fbb46e": "SSH远程", "63c2be1914": "SSH 已断开连接", "95be6587d3": "创建工作树“{{value0}}”", @@ -2538,7 +2602,10 @@ "27f10cca63": "搜索聊天、终端、工作区、任务、设置和操作...", "2770f02910": "搜索聊天、终端、工作区、任务、设置和操作", "recentChatsTerminalsHeader": "最近的聊天和终端", - "lastActiveTime": "最后活跃时间 {{value0}} 前" + "lastActiveTime": "最后活跃时间 {{value0}} 前", + "resultsFound_other": "找到 {{count}} 个结果。", + "itemsAvailable_other": "{{count}} 个项目可用。", + "createActionAvailable": "可执行创建工作树操作。" }, "github": { "pr": { @@ -2579,7 +2646,8 @@ "8f6cb3772f": "满足要求后自动合并此PR", "def355ff38": "可以合并", "e42c5bae67": "GitHub 显示此 PR 可以合并且检查已通过", - "cbf0113af6": "GitHub 显示此 PR 可以合并" + "cbf0113af6": "GitHub 显示此 PR 可以合并", + "autoMergeOn": "自动合并已开启" } } }, @@ -2753,10 +2821,10 @@ "imageUrlTooLarge": "图片 URL 过长。" }, "IssueSourceSelector": { - "d6aeb2012b": "显示议题来自", "787c970baf": "议题来源", "51d1608920": "origin", - "30b2c9df91": "上游" + "30b2c9df91": "上游", + "showingIssuesFromRepo": "正在显示来自 的议题" }, "PRFilterDropdowns": { "979be3cf6b": "负责人", @@ -2766,12 +2834,18 @@ "01f3f3d161": "作者", "13b3ac0a84": "状态", "79c54552f7": "筛选条件", - "8a2ffbf9b3": "删除 {{value0}} 筛选条件" + "8a2ffbf9b3": "删除 {{value0}} 筛选条件", + "anyState": "任意", + "currentUser": "当前用户" }, "PRFilterPickers": { - "fdf387297c": "清除 (", "472c12ae03": "清除", - "2d1f58eda6": "使用" + "pressEnterToUseValue": "按 Enter 使用输入的值。", + "useTypedValue": "使用 ", + "clearSelected": "清除({{count}})", + "loading": "加载中…", + "searchTextTooLarge": "搜索文本过长。", + "noMatches": "无匹配项" }, "PRFilterSections": { "a00830d3f7": "没有用户", @@ -2781,7 +2855,6 @@ "458ea3602b": "没有作者", "b69fa4fa20": "返回", "30ebb6ca44": "清除所有筛选条件", - "8177eda37e": "筛选", "ea3416d646": "负责人", "b1d9fdea08": "标签", "24754c44ad": "作者", @@ -2793,7 +2866,14 @@ "2b2f019091": "任意状态", "0fd3249e2e": "已关闭", "d78b60b5c2": "开放", - "bd162b7d5a": "合并" + "bd162b7d5a": "合并", + "draft": "草稿", + "labelCount_other": "{{count}} 个标签", + "allStates": "全部", + "filterPullRequests": "筛选 PR", + "filterIssues": "筛选议题", + "filterOrTypeLogin": "筛选或输入登录名...", + "filterLabels": "筛选标签..." }, "github": { "rate": { @@ -2804,15 +2884,14 @@ "d12d3d6f33": "刷新 GitHub API 预算", "d5e5de9070": "Orca 通过 GitHub CLI 使用 REST、搜索和 GraphQL。", "58c5f88216": "GitHub API 预算", - "6da1858354": "剩余 · 重置于", - "f42790d150": "的", "01f7323e58": "GraphQL API", "1daf0f22a9": "GraphQL", "1f2f28a4de": "搜索 API", "c377a4f06a": "搜索", "c392c749a6": "REST API", "bb227706a6": "REST", - "budget_scope_prefix": "预算范围" + "budget_scope_prefix": "预算范围", + "remainingOfLimitResetsIn": "剩余 {{remaining}} / {{limit}} · {{reset}} 后重置" } } } @@ -2820,7 +2899,29 @@ "CommentReactions": { "addReaction": "添加反应", "removeNamedReaction": "去除 {{value0}} 反应", - "addNamedReaction": "添加 {{value0}} 反应" + "addNamedReaction": "添加 {{value0}} 反应", + "reaction": { + "thumbsUp": "赞", + "thumbsDown": "踩", + "laugh": "大笑", + "confused": "困惑", + "heart": "爱心", + "hooray": "欢呼", + "rocket": "火箭", + "eyes": "眼睛" + } + }, + "CommentCodeContext": { + "showSurroundingCodeBlock": "显示周围代码块", + "showNearbyCodeContext": "显示附近代码上下文" + }, + "prCheckPresentation": { + "successful": "成功", + "inProgress": "进行中" + }, + "IssueSourceIndicator": { + "issueFromRepo": "来自 的议题", + "issuesFromRepo": "来自 的议题" } }, "linear": { @@ -2840,11 +2941,6 @@ } } }, - "priority": { - "icon": { - "c43d3e065b": "优先事项:" - } - }, "project": { "view": { "surfaces": { @@ -2863,7 +2959,6 @@ "c8db98b73b": "资源", "bb1405eff8": "里程碑", "5d99315fb8": "规划", - "3ad562bdf4": "范围议题", "563501f191": "进度", "bb5664d456": "无项目描述。", "7b147907dc": "Linear", @@ -2874,8 +2969,6 @@ "7616c986c6": "打开 {{value0}} 议题", "openInLinear": "在 Linear 中打开 {{value0}}", "93e1f6bfca": "加载中", - "98730088a6": "。在 Linear 中搜索或打开以查看完整列表。", - "06b887d622": "首先显示", "linearLoginUnreadable": "无法读取已保存的 Linear 登录信息。请在设置中重新连接。", "f2cc1e0ff6": "Linear/项目", "906b5e4cb8": "Linear/项目/{{value0}}", @@ -2890,7 +2983,9 @@ "df4bd63c1d": "未分配", "30402d2c6e": "尝试搜索或刷新。", "a2f31c4cd6": "未找到 Linear 项目", - "c9b6e9f90d": "无法加载 Linear 项目" + "c9b6e9f90d": "无法加载 Linear 项目", + "scopedIssueCount_other": "范围内有 {{count}} 个议题", + "backlog": "待办" } } }, @@ -2903,7 +2998,13 @@ "05baa5ae90": "工作区", "89f6580dbf": "搜索团队...", "b3488fad3c": "没有提取任何团队。访问权限可能取决于密钥范围、私有团队成员资格、存档团队、权限或获取失败。", - "405b33c378": "没有提取的团队与您的搜索相匹配。" + "405b33c378": "没有提取的团队与您的搜索相匹配。", + "teamCount_other": "{{count}} 个团队" + } + }, + "priority": { + "icon": { + "priorityValue": "优先级:{{label}}" } } }, @@ -4398,10 +4499,7 @@ }, "UsageBreakdownSection": { "7765a4c3e1": "n/a", - "247c93ca92": "• 推理价格", - "32176e1d44": "轮次", - "79a69522a5": "事件", - "02a046792e": "会话 •" + "247c93ca92": "• 推理价格" }, "GrokUsagePane": { "g8h9i0j1k2": "Grok 使用量", @@ -5473,7 +5571,7 @@ "5d1a5d51bb": "已停止 {{value0}} 上的进程", "c89f290e25": "已复制 {{value0}}", "d1113f4660": "无法打开浏览器", - "fed49903c9": "{{value0}} 直播 {{value1}}", + "fed49903c9": "{{value0}} 个正在运行的 {{value1}}", "unknownProcess": "未知进程" }, "WorktreeContextMenu": { @@ -5909,7 +6007,8 @@ }, "sidebarHostOptions": { "3e102f111c": "所有主机", - "visibleHostsCount": "{{value0}} 个主机" + "hosts": "主机", + "visibleHosts_other": "{{count}} 个主机" }, "HostRemoveDialog": { "1a2b3c4d5e": "已移除 {{value0}}", @@ -5924,12 +6023,10 @@ "oneWorkspace": "1 个工作区", "manyWorkspaces": "{{count}} 个工作区", "hostHasWorkspacesDefault": "从此计算机移除 {{value0}} 及其凭据。其 {{value1}} 保留在 Orca 中 — 远程文件不会被删除。", - "alsoDeleteRemote": "同时在 {{value1}} 上删除这些 {{value0}}", "alsoForgetLocal": "同时从 Orca 中移除这些 {{value0}}", "advanced": "高级", - "alsoDeleteRemoteHint": "永久删除远程 Git 工作树及其分支。此操作不可撤销。", "alsoForgetLocalHint": "仅从 Orca 中清除。远程文件、工作树和分支均不受影响。", - "wslHostEndsTerminals": "从 Orca 中移除 {{value0}},结束其打开的终端,并停止该发行版中的 Orca 服务器。发行版中的文件不受影响。" + "wslHostEndsTerminalsUnlessShared": "从 Orca 中移除 {{value0}}。除非此计算机上打开的另一个 Orca 正在使用它,否则还会结束其打开的终端,并停止该发行版中的 Orca 服务器。发行版中的文件不受影响。" }, "HostRenameDialog": { "1a2b3c4d5e": "重命名主机", @@ -6083,14 +6180,9 @@ "sshImportSyncedSingular": "已将 {{count}} 个主机添加到 Orca。" }, "ForgetSshWorkspaceDialog": { - "reconnectFailed": "重新连接失败", - "forgetBody": "仅从 Orca 中移除此工作区。文件、Git 工作树和 {{host}} 上的分支保持不变。", - "title": "从 Orca 中移除“{{name}}”?", - "disconnectedBody": "此工作区的 SSH 主机未连接。重新连接以同时在远程删除,或仅从 Orca 中移除。", "ghostBody": "{{host}} 不再是已保存的 SSH 主机,因此此工作区不再连接到活跃主机。只能从 Orca 中移除 — 远程文件和分支保持不变。", "cancel": "取消", - "forget": "从 Orca 中移除", - "reconnectAndDelete": "重新连接并删除" + "forget": "从 Orca 中移除" }, "MarkdownImageLightbox": { "image": "Image", @@ -6204,7 +6296,7 @@ "running": "运行中", "stopped": "已停止", "title": "添加 WSL 发行版", - "description": "Orca 在发行版内运行其服务器,因此 git、文件和终端都在 Linux 中原生运行。请将其用于新项目;通过 \\\\wsl.localhost 打开的项目会照常工作。", + "description": "Orca 在发行版内运行其服务器,因此 git、文件和终端都在 Linux 中原生运行。此发行版中通过 \\\\wsl.localhost 打开的项目会在其终端空闲时自动移到此主机;位于 Windows 驱动器 (/mnt/…) 上的项目会留在此电脑。你可以从侧边栏将已移动的项目移回。", "distro": "发行版", "loading": "正在查找 WSL 发行版…", "placeholder": "选择发行版", @@ -6231,6 +6323,7 @@ "removalPending": "移除未完成" }, "wslHostRemoval": { + "keptForOthers": "已从此 Orca 中移除。该主机将继续为 {{value0}} 运行。", "partial": "主机已被移除,但发行版中仍有内容在运行:{{value0}}", "pending": "Orca 尚未移除该主机:{{value0}} 可再次移除以重试,或连接以保留它。" }, @@ -6293,7 +6386,11 @@ "e8f25bd903": "无法完成终端清理。", "a702d4196e": "这将关闭所有工作区中的每个终端标签页,并请求关闭其当前终端会话。任何未保存的终端工作将丢失。守护进程本身将继续运行,可以立即打开新终端。此操作不可撤销。", "01d6b7c64e": "打开终端,智能体将重新启动。远程主机上的终端不受影响。", - "922548bc66": "重启终端服务?" + "922548bc66": "重启终端服务?", + "confirmRestart": "重启", + "busyRestarting": "正在重启…", + "confirmKillAll": "终止所有会话", + "busyKilling": "正在结束…" }, "MacFolderAccessFixDialog": { "stepAllow": "在文件和文件夹下允许 Orca", @@ -7900,7 +7997,9 @@ "builtin_themes": "内置", "imported_from": "从 {{value0}} 导入", "imported_themes": "已导入", - "search_terminal_themes": "搜索终端主题" + "search_terminal_themes": "搜索终端主题", + "plugin_themes": "插件", + "from_plugin": "来自 {{value0}}" }, "SettingsSidebar": { "e0900f83e7": "SSH", @@ -8186,7 +8285,6 @@ "a016ffbeed": "Auto 现在使用 Windows PowerShell,并在安装后切换到 PowerShell 7+。", "5ed5c95344": "为新的终端窗格选择 Windows PowerShell 和 PowerShell 7+。", "3d88af864d": "选择 PowerShell shell 选项是为新终端窗格启动 Windows PowerShell 还是 PowerShell 7+。", - "8a956cc91e": "双击选择时将字符视为单词边界。", "4bebcc2b2c": "单词分隔符", "12e06178fa": "行", "907b0b9d3e": "自定义", @@ -10939,7 +11037,7 @@ "mixedTitle": "审查访问和内容", "instructionalTitle": "审查插件内容", "subtitle": "{{value0}} v{{value1}} · {{value2}}", - "reconsent": "权限、工作进程信任级别或指令内容自您上次审查此插件以来已更改。在运行之前请再次审查。", + "reconsent": "此插件在你批准后已更改。请重新审查以再次运行。", "capabilities": "此插件可以", "warning": "这些权限限制了插件如何使用 Orca 的 API。其工作进程仍作为普通进程在您的计算机上运行,可以完全访问您的文件、网络和其他进程。", "instructionalWarning": "此插件没有工作进程。其指令内容在您或智能体使用时仍可能引发操作。在启用之前,请审查以下指令和命令。", @@ -11742,7 +11840,8 @@ "migration": "未完成:迁移到此服务器的操作尚未完成。请先继续该操作。", "deferred": "尚未完成:服务器尚未准备好执行此操作。请稍后重试。", "failed": "Orca 无法在服务器上完成此操作。请重试。", - "defaultServer": "未执行:此服务器是新项目的默认主机。停止前请在“新项目打开位置”中选择其他主机。" + "defaultServer": "未执行:此服务器是新项目的默认主机。停止前请在“新项目打开位置”中选择其他主机。", + "wslMoveRunning": "未完成:有项目正在移到此服务器上。移动完成后,Orca 会更新它。" }, "reassurance": "在各个主机上运行,通过你自己的 SSH 连接访问。你的代码和文件留在原处。只有 Orca 的项目、标签页和终端列表会移到该主机。" }, @@ -12099,6 +12198,9 @@ "noMatches": "没有匹配的版本。", "searchLabel": "搜索构建" }, + "AppearanceThemeControl": { + "useTerminalTheme": "使用其终端配色" + }, "notification": { "settings": { "copy": { @@ -12113,14 +12215,13 @@ "right": { "sidebar": { "BulkActionBar": { - "79a9f5f712": "取消暂存(", - "ef5f5bd06e": "暂存(", - "60ed678138": "已选择" + "selectedCount_other": "已选择 {{count}} 项", + "stageCount": "暂存({{count}})", + "unstageCount": "取消暂存({{count}})" }, "ChecksPanel": { "2ef90c9819": "已启动 AI 智能体处理失败的检查。", "a0181a8d76": "已启动 AI 智能体处理冲突。", - "34464d00b9": "已更新", "058039787c": "取消", "2ab7fd4b6d": "保存", "dda5924a40": "检查需要 Git 分支和托管评审上下文", @@ -12166,7 +12267,8 @@ "430f1a62d4": "无法在主机上解决选中的讨论串。", "updateReactionFailed": "无法更新反应。", "gitlabMoreActions": "更多 MR 动作", - "gitlabLinkAnother": "链接另一个 MR" + "gitlabLinkAnother": "链接另一个 MR", + "reviewUpdatedAt": "{{review}} 更新于 {{time}}" }, "CreateHostedReviewComposer": { "741ff8a0d2": "推送并创建 {{value0}}" @@ -12323,7 +12425,14 @@ "740aca88ab": "工作区端口扫描失败。", "5be4f7f727": "端口 {{value0}} 菜单", "1004af16ab": "复制 {{value0}}", - "153d3a8026": "工作区主机未知" + "153d3a8026": "工作区主机未知", + "unknownProcess": "未知进程", + "containerOrForwardedService": "容器或转发的服务", + "unassigned": "未分配", + "remotePortOutOfRange": "远程端口必须在 1–65535 范围内", + "localPortOutOfRange": "本地端口必须在 1–65535 范围内", + "localPortInUse": "端口 {{port}} 已被占用。请选择其他本地端口。", + "localPortRequiresPrivileges": "端口 {{port}} 需要提升权限。请使用本地端口 ≥ 1024。" }, "Search": { "1abfb25a66": "输入要在文件中搜索的内容", @@ -12380,7 +12489,6 @@ "476b77745b": "更改基础引用", "ed34038d0d": "刷新分支比较", "493f963029": "更改基础引用", - "3278b2767b": "前面", "11b5dd8e41": "比较", "a9bf7c171a": "提交失败", "011f9713fc": "提交被阻止", @@ -12425,7 +12533,6 @@ "574d2f4413": "清晰的笔记", "05bb8f4a48": "取消", "48db37cca9": "查看全部", - "78ce2d37ac": "推送到 fork", "c05fe04839": "推送到 {{value0}} 的 fork(非 origin)", "c35baf2f1e": "搜索文件...", "2fe2a67580": "更多笔记动作", @@ -12433,14 +12540,12 @@ "cc474e0b8c": "笔记", "e131cd7128": "源代码管理仅适用于 Git 仓库", "c07b236287": "选择一个工作区以查看更改", - "dc5a6465fc": "{{value0}}(例如 {{value1}}{{value2}})", "a5e5a11090": "放弃所有失败 - 无法在放弃之前取消暂存文件", "8a5ba6a988": "无法加载提交差异", "fe5bd1a610": "创建 {{value0}}...", "812cb992ee": "打开于 {{value0}}", "eef5446523": "{{value0}} #{{value1}} 已开放", "0453ca3a9a": "{{value0}} 已创建,但 Orca 尚无法刷新它。", - "f99560ab29": "中止 {{value0}} 失败", "eae7a1da5f": "无法清除笔记。", "df5040e3c3": "取消暂存", "8cde1a2fb0": "暂存", @@ -12468,8 +12573,6 @@ "aaf1451654": "创建草稿 {{value0}}", "26511c22b4": "创建中...", "d7ae61269b": "已提交的更改", - "branchFilesChangedVsBaseOne": "与 {{ref}} 相比更改了 1 个文件", - "branchFilesChangedVsBaseOther": "与 {{ref}} 相比更改了 {{count}} 个文件", "48a003c1b1": "已暂存的更改", "d4ef4bafc5": "更改", "9339382454": "全部取消暂存", @@ -12479,7 +12582,6 @@ "72f2bea3f4": "展开注释", "d13edef890": "折叠笔记", "d6fb1df5fe": "{{value0}} 已打开", - "05838cfdeb": "{{value0}} 冲突", "0b5b8c234c": "打开 {{value0}} ({{value1}})", "d97ef8f221": "第 {{value0}}-{{value1}} 行", "6f8bfa0eb9": "第 {{value0}} 行", @@ -12492,7 +12594,6 @@ "5b176fa431": "双方都删除", "31f6d46278": "未解决", "2c417432b7": "已在本地解决", - "d206117f90": "{{value0}} 冲突 ({{value1}})", "f3a8b2c1d0e5": "请输入 {{value0}} 标题。", "e2b7a1c0d9f4": "创建 {{value0}} 失败", "hugeRepoIgnorePrompt": "此仓库的活动更改过多。是否将 \"{{value0}}\" 添加到 .gitignore?", @@ -12533,10 +12634,6 @@ "b3c8f1a902": "按文件名筛选", "d4f8c2a901": "清除并关闭筛选器", "e8a1c4b203": "vs", - "compareBaseCommitsAheadOne": "领先 {{ref}} 1 个提交", - "compareBaseCommitsAheadOther": "领先 {{ref}} {{count}} 个提交", - "compareBaseCommitsBehindOne": "落后 {{ref}} 1 个提交", - "compareBaseCommitsBehindOther": "落后 {{ref}} {{count}} 个提交", "4b4a7de138": "在浏览器中打开审查页面", "createPrIntentCommitBlockedSummary": "提交被阻止:{{value0}} 修复问题后重试创建 PR。", "pushRecovery": { @@ -12567,17 +12664,41 @@ "diffCommentNotesCopyFailed": "复制笔记失败", "conflictCount_one": "{{count}} 个冲突", "conflictCount_other": "{{count}} 个冲突", - "discardFailedSingular": "无法丢弃 {{count}} 个文件", - "discardFailedPlural": "无法丢弃 {{count}} 个文件", - "noteCountSingular": "{{count}} 条备注", - "noteCountPlural": "{{count}} 条备注" + "discardFailedSampleMore_other": "{{paths}},另有 +{{count}} 个", + "discardFailed_other": "无法丢弃 {{count}} 个文件的更改", + "discardFailedWithSample": "{{error}}(例如 {{paths}})", + "compareBaseCommitsAhead_other": "领先 {{ref}} {{count}} 个提交", + "compareBaseCommitsBehind_other": "落后 {{ref}} {{count}} 个提交", + "branchFilesChangedVsBase_other": "与 {{ref}} 相比更改了 {{count}} 个文件", + "noteCount_other": "{{count}} 条备注", + "comparingAgainstRef": "正在与 {{ref}} 比较", + "commitsAheadShort_other": "领先 {{count}} 个", + "unresolvedConflictOfKind": "未解决的冲突({{kind}})", + "unresolvedConflict": "未解决的冲突", + "locallyResolvedConflictOfKind": "已在本地解决的冲突({{kind}})", + "locallyResolvedConflict": "已在本地解决的冲突", + "pushesToForkTarget": "推送到 fork {{target}}", + "abortRebaseConfirmTitle": "中止变基?", + "abortMergeConfirmTitle": "中止合并?", + "abortRebaseConfirmDescription": "这将取消正在进行的变基,并可能丢弃此次变基期间的冲突解决结果。", + "abortMergeConfirmDescription": "这将取消正在进行的合并,并可能丢弃此次合并期间的冲突解决结果。", + "abortRebaseFailedFallback": "无法中止变基", + "abortMergeFailedFallback": "无法中止合并", + "abortRebaseFailed": "中止变基失败", + "abortMergeFailed": "中止合并失败", + "clearNotesFromWorkspace_other": "清除此工作区中的 {{count}} 条备注?", + "clearNotesFromFile_other": "清除 {{path}} 中的 {{count}} 条备注?" }, "SourceControlAgentActionDialog": { "8e856842d1": "无法启动选定的智能体。", "c075d00de1": "无法解析工作区连接。", "808cfe0a3b": "仅保存到此仓库", "994cddd1f7": "不保存", - "38b899cc02": "所有仓库" + "38b899cc02": "所有仓库", + "agentNotEnabledOrDetected": "{{agent}} 未在此工作区主机上启用,或未检测到。", + "workspaceConnectionUnresolved": "无法解析工作区连接。", + "noEnabledAgentsDetected": "此工作区主机上未检测到已启用的智能体。", + "startAgent": "启动智能体" }, "SourceControlAgentActionDialogForm": { "7ec6abbf2a": "重置", @@ -12642,9 +12763,6 @@ "cbcc4ab3db": "显示前 100 项检查", "0dca6bfab5": "打开检查详细信息", "991f50c7e4": "尚未报告任何 CI 检查", - "9ad98f2a17": "待办的", - "5e52f4ef7f": "失败", - "02ca4f9074": "通过", "e15a8b77ef": "此检查没有可用的内联详细信息。", "679bf2093c": "复制日志尾部", "d713f500b2": "日志尾部(最后 200 行)", @@ -12661,7 +12779,6 @@ "1f2b980522": "正在加载检查详细信息...", "0c96cd25e5": "解决", "3a71a6ed0b": "在检查和合并完成之前解决冲突。", - "60186d8498": "冲突阻碍了这一点", "c16762ac8c": "下面的检查和注释显示当前获取的上下文。", "9d0e7bcefc": "没有阻塞 PR 操作", "5856874b59": "当该面板保持打开状态时,Orca 将刷新检查。", @@ -12686,7 +12803,6 @@ "084c516efb": "复制命令", "5dc3af25c0": "选择评论", "d7a2f9c401": "发送未解决的 {{value0}} 评论", - "d91f2a6c39": "发送 {{value0}} 条已排队评论给 AI", "a6de3e5a20": "清除已排队评论", "f8a2c91d04": "加入智能体队列", "b4e8a1c902": "已加入队列", @@ -12701,7 +12817,6 @@ "b3195cba33": "取消将作者标记为机器人", "f588b46a6c": "将作者标记为机器人", "e45324fbed": "加载检查详细信息失败。", - "checksUnresolvedChip": "未解决的", "checksUnresolvedStripHint": "这些检查完成后没有得出通过或失败的结论。", "dcb3c546fe": "重试", "commitsBehind_one": "落后 {{count}} 个提交", @@ -12712,7 +12827,23 @@ "pendingChecks_one": "{{count}} 项检查待处理", "pendingChecks_other": "{{count}} 项检查待处理", "unresolvedChecks_one": "{{count}} 项检查未解决", - "unresolvedChecks_other": "{{count}} 项检查未解决" + "unresolvedChecks_other": "{{count}} 项检查未解决", + "passingCount_other": "{{count}} 个通过", + "failingCount_other": "{{count}} 个失败", + "pendingCount_other": "{{count}} 个等待中", + "unresolvedCount_other": "{{count}} 个未解决", + "sendQueuedCommentsToAi_other": "发送 {{count}} 条排队评论给 AI", + "conflictsBlockThisMr": "冲突阻止了此 MR", + "conflictsBlockThisPr": "冲突阻止了此 PR", + "copyComment": "复制评论", + "sendComment": "发送", + "commentingRequiresGitHubPrTarget": "发表评论需要指定 GitHub PR 的目标仓库。", + "selectWorkspaceBeforeAiAction": "启动 AI 操作前请选择工作区。", + "operation": { + "rebase": "变基", + "merge": "合并", + "cherryPick": "挑选" + } }, "empty": { "state": { @@ -12954,10 +13085,10 @@ "dialog": { "3bc61dc989": "取消", "15efa778e3": "放弃", - "42f89dd030": "文件", - "e7611dca35": "文件", "0d2d88cba5": "此操作无法撤销。", - "1551c14668": "放弃更改?" + "1551c14668": "放弃更改?", + "fileCount_one": "{{count}} 个文件", + "fileCount_other": "{{count}} 个文件" } }, "dropdown": { @@ -13119,8 +13250,7 @@ }, "compare": { "summary": { - "commitsAheadSingular": "领先 {{ref}} {{count}} 个提交", - "commitsAheadPlural": "领先 {{ref}} {{count}} 个提交" + "commitsAhead_other": "领先 {{ref}} {{count}} 个提交" } }, "conflict": { @@ -13184,24 +13314,28 @@ "unresolved": "无法确定哪个主机拥有此工作区。请检查连接后重试。" }, "useFileDeletion": { - "72691dfebc": "无法 {{value0}}“{{value1}}”。", "d979a4fbb5": "永久删除“{{value0}}”?", "92276aceb7": "删除", "7fb9435c86": "这会永久删除远程主机上的目录及其内容。此操作无法撤销。", "23e98f192f": "这会永久删除远程主机上的文件。此操作无法撤销。", "8b8ee9d22f": "无法确定哪个主机拥有此文件。请检查工作区连接后重试。", - "af1270b90d": "永久删除 {{count}} 项?", "dd029aa5cd": "这会永久删除远程主机上所选的各项及任何目录内容。此操作无法撤销。", - "77fdc36183": "删除 {{count}} 个项目?", - "fca915a67a": "远程项目将永久删除且无法撤销。本地项目将移至 {{value0}}。" + "deleteFailed": "删除“{{name}}”失败。", + "deleteItems_other": "删除 {{count}} 项内容?", + "mixedRecycleBin": "远程内容将被永久删除,此操作无法撤销。本地内容将移到回收站。", + "mixedTrash": "远程内容将被永久删除,此操作无法撤销。本地内容将移到废纸篓。", + "permanentlyDeleteItems_other": "永久删除 {{count}} 项内容?", + "recycleBinFailed": "无法将“{{name}}”移到回收站。", + "trashFailed": "无法将“{{name}}”移到废纸篓。" }, "useFileExplorerHandlers": { "32cd9fd991": "无法打开符号链接目标", "folderLinksOutsideProject": "此文件夹链接到项目之外,无法在此打开。" }, "useFileExplorerImport": { - "25919b2050": "跳过 {{value0}} {{value1}}。", - "132fd0e1e9": "无法导入 {{value0}} {{value1}}。" + "importFailedCount_other": "无法导入 {{count}} 个文件。", + "importSkippedCount_other": "已跳过 {{count}} 个文件。", + "importFailed": "无法导入文件。" }, "useFileExplorerKeys": { "8adb953095": "操作失败" @@ -13238,7 +13372,6 @@ "refreshSessionHistory": "刷新会话历史", "searchSessions": "搜索会话", "clearSearch": "清除搜索", - "transcriptsSkipped": "跳过了 {{count}} 个记录", "noAgentSessionsFound": "未找到智能体会话", "noSessionsMatchFilters": "没有会话符合当前筛选条件", "noAgentsSelected": "未选择任何智能体", @@ -13258,7 +13391,8 @@ "resumeInChatFailed": "无法在新聊天中恢复此会话。", "resumeInNewCliUnavailable": "无法在 CLI 中打开此会话。", "resumeInNewCliHostTooOld": "请更新运行此聊天的主机上的 Orca,才能在新的 CLI 中恢复它。", - "folderWorkspaceUnavailable": "文件夹工作区不再可用。" + "folderWorkspaceUnavailable": "文件夹工作区不再可用。", + "transcriptsSkippedCount_other": "已跳过 {{count}} 份对话记录" }, "AiVaultPanelControls": { "scanningSessions": "正在扫描会话", @@ -13304,11 +13438,8 @@ "sessionRole": "会话", "worktree": "工作树", "conversationNotSaved": "对话未保存", - "recoverableEmptyDetail": "此会话没有已保存的对话,但仍有 {{value0}} 个可恢复项。", "recoverableEmptyOpenLogHint": "打开日志以恢复它们。", "emptyConversationDetail": "此会话没有已保存的对话,无法恢复。", - "queuedMessages": "{{value0}} 条排队消息", - "subagentTranscripts": "{{value0}} 个子智能体记录", "prompt": "提示", "firstPrompt": "首次提示", "recentPrompt": "最近提示", @@ -13322,7 +13453,10 @@ "noFirstPromptAvailable": "没有可用的首次提示", "loadingFirstPrompt": "正在加载首次提示…", "folder": "文件夹", - "resumeInFolder": "在文件夹中恢复" + "resumeInFolder": "在文件夹中恢复", + "recoverableEmptyDetailCount_other": "此会话没有已保存的对话,但仍有 {{count}} 个可恢复项。", + "queuedMessageCount_other": "{{count}} 条排队消息", + "subagentTranscriptCount_other": "{{count}} 份子智能体对话记录" }, "AiVaultSessionRow": { "resumeInNewTab": "在新标签页中恢复", @@ -13456,26 +13590,21 @@ "confirmation": { "84f6f5b9eb": "包括:{{numbers}}。", "541984b2eb": "通过 #{{pr}} 排队?", - "4809f55cdb": "{{included}}GitHub 会将 {{count}} 拉取请求一起添加到合并队列中。队列选择合并方法,并可能将它们合并到不同的组中。", - "be8f2621be": "{{included}}GitHub 会将 {{count}} 拉取请求一起添加到合并队列中。队列选择合并方法,并可能将它们合并到不同的组中。", - "92ca033e72": "队列 {{count}} PR", - "478a527b15": "队列 {{count}} PR", "1feef35ca4": "通过#{{pr}} 合并?", - "c3e036c99f": "{{included}}GitHub 将使用 {{method}} 以原子方式合并 {{count}} 拉取请求。如果无法合并,则不会合并任何内容。", - "369aba4b32": "{{included}}GitHub 将使用 {{method}} 以原子方式合并 {{count}} 拉取请求。如果有一个无法合并,那么就没有一个会合并。", - "493c78f521": "合并 {{count}} PR", - "eb7051d268": "合并 {{count}} PR" + "queueDescription_other": "{{included}}GitHub 会将 {{count}} 个 PR 一起添加到合并队列。队列会选择合并方法,并可能分组进行合并。", + "queueConfirm_other": "将 {{count}} 个 PR 加入队列", + "mergeDescription_other": "{{included}}GitHub 将使用 {{method}} 以原子方式合并 {{count}} 个 PR。如果其中任何一个无法合并,则所有 PR 都不会合并。", + "mergeConfirm_other": "合并 {{count}} 个 PR" }, "merge": { - "55ae29b907": "通过 #{{pr}} · {{count}} PR 合并", - "b8446f6ec2": "通过 #{{pr}} · {{count}} PR 合并", "189d0ec614": "#{{pr}} 仍然是草案。", "640fb50d9c": "#{{pr}} 已关闭。", "46ffcbda75": "#{{pr}} 有合并冲突。", "6dabefd63e": "#{{pr}} 已请求更改。", "2bb21fc326": "#{{pr}} 仍需评审批准。", "c23faf74df": "#{{pr}} 必须更新。", - "f561e80968": "#{{pr}} 被阻止。" + "f561e80968": "#{{pr}} 被阻止。", + "mergeThroughLabel_other": "合并至 #{{pr}}(含)· {{count}} 个 PR" } } } @@ -13532,14 +13661,14 @@ "sourceActionsUnavailable": "转录来源不可用。" }, "AiVaultScanProgressStrip": { - "agentChecked": "{{agent}}:已检查 {{settled}} / {{total}} 个历史记录候选项", "fileCount_one": "{{value0}} 个文件", "fileCount_other": "{{value0}} 个文件", "databaseCount_one": "{{value0}} 个数据库", "databaseCount_other": "{{value0}} 个数据库", "scanning": "正在扫描 {{value0}}", "checking": "正在检查 {{value0}}", - "scanned": "已扫描 {{value0}}" + "scanned": "已扫描 {{value0}}", + "agentCheckedCount_other": "{{agent}}:已检查 {{settled}} / {{total}} 个历史记录候选项" }, "run": { "source": { @@ -13568,6 +13697,14 @@ } } } + }, + "fileExplorerMultiDrag": { + "moreItems_other": "另有 +{{count}} 项" + }, + "CreatePullRequest": { + "createInProgress": "正在创建 PR...", + "workspaceHostUnresolved": "无法解析工作区主机。请刷新工作区后重试。", + "branchDiscoveryFailed": "分支发现失败。" } } }, @@ -14092,11 +14229,11 @@ "a2f68645ac": "刷新 GitLab API 预算", "2f9c16d6c3": "Orca 通过 GitLab CLI 使用 REST。", "14e144f7a7": "GitLab API预算", - "3e2c982cfa": "向左,重置于", - "ea8ad0bae8": "的", "0a891e8935": "REST API", "953f7c6062": "此 GitLab 主机未返回速率限制标头。", - "budget_scope_prefix": "预算范围" + "budget_scope_prefix": "预算范围", + "resetUnknown": "未知", + "remainingOfLimit": "剩余 {{remaining}}/{{limit}},{{reset}} 后重置" } } } @@ -14168,13 +14305,13 @@ "9ee54037a4": "自定义命令", "4b2fc4b80c": "思考努力", "be8917699e": "模型", - "4d9b6d84df": "不支持。选择 Claude、Codex 或 Custom。", "560d4feb00": "自定义", "29d119fe95": "智能体", "f9382b48a1": "启用AI作者", "1c0cb4fabb": "AI 作者", "bd14e9c42a": "未配置", - "1f9468c5c9": "{{value0}} 不支持" + "1f9468c5c9": "{{value0}} 不支持", + "unsupportedAgent": "不支持 {{agent}}。请选择 Claude、Codex 或自定义。" }, "BrowserAnimatedVisual": { "46df009982": "开始免费试用", @@ -14715,17 +14852,14 @@ "ConflictComponents": { "f338288514": "正在加载冲突内容...", "90d576adb2": "刷新", - "a1ce36f77d": "快照拍摄于", "c8ca989aea": "显示文件树", "58ad5ad431": "关闭", "28e7db4a90": "源代码控制", "31931dec46": "此评审快照不再有任何未解决的实时冲突。", "992145ff5a": "所有冲突均已解决", - "d5edd81755": "重命名自", "6e459867ad": "会话本地连续性状态。 Git 不再将此文件报告为未合并。", "9c2901ef8a": "下一次冲突", "41d9af2e7a": "上一个冲突", - "55d61a0ccd": "冲突 ·", "da539359b6": "对于此冲突,没有可编辑的工作树文件。", "unresolvedConflicts_one": "{{count}} 个未解决的冲突", "unresolvedConflicts_other": "{{count}} 个未解决的冲突" @@ -15421,7 +15555,9 @@ "6978871a3d": "打开", "cce596969e": "删除注释", "cad3384faa": "编辑备注", - "508ee678a5": "在浏览器中打开" + "508ee678a5": "在浏览器中打开", + "noteAuthorFallback": "备注", + "sentMeta": "已发送" }, "DiffCommentPopover": { "2b3ce6d394": "取消", @@ -15434,6 +15570,9 @@ }, "useDiffCommentDecorator": { "995fa28b50": "此注" + }, + "diffCommentZoneCard": { + "noteAlreadySent": "备注已发送" } } }, @@ -16028,7 +16167,18 @@ "b09b2384fd": "已暂停", "eaa02014f8": "启用", "29baf8f4c2": "来源", - "lastRunFailed": "上次运行失败。" + "lastRunFailed": "上次运行失败。", + "noGrace": "无宽限期", + "graceMinutes_other": "{{count}} 分钟", + "graceHours_other": "{{count}} 小时", + "usageCoverageRuns_other": "{{known}}/{{count}} 次运行", + "usageUnavailable": "不可用", + "noRuns": "无运行记录", + "projectDefault": "项目默认值", + "reuseLiveSession": "复用活动会话", + "freshEachRun": "每次运行新建", + "precheckEnabled": "已启用,{{timeout}}", + "precheckNone": "无" }, "AutomationEditorDialog": { "fb1896a5e7": "取消", @@ -16129,11 +16279,8 @@ "2faecab10b": "立即运行", "13118faadf": "未知项目", "73f630b49d": "取消", - "1b586f0e2b": "在", - "02a33e3204": "从", "9adfab2596": "删除外部自动化", "1e2e41392f": "不要再问", - "b264564427": "及其运行历史记录。先前运行创建的工作区不会被删除。", "080dcb5fbb": "删除自动化", "19a6e30eae": "刷新自动化", "77c2778945": "自动化", @@ -16168,7 +16315,6 @@ "pendingAutomationRunMissing": "运行历史已不可用。", "paused": "已暂停", "missingWorkspace": "缺少工作区", - "runUsageSummary": "约 {{cost}} · {{tokens}} tokens", "usageUnavailable": "用量不可用", "noRunUsageYet": "尚无运行用量", "noWorkspace": "无工作区", @@ -16183,7 +16329,10 @@ "rowActions": "自动化操作", "tableLastRun": "最后一次运行", "ownerChanged": "这种自动化改变了主机。刷新并重试。", - "runError": "错误:" + "runError": "错误:", + "deleteAutomationDescription": "删除 及其运行历史。不会删除之前运行创建的工作区。", + "deleteExternalAutomationDescription": "从 上的 中删除 。", + "runUsageSummaryTokens_other": "预估 {{cost}} · {{tokens}} token" }, "CreateFromPicker": { "f061f49e3f": "搜索仓库分支...", @@ -16210,8 +16359,7 @@ "92405f1431": "不可用", "dbdcec22bd": "只读", "0a2d4359a8": "易于管理", - "e2532150ed": "自动化", - "701515f010": "自动化" + "automationCount_other": "{{count}} 个自动化" }, "WorkspaceCombobox": { "ee5b280eba": "未找到工作区。", @@ -16263,7 +16411,8 @@ "last": { "run": { "done": "完成", - "failed": "失败的" + "failed": "失败的", + "statusWithRelative": "{{status}} · {{relative}}" } } } @@ -16419,15 +16568,11 @@ }, "externalScope": { "uncheckedHost": "无法检查 {{hostLabel}} 上的外部自动化管理器。", - "uncheckedHosts": "无法检查 {{count}} 主机上的外部自动化管理器。" + "uncheckedHostCount_other": "无法检查 {{count}} 台主机上的外部自动化管理器。" }, "enablement": { "paused": "已暂停" }, - "runHistory": { - "occurrencesWithLatest": "{{times}} 次,最近一次 {{date}}", - "occurrences": "{{times}} 次" - }, "extraAgentArgs": { "advanced": "高级", "clear": "清除参数", @@ -16437,6 +16582,67 @@ "useFreshSessions": "使用新会话", "helper": "每次新会话时附加到此主机的默认参数之后。", "detailLabel": "额外参数" + }, + "runHistory": { + "runCountSummary_other": "运行 {{count}} 次 · 已完成 {{completed}} 次", + "occurrencesWithLatestCount_other": "{{count}} 次,最近一次为 {{date}}", + "occurrencesCount_other": "{{count}} 次" + }, + "capabilityProbe": { + "createIdempotencyUpdateRequired": "将自动化移至此主机需要更新版本的 Orca 服务器。请更新 HUB 后重试。" + }, + "editDraft": { + "unsupportedSchedule": "此自动化保存的计划不受支持。请在保存更改前选择受支持的计划。" + }, + "hostCatalog": { + "orphanEntryLabel": "未分配的旧版自动化" + }, + "automationPageParts": { + "never": "从未", + "now": "刚刚", + "runStatusPending": "已排队", + "runStatusDispatching": "正在启动", + "runStatusDispatched": "已启动", + "runStatusCompleted": "完成", + "runStatusSkippedPrecheck": "因预检查而跳过", + "runStatusSkippedMissed": "已跳过", + "runStatusSkippedUnavailable": "不可用", + "runStatusSkippedNeedsInteractiveAuth": "需要凭据", + "runStatusDispatchFailed": "失败" + }, + "runContent": { + "noOutput": "没有可用的输出内容。" + }, + "runViewState": { + "viewRun": "查看运行", + "runOpen": "运行已打开", + "terminalOnPairedServer": "运行终端位于已配对的服务器上。", + "terminalUnavailable": "运行终端不可用。", + "openWorkspace": "打开工作区", + "workspaceAvailable": "工作区可用。", + "snapshotSaved": "快照已保存", + "showingSnapshot": "正在显示已保存的运行快照。", + "namedWorkspaceGone": "{{name}} 已不可用", + "workspaceGone": "工作区已不可用", + "noWorkspaceLaunched": "未启动工作区" + }, + "runWorkspaceDisplay": { + "notLaunched": "未启动", + "namedWorkspaceGone": "{{name}}(已不可用)" + }, + "usage": { + "tokensAndCost_other": "{{tokens}} token · {{cost}}" + }, + "externalDisplay": { + "sshHost": "SSH 主机", + "local": "本地" + }, + "externalActionDisabled": { + "actionInProgress": "另一个自动化操作仍在运行。", + "sshConnecting": "请等待此 SSH 主机完成连接。", + "connectSshHost": "请先连接此 SSH 主机,再管理 {{provider}} 自动化。", + "cannotManageOnSshHost": "{{provider}} 无法管理此 SSH 主机上的自动化。", + "cannotManageLocally": "{{provider}} 无法管理此计算机上的自动化。" } }, "agent": { @@ -16577,8 +16783,6 @@ "63ce735809": "连接", "4a2ab52781": "正在验证…", "79e7aaed39": "取消", - "fdd26d81cc": "Atlassian 账户设置", - "8090504a3e": "在此创建 token:", "7b3967c12f": "Atlassian API 令牌", "3d81bf3ab3": "API 令牌", "e91b9a4073": "you@example.com", @@ -16603,17 +16807,17 @@ "be9eba0a1b": "username", "70035652d7": "Password", "c50abbf340": "Jira 账户密码", - "d8737db691": "使用你的 Jira Server 或 Data Center 账户用户名和密码。" + "d8737db691": "使用你的 Jira Server 或 Data Center 账户用户名和密码。", + "createTokenInSettings": "在 Atlassian 账户设置中创建令牌。" } } }, "rightSidebar": { "FolderWorkspaceWorktreesPanel": { "unavailable": "仅显示文件夹工作区的工作区。", - "countOne": "1 个附加的工作树", - "countMany": "{{value0}} 个附加的工作树", "emptyTitle": "还没有附加的工作树", - "emptyCopy": "从此工作区创建的工作树将显示在这里。" + "emptyCopy": "从此工作区创建的工作树将显示在这里。", + "attachedCount_other": "{{count}} 个附加的工作树" }, "FolderWorkspacePrChecksPanel": { "unavailable": "PR 检查仅在文件夹工作区中显示。", @@ -16625,12 +16829,9 @@ "hideDetails": "隐藏 {{value0}} 的 PR 检查详情", "reviewChecks": "评审检查", "allChecksPassing": "所有检查均通过", - "oneWorktree": "1 个工作树", - "worktreeCount": "{{value0}} 个工作树", - "oneFailing": "1 个失败", - "failingCount": "{{value0}} 个失败", - "onePending": "1 个等待中", - "pendingCount": "{{value0}} 个等待中" + "worktreeCountLabel_other": "{{count}} 个工作树", + "failingCountLabel_other": "{{count}} 个失败", + "pendingCountLabel_other": "{{count}} 个等待中" }, "parentPrChecks": { "rowSummary": { @@ -16712,10 +16913,10 @@ "combobox": { "noProjects": "没有项目", "allProjects": "所有项目", - "hostCount": "{{value0}} 个主机", "searchProjects": "搜索项目...", "noMatches": "没有匹配搜索的项目。", - "chooseSource": "选择任务来源" + "chooseSource": "选择任务来源", + "hostCount_other": "{{count}} 台主机" } } }, @@ -16752,7 +16953,31 @@ "taskSourceContextSummary": { "sourceUnavailable": "{{value0}} 来源不可用:{{value1}}", "someSourceHostsUnavailable": "部分 {{value0}} 来源主机不可用:{{value1}}", - "reconnectOrUpdateTitle": "重新连接或更新 {{value0}} 以加载此来源。" + "reconnectOrUpdateTitle": "重新连接或更新 {{value0}} 以加载此来源。", + "providerSourceTitle": "{{provider}} 来源", + "hostTitle": "主机:{{hosts}}", + "accountTitle": "账户:{{accounts}}", + "sourceTitle": "来源:{{source}}", + "sourceHostCount_other": "{{count}} 台来源主机", + "noHost": "无主机", + "projectCount_other": "{{count}} 个项目", + "selectedProject": "所选项目", + "selectedProjectCount_other": "已选择 {{count}} 个项目", + "currentAccount": "当前账户", + "statusCheckingCapabilities": "正在检查服务器能力", + "statusServerUpdateForTaskSources": "任务来源需要更新服务器", + "statusProviderAuthNeeded": "需要提供商认证", + "statusSourceToolUnavailable": "来源工具不可用", + "statusProviderUnsupported": "此主机不支持该提供商", + "statusServerUpdateNeeded": "需要更新服务器", + "unavailableCount_other": "{{count}} 项不可用", + "statusConnected": "已连接", + "statusAuthNeeded": "需要认证", + "statusConnecting": "正在连接", + "statusConnectionIssue": "连接异常", + "statusDisconnected": "已断开连接", + "hostStatus": "{{host}} {{status}}", + "availabilityTitle": "可用性:{{hosts}}" }, "ShortcutKeyCombo": { "07eb4985a1": "双击 {{value0}}" @@ -17004,8 +17229,6 @@ "serverBody": "这些聊天在 {{machine}} 上的 Orca 重启时正在进行中。恢复会把每个聊天还原到中断处,并让智能体继续。你自己的提示词不会重新发送。", "serverDismiss": "忽略", "serverResumeAll": "恢复 {{machine}} 上的全部 {{count}} 个", - "serverResumeHereOne": "恢复此处开始的 1 个聊天", - "serverResumeHere": "恢复此处开始的 {{count}} 个聊天", "title": "恢复中断的聊天?", "body": "当 Orca 关闭时,这些聊天正在工作。恢复会将每个聊天还原到停止的位置及其完整上下文,并要求智能体在继续之前检查它正在做的事情。您自己的提示不会重新发送。", "updateBody": "当 Orca 安装更新时,这些聊天正在工作。恢复会将每个聊天还原到停止的位置及其完整上下文,并要求智能体在继续之前检查它正在做的事情。您自己的提示不会重新发送。", @@ -17013,19 +17236,9 @@ "untitled": "无标题聊天", "listLabel": "将恢复的聊天", "dontAskAgain": "不再询问(自动恢复)", - "dontAskAgainHint": "您可以在“设置”→“实验”→“聊天 UI”中关闭此功能。", - "continuedOne": "已恢复 1 个聊天", - "continuedMany": "已恢复 {{value0}} 个聊天", + "dontAskAgainHint": "你可以在设置 → 聊天 → 行为中关闭此选项。", "selectAgent": "在 {{value2}} 中恢复 {{value0}} 聊天“{{value1}}”", - "resumeSelected": "恢复 {{value0}} 聊天", - "resumeSelectedOne": "恢复 1 次聊天", "dismissAll": "全部关闭", - "notContinuedOne": "1 个聊天无法恢复", - "notContinuedMany": "{{value0}} 个聊天无法恢复", - "notConfirmedOne": "无法确认 1 个聊天已恢复", - "notConfirmedMany": "无法确认 {{value0}} 个聊天已恢复", - "notConfirmedOtherOne": "无法确认另外 1 个聊天已恢复", - "notConfirmedOtherMany": "无法确认另外 {{value0}} 个聊天已恢复", "viewChats": "查看聊天", "review": "检查", "activityUnnamed": "未命名", @@ -17033,9 +17246,7 @@ "activityQuestion": "等待您的回答:{{value0}}", "activityMidReply": "回复进行中", "activitySubagentOne": "子智能体运行中:{{value0}}", - "activitySubagentMany": "{{value0}} 个子智能体运行中", "activityMonitorOne": "正在监控:{{value0}}", - "activityMonitorMany": "正在监控 {{value0}} 个后台任务", "selectWorkspace": "选择 {{value0}} 中的全部聊天", "workspaceSelectedCount": "{{value0}}/{{value1}}", "selectAll": "选择全部聊天", @@ -17047,7 +17258,16 @@ "selectMachine": "选择 {{value0}} 上的全部聊天", "sshHost": "SSH", "done": "完成", - "resultListLabel": "本次恢复的聊天" + "resultListLabel": "本次恢复的聊天", + "resumeChats_one": "恢复 {{count}} 个聊天", + "resumeChats_other": "恢复 {{count}} 个聊天", + "serverResumeHereCount_other": "恢复在此启动的 {{count}} 个聊天", + "continuedCount_other": "已恢复 {{count}} 个聊天", + "notContinuedCount_other": "{{count}} 个聊天无法恢复", + "notConfirmedCount_other": "无法确认 {{count}} 个聊天是否已恢复", + "notConfirmedOtherCount_other": "无法确认其他 {{count}} 个聊天是否已恢复", + "activitySubagentCount_other": "{{count}} 个子智能体正在运行", + "activityMonitorCount_other": "正在监控 {{count}} 个后台任务" }, "linear-issue-attribute-filter-coverage-notice": { "statusPartialTeamCoverage": "过滤 {{value1}} 团队状态中的 {{value0}} — 不包括其余团队的问题。", @@ -17199,15 +17419,13 @@ } }, "NativeChatResumeRunPanel": { - "resumedTitle": "已恢复 {{value0}}/{{value1}} 个聊天", - "resumedTitleOne": "已恢复 {{value0}}/1 个聊天", - "resumingTitleOne": "正在恢复 1 个聊天", - "resumingTitle": "正在恢复 {{value0}} 个聊天", "description": "每个聊天都会带着完整上下文恢复,并被要求检查它停在了哪里。你可以关闭此窗口,状态栏会继续显示进度。", "finished": "Orca 关闭时这些聊天正在工作。Orca 已将每个聊天恢复到停止的位置并保留完整上下文,并让智能体在继续之前先检查它之前在做什么。你自己的提示没有被重新发送。", "finishedUpdate": "Orca 安装更新时这些聊天正在工作。Orca 已将每个聊天恢复到停止的位置并保留完整上下文,并让智能体在继续之前先检查它之前在做什么。你自己的提示没有被重新发送。", "finishedPartial": "Orca 关闭时这些聊天正在工作。Orca 恢复的聊天已回到停止的位置并保留完整上下文,并被要求在继续之前先检查之前在做什么。你自己的提示没有被重新发送。请在列表中查看仍需处理或可以恢复的聊天。", - "finishedPartialUpdate": "Orca 安装更新时这些聊天正在工作。Orca 恢复的聊天已回到停止的位置并保留完整上下文,并被要求在继续之前先检查之前在做什么。你自己的提示没有被重新发送。请在列表中查看仍需处理或可以恢复的聊天。" + "finishedPartialUpdate": "Orca 安装更新时这些聊天正在工作。Orca 恢复的聊天已回到停止的位置并保留完整上下文,并被要求在继续之前先检查之前在做什么。你自己的提示没有被重新发送。请在列表中查看仍需处理或可以恢复的聊天。", + "resumedOfTotal_other": "已恢复 {{resumed}}/{{count}} 个聊天", + "resumingCount_other": "正在恢复 {{count}} 个聊天" }, "NativeChatResumeRunStatusIcon": { "waitingForReply": "等待回复", @@ -17272,6 +17490,68 @@ "cancelled": "此普通 SSH 终端在启动前已关闭。", "terminalUnavailable": "Orca 无法在此处打开终端。", "openHint": "在 Orca 无法在该主机上完成设置时,仍可让你继续在主机上工作。" + }, + "AgentStateDot": { + "working": "工作中", + "monitoring": "正在监控后台任务", + "blocked": "受阻", + "waiting": "等待输入", + "interrupted": "已中断", + "failed": "失败", + "done": "完成", + "idle": "空闲", + "unverifiable": "无近期更新", + "unconfirmed": "无法确认", + "permission": "需要关注" + }, + "issueComments": { + "you": "你" + }, + "ZoomOverlay": { + "uiZoom": "界面缩放", + "editorZoom": "编辑器缩放", + "terminalZoom": "终端缩放" + }, + "issueCopy": { + "urlCopied": "URL 已复制", + "keyCopied": "标识已复制", + "identifierCopied": "标识符已复制", + "branchNameCopied": "分支名称已复制", + "promptCopied": "提示词已复制", + "urlCopyFailed": "复制 URL 失败", + "keyCopyFailed": "复制标识失败", + "identifierCopyFailed": "复制标识符失败", + "branchNameCopyFailed": "复制分支名称失败", + "promptCopyFailed": "复制提示词失败" + }, + "prCheckCounts": { + "noChecksFound": "未找到检查", + "checksFailing_other": "{{count}} 项检查失败", + "checksNeedAction_other": "{{count}} 项检查需要处理", + "checksPending_other": "{{count}} 项检查待完成", + "allChecksPassing": "所有检查均通过", + "checksPassingOfTotal_other": "{{count}} 项检查中有 {{passing}} 项通过" + }, + "taskPageJiraBoard": { + "changeStatusFailed": "更改状态失败。" + }, + "jiraIssue": { + "loadStatusChangesFailed": "加载状态变更失败。", + "loadCommentsFailed": "加载评论失败。" + }, + "taskPageJiraLinkedIssues": { + "someIssuesFailed": "无法加载部分与工作区关联的 Jira 议题。请刷新重试。" + }, + "taskPageJiraLoadState": { + "failedToLoadIssues": "加载 Jira 议题失败。", + "authFailed": "Jira 认证失败。请在设置中重新连接 Jira 后重试。", + "accessDenied": "Jira 拒绝了此次议题搜索的访问。请检查项目权限或尝试其他 JQL 查询。", + "rateLimited": "此次议题搜索触发了 Jira 速率限制。请稍后重试。", + "serverError": "加载议题时 Jira 出现服务器错误。请稍后重试。", + "jqlFailed": "Jira 无法执行此 JQL 查询。请检查语法后重试。", + "unreachable": "无法连接 Jira。请检查连接后重试。", + "loadFailed": "无法加载 Jira 议题。请稍后重试。", + "errorWithCode": "错误 {{code}}:{{summary}}" } }, "i18n": { @@ -17436,6 +17716,7 @@ "agentCommandNotRunnable": "{{agent}} 在设置 → 智能体中的命令必须是 Orca 能找到的程序路径或名称,且不能包含参数或变量。请修改或重置。", "runtimeNotInstalled": "运行此聊天的计算机上未安装 {{agent}}。请在最新版本的 Orca 中从聊天里安装。", "fullAccessAsRoot": "{{agent}} 以 root 身份运行时不会使用完全访问。请在运行此聊天的计算机的“设置”→“智能体”中为 {{agent}} 选择其他权限,然后开始新的聊天。", + "launchPreparationFailed": "Orca 无法在运行此聊天的计算机上准备启动 {{agent}}。", "conversationOpenElsewhere": "Codex 仍在保持此对话打开。请稍后重试,或关闭其他 Codex 终端。", "conversationOpenInTerminal": "{{agent}} 已在另一个终端中运行此对话。请退出那里的 {{agent}} 或关闭该终端,然后在这里继续。", "chooseClaudeAccount": "请在 Claude 账户设置中选择或添加一个。", @@ -18097,7 +18378,6 @@ "pausedSendFailedWaiting": "无法发送。智能体完成后,点按发送以重试。", "save": "保存", "editingMessage": "正在编辑消息", - "cancelEditing": "取消编辑", "editChanged": "你编辑时此消息已更改。你编辑的内容已放入聊天输入框。", "editChangedPrompt": "你编辑时此消息已更改。回答智能体后,你编辑的内容会出现在聊天输入框中。", "editChangedNotSaved": "你编辑时此消息已更改。你的编辑未保存。", @@ -18110,9 +18390,7 @@ "collapse": "收起", "expand": "展开", "queued": "已排队", - "clearAll": "全部清除", - "pasteOrDropImages": "粘贴或拖入图片", - "saveNeedsContent": "添加文字或图片后才能保存" + "clearAll": "全部清除" }, "thought": "已思考", "thoughtForDuration": "思考了 {{duration}}", @@ -18262,6 +18540,15 @@ "settings": "在终端中打开设置", "extensions": "在终端中打开扩展面板", "hotkeys": "在终端中显示键盘快捷键" + }, + "modelDescriptions": { + "grok_4_7": "xAI 最新的前沿模型", + "grok_4_6": "xAI 上一代前沿模型", + "grok_4_5": "xAI 较早的前沿模型", + "fable": "最擅长处理最困难、耗时最长的任务", + "opus": "最适合日常复杂任务", + "sonnet": "高效处理日常任务", + "haiku": "快速回答的最快选择" } }, "tab": { @@ -18833,7 +19120,6 @@ "subagents_other": "{{count}} 个子智能体" }, "terminal": { - "closed": "没有活动的终端 — 该智能体的窗格已关闭。", "focusWorktree": "聚焦工作树", "close": "关闭", "remotePreviewUnavailable": "此远程会话没有预览 - 打开工作区以查看终端。" @@ -19056,6 +19342,15 @@ "title": "历史记录", "today": "今天", "yesterday": "昨天" + }, + "viewport": { + "mobile-s": "小屏手机 — 320 × 568", + "mobile-m": "中屏手机 — 375 × 667", + "mobile-l": "大屏手机 — 425 × 812", + "tablet": "平板电脑 — 768 × 1024", + "laptop": "笔记本电脑 — 1024 × 768", + "laptop-l": "大屏笔记本电脑 — 1440 × 900", + "desktop": "桌面电脑 — 1920 × 1080" } }, "runtimeRpc": { @@ -19122,6 +19417,30 @@ "confirm": "调整滤镜并显示", "cancel": "保留过滤器" }, + "wslMoved": { + "movedToHost": "已移至 {{distro}} 主机", + "useHere": "重新在此电脑上使用", + "useHereTitle": "要重新在此电脑上使用 {{name}} 吗?", + "useHereDescription": "Orca 会按移动前的状态在这里打开此项目。你的代码不受影响:它从未移动。移动后在 {{distro}} 主机上所做的更改(例如新标签页和聊天)会留在主机上,不会回来。与它一起移动的项目也会一起回来。在你于 {{distro}} 主机上将其移除之前,项目也会一直保留在那里。此窗口将重新加载。", + "useHereConfirm": "在此电脑上使用", + "useHereSuperseded": "之后一次移动到 {{distro}} 主机的操作包含此项目。请先将那次移动恢复。", + "useHereRefusedTitle": "暂时无法在此处使用 {{name}}", + "useHereRefusedOk": "确定", + "useHereSupersededBy": "{{names}} 在此项目之后移到了 {{distro}} 主机。请先重新在此电脑上使用它们,再处理此项目。", + "useHereMoveRunning": "移动到 {{distro}} 主机的操作仍在进行。请在其结束后重试。", + "useHereHostKeptForPeers": "{{project}} 已移到 {{distro}} 主机,该主机仍在为另一个 Orca 运行。重新添加该主机即可在此处再次使用它。", + "useHereHostUnreachable": "{{distro}} 主机没有响应,Orca 无法停止它上面的此项目副本,其智能体可能仍在运行。请在设置中连接或移除该主机,然后重试。", + "useHereHostStillRunning": "{{distro}} 主机上的此项目副本仍有终端在运行,其智能体可能会运行两次。请稍候再试。", + "useHereFailed": "无法将此项目恢复到此电脑。", + "useHereHostRemovalPending": "{{distro}} 主机仍在移除中,因此 Orca 不会改动它。请在设置中完成移除,然后重试。", + "useHereHostAutomations": "Orca 无法关闭此项目在 {{distro}} 主机上的自动化,它们可能会运行两次。请在设置中连接该主机,然后重试。", + "useHereUnsavedTitle": "请先保存文件", + "useHereUnsavedDescription": "将 {{name}} 恢复到此电脑会重新加载此窗口。请先保存或关闭以下文件:{{files}}", + "automationRunsOnHost": "在 {{distro}} 主机上运行", + "quitDuringMoveTitle": "要在项目移动期间退出吗?", + "quitDuringMoveDescription": "有项目正在移到其 WSL 主机。仍要退出吗?下次启动时将撤销此次移动。", + "quitDuringMoveConfirm": "仍要退出" + }, "startupWorktreeRefresh": { "loading": "正在发现工作区…", "description": "本地和远程项目加载期间,可能会显示更多工作区。" @@ -19223,7 +19542,9 @@ }, "quickOpen": { "moreMatchesAvailable": "可能还有更多匹配结果。请细化搜索以缩小范围。", - "recentValidationFailed": "无法检查最近的文件:{{error}}" + "recentValidationFailed": "无法检查最近的文件:{{error}}", + "installRipgrepOnRemote": "在远程主机上安装 ripgrep,即可按 .gitignore 规则快速列出文件:", + "scanTooLarge": "“快速打开”的扫描范围过大({{reason}})。" }, "checksPanel": { "unlinked": { @@ -19239,11 +19560,18 @@ }, "discard": { "deleteUntrackedFileDescription": "这将永久删除此未跟踪文件。此操作无法撤销。", - "deleteUntrackedFilesDescription": "这将永久删除这 {{count}} 个未跟踪文件。此操作无法撤销。", + "deleteUntrackedFilesDescription_other": "这将永久删除这 {{count}} 个未跟踪文件。此操作无法撤销。", "restoreStagedVersionDescription": "这将恢复最后一个暂存版本并放弃删除。此操作无法撤消。", "unstagedChangesDescription": "这将恢复对此文件的未暂存更改。此操作无法撤消。", "unstagedSelectionIncludingUntrackedDescription": "这将还原未暂存的更改,并永久删除此选择中的任何未跟踪文件。此操作无法撤销。", - "unstagedFilesIncludingUntrackedDescription": "这将还原未暂存的更改,并永久删除这 {{count}} 个文件中的任何未跟踪文件。此操作无法撤销。" + "unstagedFilesIncludingUntrackedDescription_other": "这将还原未暂存的更改,并永久删除这 {{count}} 个文件中的任何未跟踪文件。此操作无法撤销。", + "delete": "删除", + "restore": "恢复", + "discard": "放弃", + "discardAll": "全部丢弃", + "deleteUntrackedTitle_one": "删除 {{count}} 个未跟踪文件?", + "deleteUntrackedTitle_other": "删除 {{count}} 个未跟踪文件?", + "deleteCount": "删除 {{count}} 个" }, "createReviewFailure": { "authRequiredCommand": "{{providerName}} 未通过身份验证。下一步:在此环境中运行 {{command}}。", @@ -19274,6 +19602,34 @@ "creationUnconfirmed": "{{shortLabel}} 可能已创建完成。正在刷新分支评审状态...", "withDetail": "创建 {{shortLabel}} 失败:{{detail}}", "pushFailed": "推送失败。请解决推送错误后重试。" + }, + "model": { + "auto": "自动", + "configDefault": "配置默认值" + }, + "thinking": { + "off": "关闭", + "minimal": "最低", + "low": "低的", + "medium": "中等的", + "high": "高的", + "max": "最高", + "xhigh": "极高" + }, + "variables": { + "basePrompt": "Orca 为此操作内置的提示词,包含 Orca 能安全收集的上下文。", + "branch": "当前源代码管理分支名称。", + "stagedFiles": "用于生成提交信息的已暂存文件列表,每行一个文件。", + "stagedPatch": "用于生成提交信息的已暂存 Git 补丁。", + "baseBranch": "在创建 PR 编辑器中选择的目标分支。", + "currentTitle": "开始生成前,编辑器中当前输入的 PR 标题。", + "currentBody": "开始生成前,编辑器中当前输入的 PR 描述。", + "commitSummary": "当前分支相对于基准分支的提交列表,每行一个提交。", + "changedFiles": "当前分支与基准分支之间的文件更改摘要。", + "patch": "用于生成 PR 详情的当前分支与基准分支的差异。", + "firstPrompt": "此工作区或聊天中的第一个用户请求。", + "assistantMessage": "Orca 可获取的智能体初始回复。", + "linkedIssue": "与此工作区关联的 GitHub issue 编号。未关联 GitHub issue 时为空(包括关联 GitLab 的工作区)。优先使用带指示的模板:未关联时,单独的“Fixes #{linkedIssue}”会变成“Fixes #”。" } }, "rendererRecovery": { @@ -19298,8 +19654,6 @@ }, "sessionSearch": { "panel": { - "resultsOne": "{{count}} 结果", - "resultsOther": "{{count}} 结果", "noMatches": "索引历史记录中没有匹配的会话。尝试另一个查询或范围。", "loadMore": "加载更多匹配项", "indexedHistory": "索引历史记录", @@ -19320,12 +19674,21 @@ "retry": "重试", "scopeUnknown": "此计算机没有此工作区或项目。将范围切换到全部以搜索其上的所有内容。", "sortSessionsAriaLabel": "对会话进行排序:{{value0}}", - "sessionsOne": "{{count}} 会话", - "sessionsOther": "{{count}} 会话", - "sessionsOfLoaded": "{{value0}} 次(共 {{value1}} 次)", "showMoreSessions": "显示更多会话", "loadingMoreSessions": "正在加载更多会话...", - "unsupportedAgent": "此计算机不支持所选智能体的历史搜索。更新该计算机上的 Orca 或选择其他智能体。" + "unsupportedAgent": "此计算机不支持所选智能体的历史搜索。更新该计算机上的 Orca 或选择其他智能体。", + "resultCount_other": "{{count}} 个结果", + "sessionCount_other": "{{count}} 个会话", + "sessionsShownOfLoaded_other": "{{shown}} / {{count}} 个会话", + "hostSkipReason": { + "indexChanged": "索引已更改", + "searchOff": "搜索已关闭", + "notReady": "尚未就绪", + "unavailable": "不可用", + "unreachable": "无法连接", + "scopeNotFound": "该主机上未找到搜索范围", + "agentNotSupported": "不支持该智能体" + } } }, "sessionHistory": { @@ -19447,9 +19810,9 @@ "pathAdded": "Added", "openFolder": "Open {{name}}", "findOrTypePath": "查找文件夹,或输入任意路径...", - "addTypedPath": "Add", "noDirectories": "尚未添加文件夹。", - "removePath": "Remove {{name}}" + "removePath": "Remove {{name}}", + "addTypedPathCode": "添加 " }, "accounts": { "wslAccountNotApplied": { @@ -19550,14 +19913,11 @@ "keep": "保持原样", "restartOne": "重新启动会话", "title": "切换到 {{account}}", - "bodyOne": "{{previous}} 账户上仍有 1 个 Claude 会话正在运行。重启后,对话将在 {{next}} 账户上继续。正在工作的会话会等到空闲后再重启。", "dontAskAgainHint": "您可以在“设置”→“AI 提供商帐户”中关闭此功能。", - "bodyOther": "{{previous}} 账户上仍有 {{count}} 个 Claude 会话正在运行。重启后,各对话将在 {{next}} 账户上继续。正在工作的会话会等到空闲后再重启。", "listLabel": "要重新启动的 Claude 会话", "settingTitle": "Claude 运行期间切换账户时", "settingDescription": "重启后,每个正在进行的对话都会在新账户上继续。", "settingRestart": "总是重新启动", - "restartOther": "重启 {{count}} 个会话", "session": "Claude 会话", "restartingOther": "正在 {{account}} 账户上重启 {{count}} 个 Claude 会话", "uncheckedOne": "无法检查 1 个终端中的 Claude。如果 Claude 正在那里运行,它会保持 {{previous}} 直到重启。", @@ -19572,11 +19932,12 @@ "reasonOwnFolder": "使用你自己的 Claude 文件夹", "reasonUnknownAccount": "账户未知", "reasonNoSession": "无法恢复", - "reviewBodyOne": "另有 1 个 Claude 会话未移至 {{next}}。", - "reviewBodyOther": "另有 {{count}} 个 Claude 会话未移至 {{next}}。", "notMovedOne": "另有 1 个会话未移动。", "notMovedOther": "另有 {{count}} 个会话未移动。", - "review": "查看" + "review": "查看", + "restartCount_other": "重启 {{count}} 个会话", + "reviewBody_other": "其他 {{count}} 个 Claude 会话未移至 {{next}}。", + "body_other": "{{count}} 个 Claude 会话仍在 {{previous}} 上运行。重启后,各对话将在 {{next}} 上继续。忙碌的会话会等待空闲后再重启。" } }, "hostSignIn": { @@ -19690,7 +20051,9 @@ "confirmTitle": "重新启动终端守护进程?", "confirmBody": "重新启动会结束 {{sessions}} 中运行的所有进程。支持恢复的智能体之后可以恢复;shell 和其他作业则不能,必须重新启动。请在智能体空闲时执行此操作。", "cancel": "取消", - "confirm": "重新启动并结束进程" + "confirm": "重新启动并结束进程", + "count_other": "{{count}} 个正在运行的终端", + "count_one": "{{count}} 个运行中的终端" }, "restartedInputNotSent": "终端在您输入时重新启动,部分输入可能未送达。请先查看新的 shell,再重新输入。", "stalledDaemonBanner": { @@ -19807,7 +20170,11 @@ "picker": { "pasteUnparseable": "应为项目 URL 或 owner/number", "ownerLoadFailed": "无法加载 {{owner}} 的项目。", - "organizationsLoadFailed": "部分组织未能加载({{failureCount}})。" + "organizationsLoadFailed": "部分组织未能加载({{failureCount}})。", + "organizations": "组织", + "listFailed": "无法列出项目", + "detailsFailed": "无法加载详情", + "viewFailed": "无法获取项目视图" }, "error": { "notFoundState": "找不到此项目或视图。", @@ -19840,8 +20207,11 @@ "rateLimited": "已达到 GitHub 速率限制。请几分钟后重试。", "network": "网络错误 — 请检查你的网络连接。", "tooLargeUnknownCount": "此视图条目过多,无法在 Orca 中渲染。请在 GitHub 上缩小视图的筛选范围。", - "tooLarge": "此视图有 {{itemCount}} 个条目,过多而无法在 Orca 中渲染。请在 GitHub 上缩小视图的筛选范围。", - "schemaDriftDetail": "无法读取此项目视图:{{detail}}。" + "schemaDriftDetail": "无法读取此项目视图:{{detail}}。", + "tooLargeCount_other": "此视图有 {{count}} 个条目,过多而无法在 Orca 中显示。请在 GitHub 上缩小视图的筛选范围。" + }, + "columns": { + "type": "类型" } }, "projectField": { @@ -19928,6 +20298,27 @@ "attachments": { "updateRuntime": "更新远程运行时以更改工作区链接", "updateRuntimeSafely": "更新远程运行时以安全地更改工作区链接" + }, + "activity": { + "active": "当前", + "working": "工作中", + "monitoring": "监控后台任务", + "failed": "失败的", + "interrupted": "已中断", + "unconfirmed": "无法确认", + "done": "完成", + "inactive": "未生效", + "permission": "需要授权", + "unreadLabel": "{{status}} · 未读" + }, + "reviewStatus": { + "checksFailed": "{{review}} 检查:失败", + "checksPassing": "{{review}} 检查:通过", + "checksPending": "{{review}} 检查:待处理", + "closed": "{{review}}:已关闭", + "draft": "{{review}}:草稿", + "merged": "{{review}}:已合并", + "open": "{{review}}:开放" } }, "tabHoverCard": { @@ -19971,13 +20362,12 @@ "optionalEmail": "Atlassian 邮箱(作用域令牌可选)" }, "workspace": { - "count": "{{count}} 个关联到 {{key}} 的工作区", "startAnother": "启动新工作区", "empty": "将 Jira 议题关联到工作区,或选择其他视图。", "openFailed": "无法打开关联到此 Jira 议题的工作区。", "mode": "有工作区", "search": "搜索关联的议题", - "single": "1 个关联到 {{key}} 的工作区" + "linkedCount_other": "{{count}} 个工作区已关联到 {{key}}" }, "prompt": { "dialogTitle": "从模板复制提示词", @@ -20070,7 +20460,9 @@ "preparingAriaLabel": "正在准备更新。点击展开。", "browserGuidance": "结束下方进程后重试:其服务器会继续运行,无需浏览器。如果其他计算机通过 SSH 连接到这台 Mac,请更新那台计算机上的 Orca,以便浏览器在更新时自动暂停。", "browserSummary": "后台 Orca 服务器的浏览器仍在使用此应用程序。" - } + }, + "wslMoveInstallHeld": "项目正在移到其 WSL 主机。移动完成后再安装更新。", + "wslMoveUndoInstallHeld": "项目正在从其 WSL 主机移回。完成后再安装更新。" }, "onboarding": { "language": { @@ -20173,7 +20565,7 @@ "email": "获取你的电子邮件地址", "allSites": "读取和更改你在所有网站上的数据", "someSites": "读取和更改你在 {{hosts}} 上的数据", - "manySites": "读取和更改你在 {{hosts}} 及其他 {{count}} 个网站上的数据" + "manyOtherSites_other": "读取和更改你在 {{hosts}} 及其他 {{count}} 个网站上的数据" }, "install": { "title": "添加 {{name}}?", @@ -20483,5 +20875,340 @@ "signatureRequirement": "该构建必须具有与 Orca 相同的有效代码签名,否则安装将停止。", "useButton": "使用本地构建", "cancelButton": "取消" + }, + "runtime": { + "health": { + "local": "本机", + "available": "已连接", + "connecting": "连接中", + "disconnected": "已断开", + "error": "需要处理", + "mixed": "混合状态", + "repair": "需要重新配对", + "update": "需要更新" + }, + "compat": { + "compatible": "运行时客户端与服务器兼容。", + "clientTooOld": "此 Orca 客户端版本过旧,无法连接所选服务器。请更新本机上的 Orca。客户端协议版本为 {{clientProtocol}},服务器要求的客户端协议版本为 {{requiredProtocol}}。", + "serverTooOld": "所选 Orca 服务器版本过旧,无法与此客户端兼容。请更新服务器上的 Orca。服务器协议版本为 {{serverProtocol}},客户端要求的服务器协议版本为 {{requiredProtocol}}。" + } + }, + "native": { + "about": { + "gpu": { + "unknownStatus": "状态不可用", + "enabled": "启用", + "disabled": "已禁用", + "unavailable": "不可用", + "safeMode": "已禁用(安全图形模式)", + "software": "软件渲染", + "unknown": "未知({{status}})", + "summary": "GPU 加速:{{status}}" + } + }, + "dialog": { + "importCookies": "导入 Cookie", + "spaceTitle": "Orca 空间测试版", + "dashboardTitle": "Orca 智能体仪表盘", + "cookieFiles": "Cookie 文件", + "allFiles": "所有文件", + "importPetBundle": "选择 .codex-pet 包", + "pickPet": "选择宠物", + "petImage": "宠物图片", + "importWarpTheme": "导入 Warp 主题", + "warpThemeYaml": "Warp 主题 YAML", + "importWarpFolder": "导入 Warp 主题文件夹", + "images": "图片", + "repoIconImages": "仓库图标图片", + "audio": "音频" + } + }, + "taskProviders": { + "linear": { + "updateAccess": "更新访问权限", + "addAccess": "添加 Linear 访问", + "fetchMore": "加载更多", + "connectionFailed": "连接失败", + "listLabel": "Linear 列表", + "projectsLoadFailed": "无法加载项目。", + "projectNotFound": "未找到项目。", + "projectLoadFailed": "无法加载项目。", + "projectIssuesLoadFailed": "无法加载项目 issue。", + "viewsLoadFailed": "无法加载视图。", + "viewContentsLoadFailed": "无法加载视图内容。", + "issuesLoadFailed": "无法加载 Linear issue。", + "apiKeyHint": "粘贴你希望 Orca 使用的 Linear 工作区的个人 API 密钥。如果该工作区已连接,Orca 会替换其已存储的密钥。", + "remoteKeyStorage": "此密钥由当前远程运行时存储。", + "localKeyStorage": "本地运行时的密钥存储在此设备上,并在可用时使用 Electron 加密存储。", + "commentsLoadFailed": "无法加载评论。", + "updateWorkspaceAccess": "更新 {{workspace}} 的 Linear 访问权限", + "workspaceApiKeyHint": "粘贴 {{workspace}} 的个人 API 密钥。如果此工作区已连接,Orca 会替换其已存储的密钥。", + "connect": "连接", + "descriptionUpdateFailed": "无法更新描述", + "titleUpdateFailed": "无法更新标题", + "truncated": { + "issues_one": "仅显示前 {{count}} 个议题。请搜索或打开 Linear 查看完整列表。", + "issues_other": "仅显示前 {{count}} 个议题。请搜索或打开 Linear 查看完整列表。", + "projectIssues_one": "仅显示项目中的前 {{count}} 个议题。请搜索或打开 Linear 查看完整列表。", + "projectIssues_other": "仅显示项目中的前 {{count}} 个议题。请搜索或打开 Linear 查看完整列表。", + "projects_one": "仅显示前 {{count}} 个项目。请搜索或打开 Linear 查看完整列表。", + "projects_other": "仅显示前 {{count}} 个项目。请搜索或打开 Linear 查看完整列表。", + "viewIssues_one": "仅显示视图中的前 {{count}} 个议题。请搜索或打开 Linear 查看完整列表。", + "viewIssues_other": "仅显示视图中的前 {{count}} 个议题。请搜索或打开 Linear 查看完整列表。", + "views_one": "仅显示前 {{count}} 个视图。请搜索或打开 Linear 查看完整列表。", + "views_other": "仅显示前 {{count}} 个视图。请搜索或打开 Linear 查看完整列表。" + } + }, + "jira": { + "connectionFailed": "连接失败", + "remoteTokenStorage": "你的令牌会发送到所选的远程运行时,并使用该运行时支持的加密方式存储。", + "localTokenStorage": "你的令牌存储在本机,并在本地运行时存储支持加密时进行加密。" + }, + "errors": { + "jira": { + "createFailed": "无法创建议题。", + "commentFailed": "添加评论失败。", + "notConnected": "未连接到 Jira。", + "titleRequired": "必须填写标题。", + "labelsConflict": "请提供 labels 或 labelOperations,不可同时提供两者。", + "updateFailed": "无法更新 issue。", + "credentialsRequired": "必须填写站点 URL、电子邮件和 API 令牌。", + "projectRequired": "必须选择项目。", + "issueTypeRequired": "必须选择 issue 类型。", + "issueKeyRequired": "必须提供 issue 键。", + "updatesRequired": "必须提供更新对象。", + "commentBodyRequired": "必须填写评论正文。", + "invalidSiteUrl": "请输入有效的 Jira 站点 URL。", + "passwordRequired": "必须填写密码。", + "personalTokenRequired": "必须填写个人访问令牌。", + "apiTokenRequired": "必须填写 API 令牌。", + "connectionFailed": "连接失败。", + "invalidSiteIdentity": "请输入不含凭据的 HTTP 或 HTTPS Jira 站点 URL。", + "missingProjectIdentity": "Jira 返回的项目缺少 ID 或键。", + "invalidIssuePage": "Jira 返回了无效的 issue 页面。", + "incompleteIssuePage": "Jira 返回了不完整的 issue 页面。", + "repeatedIssueToken": "Jira 返回了无效或重复的 issue 页面令牌。", + "issueSearchLimit": "Jira issue 搜索超出了页面数量限制。请改用 JQL 选择项目。", + "invalidProjectPage": "Jira 返回了无效的项目页面。", + "incompleteProjectPage": "Jira 返回了不完整的项目页面。", + "projectListLimit": "Jira 项目列表超出了页面数量限制。请改用 JQL 选择项目。", + "invalidCloudId": "站点未返回有效的 Atlassian Cloud ID。" + }, + "linear": { + "notConnected": "未连接到 Linear", + "createFailed": "Linear 创建失败", + "createdButUnavailable": "已创建 issue,但无法获取其详情", + "updateFailed": "Linear 更新失败", + "commentFailed": "无法创建评论", + "projectCreateFailed": "Linear 项目创建失败", + "noApiKey": "未存储 API 密钥。", + "workspaceAuthExpired": "此工作区的 Linear 身份验证已过期。", + "projectNameRequired": "必须填写项目名称", + "projectIdRequired": "必须提供项目 ID", + "projectNotFound": "未找到项目", + "viewIdRequired": "必须提供自定义视图 ID", + "viewHasNoIssues": "自定义视图不包含 issue", + "viewHasNoProjects": "自定义视图不包含项目" + } + } + }, + "workspaceOptions": { + "activeFilterCount_one": "{{count}} 个筛选条件", + "activeFilterCount_other": "{{count}} 个筛选条件" + }, + "editorConflicts": { + "kind": { + "addedByUs": "我们添加", + "bothAdded": "双方都添加", + "deletedByUs": "我们删除", + "addedByThem": "对方添加", + "bothDeleted": "双方都删除", + "bothModified": "双方都修改", + "deletedByThem": "对方删除" + }, + "resolvedBanner": "冲突已在本地解决 · {{kind}}", + "hint": { + "addedByUs": "检查添加的文件,决定是否保留", + "bothModified": "处理冲突标记", + "addedByThem": "保留前先检查添加的文件", + "bothDeleted": "在 Git 中解决冲突,或先恢复其中一方的版本再编辑", + "deletedByThem": "决定是保留文件还是接受删除", + "deletedByUs": "决定是否恢复文件", + "bothAdded": "选择要保留的版本,或将两者合并" + }, + "renamedFrom": "由 {{path}} 重命名而来", + "snapshotCapturedAt": "快照创建于 {{time}}。", + "unresolvedBanner": "未解决的冲突 · {{kind}}" + }, + "stats": { + "usageBreakdown": { + "turns_one": "{{count}} 轮", + "events_one": "{{count}} 个事件", + "sessions_one": "{{count}} 个会话", + "events_other": "{{count}} 个事件", + "sessions_other": "{{count}} 个会话", + "turns_other": "{{count}} 轮" + } + }, + "github": { + "viewed": { + "markFile": "将 {{path}} 标记为已查看", + "unmarkFile": "取消 {{path}} 的已查看标记" + } + }, + "wslMove": { + "entry": { + "hostRow": "从此发行版移动项目…", + "projectMenu": "移到 {{distro}} 主机…" + }, + "blockers": { + "title": "这些项目移动前需要处理", + "inProjects": "位于 {{names}}", + "skipOne": "此次移动不包括 {{name}}", + "skipMany": "此次移动不包括这 {{n}} 个项目" + }, + "title": "将项目移到 {{distro}} 主机", + "loading": "正在检查 {{distro}} 中的项目…", + "runningTitle": "正在移到 {{distro}} 主机", + "preview": { + "counts": "项目:{{projects}} · 工作区:{{workspaces}} · 终端:{{terminals}} · 聊天:{{chats}}", + "whatHappens": "你的文件保留在原处。终端会在同一文件夹中重新启动;其输出、Shell 历史记录和智能体对话都会保留。", + "projects": "{{distro}} 中的项目", + "folderBadge": "文件夹", + "notMoving": "不移动", + "checking": "正在检查所选项目…", + "checkAgain": "重新检查", + "moveOne": "移动 1 个项目", + "moveMany": "移动 {{n}} 个项目", + "heldByHost": "已在 {{distro}} 主机上。", + "changed": "之前已移动,之后又被旧版 Orca 在此处更改。不会再次移动。", + "chatsStay": "现有聊天保留在此电脑上。此项目中的新聊天将在 WSL 主机上开始。", + "browserLoginsConflict": "浏览器登录状态不会迁移,因为主机的浏览器配置文件已在使用中。移动后,请在主机的浏览器标签页中重新登录。", + "browserLoginsNotCarried": "浏览器登录状态不会迁移到此主机。移动后,请在其浏览器标签页中重新登录。" + }, + "cancel": "取消", + "progress": { + "bytes": "{{sent}} / {{total}}", + "tooLate": "已无法取消:主机正在切换。请保持 Orca 打开,直到切换完成。", + "switching": "切换无法取消。请保持 Orca 打开,直到切换完成。", + "readOnly": "这些项目在移动期间为只读。切换开始前你都可以取消。", + "cancelUntilSwitch": "切换开始前你都可以取消。", + "closeKeepsGoing": "关闭此对话框不会停止移动;移动结束时它会重新打开。", + "cancelling": "正在取消…", + "cancel": "取消移动" + }, + "result": { + "movedTitle": "已移到 {{distro}} 主机", + "resetTitle": "未移动任何内容", + "waitingTitle": "正在等待 {{distro}} 主机", + "earlierMoveTitle": "之前的一次移动先完成了", + "refusedTitle": "项目未移动", + "reloadCheckpointRefused": "Orca 无法备份未保存的文件,因此窗口未重新加载。请关闭此对话框,保存或关闭这些文件,然后在保持显示的通知中点击“立即重新加载”。", + "reloadVetoed": "有内容阻止了窗口重新加载。请关闭此对话框,保存你的工作,然后在保持显示的通知中点击“立即重新加载”。", + "reloadFailed": "窗口未重新加载。请重试。", + "moved": "重新加载此窗口,即可在 {{distro}} 主机下看到这些项目。Orca 会在重新加载前备份未保存的文件。", + "automationsPendingOne": "主机上有一个自动化暂时处于关闭状态。Orca 会持续请求主机将其重新开启。", + "automationsPendingMany": "主机上有 {{n}} 个自动化暂时处于关闭状态。Orca 会持续请求主机将其重新开启。", + "undoHint": "改变主意了?重新加载后,侧边栏会将这些项目显示为“已移至 {{distro}} 主机”。在那里选择“重新在此电脑上使用”,即可将它们恢复到移动前的状态。", + "reset": "移动已停止,所有内容均已还原。这些项目会像之前一样在此电脑上工作;已暂停的终端会在你打开时重新启动。", + "resetReason": "停止原因:{{detail}}", + "waiting": "此次移动可能已到达 {{distro}} 主机,但主机没有响应。在主机响应之前,这些项目在此处保持只读。请在设置中连接该主机,然后再次打开此对话框并开始移动:Orca 会先完成或撤销这次移动。", + "reloading": "正在重新加载…", + "reload": "立即重新加载", + "close": "关闭", + "review": "返回项目", + "browserLoginsHostUnknown": "浏览器登录状态未复制,因为 Orca 无法识别主机的浏览器配置文件。请在主机的浏览器标签页中重新登录。", + "browserLoginsConflict": "浏览器登录状态未复制,因为主机的浏览器配置文件已在使用中。请在主机的浏览器标签页中重新登录。", + "browserLoginsNotCopied": "浏览器登录状态未复制到主机。请在主机的浏览器标签页中重新登录。" + }, + "runtime": { + "label": "项目运行环境", + "description": "此项目通过此电脑在 {{distro}} 中运行。将其移到 {{distro}} 主机即可在那里运行。", + "move": "移动项目" + }, + "unfinished": { + "one": "已移到 {{distro}} 主机的一个自动化仍处于关闭状态。Orca 会持续请求主机将其重新开启。", + "many": "已移到 {{distro}} 主机的 {{n}} 个自动化仍处于关闭状态。Orca 会持续请求主机将其重新开启。" + }, + "refusal": { + "previewFailed": "Orca 无法检查这些项目。请重试。", + "startFailed": "Orca 与此次移动失去了联系。请重新打开此对话框查看其进展。", + "unavailable": "此窗口无法将项目移到 WSL 主机。", + "alreadyRunning": "移到 {{distro}} 的操作已在进行中。请等待其完成,然后重试。", + "alreadyInFlightPreview": "{{distro}} 的一次移动仍在收尾。开始此次移动时,Orca 会尽可能先完成或撤销那次移动。", + "alreadyInFlight": "{{distro}} 的一次移动仍在收尾,因此此次移动未开始。请保持 {{distro}} 主机连接,稍后重试。", + "nothingNew": "这些项目已在 {{distro}} 主机上。", + "destinationChanged": "之前来自 {{distro}} 的项目已移到另一个 WSL 主机。请连接该主机以移动更多项目。", + "hostUnavailable": "{{distro}} 主机未连接。请在设置中连接它,然后重试。", + "hostUpdateRequired": "{{distro}} 主机运行的是旧版 Orca。请在设置中更新它,然后重试。", + "terminalsBlocked": "这些项目中的部分终端、智能体或自动化正忙。未移动任何内容。", + "exportIncomplete": "这些项目中的部分已保存状态暂时无法移动,因此未移动任何内容:", + "exportIncompletePreview": "这些项目中的部分已保存状态暂时无法移动:", + "tooLarge": "这些项目的已保存状态过多,无法一次移动。请每次少移动一些项目。", + "pauseFailed": "Orca 无法暂停这些项目中的终端,因此未移动任何内容。已暂停的终端会在你打开时重新启动。请重试。", + "scopeChanged": "移动准备期间有项目发生了更改,因此未移动任何内容。请检查项目后重试。", + "cancelled": "移动已取消。未移动任何内容。", + "finishedEarlierMove": "Orca 先完成了之前一次移到 {{distro}} 的操作。请重新加载窗口,然后重新开始此次移动。" + }, + "step": { + "preparing": "准备中", + "pausingTerminals": "正在暂停终端", + "copying": "正在复制", + "switching": "正在切换", + "finishing": "正在收尾", + "done": "完成" + }, + "blocker": { + "agentWorkingOne": "有一个智能体正在工作或等待回复", + "agentWorkingMany": "有 {{n}} 个智能体正在工作或等待回复", + "processRunningOne": "有一个终端正在运行程序", + "processRunningMany": "有 {{n}} 个终端正在运行程序", + "agentNotResumableOne": "有一个智能体在移动后无法恢复", + "agentNotResumableMany": "有 {{n}} 个智能体在移动后无法恢复", + "unverifiableOne": "Orca 目前无法检查一个终端", + "unverifiableMany": "Orca 目前无法检查 {{n}} 个终端", + "automationRunningOne": "有一个自动化运行正在进行", + "automationRunningMany": "有 {{n}} 个自动化运行正在进行", + "dispatchRunningOne": "有一个智能体任务正在进行", + "dispatchRunningMany": "有 {{n}} 个智能体任务正在进行", + "scrollbackTooLargeOne": "有一个终端的输出历史记录过多,无法移动", + "scrollbackTooLargeMany": "有 {{n}} 个终端的输出历史记录过多,无法移动" + }, + "blockerHint": { + "agentWorking": "等待它完成,或在其终端中停止它,然后重新检查。", + "processRunning": "停止该程序(例如开发服务器或编辑器),然后重新检查。", + "agentNotResumable": "在其终端中退出该智能体,然后重新检查。", + "unverifiable": "请稍候,然后重新检查。Orca 不会为了移动而停止任何内容。", + "wait": "等待其完成,然后重新检查。", + "scrollbackTooLarge": "清除这些终端中的输出,然后重新检查。" + }, + "scopeRefused": { + "windowsDrive": "其文件夹位于 Windows 驱动器上,因此保留在此电脑上。", + "mixedLocations": "其部分文件夹不在此发行版中,因此保留在此电脑上。", + "notLocal": "它已在另一台主机上运行。", + "other": "它无法移动。" + }, + "reloadToast": { + "title": "重新加载以完成移动" + }, + "orchestrator": { + "showTerminal": "显示终端", + "moveAgain": "再次移动", + "checkAgain": "重新检查", + "deferred": "正在完成到 {{distro}} 主机的移动:部分终端仍在忙碌。", + "stuck": "之前一次到 {{distro}} 主机的移动尚未完全结束。", + "declined": "移动已暂停,因为你已将这些项目恢复到此电脑。", + "doneToast": "项目已移到 {{distro}} 主机", + "terminalGone": "该终端已不在此窗口中打开。请重新检查以刷新。", + "blocker": "{{title}}。{{hint}}", + "paused": "将项目移到 {{distro}} 主机的操作已暂停:{{reason}}。", + "pausedReason": { + "exportIncomplete": "部分已保存状态暂时无法迁移", + "manifestTooLarge": "已保存状态超出了一次移动的容量", + "hostUpdate": "需要先更新主机", + "attemptsExhausted": "多次尝试后仍未完成" + }, + "finishPending": "之前一次到 {{distro}} 主机的移动已在主机上完成。Orca 会在重启时在此处完成它,也可以点击“重新检查”立即完成。" + } } } diff --git a/src/renderer/src/lib/adopt-agent-background-session-tab.ts b/src/renderer/src/lib/adopt-agent-background-session-tab.ts new file mode 100644 index 000000000000..d3d6d13ebd79 --- /dev/null +++ b/src/renderer/src/lib/adopt-agent-background-session-tab.ts @@ -0,0 +1,114 @@ +import { useAppStore } from '@/store' +import { makePaneKey, parsePaneKey, type PaneKey } from '../../../shared/stable-pane-id' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' +import type { AgentType } from '../../../shared/agent-status-types' +import { bindAutomationTerminal } from '@/lib/automation-terminal-ownership' +import { createBrowserUuid } from '@/lib/browser-uuid' +import { retireProvider, retireUnownedTerminal } from '@/lib/retire-unowned-background-terminal' +import { isTerminalTabPresent } from '@/store/slices/terminal-tab-retirement' +import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' + +type Store = ReturnType +type RegisterArgs = Parameters + +/** Reserves env-stable tab and pane identities before spawning the PTY. */ +export function reserveAgentBackgroundSessionIdentity(args: { + store: Store + agentType: AgentType + worktreeId: string + launchConfig: RegisterArgs[1] + env: Record | undefined +}): { + reservedTabId: string + leafId: string + paneKey: PaneKey + launchToken: string + launchRegistration: NonNullable + paneEnv: Record +} { + const reservedTabId = createBrowserUuid() + const leafId = createBrowserUuid() + const paneKey = makePaneKey(reservedTabId, leafId) + const launchToken = createBrowserUuid() + const launchRegistration = { + agentType: args.agentType, + launchToken, + tabId: reservedTabId, + leafId + } + args.store.registerAgentLaunchConfig(paneKey, args.launchConfig, launchRegistration) + return { + reservedTabId, + leafId, + paneKey, + launchToken, + launchRegistration, + paneEnv: { + ...args.env, + ORCA_PANE_KEY: paneKey, + ORCA_TAB_ID: reservedTabId, + ORCA_WORKTREE_ID: args.worktreeId, + ORCA_AGENT_LAUNCH_TOKEN: launchToken + } + } +} + +export async function adoptAgentBackgroundSessionTab(args: { + store: Store + worktreeId: string + reservedTabId: string + ptyId: string + paneKey: PaneKey + launchConfig: RegisterArgs[1] + launchRegistration: NonNullable + runtimeTarget: RuntimeClientTarget + runtimeTerminalHandle: string | null + onRetire: () => void + title?: string +}): Promise<{ + tab: ReturnType + paneKey: PaneKey + terminalOwnership: ReturnType +} | null> { + const { store, reservedTabId, ptyId, launchRegistration } = args + // The worktree can disappear while its PTY spawn is pending. + if ( + await retireUnownedTerminal({ + owner: { worktreeId: args.worktreeId }, + ptyId, + runtimeTarget: args.runtimeTarget, + runtimeTerminalHandle: args.runtimeTerminalHandle, + onRetire: args.onRetire + }) + ) { + return null + } + // Re-keying would desynchronize env-baked routing identities; fail closed. + if (isTerminalTabPresent(useAppStore.getState(), reservedTabId)) { + store.clearAgentLaunchConfig(args.paneKey) + args.onRetire() + await retireProvider({ + ptyId, + runtimeTarget: args.runtimeTarget, + runtimeTerminalHandle: args.runtimeTerminalHandle + }) + return null + } + const tab = store.createTab(args.worktreeId, undefined, undefined, { + id: reservedTabId, + initialPtyId: ptyId, + activate: false, + recordInteraction: false, + ...(ORCA_LAYOUT_OWNER_IS_MAIN ? { initialLeafId: parsePaneKey(args.paneKey)?.leafId } : {}) + }) + const paneKey = args.paneKey + store.registerAgentLaunchConfig(paneKey, args.launchConfig, launchRegistration) + const terminalOwnership = bindAutomationTerminal( + tab, + paneKey, + ptyId, + args.runtimeTarget.kind, + args.title + ) + return { tab, paneKey, terminalOwnership } +} diff --git a/src/renderer/src/lib/agent-background-session-contract.ts b/src/renderer/src/lib/agent-background-session-contract.ts new file mode 100644 index 000000000000..bda9de8eac16 --- /dev/null +++ b/src/renderer/src/lib/agent-background-session-contract.ts @@ -0,0 +1,28 @@ +import type { ParsedAgentStatusPayload } from '../../../shared/agent-status-types' +import type { LaunchSource } from '../../../shared/telemetry-events' +import type { TuiAgent } from '../../../shared/tui-agent' +import type { AgentStartupPlan } from '@/lib/tui-agent-startup' +import type { AutomationTerminalOwnership } from '@/lib/automation-terminal-ownership' + +export type LaunchAgentBackgroundSessionArgs = { + agent: TuiAgent + worktreeId: string + prompt?: string + /** An automation's saved extras, merged over this host's default Arguments. */ + extraAgentArgs?: string + launchSource?: LaunchSource + title?: string + onData?: (chunk: string) => void + onExit?: (ptyId: string, code: number) => void + onAgentStatus?: (payload: ParsedAgentStatusPayload) => void +} + +export type LaunchAgentBackgroundSessionResult = { + tabId: string + paneKey: string + ptyId: string + startupPlan: AgentStartupPlan + terminalOwnership: AutomationTerminalOwnership | null + /** Ends a remote runtime's exit wait and data stream; a no-op for local/SSH PTYs. */ + releaseRuntimeObservers: () => void +} diff --git a/src/renderer/src/lib/automation-terminal-bind-layout-owner.test.ts b/src/renderer/src/lib/automation-terminal-bind-layout-owner.test.ts index 5c6bb14499ed..3f2d7fd2865e 100644 --- a/src/renderer/src/lib/automation-terminal-bind-layout-owner.test.ts +++ b/src/renderer/src/lib/automation-terminal-bind-layout-owner.test.ts @@ -4,8 +4,7 @@ import { createTestStore, makeWorktree, seedStore } from '@/store/slices/store-t import { createStoreCascadesMockApi } from '@/store/slices/store-cascades-test-harness' import { makePaneKey } from '../../../shared/stable-pane-id' import { LayoutApplyParams } from '../../../shared/rpc-contract/workspace-layout-params' -import { publishAgentLaunchTab } from './agent-launch-tab-publication' -import { registerTerminalPresentationIpcBridge } from '@/hooks/ipc-events/terminal-presentation-ipc-bridge' +import { bindAutomationTerminal } from './automation-terminal-ownership' const mocks = vi.hoisted(() => { const storeRef: { current: unknown } = { current: null } @@ -51,98 +50,27 @@ beforeEach(() => { }) describe('a background agent tab in a layout-owner build', () => { - it('binds the published reserved pane without another layout RPC', () => { - const onLifecycle = vi.fn( - () => () => {} + it('binds the one-pane tree main made the tab with, so the bind changes no pane tree', () => { + // As adoptAgentBackgroundSessionTab: the tab is made under its terminal's pane id. + const tab = store.getState().createTab(WT, undefined, undefined, { + id: 'tab-run', + initialLeafId: LEAF, + initialPtyId: 'pty-run', + activate: false, + recordInteraction: false + }) + const [create] = mocks.callRuntimeRpc.mock.calls.map( + ([, , params]) => LayoutApplyParams.parse(params).command ) - const respond = vi.fn() - const onCreate = vi.fn(() => () => {}) - vi.stubGlobal('window', { - dispatchEvent: vi.fn(), - api: { - ...window.api, - automations: { onTerminalLifecycleRequest: onLifecycle, respondTerminalLifecycle: respond }, - ui: { - onLaunchRecipe: () => () => {}, - onCreateTerminal: onCreate, - onRequestTerminalTabMount: () => () => {}, - replyTerminalCreate: vi.fn() - } - } + + bindAutomationTerminal(tab, makePaneKey(tab.id, LEAF), 'pty-run', 'environment') + + expect(create).toEqual(expect.objectContaining({ type: 'createTerminalTab', leafId: LEAF })) + expect(store.getState().terminalLayoutsByTabId[tab.id]?.root).toEqual({ + type: 'leaf', + leafId: LEAF }) - const unsubs: (() => void)[] = [] - registerTerminalPresentationIpcBridge(unsubs) - try { - const lifecycle = onLifecycle.mock.calls[0][0] - const correlation = { - requestId: 'arm', - registrationId: 'registration', - runId: 'run', - operationId: 'operation', - serviceGeneration: 'generation', - documentEpoch: null - } - const target = { - worktreeId: WT, - tabId: 'tab-run', - leafId: LEAF, - paneKey: makePaneKey('tab-run', LEAF) - } - lifecycle({ ...correlation, operation: 'arm', target }) - expect(respond).toHaveBeenLastCalledWith(expect.objectContaining({ disposition: 'armed' })) - const epoch = respond.mock.calls[0][0].documentEpoch - const published = publishAgentLaunchTab({ - requestId: 'publish', - worktreeId: WT, - tabId: target.tabId, - leafId: LEAF, - launchAgent: 'codex', - viewMode: 'terminal', - viewer: 'none' - }) - expect(published).toMatchObject({ tabId: target.tabId, created: true }) - onCreate.mock.calls[0][0]({ - requestId: 'materialize', - worktreeId: WT, - tabId: target.tabId, - leafId: LEAF, - ptyId: 'pty-run', - presentation: 'background', - surfaceOwner: false, - agentLaunchViewer: 'none' - }) - lifecycle({ - ...correlation, - requestId: 'bind', - documentEpoch: epoch, - operation: 'bind', - ptyId: 'pty-run', - incarnationId: 'original', - hostId: 'local' - }) - expect(respond).toHaveBeenLastCalledWith( - expect.objectContaining({ - ...correlation, - requestId: 'bind', - documentEpoch: epoch, - disposition: 'bound' - }) - ) - expect( - store.getState().tabsByWorktree[WT].find((tab) => tab.id === target.tabId)?.ptyId - ).toBe('pty-run') - const layout = store.getState().terminalLayoutsByTabId[target.tabId] - expect(layout?.root).toEqual({ type: 'leaf', leafId: LEAF }) - expect(layout?.ptyIdsByLeafId).toEqual({ [LEAF]: 'pty-run' }) - expect(store.getState().ptyIdsByTabId[target.tabId]).toEqual(['pty-run']) - expect(store.getState().tabsByWorktree[WT]).toHaveLength(1) - expect(mocks.callRuntimeRpc).toHaveBeenCalledTimes(1) - expect(LayoutApplyParams.parse(mocks.callRuntimeRpc.mock.calls[0][2]).command).toEqual( - expect.objectContaining({ type: 'createTerminalTab', leafId: LEAF }) - ) - } finally { - unsubs.forEach((release) => release()) - vi.unstubAllGlobals() - } + // The bind sends nothing more: main already holds this tree. + expect(mocks.callRuntimeRpc).toHaveBeenCalledTimes(1) }) }) diff --git a/src/renderer/src/lib/automation-terminal-ownership.test.ts b/src/renderer/src/lib/automation-terminal-ownership.test.ts new file mode 100644 index 000000000000..836582286904 --- /dev/null +++ b/src/renderer/src/lib/automation-terminal-ownership.test.ts @@ -0,0 +1,273 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { AppState } from '@/store/types' +import { singlePaneLayoutSnapshot } from '@/store/slices/terminal-helpers' +import type { AgentStatusEntry } from '../../../shared/agent-status-types' +import { + createAutomationTerminalOwnership, + type AutomationTerminalOwnershipStore +} from './automation-terminal-ownership' + +const WORKTREE_ID = 'worktree-1' +const TAB_ID = 'tab-1' +const LEAF_ID = '7c6fb4e5-3bf1-4ff4-8259-03f7ae81c40d' +const PANE_KEY = `${TAB_ID}:${LEAF_ID}` +const PTY_ID = 'pty-1' +const CREATED_AT = 100 + +type OwnershipState = Pick< + AppState, + | 'activeWorktreeId' + | 'activeTabId' + | 'activeTabType' + | 'tabsByWorktree' + | 'ptyIdsByTabId' + | 'terminalLayoutsByTabId' + | 'lastTerminalInputAtByPaneKey' + | 'agentStatusByPaneKey' + | 'retainedAgentsByPaneKey' + | 'sleepingAgentSessionsByPaneKey' + | 'agentLaunchConfigByPaneKey' + | 'closeTab' + | 'shutdownCompletedAgentPaneForHibernation' +> + +// A finished Claude turn whose hook reported its conversation id, as a live run leaves it. +const RESUMABLE_DONE_ENTRY: AgentStatusEntry = { + state: 'done', + prompt: 'Reply with pineapple', + updatedAt: 300, + stateStartedAt: 300, + paneKey: PANE_KEY, + worktreeId: WORKTREE_ID, + agentType: 'claude', + providerSession: { key: 'session_id', id: 'c569e233-595e-4085-8660-5af742f81e59' }, + stateHistory: [] +} + +function createStore() { + const closeTab = vi.fn() + const shutdownCompletedAgentPaneForHibernation = vi.fn(async () => {}) + let state: OwnershipState = { + activeWorktreeId: 'other-worktree', + activeTabId: 'other-tab', + activeTabType: 'terminal' as const, + tabsByWorktree: { + [WORKTREE_ID]: [ + { + id: TAB_ID, + worktreeId: WORKTREE_ID, + ptyId: PTY_ID, + title: 'Automation', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: CREATED_AT + } + ] + }, + ptyIdsByTabId: { [TAB_ID]: [PTY_ID] }, + terminalLayoutsByTabId: { + [TAB_ID]: singlePaneLayoutSnapshot(LEAF_ID, PTY_ID) + }, + lastTerminalInputAtByPaneKey: {}, + agentStatusByPaneKey: { [PANE_KEY]: RESUMABLE_DONE_ENTRY }, + retainedAgentsByPaneKey: {}, + sleepingAgentSessionsByPaneKey: {}, + agentLaunchConfigByPaneKey: {}, + closeTab, + shutdownCompletedAgentPaneForHibernation + } + const listeners = new Set<(state: AppState, previousState: AppState) => void>() + const store: AutomationTerminalOwnershipStore = { + getState: () => state as unknown as AppState, + subscribe: (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + } + } + const update = (patch: Partial): void => { + const previousState = state + state = { ...state, ...patch } + for (const listener of listeners) { + listener(state as unknown as AppState, previousState as unknown as AppState) + } + } + return { + closeTab, + getState: () => state, + shutdownCompletedAgentPaneForHibernation, + store, + update + } +} + +function own( + store: AutomationTerminalOwnershipStore, + overrides: Partial[0]> = {} +) { + return createAutomationTerminalOwnership({ + store, + worktreeId: WORKTREE_ID, + tabId: TAB_ID, + paneKey: PANE_KEY, + ptyId: PTY_ID, + tabCreatedAt: CREATED_AT, + runtimeKind: 'desktop', + ...overrides + }) +} + +describe('automation terminal ownership', () => { + beforeEach(() => vi.clearAllMocks()) + + it('closes the exact fresh desktop tab once after the PTY exit binding is cleared', async () => { + const { closeTab, store, update } = createStore() + const ownership = own(store) + update({ + ptyIdsByTabId: { [TAB_ID]: [] }, + tabsByWorktree: { + [WORKTREE_ID]: [{ ...store.getState().tabsByWorktree[WORKTREE_ID]![0]!, ptyId: null }] + } + }) + + expect(await ownership.finalize({ preservePane: false })).toBe('closed') + expect(await ownership.finalize({ preservePane: false })).toBeNull() + expect(closeTab).toHaveBeenCalledTimes(1) + expect(closeTab).toHaveBeenCalledWith(TAB_ID, { + recordInteraction: false, + reason: 'cleanup' + }) + }) + + it('preserves a tab activated after launch even when focus later moves away', async () => { + const { closeTab, store, update } = createStore() + const ownership = own(store) + + update({ activeWorktreeId: WORKTREE_ID, activeTabId: TAB_ID }) + update({ activeWorktreeId: 'other-worktree', activeTabId: 'other-tab' }) + + expect(await ownership.finalize({ preservePane: false })).toBeNull() + expect(closeTab).not.toHaveBeenCalled() + }) + + it('preserves a tab that received user input after launch', async () => { + const { closeTab, store, update } = createStore() + const ownership = own(store) + + update({ lastTerminalInputAtByPaneKey: { [PANE_KEY]: 200 } }) + + expect(await ownership.finalize({ preservePane: false })).toBeNull() + expect(closeTab).not.toHaveBeenCalled() + }) + + it.each([ + ['tab PTY', { tabsByWorktree: undefined, ptyIdsByTabId: undefined, layoutPty: undefined }], + [ + 'PTY index', + { tabsByWorktree: null, ptyIdsByTabId: ['pty-replacement'], layoutPty: undefined } + ], + [ + 'pane layout', + { tabsByWorktree: null, ptyIdsByTabId: undefined, layoutPty: 'pty-replacement' } + ] + ])('refuses a replacement identity in the %s binding', async (_label, drift) => { + const { closeTab, getState, store, update } = createStore() + const ownership = own(store) + const tab = getState().tabsByWorktree[WORKTREE_ID]![0]! + update({ + ...(drift.tabsByWorktree === undefined + ? { tabsByWorktree: { [WORKTREE_ID]: [{ ...tab, ptyId: 'pty-replacement' }] } } + : {}), + ...(drift.ptyIdsByTabId ? { ptyIdsByTabId: { [TAB_ID]: drift.ptyIdsByTabId } } : {}), + ...(drift.layoutPty + ? { + terminalLayoutsByTabId: { + [TAB_ID]: { + ...getState().terminalLayoutsByTabId[TAB_ID]!, + ptyIdsByLeafId: { [LEAF_ID]: drift.layoutPty } + } + } + } + : {}) + }) + + expect(await ownership.finalize({ preservePane: false })).toBeNull() + expect(closeTab).not.toHaveBeenCalled() + }) + + it('refuses a tab recreated with the same id', async () => { + const { closeTab, getState, store, update } = createStore() + const ownership = own(store) + update({ + tabsByWorktree: { + [WORKTREE_ID]: [ + { ...getState().tabsByWorktree[WORKTREE_ID]![0]!, createdAt: CREATED_AT + 1 } + ] + } + }) + + expect(await ownership.finalize({ preservePane: false })).toBeNull() + expect(closeTab).not.toHaveBeenCalled() + }) + + it.each([ + ['remote runtime', { runtimeKind: 'environment' as const }], + ['remote PTY identity', { ptyId: 'remote:env-1@@terminal-1' }] + ])('never owns a %s terminal', async (_label, overrides) => { + const { closeTab, store } = createStore() + const ownership = own(store, overrides) + + expect(await ownership.finalize({ preservePane: false })).toBeNull() + expect(closeTab).not.toHaveBeenCalled() + }) + + it('sleeps a resumable pane in a workspace the run owns instead of closing it', async () => { + const { closeTab, shutdownCompletedAgentPaneForHibernation, store } = createStore() + const ownership = own(store) + + expect(await ownership.finalize({ preservePane: true })).toBe('hibernated') + expect(shutdownCompletedAgentPaneForHibernation).toHaveBeenCalledExactlyOnceWith(WORKTREE_ID, { + paneKey: PANE_KEY, + tabId: TAB_ID, + leafId: LEAF_ID, + ptyId: PTY_ID + }) + expect(closeTab).not.toHaveBeenCalled() + }) + + it.each([ + ['the agent reported no conversation id', { providerSession: undefined }, [PTY_ID]], + ['the run ended by its process exiting', {}, []] + ])('closes the tab when %s', async (_label, entryPatch, livePtyIds) => { + const { closeTab, shutdownCompletedAgentPaneForHibernation, store, update } = createStore() + const ownership = own(store) + update({ + agentStatusByPaneKey: { [PANE_KEY]: { ...RESUMABLE_DONE_ENTRY, ...entryPatch } }, + ptyIdsByTabId: { [TAB_ID]: livePtyIds } + }) + + expect(await ownership.finalize({ preservePane: true })).toBe('closed') + expect(shutdownCompletedAgentPaneForHibernation).not.toHaveBeenCalled() + expect(closeTab).toHaveBeenCalledTimes(1) + }) + + it('keeps the terminal running when its stop fails', async () => { + const { closeTab, shutdownCompletedAgentPaneForHibernation, store } = createStore() + shutdownCompletedAgentPaneForHibernation.mockRejectedValueOnce(new Error('kill failed')) + vi.spyOn(console, 'error').mockImplementation(() => {}) + const ownership = own(store) + + expect(await ownership.finalize({ preservePane: true })).toBeNull() + expect(closeTab).not.toHaveBeenCalled() + }) + + it('release consumes ownership without closing the terminal', async () => { + const { closeTab, store } = createStore() + const ownership = own(store) + + ownership.release() + + expect(await ownership.finalize({ preservePane: false })).toBeNull() + expect(closeTab).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/lib/automation-terminal-ownership.ts b/src/renderer/src/lib/automation-terminal-ownership.ts index c507f61e45dc..1443312a6358 100644 --- a/src/renderer/src/lib/automation-terminal-ownership.ts +++ b/src/renderer/src/lib/automation-terminal-ownership.ts @@ -1,31 +1,40 @@ -import { - automationTerminalLifecycleResponse, - isCurrentAutomationTerminalRequest -} from '../../../shared/automation-terminal-lifecycle' import { isRemoteRuntimePtyId } from '../../../shared/remote-runtime/remote-runtime-pty-id' -import type { - AutomationTerminalLifecycleOwner, - AutomationTerminalTarget, - AutomationTerminalLifecycleResponse -} from '../../../shared/automation-terminal-lifecycle' import { useAppStore } from '@/store' import type { AppState } from '@/store/types' +import type { TerminalTab } from '../../../shared/terminal-tab-types' import { parsePaneKey } from '../../../shared/stable-pane-id' -import { mobilePublicationEpoch } from '@/runtime/sync-runtime-graph/graph-state' +import '@/store/slices/agent-status/agent-status' +import { collectSleepingAgentSessionRecordsForWorktree } from '@/store/slices/agent-status/agent-status-recovery-collection' +import { singlePaneLayoutSnapshot } from '@/store/slices/terminal-helpers' import { readLastTerminalInputAt } from './terminal-input-activity-coalescing' -import { persistWorkspaceSessionByHost } from './workspace-session-host-persistence' -import { buildWorkspaceSessionPayload } from './workspace-session' -import { closeTerminalTab } from '@/components/terminal/terminal-tab-actions' -import { isUnifiedTabPinned } from '@/store/pinned-tab-close-guard' export type AutomationTerminalOwnershipStore = { getState: () => AppState subscribe: (listener: (state: AppState, previousState: AppState) => void) => () => void } +/** How finalize retired the run's terminal; null when it left the terminal as it was. */ +export type AutomationTerminalRetirement = 'closed' | 'hibernated' | null + +export type AutomationTerminalOwnership = { + /** `preservePane` sleeps a resumable pane in place instead of closing its tab. */ + finalize: (options: { preservePane: boolean }) => Promise + release: () => void +} + +type CreateAutomationTerminalOwnershipArgs = { + store: AutomationTerminalOwnershipStore + worktreeId: string + tabId: string + paneKey: string + ptyId: string + tabCreatedAt: number + runtimeKind: 'desktop' | 'environment' +} + function isOwnedTabIdentityCurrent( state: AppState, - args: AutomationTerminalTarget & { ptyId: string; tabCreatedAt: number } + args: Omit ): boolean { const parsedPane = parsePaneKey(args.paneKey) if (!parsedPane || parsedPane.tabId !== args.tabId) { @@ -67,240 +76,129 @@ function isOwnedTabIdentityCurrent( return layoutPtyId === undefined || layoutPtyId === args.ptyId } -export function createAutomationTerminalOwnership( - store: AutomationTerminalOwnershipStore, - target: AutomationTerminalTarget -) { - let taken = false - let lost = false - let materialized = false - let createdAt = 0 - let ptyId: string | null = null - const initial = store.getState() - const input = readLastTerminalInputAt(initial.lastTerminalInputAtByPaneKey, target.paneKey) - let tabs = initial.tabsByWorktree[target.worktreeId] - let layout = initial.terminalLayoutsByTabId[target.tabId] - let ptys = initial.ptyIdsByTabId[target.tabId] - // Enrollment cannot infer the history of a surface that already existed. - if (tabs?.some((tab) => tab.id === target.tabId)) { - lost = true +function canHibernateOwnedPane( + state: AppState, + args: Pick +): boolean { + // Why: a run that ended by exiting has no process left to stop in place. + if (!(state.ptyIdsByTabId[args.tabId] ?? []).includes(args.ptyId)) { + return false } - const observe = (state: AppState): void => { - taken ||= - (state.activeWorktreeId === target.worktreeId && - state.activeTabId === target.tabId && + return Boolean( + collectSleepingAgentSessionRecordsForWorktree(state, args.worktreeId, { + paneKeys: [args.paneKey], + captureMode: 'completed-agent-hibernation' + })[args.paneKey] + ) +} + +export function createAutomationTerminalOwnership( + args: CreateAutomationTerminalOwnershipArgs +): AutomationTerminalOwnership { + let consumed = false + let userTookOver = false + // Include coalesced pending keystrokes or a recent user takeover can be missed. + const inputAtLaunch = readLastTerminalInputAt( + args.store.getState().lastTerminalInputAtByPaneKey, + args.paneKey + ) + const observeTakeover = (): void => { + const state = args.store.getState() + if ( + (state.activeWorktreeId === args.worktreeId && + state.activeTabId === args.tabId && state.activeTabType === 'terminal') || - readLastTerminalInputAt(state.lastTerminalInputAtByPaneKey, target.paneKey) !== input - const nextTabs = state.tabsByWorktree[target.worktreeId] - const nextLayout = state.terminalLayoutsByTabId[target.tabId] - const nextPtys = state.ptyIdsByTabId[target.tabId] - if (tabs === nextTabs && layout === nextLayout && ptys === nextPtys) { - return - } - tabs = nextTabs - layout = nextLayout - ptys = nextPtys - const tab = tabs?.find((candidate) => candidate.id === target.tabId) - if (!materialized && tab) { - materialized = true - createdAt = tab.createdAt - } else if (materialized && (!tab || tab.createdAt !== createdAt)) { - lost = true - } - if (ptyId && !isOwnedTabIdentityCurrent(state, { ...target, ptyId, tabCreatedAt: createdAt })) { - lost = true + readLastTerminalInputAt(state.lastTerminalInputAtByPaneKey, args.paneKey) !== inputAtLaunch + ) { + userTookOver = true } } - const release = store.subscribe(observe) - observe(initial) - const eligible = (): boolean => { - observe(store.getState()) - return ( - !taken && - !lost && - materialized && - ptyId !== null && - isOwnedTabIdentityCurrent(store.getState(), { ...target, ptyId, tabCreatedAt: createdAt }) - ) + const unsubscribe = args.store.subscribe(observeTakeover) + observeTakeover() + + const release = (): void => { + if (consumed) { + return + } + consumed = true + unsubscribe() } + return { release, - eligible, - bind: (original: string): boolean => { - if (ptyId || isRemoteRuntimePtyId(original)) { - return false + finalize: async ({ preservePane }) => { + if (consumed) { + return null + } + // Consume before identity checks: completion and exit can race to retire the same session. + consumed = true + unsubscribe() + observeTakeover() + if (args.runtimeKind !== 'desktop' || isRemoteRuntimePtyId(args.ptyId) || userTookOver) { + return null + } + const state = args.store.getState() + const leafId = parsePaneKey(args.paneKey)?.leafId + if (!leafId || !isOwnedTabIdentityCurrent(state, args)) { + return null + } + if (preservePane && canHibernateOwnedPane(state, args)) { + try { + // Why: sleeping keeps the tab and its resume record, so opening the run resumes it. + await state.shutdownCompletedAgentPaneForHibernation(args.worktreeId, { + paneKey: args.paneKey, + tabId: args.tabId, + leafId, + ptyId: args.ptyId + }) + } catch (error) { + // Failed stop rolls back to a live agent; closing would discard the session it preserved. + console.error('[automations] Failed to hibernate owned automation terminal:', error) + return null + } + return 'hibernated' + } + try { + // Use closeTab’s provider/pane teardown authority rather than adding a second direct-kill path. + state.closeTab(args.tabId, { recordInteraction: false, reason: 'cleanup' }) + } catch (error) { + // A throwing close leaves the terminal live; retain its valid identity and report not-closed. + console.error('[automations] Failed to close owned automation terminal:', error) + return null } - ptyId = original - return eligible() + return 'closed' } } } -export function registerAutomationTerminalLifecycle( - store: AutomationTerminalOwnershipStore = useAppStore -): () => void { - const api = window.api.automations - if (!api.onTerminalLifecycleRequest) { - return () => {} - } - const owners = new Map< - string, - AutomationTerminalLifecycleOwner> - >() - const persist = async (): Promise => { - const state = store.getState() - await persistWorkspaceSessionByHost( - window.api.session, - buildWorkspaceSessionPayload(state), - state - ) +export function bindAutomationTerminal( + tab: TerminalTab, + paneKey: string, + ptyId: string, + runtimeKind: 'local' | 'environment', + title?: string +): AutomationTerminalOwnership | null { + const parsedPane = parsePaneKey(paneKey) + if (!parsedPane || parsedPane.tabId !== tab.id) { + throw new Error('Automation terminal pane identity is invalid.') } - const dispose = (id: string): void => { - const owner = owners.get(id) - owners.delete(id) - owner?.ownership.release() - owner?.settle?.(owner.authorized ? 'unproven' : 'live') + const store = useAppStore.getState() + if (title) { + store.setTabCustomTitle(tab.id, title, { recordInteraction: false }) } - const release = api.onTerminalLifecycleRequest((request) => { - const respond = (disposition: AutomationTerminalLifecycleResponse['disposition']): void => - api.respondTerminalLifecycle( - automationTerminalLifecycleResponse(request, mobilePublicationEpoch, disposition) - ) - if (request.operation === 'arm') { - if (owners.has(request.registrationId) || request.documentEpoch !== null) { - respond('kept') - return - } - owners.set(request.registrationId, { - request, - target: request.target, - ownership: createAutomationTerminalOwnership(store, request.target), - ptyId: null, - prepared: false, - authorized: false - }) - respond('armed') - return - } - const owner = owners.get(request.registrationId) - if (!isCurrentAutomationTerminalRequest(owner, request, mobilePublicationEpoch)) { - respond('kept') - return - } - if (request.operation === 'release') { - dispose(request.registrationId) - respond('released') - return - } - if (request.operation === 'bind') { - if (owner.ptyId || !owner.ownership.bind(request.ptyId)) { - respond('kept') - return - } - owner.ptyId = request.ptyId - respond('bound') - return - } - if (request.phase === 'authorize') { - const allowed = - owner.prepared && - !owner.authorized && - owner.transactionCurrent?.() === true && - owner.ownership.eligible() - owner.authorized ||= allowed - respond(allowed ? 'authorized' : 'kept') - return - } - if (request.phase === 'stop-settled') { - if (!owner.prepared || !owner.completion || !owner.settle) { - respond('unproven') - return - } - const proof = request.proof === 'stopped' && !owner.authorized ? 'unproven' : request.proof - owner.proof = proof - owner.settle(proof) - void owner.completion.then(respond).finally(() => dispose(request.registrationId)) - return - } - const state = store.getState() - const { target, ptyId } = owner - if (owner.completion || !ptyId || !owner.ownership.eligible()) { - respond('kept') - return - } - let preservePane = request.preservePane - owner.completion = (async () => { - try { - await state.shutdownCompletedAgentPaneForHibernation(target.worktreeId, { - ...target, + store.updateTabPtyId(tab.id, ptyId) + store.setTabLayout(tab.id, singlePaneLayoutSnapshot(parsedPane.leafId, ptyId)) + const ownership = + runtimeKind === 'local' + ? createAutomationTerminalOwnership({ + store: useAppStore, + worktreeId: tab.worktreeId, + tabId: tab.id, + paneKey, ptyId, - lifecycle: { - preservePane, - stop: async (captured, transactionCurrent) => { - owner.transactionCurrent = transactionCurrent - preservePane = captured - if ( - !preservePane && - isUnifiedTabPinned(store.getState(), target.worktreeId, target.tabId) - ) { - return 'live' - } - await persist() - if (!owner.ownership.eligible() || owners.get(request.registrationId) !== owner) { - return 'live' - } - const settlement = new Promise<'stopped' | 'live' | 'unproven'>((resolve) => { - owner.settle = resolve - }) - owner.prepared = true - respond('prepared') - return settlement - } - } + tabCreatedAt: tab.createdAt, + runtimeKind: 'desktop' }) - if (!preservePane) { - if (!owner.ownership.eligible()) { - return 'stopped-but-uncommitted' - } - let closed = false - closeTerminalTab(target.tabId, { - reason: 'cleanup', - rejectPinned: true, - skipRunningProcessConfirm: true, - localPtyTeardownOwnedExternally: true, - onClosed: () => { - closed = true - } - }) - if (!closed) { - return 'stopped-but-uncommitted' - } - } - await persist() - return preservePane ? 'hibernated' : 'closed' - } catch { - if (!owner.prepared) { - respond('kept') - } - try { - await persist() - } catch { - /* Preserve the captured record on an uncertain commit. */ - } - return owner.proof === 'stopped' - ? 'stopped-but-uncommitted' - : owner.proof === 'live' - ? 'kept-live' - : owner.authorized - ? 'unproven' - : 'kept-live' - } - })() - }) - return () => { - release() - for (const id of owners.keys()) { - dispose(id) - } - } + : null + return ownership } diff --git a/src/renderer/src/lib/launch-agent-background-session-extra-args.test.ts b/src/renderer/src/lib/launch-agent-background-session-extra-args.test.ts new file mode 100644 index 000000000000..ac0c3b912c5e --- /dev/null +++ b/src/renderer/src/lib/launch-agent-background-session-extra-args.test.ts @@ -0,0 +1,131 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + createAgentBackgroundSessionTestState, + resetAgentBackgroundSessionTestHarness, + useRemoteAgentBackgroundRuntime +} from '@/lib/agent-background-session-test-state' + +const mockSpawn = vi.fn() +const mockKill = vi.fn() +const mockWrite = vi.fn() +const mockRuntimeEnvironmentCall = vi.fn() +const mockRuntimeEnvironmentTransportCall = vi.fn() +const mockRuntimeEnvironmentSubscribe = vi.fn() +const mockCreateTab = vi.fn() +const mockSetTabCustomTitle = vi.fn() +const mockUpdateTabPtyId = vi.fn() +const mockCloseTab = vi.fn() +const mockSetTabLayout = vi.fn() +const mockRegisterAgentLaunchConfig = vi.fn() +const mockRegisterEagerPtyBuffer = vi.fn() +const mockSubscribeToPtyData = vi.fn() +const mockSubscribeToPtyExit = vi.fn() +const mockPasteDraftWhenAgentReady = vi.fn() +const mockDispatchEvent = vi.fn() +const mockGetAgentLaunchPlatformForRepo = vi.fn<() => NodeJS.Platform>() +const state = createAgentBackgroundSessionTestState({ + createTab: mockCreateTab, + setTabCustomTitle: mockSetTabCustomTitle, + updateTabPtyId: mockUpdateTabPtyId, + closeTab: mockCloseTab, + setTabLayout: mockSetTabLayout, + registerAgentLaunchConfig: mockRegisterAgentLaunchConfig +}) +let currentStoreState = state + +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => currentStoreState, + subscribe: vi.fn(() => () => {}) + } +})) + +// Why: the background mount's sleeping-agent scan reads store state these launches never seed. +vi.mock('@/lib/sleeping-agent-wake-requests', () => ({ requestSleepingAgentWakeOnMount: vi.fn() })) + +vi.mock('@/lib/telemetry', () => ({ + track: vi.fn(), + tuiAgentToAgentKind: (agent: string) => agent +})) + +vi.mock('@/lib/agent-paste-draft', () => ({ + pasteDraftWhenAgentReady: mockPasteDraftWhenAgentReady +})) + +vi.mock('@/lib/execution-host-facts', async (importOriginal) => { + const hostFact = () => ({ + kind: 'known' as const, + platform: mockGetAgentLaunchPlatformForRepo(), + hostKind: 'local' as const + }) + return { + ...(await importOriginal>()), + resolveRepoExecutionHostPlatform: hostFact, + resolveWorktreeExecutionHostPlatform: hostFact + } +}) + +vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({ + registerEagerPtyBuffer: mockRegisterEagerPtyBuffer, + subscribeToPtyExit: mockSubscribeToPtyExit +})) + +vi.mock('@/components/terminal-pane/pty-data-sidecar-subscriptions', () => ({ + subscribeToPtyData: mockSubscribeToPtyData +})) + +describe('launchAgentBackgroundSession with automation extras', () => { + beforeEach(() => { + currentStoreState = state + resetAgentBackgroundSessionTestHarness({ + state, + createTab: mockCreateTab, + closeTab: mockCloseTab, + getLaunchPlatform: mockGetAgentLaunchPlatformForRepo, + runtimeCall: mockRuntimeEnvironmentCall, + runtimeTransportCall: mockRuntimeEnvironmentTransportCall, + runtimeSubscribe: mockRuntimeEnvironmentSubscribe, + subscribeToData: mockSubscribeToPtyData, + subscribeToExit: mockSubscribeToPtyExit, + setTabLayout: mockSetTabLayout, + updateTabPtyId: mockUpdateTabPtyId, + dispatchEvent: mockDispatchEvent, + kill: mockKill, + spawn: mockSpawn, + write: mockWrite + }) + }) + + it('fails before reserving a tab or spawning when the extras are refused', async () => { + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await expect( + launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run the automation', + extraAgentArgs: '--permission-mode bypassPermissions' + }) + ).rejects.toThrow('"--permission-mode"') + expect(mockSpawn).not.toHaveBeenCalled() + expect(mockCreateTab).not.toHaveBeenCalled() + expect(mockRegisterAgentLaunchConfig).not.toHaveBeenCalled() + }) + + it('refuses a client-side launch that would drop extras on a paired server', async () => { + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + useRemoteAgentBackgroundRuntime(state) + + await expect( + launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run the automation', + extraAgentArgs: '--model opus' + }) + ).rejects.toThrow("Extra arguments can't be applied to a paired server's workspace from here.") + expect(mockRuntimeEnvironmentCall).not.toHaveBeenCalled() + expect(mockSpawn).not.toHaveBeenCalled() + expect(mockRegisterAgentLaunchConfig).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/lib/launch-agent-background-session-launch-parity.test.ts b/src/renderer/src/lib/launch-agent-background-session-launch-parity.test.ts new file mode 100644 index 000000000000..d181c3347beb --- /dev/null +++ b/src/renderer/src/lib/launch-agent-background-session-launch-parity.test.ts @@ -0,0 +1,121 @@ +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' +import type * as TransportFixtureModule from '@/runtime/layout-apply-test-transport.test-fixture' +import { + launchWorkspaceState, + perClientLoader, + type LaunchStoreHolder +} from '@/lib/launch-parity-renderer.test-fixture' +import { getDefaultSettings } from '../../../shared/constants' +import { + AUTOMATION_LAUNCH_CASES, + AUTOMATION_PROMPT, + automationPhoneTab, + automationSpawnRequest, + type AutomationLaunchCase +} from '../../../shared/launch-parity-automation-cases.test-fixture' +import { + LAUNCH_LEAF_ID, + LAUNCH_TAB_ID, + LAUNCH_TOKEN, + launchWorkspaceId +} from '../../../shared/launch-parity-window-request.test-fixture' + +// Keep main’s mocked layout transport outside module resets so each rebuilt client still reaches it. +type TransportFixture = typeof TransportFixtureModule +const main = vi.hoisted((): { transport: TransportFixture['layoutApplyTestTransport'] | null } => ({ + transport: null +})) +vi.mock('@/runtime/runtime-rpc-client', async (importOriginal) => { + const fixture = await import('@/runtime/layout-apply-test-transport.test-fixture') + main.transport = fixture.layoutApplyTestTransport + return fixture.runtimeRpcClientWithLayoutApply(await importOriginal()) +}) + +const holder = vi.hoisted((): LaunchStoreHolder => ({ store: null })) +vi.mock('@/store', async () => + (await import('@/lib/launch-parity-renderer.test-fixture')).launchStoreModuleMock(holder) +) +// The stdin-after-start paste is pinned by launch-agent-background-session.test.ts. +vi.mock('@/lib/agent-paste-draft', () => ({ pasteDraftWhenAgentReady: vi.fn() })) +vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({ + registerEagerPtyBuffer: vi.fn(), + subscribeToPtyExit: vi.fn(() => () => {}) +})) +vi.mock('@/components/terminal-pane/pty-data-sidecar-subscriptions', () => ({ + subscribeToPtyData: vi.fn(() => () => {}) +})) + +const load = perClientLoader(async () => ({ + launch: await import('./launch-agent-background-session'), + phone: await import('@/runtime/sync-runtime-graph/mobile-session-snapshots'), + switch: await import('../../../shared/layout-owner-switch') +})) + +async function runAutomation(c: AutomationLaunchCase) { + const modules = await load(c.client) + const store = modules.createStore() + holder.store = store + store.setState( + launchWorkspaceState(c.workspace, { ...getDefaultSettings('/home/alice'), ...c.settings }) + ) + const spawn = vi.fn(async (_request: Record) => ({ id: 'pty-1' })) + vi.stubGlobal('window', { + dispatchEvent: vi.fn(), + api: { pty: { spawn, write: vi.fn(), kill: vi.fn() }, runtime: { call: vi.fn() } } + }) + await modules.launch.launchAgentBackgroundSession({ + agent: c.agent, + worktreeId: launchWorkspaceId(c.workspace), + prompt: AUTOMATION_PROMPT, + launchSource: 'unknown', + title: c.title + }) + const phone = modules.phone.buildMobileSessionTabSnapshots(store.getState(), false) + if (modules.switch.ORCA_LAYOUT_OWNER_IS_MAIN) { + const tabBarId = store.getState().unifiedTabsByWorktree[launchWorkspaceId(c.workspace)]![0]!.id + expect(main.transport?.sentOfType('renameTab').at(-1)).toEqual( + expect.objectContaining({ tabId: tabBarId, kind: 'custom', title: c.title }) + ) + for (const snapshot of phone) { + snapshot.tabs = snapshot.tabs.map((tab) => ({ ...tab, title: c.title })) + } + } + return { spawn, phone } +} + +function withFixedIds(value: unknown): unknown { + const text = JSON.stringify(value) + const ids = [ + ...new Set(text.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g)) + ] + const fixed = [LAUNCH_TAB_ID, LAUNCH_LEAF_ID, LAUNCH_TOKEN] + return JSON.parse(ids.reduce((out, id, index) => out.replaceAll(id, fixed[index] ?? id), text)) +} + +// Pin automation pty:spawn and mobile-tab behavior as the convergence baseline before C7 replaces this producer. +describe('row 5: desktop automation pty:spawn request', () => { + beforeAll(async () => { + await load('darwin') + await load('linux') + await load('win32') + }, 240_000) + afterEach(() => vi.unstubAllGlobals()) + + it.each(AUTOMATION_LAUNCH_CASES)('$name', async (c) => { + const { spawn, phone } = await runAutomation(c) + expect(withFixedIds(spawn.mock.calls[0]?.[0])).toEqual(automationSpawnRequest(c)) + expect( + phone.map(({ tabs }) => + tabs.map((tab) => ({ + title: tab.title, + launchAgent: recordOf(tab).launchAgent, + isActive: tab.isActive + })) + ) + ).toEqual([[automationPhoneTab(c)]]) + }) +}) + +function recordOf(value: unknown): Record { + return value && typeof value === 'object' ? { ...value } : {} +} diff --git a/src/renderer/src/lib/launch-agent-background-session-remote.test.ts b/src/renderer/src/lib/launch-agent-background-session-remote.test.ts new file mode 100644 index 000000000000..27f4339f3499 --- /dev/null +++ b/src/renderer/src/lib/launch-agent-background-session-remote.test.ts @@ -0,0 +1,487 @@ +import { createCompatibleRuntimeStatusResponseIfNeeded } from '@/runtime/runtime-compatibility-test-fixture' +import { AGENT_SESSION_KEYBOARD_RUNTIME_CAPABILITY } from '../../../shared/protocol-version' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + AGENT_BACKGROUND_SESSION_UUID_RE as UUID_RE, + createAgentBackgroundSessionTestState, + resetAgentBackgroundSessionTestHarness, + useRemoteAgentBackgroundRuntime +} from '@/lib/agent-background-session-test-state' + +const mockSpawn = vi.fn() +const mockKill = vi.fn() +const mockWrite = vi.fn() +const mockRuntimeEnvironmentCall = vi.fn() +const mockRuntimeEnvironmentTransportCall = vi.fn() +const mockRuntimeEnvironmentSubscribe = vi.fn() +const mockCreateTab = vi.fn() +const mockSetTabCustomTitle = vi.fn() +const mockUpdateTabPtyId = vi.fn() +const mockCloseTab = vi.fn() +const mockSetTabLayout = vi.fn() +const mockRegisterAgentLaunchConfig = vi.fn() +const mockRegisterEagerPtyBuffer = vi.fn() +const mockSubscribeToPtyData = vi.fn() +const mockSubscribeToPtyExit = vi.fn() +const mockPasteDraftWhenAgentReady = vi.fn() +const mockDispatchEvent = vi.fn() +const mockGetAgentLaunchPlatformForRepo = vi.fn<() => NodeJS.Platform>() +const state = createAgentBackgroundSessionTestState({ + createTab: mockCreateTab, + setTabCustomTitle: mockSetTabCustomTitle, + updateTabPtyId: mockUpdateTabPtyId, + closeTab: mockCloseTab, + setTabLayout: mockSetTabLayout, + registerAgentLaunchConfig: mockRegisterAgentLaunchConfig +}) + +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => state, + subscribe: vi.fn(() => () => {}) + } +})) + +// Why: the background mount's sleeping-agent scan reads store state these launches never seed. +vi.mock('@/lib/sleeping-agent-wake-requests', () => ({ requestSleepingAgentWakeOnMount: vi.fn() })) + +vi.mock('@/lib/telemetry', () => ({ + track: vi.fn(), + tuiAgentToAgentKind: (agent: string) => agent +})) + +vi.mock('@/lib/agent-paste-draft', () => ({ + pasteDraftWhenAgentReady: mockPasteDraftWhenAgentReady +})) + +vi.mock('@/lib/execution-host-facts', async (importOriginal) => { + const hostFact = () => ({ + kind: 'known' as const, + platform: mockGetAgentLaunchPlatformForRepo(), + hostKind: 'local' as const + }) + return { + ...(await importOriginal>()), + resolveRepoExecutionHostPlatform: hostFact, + resolveWorktreeExecutionHostPlatform: hostFact + } +}) + +vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({ + registerEagerPtyBuffer: mockRegisterEagerPtyBuffer, + subscribeToPtyExit: mockSubscribeToPtyExit +})) + +vi.mock('@/components/terminal-pane/pty-data-sidecar-subscriptions', () => ({ + subscribeToPtyData: mockSubscribeToPtyData +})) + +describe('launchAgentBackgroundSession remote runtime and SSH startup delivery', () => { + beforeEach(() => { + resetAgentBackgroundSessionTestHarness({ + state, + createTab: mockCreateTab, + closeTab: mockCloseTab, + getLaunchPlatform: mockGetAgentLaunchPlatformForRepo, + runtimeCall: mockRuntimeEnvironmentCall, + runtimeTransportCall: mockRuntimeEnvironmentTransportCall, + runtimeSubscribe: mockRuntimeEnvironmentSubscribe, + subscribeToData: mockSubscribeToPtyData, + subscribeToExit: mockSubscribeToPtyExit, + setTabLayout: mockSetTabLayout, + updateTabPtyId: mockUpdateTabPtyId, + dispatchEvent: mockDispatchEvent, + kill: mockKill, + spawn: mockSpawn, + write: mockWrite + }) + }) + + it('closes a runtime terminal when its worktree disappears before creation resolves', async () => { + useRemoteAgentBackgroundRuntime(state) + let resolveCreate!: (result: { + ok: true + result: { terminal: { handle: string; worktreeId: string; title: null } } + }) => void + const createResult = new Promise<{ + ok: true + result: { terminal: { handle: string; worktreeId: string; title: null } } + }>((resolve) => { + resolveCreate = resolve + }) + mockRuntimeEnvironmentCall.mockImplementation((args: { method: string }) => { + if (args.method === 'terminal.createAgentSession') { + return createResult + } + return Promise.resolve({ ok: true, result: {} }) + }) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + const launch = launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run remotely' + }) + await vi.waitFor(() => + expect(mockRuntimeEnvironmentCall).toHaveBeenCalledWith( + expect.objectContaining({ method: 'terminal.createAgentSession' }) + ) + ) + state.worktreesByRepo['repo-1'] = [] + resolveCreate({ + ok: true, + result: { terminal: { handle: 'terminal-after-close', worktreeId: 'wt-1', title: null } } + }) + + await expect(launch).resolves.toBeNull() + expect(mockRuntimeEnvironmentCall).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'terminal.close', + params: { terminal: 'terminal-after-close' } + }) + ) + expect(mockCreateTab).not.toHaveBeenCalled() + expect(mockUpdateTabPtyId).not.toHaveBeenCalled() + expect(mockRuntimeEnvironmentSubscribe).not.toHaveBeenCalled() + expect(mockDispatchEvent).not.toHaveBeenCalled() + }) + + it('forwards Hermes startup queries through SSH command transport', async () => { + state.repos = [{ id: 'repo-1', connectionId: 'ssh-1', path: '/repo' }] + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'hermes', + worktreeId: 'wt-1', + prompt: 'remote automation prompt' + }) + + expect(mockSpawn).toHaveBeenCalledWith( + expect.objectContaining({ + command: expect.stringContaining('ORCA_HERMES_STARTUP_QUERY'), + connectionId: 'ssh-1', + env: expect.objectContaining({ ORCA_HERMES_STARTUP_QUERY: 'remote automation prompt' }) + }) + ) + }) + + it.each(['claude', 'codex'] as const)( + 'has the relay type the %s launch line instead of writing it from the renderer', + async (agent) => { + vi.useFakeTimers() + try { + state.repos = [{ id: 'repo-1', connectionId: 'ssh-1', path: '/repo' }] + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent, + worktreeId: 'wt-1', + prompt: 'run the automation' + }) + + expect(mockSpawn.mock.calls[0]?.[0]).toEqual( + expect.objectContaining({ + command: expect.stringContaining("'run the automation'"), + connectionId: 'ssh-1', + commandDelivery: 'provider', + startupCommandDelivery: 'shell-ready' + }) + ) + const dataSidecar = mockSubscribeToPtyData.mock.calls[0]?.[1] as (data: string) => void + dataSidecar('\x1b]777;orca-shell-ready\x07user@remote repo % ') + vi.advanceTimersByTime(20_000) + expect(mockWrite).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + } + ) + + it('has the relay type a promptless SSH background launch too', async () => { + state.repos = [{ id: 'repo-1', connectionId: 'ssh-1', path: '/repo' }] + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ agent: 'codex', worktreeId: 'wt-1' }) + + expect(mockSpawn.mock.calls[0]?.[0]).toEqual( + expect.objectContaining({ + commandDelivery: 'provider', + startupCommandDelivery: 'shell-ready' + }) + ) + }) + + it.each([true, false])( + 'creates background sessions with negotiated keyboard support: %s', + async (keyboardSupported) => { + useRemoteAgentBackgroundRuntime(state) + mockRuntimeEnvironmentTransportCall.mockImplementation((request: { method: string }) => { + const status = createCompatibleRuntimeStatusResponseIfNeeded(request) + if (status?.ok) { + return Promise.resolve({ + ...status, + result: { + ...status.result, + capabilities: status.result.capabilities?.filter( + (capability) => + keyboardSupported || capability !== AGENT_SESSION_KEYBOARD_RUNTIME_CAPABILITY + ) + } + }) + } + return mockRuntimeEnvironmentCall(request) + }) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + const result = await launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run the automation' + }) + + expect(mockSpawn).not.toHaveBeenCalled() + const params = mockRuntimeEnvironmentCall.mock.calls[0]?.[0]?.params + if (keyboardSupported) { + expect(params).toHaveProperty('terminalKittyKeyboardProtocol', true) + } else { + expect(params).not.toHaveProperty('terminalKittyKeyboardProtocol') + } + const leafId = params?.placement?.leafId + const tabId = params?.placement?.tabId + expect(leafId).toMatch(UUID_RE) + expect(tabId).toMatch(UUID_RE) + // Why: background launches have no explicit recipe override, so remote host settings win. + expect(params).not.toHaveProperty('agentArgs') + expect(mockRegisterAgentLaunchConfig).toHaveBeenCalledWith( + `${tabId}:${leafId}`, + { + agentCommand: "claude '--dangerously-skip-permissions'", + agentArgs: '--dangerously-skip-permissions', + agentEnv: {} + }, + { + agentType: 'claude', + launchToken: expect.stringMatching(UUID_RE), + tabId, + leafId + } + ) + expect(mockSetTabLayout).toHaveBeenCalledWith( + tabId, + expect.objectContaining({ + root: { type: 'leaf', leafId }, + activeLeafId: leafId, + ptyIdsByLeafId: { [leafId]: 'remote:env-1@@terminal-1' } + }) + ) + expect(mockRuntimeEnvironmentCall).toHaveBeenCalledWith({ + selector: 'env-1', + method: 'terminal.createAgentSession', + params: expect.objectContaining({ + clientOperationId: expect.stringMatching(/^\d{13}-[0-9a-f]{32}$/), + worktree: 'id:wt-1', + agent: 'claude', + prompt: 'run the automation', + promptDelivery: 'auto-submit', + placement: { tabId, leafId }, + presentation: 'background' + }), + timeoutMs: 15_000 + }) + expect(mockUpdateTabPtyId).toHaveBeenCalledWith(tabId, 'remote:env-1@@terminal-1') + expect(mockRegisterEagerPtyBuffer).not.toHaveBeenCalled() + expect(mockRuntimeEnvironmentSubscribe).toHaveBeenCalledWith( + expect.objectContaining({ + selector: 'env-1', + method: 'terminal.multiplex', + params: {} + }), + expect.any(Object) + ) + expect(result).toMatchObject({ + tabId, + paneKey: `${tabId}:${leafId}`, + ptyId: 'remote:env-1@@terminal-1', + terminalOwnership: null + }) + } + ) + + it('advertises keyboard support for a background OMP launch', async () => { + useRemoteAgentBackgroundRuntime(state) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + await launchAgentBackgroundSession({ agent: 'omp', worktreeId: 'wt-1', prompt: 'review' }) + expect(mockRuntimeEnvironmentCall).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'terminal.createAgentSession', + params: expect.objectContaining({ + agent: 'omp', + terminalKittyKeyboardProtocol: true, + presentation: 'background' + }) + }) + ) + }) + + it('aborts the remote exit wait and closes the stream when run observers are released', async () => { + useRemoteAgentBackgroundRuntime(state) + const streamSend = vi.fn() + const waitUnsubscribe = vi.fn() + mockRuntimeEnvironmentSubscribe.mockImplementation(async (request, callbacks) => { + if (request.method === 'terminal.multiplex') { + queueMicrotask(() => callbacks.onResponse({ ok: true, result: { type: 'ready' } })) + return { unsubscribe: vi.fn(), sendBinary: streamSend } + } + if (request.method === 'terminal.wait') { + return { unsubscribe: waitUnsubscribe, sendBinary: vi.fn() } + } + throw new Error(`Unexpected runtime subscription: ${request.method}`) + }) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + const result = await launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run the automation' + }) + await vi.waitFor(() => + expect(mockRuntimeEnvironmentSubscribe).toHaveBeenCalledWith( + expect.objectContaining({ method: 'terminal.wait' }), + expect.any(Object) + ) + ) + const sendsBeforeRelease = streamSend.mock.calls.length + + result?.releaseRuntimeObservers() + result?.releaseRuntimeObservers() + + await vi.waitFor(() => expect(waitUnsubscribe).toHaveBeenCalledOnce()) + // One unsubscribe frame for the terminal's data stream. + expect(streamSend.mock.calls.length).toBe(sendsBeforeRelease + 1) + }) + + it('preserves the legacy background spawn on an old remote host', async () => { + useRemoteAgentBackgroundRuntime(state) + mockRuntimeEnvironmentTransportCall.mockImplementation((request: { method: string }) => { + if (request.method === 'status.get') { + return Promise.resolve({ + id: 'status', + ok: true, + result: { + runtimeId: 'old-runtime', + graphStatus: 'ready', + runtimeProtocolVersion: 3, + minCompatibleRuntimeClientVersion: 2, + capabilities: [] + } + }) + } + return Promise.resolve({ + id: 'create', + ok: true, + result: { terminal: { handle: 'legacy-terminal-1' } } + }) + }) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await expect( + launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run remotely' + }) + ).resolves.toMatchObject({ ptyId: 'remote:env-1@@legacy-terminal-1' }) + + expect(mockRuntimeEnvironmentTransportCall).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'terminal.create', + params: expect.objectContaining({ + worktree: 'id:wt-1', + command: "claude '--dangerously-skip-permissions' 'run remotely'", + terminalKittyKeyboardProtocol: true, + launchAgent: 'claude', + presentation: 'background' + }) + }) + ) + }) + + it('closes a created runtime terminal when its data subscription fails', async () => { + useRemoteAgentBackgroundRuntime(state) + mockRuntimeEnvironmentSubscribe.mockRejectedValueOnce(new Error('subscription failed')) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await expect( + launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run the automation' + }) + ).rejects.toThrow('subscription failed') + + expect(mockRuntimeEnvironmentCall).toHaveBeenCalledWith({ + selector: 'env-1', + method: 'terminal.close', + params: { terminal: 'terminal-1' }, + timeoutMs: undefined + }) + const tabId = mockRuntimeEnvironmentCall.mock.calls[0]?.[0]?.params?.placement?.tabId + expect(tabId).toMatch(UUID_RE) + expect(state.clearTabPtyId).toHaveBeenCalledWith(tabId, 'remote:env-1@@terminal-1') + expect(state.clearAgentLaunchConfig).toHaveBeenCalledWith( + expect.stringMatching(new RegExp(`^${tabId}:`)) + ) + expect(mockCloseTab).toHaveBeenCalledWith(tabId, { + recordInteraction: false, + reason: 'cleanup' + }) + expect(mockDispatchEvent).not.toHaveBeenCalled() + }) + + it('spawns an SSH folder-workspace automation on the owning host, not locally', async () => { + // Folder workspaces have no repo row, so launch ownership comes from their scope. + state.repos = [ + { id: 'repo-1', connectionId: 'ssh-1', path: '/srv/proj/api', projectGroupId: 'grp-1' } + ] + state.projectGroups = [{ id: 'grp-1', parentGroupId: null, connectionId: 'ssh-1' }] + state.folderWorkspaces = [ + { id: 'fw-1', projectGroupId: 'grp-1', folderPath: '/srv/proj', connectionId: 'ssh-1' } + ] + state.getKnownWorktreeById = (worktreeId: string) => + worktreeId === 'folder:fw-1' ? { id: 'folder:fw-1', path: '/srv/proj' } : undefined + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'codex', + worktreeId: 'folder:fw-1', + prompt: 'run the automation' + }) + + expect(mockSpawn).toHaveBeenCalledWith( + expect.objectContaining({ connectionId: 'ssh-1', cwd: '/srv/proj' }) + ) + }) + + it('keeps a local folder workspace on the local host', async () => { + state.repos = [ + { id: 'repo-1', connectionId: null, path: '/home/me/proj/api', projectGroupId: 'grp-1' } + ] + state.projectGroups = [{ id: 'grp-1', parentGroupId: null, connectionId: null }] + state.folderWorkspaces = [ + { id: 'fw-1', projectGroupId: 'grp-1', folderPath: '/home/me/proj', connectionId: null } + ] + state.getKnownWorktreeById = (worktreeId: string) => + worktreeId === 'folder:fw-1' ? { id: 'folder:fw-1', path: '/home/me/proj' } : undefined + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'folder:fw-1', + prompt: 'run the automation' + }) + + expect(mockSpawn).toHaveBeenCalledWith( + expect.objectContaining({ connectionId: null, cwd: '/home/me/proj' }) + ) + }) +}) diff --git a/src/renderer/src/lib/launch-agent-background-session.test.ts b/src/renderer/src/lib/launch-agent-background-session.test.ts new file mode 100644 index 000000000000..9098f8b9a260 --- /dev/null +++ b/src/renderer/src/lib/launch-agent-background-session.test.ts @@ -0,0 +1,642 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { BACKGROUND_MOUNT_TERMINAL_WORKTREE_EVENT } from '@/constants/terminal' +import { toAppSshPtyId } from '../../../shared/ssh-pty-id' +import { + AGENT_BACKGROUND_SESSION_UUID_RE as UUID_RE, + createAgentBackgroundSessionTestState, + expectReservedAgentBackgroundTabId, + expectStableAgentBackgroundPaneSpawn, + resetAgentBackgroundSessionTestHarness +} from '@/lib/agent-background-session-test-state' + +const mockSpawn = vi.fn() +const mockKill = vi.fn() +const mockWrite = vi.fn() +const mockRuntimeEnvironmentCall = vi.fn() +const mockRuntimeEnvironmentTransportCall = vi.fn() +const mockRuntimeEnvironmentSubscribe = vi.fn() +const mockCreateTab = vi.fn() +const mockSetTabCustomTitle = vi.fn() +const mockUpdateTabPtyId = vi.fn() +const mockCloseTab = vi.fn() +const mockSetTabLayout = vi.fn() +const mockRegisterAgentLaunchConfig = vi.fn() +const mockRegisterEagerPtyBuffer = vi.fn() +const mockSubscribeToPtyData = vi.fn() +const mockSubscribeToPtyExit = vi.fn() +const mockPasteDraftWhenAgentReady = vi.fn() +const mockDispatchEvent = vi.fn() +const mockGetAgentLaunchPlatformForRepo = vi.fn<() => NodeJS.Platform>() +const mockHostKind = vi.fn<() => 'local' | 'runtime'>(() => 'local') +const state = createAgentBackgroundSessionTestState({ + createTab: mockCreateTab, + setTabCustomTitle: mockSetTabCustomTitle, + updateTabPtyId: mockUpdateTabPtyId, + closeTab: mockCloseTab, + setTabLayout: mockSetTabLayout, + registerAgentLaunchConfig: mockRegisterAgentLaunchConfig +}) +let currentStoreState = state + +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => currentStoreState, + subscribe: vi.fn(() => () => {}) + } +})) + +// Why: the background mount's sleeping-agent scan reads store state these launches never seed. +vi.mock('@/lib/sleeping-agent-wake-requests', () => ({ requestSleepingAgentWakeOnMount: vi.fn() })) + +vi.mock('@/lib/telemetry', () => ({ + track: vi.fn(), + tuiAgentToAgentKind: (agent: string) => agent +})) + +vi.mock('@/lib/agent-paste-draft', () => ({ + pasteDraftWhenAgentReady: mockPasteDraftWhenAgentReady +})) + +vi.mock('@/lib/execution-host-facts', async (importOriginal) => { + const hostFact = () => ({ + kind: 'known' as const, + platform: mockGetAgentLaunchPlatformForRepo(), + hostKind: mockHostKind() + }) + return { + ...(await importOriginal>()), + resolveRepoExecutionHostPlatform: hostFact, + resolveWorktreeExecutionHostPlatform: hostFact + } +}) + +vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({ + registerEagerPtyBuffer: mockRegisterEagerPtyBuffer, + subscribeToPtyExit: mockSubscribeToPtyExit +})) + +vi.mock('@/components/terminal-pane/pty-data-sidecar-subscriptions', () => ({ + subscribeToPtyData: mockSubscribeToPtyData +})) + +describe('launchAgentBackgroundSession', () => { + beforeEach(() => { + currentStoreState = state + resetAgentBackgroundSessionTestHarness({ + state, + createTab: mockCreateTab, + closeTab: mockCloseTab, + getLaunchPlatform: mockGetAgentLaunchPlatformForRepo, + runtimeCall: mockRuntimeEnvironmentCall, + runtimeTransportCall: mockRuntimeEnvironmentTransportCall, + runtimeSubscribe: mockRuntimeEnvironmentSubscribe, + subscribeToData: mockSubscribeToPtyData, + subscribeToExit: mockSubscribeToPtyExit, + setTabLayout: mockSetTabLayout, + updateTabPtyId: mockUpdateTabPtyId, + dispatchEvent: mockDispatchEvent, + kill: mockKill, + spawn: mockSpawn, + write: mockWrite + }) + }) + + it('spawns a PTY first and creates the inactive tab already bound to it', async () => { + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + mockSpawn.mockResolvedValue({ id: 'pty-1', incarnationId: 'inc-fresh' }) + + const result = await launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run the automation', + title: 'Nightly audit' + }) + + const tabId = expectReservedAgentBackgroundTabId(mockSpawn) + // A store-visible PTY-less run tab fresh-spawns a shell (#2989). + expect(mockSpawn.mock.invocationCallOrder[0]).toBeLessThan( + mockCreateTab.mock.invocationCallOrder[0] ?? 0 + ) + expect(mockCreateTab).toHaveBeenCalledWith('wt-1', undefined, undefined, { + id: tabId, + initialPtyId: 'pty-1', + activate: false, + recordInteraction: false + }) + expect(mockDispatchEvent).toHaveBeenCalledWith( + expect.objectContaining({ + type: BACKGROUND_MOUNT_TERMINAL_WORKTREE_EVENT, + detail: { worktreeId: 'wt-1', tabIds: [tabId] } + }) + ) + expect(mockUpdateTabPtyId.mock.invocationCallOrder[0]).toBeLessThan( + mockDispatchEvent.mock.invocationCallOrder[0] ?? 0 + ) + expect(mockSpawn).toHaveBeenCalledWith( + expect.objectContaining({ + cwd: '/repo/worktree', + command: "claude '--dangerously-skip-permissions' 'run the automation'", + env: expect.objectContaining({ + ORCA_TAB_ID: tabId, + ORCA_WORKTREE_ID: 'wt-1' + }), + connectionId: null, + worktreeId: 'wt-1', + tabId, + placement: { kind: 'new-tab', row: { customTitle: 'Nightly audit' } } + }) + ) + const paneKey = expectStableAgentBackgroundPaneSpawn(mockSpawn) + const leafId = paneKey.slice(`${tabId}:`.length) + expect(mockSetTabLayout).toHaveBeenCalledWith( + tabId, + expect.objectContaining({ + root: { type: 'leaf', leafId }, + activeLeafId: leafId, + ptyIdsByLeafId: { [leafId]: 'pty-1' } + }) + ) + expect(mockSetTabLayout.mock.calls.at(-1)?.[1]).not.toHaveProperty('titlesByLeafId') + expect(mockSpawn.mock.calls[0]?.[0]).toMatchObject({ + launchConfig: { + agentCommand: "claude '--dangerously-skip-permissions'", + agentArgs: '--dangerously-skip-permissions', + agentEnv: {} + }, + launchAgent: 'claude', + launchToken: expect.stringMatching(UUID_RE) + }) + expect(mockSpawn.mock.calls[0]?.[0].launchToken).toBe( + mockSpawn.mock.calls[0]?.[0].env.ORCA_AGENT_LAUNCH_TOKEN + ) + expect(mockSetTabCustomTitle).toHaveBeenCalledWith(tabId, 'Nightly audit', { + recordInteraction: false + }) + expect(mockUpdateTabPtyId).toHaveBeenCalledWith(tabId, 'pty-1') + // Keep incarnation so recycled relay IDs cannot deliver a prior owner’s exit into the new session. + expect(mockRegisterEagerPtyBuffer).toHaveBeenCalledWith( + 'pty-1', + expect.any(Function), + 'inc-fresh' + ) + expect(mockSubscribeToPtyData).toHaveBeenCalledWith('pty-1', expect.any(Function)) + expect(mockSubscribeToPtyExit).toHaveBeenCalledWith('pty-1', expect.any(Function)) + expect(result).toMatchObject({ tabId, paneKey, ptyId: 'pty-1' }) + }) + + it('does not create or mount the tab while the explicit PTY spawn is unresolved', async () => { + let resolveSpawn!: (result: { id: string }) => void + mockSpawn.mockReturnValueOnce( + new Promise<{ id: string }>((resolve) => { + resolveSpawn = resolve + }) + ) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + const launch = launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run slowly' + }) + await Promise.resolve() + + // Publishing a PTY-less tab here reproduces #2989. + expect(mockCreateTab).not.toHaveBeenCalled() + expect(mockDispatchEvent).not.toHaveBeenCalled() + + resolveSpawn({ id: 'pty-slow' }) + await expect(launch).resolves.toMatchObject({ ptyId: 'pty-slow' }) + const tabId = expectReservedAgentBackgroundTabId(mockSpawn) + expect(mockCreateTab.mock.calls[0]?.[3]).toMatchObject({ + id: tabId, + initialPtyId: 'pty-slow' + }) + expect(mockUpdateTabPtyId).toHaveBeenCalledWith(tabId, 'pty-slow') + expect(mockDispatchEvent).toHaveBeenCalledWith( + expect.objectContaining({ detail: { worktreeId: 'wt-1', tabIds: [tabId] } }) + ) + }) + + it('kills a local PTY when its worktree disappears before spawn resolves', async () => { + let resolveSpawn!: (result: { id: string }) => void + mockSpawn.mockReturnValueOnce( + new Promise<{ id: string }>((resolve) => { + resolveSpawn = resolve + }) + ) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + const launch = launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run slowly' + }) + await vi.waitFor(() => expect(mockSpawn).toHaveBeenCalledOnce()) + state.worktreesByRepo['repo-1'] = [] + resolveSpawn({ id: 'pty-after-close' }) + + await expect(launch).resolves.toBeNull() + expect(mockKill).toHaveBeenCalledWith('pty-after-close') + expect(mockCreateTab).not.toHaveBeenCalled() + expect(mockUpdateTabPtyId).not.toHaveBeenCalled() + expect(mockSubscribeToPtyData).not.toHaveBeenCalled() + expect(mockDispatchEvent).not.toHaveBeenCalled() + }) + + it('launches into a folder workspace that is absent from worktreesByRepo throughout', async () => { + // Folder workspaces never appear in worktreesByRepo. + state.worktreesByRepo['repo-1'] = [] + state.folderWorkspaces = [ + { id: 'fw-1', projectGroupId: 'grp-1', folderPath: '/tmp/folder-workspace' } + ] + state.projectGroups = [{ id: 'grp-1', connectionId: null }] + state.getKnownWorktreeById = (worktreeId: string) => + worktreeId === 'folder:fw-1' + ? { id: 'folder:fw-1', path: '/tmp/folder-workspace' } + : undefined + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + const launch = launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'folder:fw-1', + prompt: 'run in a folder workspace' + }) + + await expect(launch).resolves.toMatchObject({ ptyId: 'pty-1' }) + expect(mockKill).not.toHaveBeenCalled() + expect(mockCreateTab).toHaveBeenCalledOnce() + }) + + it('launches a local WSL folder through wsl.exe', async () => { + const folderPath = '\\\\wsl.localhost\\Ubuntu\\home\\me\\project' + state.worktreesByRepo['repo-1'] = [] + state.folderWorkspaces = [ + { id: 'fw-wsl', projectGroupId: 'grp-wsl', folderPath, connectionId: null } + ] + state.projectGroups = [{ id: 'grp-wsl', connectionId: null }] + state.getKnownWorktreeById = (worktreeId: string) => + worktreeId === 'folder:fw-wsl' ? { id: worktreeId, path: folderPath } : undefined + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'folder:fw-wsl', + prompt: 'run the automation' + }) + + expect(mockSpawn).toHaveBeenCalledWith( + expect.objectContaining({ + cwd: folderPath, + shellOverride: 'wsl.exe', + command: "claude '--dangerously-skip-permissions' 'run the automation'" + }) + ) + }) + + it('records effective launch config returned by local PTY spawn', async () => { + const effectiveLaunchConfig = { + agentCommand: "claude '--dangerously-skip-permissions'", + agentArgs: '--dangerously-skip-permissions', + agentEnv: { ORCA_AGENT_TEAMS_TEAM_ID: 'team-fresh' } + } + mockSpawn.mockResolvedValue({ id: 'pty-1', launchConfig: effectiveLaunchConfig }) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run the automation' + }) + + const paneKey = expectStableAgentBackgroundPaneSpawn(mockSpawn) + const tabId = expectReservedAgentBackgroundTabId(mockSpawn) + const leafId = paneKey.slice(`${tabId}:`.length) + expect(mockRegisterAgentLaunchConfig).toHaveBeenLastCalledWith(paneKey, effectiveLaunchConfig, { + agentType: 'claude', + launchToken: mockSpawn.mock.calls[0]?.[0].env.ORCA_AGENT_LAUNCH_TOKEN, + tabId, + leafId + }) + }) + + it('uses WSL launch quoting for Windows-path projects forced to WSL', async () => { + state.projects = [ + { + id: 'repo-1', + localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' } + } + ] + state.repos = [{ id: 'repo-1', connectionId: null, path: 'C:\\Users\\jinwo\\repo' }] + state.worktreesByRepo = { + 'repo-1': [ + { + id: 'wt-1', + repoId: 'repo-1', + projectId: 'repo-1', + path: 'C:\\Users\\jinwo\\repo\\feature', + displayName: 'feature' + } + ] + } + + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: "don't use powershell quoting" + }) + + expect(mockSpawn).toHaveBeenCalledWith( + expect.objectContaining({ + cwd: 'C:\\Users\\jinwo\\repo\\feature', + command: `claude '--dangerously-skip-permissions' 'don'"'"'t use powershell quoting'`, + connectionId: null, + worktreeId: 'wt-1', + tabId: expect.stringMatching(UUID_RE) + }) + ) + }) + + it('stamps hidden SSH status from renderer fallback when the kill switch is off', async () => { + // With main authority disabled, this hidden SSH sidecar is the sole OSC 9999 store writer. + state.settings.terminalMainSideEffectAuthority = false + state.repos = [{ id: 'repo-1', connectionId: 'ssh-a', path: '/repo' }] + state.sshConnectionStates = new Map([['ssh-a', { status: 'connected' }]]) + mockSpawn.mockResolvedValue({ id: toAppSshPtyId('ssh-a', 'pty-1') }) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run the automation' + }) + + const dataSidecar = mockSubscribeToPtyData.mock.calls[0]?.[1] as (data: string) => void + dataSidecar('\x1b]9999;{"state":"done","prompt":"ok","agentType":"codex"}\x07') + + const paneKey = expectStableAgentBackgroundPaneSpawn(mockSpawn) + expect(state.setAgentStatus).toHaveBeenCalledWith( + paneKey, + expect.objectContaining({ state: 'done', prompt: 'ok', agentType: 'codex' }), + undefined, + undefined, + { connectionId: 'ssh-a' }, + { launchToken: expect.stringMatching(UUID_RE) } + ) + }) + + it('skips the duplicate OSC store write under main side-effect authority', async () => { + // Main already owns OSC 9999 store writes; avoid races while retaining automation completion callbacks. + const onAgentStatus = vi.fn() + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run the automation', + onAgentStatus + }) + + const dataSidecar = mockSubscribeToPtyData.mock.calls[0]?.[1] as (data: string) => void + dataSidecar('\x1b]9999;{"state":"done","prompt":"ok","agentType":"codex"}\x07') + + expect(state.setAgentStatus).not.toHaveBeenCalled() + expect(onAgentStatus).toHaveBeenCalledWith( + expect.objectContaining({ state: 'done', prompt: 'ok', agentType: 'codex' }) + ) + }) + + it('stamps a working status for SSH Command Code prompt launches', async () => { + state.repos = [{ id: 'repo-1', connectionId: 'ssh-a', path: '/repo' }] + state.sshConnectionStates = new Map([['ssh-a', { status: 'connected' }]]) + mockSpawn.mockResolvedValue({ id: toAppSshPtyId('ssh-a', 'pty-1') }) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'command-code', + worktreeId: 'wt-1', + prompt: 'check the status spinner' + }) + + const paneKey = expectStableAgentBackgroundPaneSpawn(mockSpawn) + expect(state.setAgentStatus).toHaveBeenCalledWith( + paneKey, + { + state: 'working', + prompt: 'check the status spinner', + agentType: 'command-code', + // Why: Orca launched this hidden session, so the seed predates any provider signal (STA-4293). + observation: expect.objectContaining({ origin: 'launch', kind: 'transition' }) + }, + undefined, + undefined, + { connectionId: 'ssh-a' }, + { + launchConfig: { + agentCommand: "command-code --trust '--yolo'", + agentArgs: '--yolo', + agentEnv: {} + }, + launchToken: expect.stringMatching(UUID_RE) + } + ) + }) + + it('uses a sidecar exit watcher so completion survives terminal attachment', async () => { + const unsubscribe = vi.fn() + mockSubscribeToPtyExit.mockReturnValue(unsubscribe) + const onExit = vi.fn() + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run the automation', + onExit + }) + + const sidecar = mockSubscribeToPtyExit.mock.calls[0]?.[1] as (code: number) => void + sidecar(0) + + const tabId = expectReservedAgentBackgroundTabId(mockSpawn) + expect(state.clearTabPtyId).toHaveBeenCalledWith(tabId, 'pty-1') + expect(state.clearAgentLaunchConfig).toHaveBeenCalledWith( + expect.stringMatching(new RegExp(`^${tabId}:`)) + ) + expect(onExit).toHaveBeenCalledWith('pty-1', 0) + expect(unsubscribe).toHaveBeenCalled() + expect(state.markUnverifiedPtyLoss).not.toHaveBeenCalled() + }) + + it('keeps the tab bound to its PTY when contact was lost rather than observed', async () => { + // Synthetic -1 loss retires transport only; retain bindings for reconnect adoption and orphan-cleanup protection. + mockSubscribeToPtyExit.mockReturnValue(vi.fn()) + const onExit = vi.fn() + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run the automation', + onExit + }) + + const sidecar = mockSubscribeToPtyExit.mock.calls[0]?.[1] as (code: number) => void + sidecar(-1) + + const tabId = expectReservedAgentBackgroundTabId(mockSpawn) + expect(state.clearTabPtyId).not.toHaveBeenCalled() + expect(state.markUnverifiedPtyLoss).toHaveBeenCalledWith(tabId) + expect(onExit).toHaveBeenCalledWith('pty-1', -1) + }) + + it('leaves no tab behind if PTY spawn fails', async () => { + mockSpawn.mockRejectedValueOnce(new Error('spawn failed')) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await expect( + launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run the automation' + }) + ).rejects.toThrow('spawn failed') + + // Why: the tab is only created once a PTY is live, so a failed spawn has nothing to close. + expect(mockCreateTab).not.toHaveBeenCalled() + expect(mockCloseTab).not.toHaveBeenCalled() + expect(state.clearAgentLaunchConfig).toHaveBeenCalledWith( + expect.stringMatching(new RegExp(`^${expectReservedAgentBackgroundTabId(mockSpawn)}:`)) + ) + expect(mockUpdateTabPtyId).not.toHaveBeenCalled() + }) + + it('closes the adopted tab if binding fails after the PTY is live', async () => { + mockSubscribeToPtyData.mockImplementationOnce(() => { + throw new Error('subscribe failed') + }) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await expect( + launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run the automation' + }) + ).rejects.toThrow('subscribe failed') + + const tabId = expectReservedAgentBackgroundTabId(mockSpawn) + expect(mockCloseTab).toHaveBeenCalledWith(tabId, { + recordInteraction: false, + reason: 'cleanup' + }) + expect(mockKill).toHaveBeenCalledWith('pty-1') + }) + + it('retires the launch instead of adopting a colliding tab id', async () => { + mockSpawn.mockImplementationOnce((args: { tabId: string }) => { + currentStoreState = { + ...state, + tabsByWorktree: { + ...state.tabsByWorktree, + 'wt-1': [{ id: args.tabId, title: 'Squatter' }] + } + } + return Promise.resolve({ id: 'pty-1' }) + }) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await expect( + launchAgentBackgroundSession({ + agent: 'claude', + worktreeId: 'wt-1', + prompt: 'run the automation' + }) + ).resolves.toBeNull() + + expect(mockCreateTab).not.toHaveBeenCalled() + expect(mockKill).toHaveBeenCalledWith('pty-1') + expect(state.clearAgentLaunchConfig).toHaveBeenCalledWith( + expectStableAgentBackgroundPaneSpawn(mockSpawn) + ) + }) + + it('submits prompts for stdin-after-start agents in background mode', async () => { + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'aider', + worktreeId: 'wt-1', + prompt: 'run the automation' + }) + + expect(mockSpawn).toHaveBeenCalledWith( + expect.objectContaining({ command: "aider '--yes-always'" }) + ) + expect(mockPasteDraftWhenAgentReady).toHaveBeenCalledWith( + expect.objectContaining({ + tabId: expectReservedAgentBackgroundTabId(mockSpawn), + content: 'run the automation', + agent: 'aider', + submit: true + }) + ) + }) + + it('passes Hermes automation prompts through the native startup query', async () => { + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'hermes', + worktreeId: 'wt-1', + prompt: 'run the automation' + }) + + expect(mockSpawn).toHaveBeenCalledWith( + expect.objectContaining({ + command: expect.stringContaining('ORCA_HERMES_STARTUP_QUERY'), + env: expect.objectContaining({ ORCA_HERMES_STARTUP_QUERY: 'run the automation' }) + }) + ) + expect(mockPasteDraftWhenAgentReady).not.toHaveBeenCalled() + }) + + it('uses the configured cmd shell for Windows Hermes background launches', async () => { + mockGetAgentLaunchPlatformForRepo.mockReturnValue('win32') + Object.assign(state.settings, { terminalWindowsShell: 'cmd.exe' }) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'hermes', + worktreeId: 'wt-1', + prompt: 'run the automation' + }) + + expect(mockSpawn).toHaveBeenCalledWith( + expect.objectContaining({ + command: expect.stringContaining('powershell.exe -NoProfile -EncodedCommand'), + env: expect.objectContaining({ ORCA_HERMES_STARTUP_QUERY: 'run the automation' }) + }) + ) + }) + + it("keeps this client's Git Bash setting off a Windows Orca server's launch", async () => { + mockGetAgentLaunchPlatformForRepo.mockReturnValue('win32') + mockHostKind.mockReturnValueOnce('runtime') + Object.assign(state.settings, { terminalWindowsShell: 'bash.exe' }) + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'hermes', + worktreeId: 'wt-1', + prompt: 'run the automation' + }) + + expect(mockSpawn).toHaveBeenCalledWith( + expect.objectContaining({ + command: expect.stringContaining('powershell.exe -NoProfile -EncodedCommand') + }) + ) + }) +}) diff --git a/src/renderer/src/lib/launch-agent-background-session.ts b/src/renderer/src/lib/launch-agent-background-session.ts new file mode 100644 index 000000000000..4885497dca58 --- /dev/null +++ b/src/renderer/src/lib/launch-agent-background-session.ts @@ -0,0 +1,310 @@ +import { useAppStore } from '@/store' +import { runtimeTargetForOwnerEnvironment } from '@/runtime/runtime-client-target' +import { buildAgentStartupPlan } from '@/lib/tui-agent-startup' +import type { + LaunchAgentBackgroundSessionArgs, + LaunchAgentBackgroundSessionResult +} from '@/lib/agent-background-session-contract' +import { tuiAgentToAgentKind } from '@/lib/telemetry' +import { scheduleAgentBackgroundDraft } from '@/lib/agent-background-draft-delivery' +import { requestBackgroundTerminalWorktreeMount } from '@/components/terminal/background-terminal-worktree-mount' +import { resolveAgentStartupPlanInputs } from '../../../shared/agent-startup-plan-inputs' +import { requireTuiAgentConfig } from '../../../shared/require-tui-agent-config' +import { resolveAgentBackgroundLaunchHost } from '@/lib/agent-background-session-launch-host' +import { makePaneKey } from '../../../shared/stable-pane-id' +import { + registerEagerPtyBuffer, + subscribeToPtyExit, + type EagerPtyHandle +} from '@/components/terminal-pane/pty-dispatcher' +import { subscribeToPtyData } from '@/components/terminal-pane/pty-data-sidecar-subscriptions' +import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' +import { runtimeEnvironmentIdOrLocalUnlessTwin } from '@/lib/worktree-runtime-owner' +import { retireProvider } from '@/lib/retire-unowned-background-terminal' +import { createRuntimeAgentBackgroundTerminal } from '@/lib/runtime-agent-background-create' +import { subscribeToRuntimeTerminalData } from '@/runtime/runtime-terminal-stream' +import { toRemoteRuntimePtyId } from '../../../shared/remote-runtime/remote-runtime-pty-id' +import { isMainTerminalSideEffectAuthorityForPty } from '@/components/terminal-pane/terminal-side-effect-facts-handler' +import { hasExtraAgentArgs } from '../../../shared/automation-extra-agent-args' +import { runBestEffortAgentBackgroundCleanups } from '@/lib/agent-background-session-cleanup' +import type { bindAutomationTerminal } from '@/lib/automation-terminal-ownership' +import { + adoptAgentBackgroundSessionTab, + reserveAgentBackgroundSessionIdentity +} from '@/lib/adopt-agent-background-session-tab' +import { createBackgroundAgentStatusConsumer } from '@/lib/background-agent-status-consumer' +import { isWslUncPath } from '../../../shared/wsl-paths' +import { runtimeWaitExitCode, settleTabPtyBinding } from '@/lib/agent-background-session-exit' + +export async function launchAgentBackgroundSession( + args: LaunchAgentBackgroundSessionArgs +): Promise { + const { agent, worktreeId, prompt, launchSource, title, onData, onExit, onAgentStatus } = args + const store = useAppStore.getState() + // Folder workspaces exist only in getKnownWorktreeById (#2989). + const worktree = store.getKnownWorktreeById(worktreeId) + const repo = worktree ? store.repos.find((entry) => entry.id === worktree.repoId) : null + if (!worktree) { + throw new Error('The target workspace is no longer available.') + } + // Folder launch ownership cannot be derived from a repo row (#2989). + const launchHost = resolveAgentBackgroundLaunchHost({ + store, + worktreeId, + worktreePath: worktree.path, + repo + }) + const { platform: launchPlatform, isRemote, isLocalHost } = launchHost + // Route by the worktree's owner host, not the focused runtime. + const runtimeTarget = runtimeTargetForOwnerEnvironment( + runtimeEnvironmentIdOrLocalUnlessTwin(store, worktreeId) + ) + if (hasExtraAgentArgs(args.extraAgentArgs) && runtimeTarget.kind === 'environment') { + // Why: that server rebuilds the command from its own settings and would drop the extras. + throw new Error("Extra arguments can't be applied to a paired server's workspace from here.") + } + // Why before any tab or PTY: an invalid launch must fail the run without creating a terminal. + const planInputs = resolveAgentStartupPlanInputs({ + agent, + // Why: the client's Windows shell setting describes this machine, not a remote host. + settings: isLocalHost + ? (store.settings ?? {}) + : { ...store.settings, terminalWindowsShell: undefined }, + platform: launchPlatform, + isRemote, + // The window quotes by its Settings shell, which its pane's spawn also reads. + shell: undefined, + extraAgentArgs: args.extraAgentArgs + }) + const trimmedPrompt = prompt?.trim() ?? '' + const hasPrompt = trimmedPrompt.length > 0 + const isFollowupPath = requireTuiAgentConfig(agent).promptInjectionMode === 'stdin-after-start' + + const pasteDraftAfterLaunch = hasPrompt && isFollowupPath ? trimmedPrompt : null + const startupPlan = buildAgentStartupPlan({ + ...planInputs, + prompt: hasPrompt && !isFollowupPath ? trimmedPrompt : '', + allowEmptyPromptLaunch: !hasPrompt || isFollowupPath + }) + if (!startupPlan) { + return null + } + + // A hidden run tab must never be store-visible without its PTY (#2989). + const { reservedTabId, leafId, launchToken, launchRegistration, paneEnv } = + reserveAgentBackgroundSessionIdentity({ + store, + agentType: agent, + worktreeId, + launchConfig: startupPlan.launchConfig, + env: startupPlan.env + }) + let paneKey = makePaneKey(reservedTabId, leafId) + const sshConnectionId = launchHost.connectionId + let ptyId = '', + runtimeTerminalHandle: string | null = null + // Capture local/SSH incarnation and actual launch config for later steps; runtime terminals supply neither. + let spawned: { incarnationId?: string; launchConfig?: typeof startupPlan.launchConfig } = {} + let tab: ReturnType | null = null + let exitHandled = false, + eagerPtyBuffer: EagerPtyHandle | null = null + let terminalOwnership: ReturnType = null + let unsubscribeExit = (): void => {}, + unsubscribeData = (): void => {}, + releaseRuntimeObservers = (): void => {} + const handleExit = (exitPtyId: string, code: number): void => { + if (exitHandled) { + return + } + exitHandled = true + unsubscribeExit() + unsubscribeData() + if (tab) { + settleTabPtyBinding(tab.id, exitPtyId, code) + } + useAppStore.getState().clearAgentLaunchConfig(paneKey) + onExit?.(exitPtyId, code) + } + // Main owns local/SSH status scanning; runtime bytes still need renderer-side writes. + const mainOwnsAgentStatusWrites = isMainTerminalSideEffectAuthorityForPty({ + settings: store.settings, + runtimeEnvironmentId: runtimeTarget.kind === 'environment' ? runtimeTarget.environmentId : null + }) + const agentStatusConsumer = createBackgroundAgentStatusConsumer({ + paneKey, + launchToken, + mainOwnsAgentStatusWrites, + expectedConnectionId: launchHost.expectedConnectionId, + runtimeEnvironmentId: runtimeTarget.kind === 'environment' ? runtimeTarget.environmentId : null, + getPtyId: () => ptyId, + onAgentStatus + }) + const handleData = (data: string): void => { + onData?.(data) + agentStatusConsumer.consume(data) + } + try { + if (runtimeTarget.kind === 'environment') { + // Runtime workspaces execute on their server; local pty.spawn would run automation on this client. + const created = await createRuntimeAgentBackgroundTerminal({ + environmentId: runtimeTarget.environmentId, + worktreeId, + tabId: reservedTabId, + leafId, + agent, + ...(hasPrompt && !isFollowupPath ? { prompt: trimmedPrompt } : {}), + ...(startupPlan.sessionOptions ? { sessionOptions: startupPlan.sessionOptions } : {}), + legacy: { + command: startupPlan.launchCommand, + env: paneEnv, + ...(startupPlan.startupCommandDelivery + ? { startupCommandDelivery: startupPlan.startupCommandDelivery } + : {}), + launchConfig: startupPlan.launchConfig, + launchToken, + ...(title ? { title } : {}) + } + }) + runtimeTerminalHandle = created.terminal.handle + ptyId = toRemoteRuntimePtyId(runtimeTerminalHandle, runtimeTarget.environmentId) + } else { + const result = await window.api.pty.spawn({ + cols: 120, + rows: 40, + cwd: worktree.path, + command: startupPlan.launchCommand, + ...(!sshConnectionId && isWslUncPath(worktree.path) ? { shellOverride: 'wsl.exe' } : {}), + // Why: the relay types, waits for the shell and stages long lines on the host that owns the PTY. + ...(sshConnectionId + ? { commandDelivery: 'provider' as const, startupCommandDelivery: 'shell-ready' as const } + : startupPlan.startupCommandDelivery + ? { startupCommandDelivery: startupPlan.startupCommandDelivery } + : {}), + env: paneEnv, + launchConfig: startupPlan.launchConfig, + launchToken, + launchAgent: agent, + connectionId: sshConnectionId, + worktreeId, + tabId: reservedTabId, + leafId, + // Why no launchAgent: the adopted tab is created without one, and the row must match it. + placement: { kind: 'new-tab', ...(title ? { row: { customTitle: title } } : {}) }, + telemetry: { + agent_kind: tuiAgentToAgentKind(agent), + launch_source: launchSource ?? 'unknown', + request_kind: 'new' + } + }) + ptyId = result.id + spawned = result + } + const adopted = await adoptAgentBackgroundSessionTab({ + store, + worktreeId, + reservedTabId, + ptyId, + paneKey, + launchConfig: spawned.launchConfig ?? startupPlan.launchConfig, + launchRegistration, + runtimeTarget, + runtimeTerminalHandle, + onRetire: () => { + exitHandled = true + store.clearAgentLaunchConfig(paneKey) + }, + ...(title ? { title } : {}) + }) + if (!adopted) { + return null + } + tab = adopted.tab + paneKey = adopted.paneKey + terminalOwnership = adopted.terminalOwnership + if (agent === 'command-code' && hasPrompt && !isFollowupPath) { + // Command Code lacks prompt-start hooks; seed working for hidden prompt launches until real status arrives. + const routing = agentStatusConsumer.resolveRouting() + if (routing) { + const observation = agentStatusConsumer.observeLaunchIngress() + store.setAgentStatus( + paneKey, + { state: 'working', prompt: trimmedPrompt, agentType: agent, observation }, + undefined, + undefined, + routing, + { launchConfig: startupPlan.launchConfig, launchToken } + ) + } + } + + if (runtimeTarget.kind === 'environment') { + if (!runtimeTerminalHandle) { + throw new Error('Runtime terminal id is invalid.') + } + unsubscribeData = await subscribeToRuntimeTerminalData( + ptyId, + `desktop:background:${tab.id}`, + handleData + ) + const exitWait = new AbortController() + // Kept-open terminals never exit; cancel their server wait instead of retaining a 24h long-wait slot. + releaseRuntimeObservers = () => { + releaseRuntimeObservers = (): void => {} + exitWait.abort() + const closeData = unsubscribeData + unsubscribeData = (): void => {} + closeData() + } + void callRuntimeRpc<{ wait: { exitCode?: number | null } }>( + runtimeTarget, + 'terminal.wait', + { terminal: runtimeTerminalHandle, for: 'exit' }, + { timeoutMs: 24 * 60 * 60 * 1000, signal: exitWait.signal } + ) + .then((result) => handleExit(ptyId, runtimeWaitExitCode(result.wait))) + .catch(() => {}) + } else { + // Incarnation prevents recycled relay IDs from delivering the previous session’s exit. + eagerPtyBuffer = registerEagerPtyBuffer(ptyId, handleExit, spawned.incarnationId) + unsubscribeData = subscribeToPtyData(ptyId, handleData) + // A mounted transport disposes the eager exit handler; this sidecar preserves completion tracking across hidden/visible transitions. + unsubscribeExit = subscribeToPtyExit(ptyId, (code) => handleExit(ptyId, code)) + } + // Bind PTY/ownership before mount to prevent duplicate spawn without missing user takeover. + requestBackgroundTerminalWorktreeMount({ worktreeId, tabIds: [tab.id] }) + + if (pasteDraftAfterLaunch !== null) { + scheduleAgentBackgroundDraft(tab.id, pasteDraftAfterLaunch, agent) + } + + return { + tabId: tab.id, + paneKey, + ptyId, + startupPlan, + terminalOwnership, + releaseRuntimeObservers: () => releaseRuntimeObservers() + } + } catch (error) { + // Creation and subscription are separate RPCs; failure between them must clean up the invisible runtime terminal. + exitHandled = true + terminalOwnership?.release() + const createdTab = tab + runBestEffortAgentBackgroundCleanups(unsubscribeExit, unsubscribeData) + runBestEffortAgentBackgroundCleanups(() => eagerPtyBuffer?.dispose()) + if (createdTab) { + runBestEffortAgentBackgroundCleanups(() => store.clearTabPtyId(createdTab.id, ptyId)) + } + runBestEffortAgentBackgroundCleanups(() => store.clearAgentLaunchConfig(paneKey)) + if (ptyId) { + await retireProvider({ ptyId, runtimeTarget, runtimeTerminalHandle }) + } + if (createdTab) { + // Cleanup closes must not enter the reopen stack. + runBestEffortAgentBackgroundCleanups(() => + store.closeTab(createdTab.id, { recordInteraction: false, reason: 'cleanup' }) + ) + } + throw error + } +} diff --git a/src/renderer/src/store/terminals/terminal-actions.ts b/src/renderer/src/store/terminals/terminal-actions.ts index b252600d451d..76870709c833 100644 --- a/src/renderer/src/store/terminals/terminal-actions.ts +++ b/src/renderer/src/store/terminals/terminal-actions.ts @@ -170,13 +170,6 @@ export type TerminalActions = { leafId: string ptyId: string expectedRuntimePtyId?: string - lifecycle?: { - preservePane: boolean - stop: ( - preservePane: boolean, - transactionCurrent: () => boolean - ) => Promise<'stopped' | 'live' | 'unproven'> - } } ) => Promise suppressPtyExit: (ptyId: string) => void diff --git a/src/renderer/src/store/terminals/terminal-pane-hibernation-commit.ts b/src/renderer/src/store/terminals/terminal-pane-hibernation-commit.ts deleted file mode 100644 index 71037dcad9e1..000000000000 --- a/src/renderer/src/store/terminals/terminal-pane-hibernation-commit.ts +++ /dev/null @@ -1,92 +0,0 @@ -import type { TerminalSlice, TerminalStoreGet, TerminalStoreSet } from './terminal-state' -import { removePanesAttention } from '../slices/workspace-attention/subject-attention-transitions' -import { settleAttentionRemovedBy } from '../slices/workspace-attention/attention-removal-follow-up' - -export function commitHibernatedPane({ - set, - get, - worktreeId, - opts, - state, - rendererShutdownPtyIds, - exitGuardPtyIds -}: { - set: TerminalStoreSet - get: TerminalStoreGet - worktreeId: string - opts: Parameters[1] - state: ReturnType - rendererShutdownPtyIds: string[] - exitGuardPtyIds: string[] -}): void { - settleAttentionRemovedBy(set, get, () => - set((s) => { - const existingPtyIds = s.ptyIdsByTabId[opts.tabId] ?? [] - const shutdownPtyIdSet = new Set(rendererShutdownPtyIds) - const remainingPtyIds = existingPtyIds.filter((ptyId) => !shutdownPtyIdSet.has(ptyId)) - const nextTabsByWorktree = { ...s.tabsByWorktree } - const tabs = nextTabsByWorktree[worktreeId] ?? [] - const tabIndex = tabs.findIndex((candidate) => candidate.id === opts.tabId) - if (tabIndex !== -1) { - const nextTabs = [...tabs] - nextTabs[tabIndex] = { - ...nextTabs[tabIndex], - ptyId: remainingPtyIds.at(-1) ?? null - } - nextTabsByWorktree[worktreeId] = nextTabs - } - const nextCodexRestartNoticeByPtyId = { ...s.codexRestartNoticeByPtyId } - for (const ptyId of exitGuardPtyIds) { - delete nextCodexRestartNoticeByPtyId[ptyId] - } - const nextLastKnownRelay = - remainingPtyIds.length === 0 - ? { ...s.lastKnownRelayPtyIdByTabId } - : s.lastKnownRelayPtyIdByTabId - if (remainingPtyIds.length === 0) { - delete nextLastKnownRelay[opts.tabId] - } - let nextRuntimePaneTitlesByTabId = s.runtimePaneTitlesByTabId - const numericPaneId = Number(opts.leafId) - if ( - Number.isInteger(numericPaneId) && - s.runtimePaneTitlesByTabId[opts.tabId]?.[numericPaneId] - ) { - const nextByPane = { ...s.runtimePaneTitlesByTabId[opts.tabId] } - delete nextByPane[numericPaneId] - nextRuntimePaneTitlesByTabId = { ...s.runtimePaneTitlesByTabId } - if (Object.keys(nextByPane).length > 0) { - nextRuntimePaneTitlesByTabId[opts.tabId] = nextByPane - } else { - delete nextRuntimePaneTitlesByTabId[opts.tabId] - } - } - const nextLastTerminalInputAtByPaneKey = { ...s.lastTerminalInputAtByPaneKey } - if ( - !opts.lifecycle || - s.lastTerminalInputAtByPaneKey[opts.paneKey] === - state.lastTerminalInputAtByPaneKey[opts.paneKey] - ) { - delete nextLastTerminalInputAtByPaneKey[opts.paneKey] - } - return { - tabsByWorktree: nextTabsByWorktree, - ptyIdsByTabId: { - ...s.ptyIdsByTabId, - [opts.tabId]: remainingPtyIds - }, - lastKnownRelayPtyIdByTabId: nextLastKnownRelay, - suppressedPtyExitIds: { - ...s.suppressedPtyExitIds, - ...Object.fromEntries(exitGuardPtyIds.map((ptyId) => [ptyId, true] as const)) - }, - codexRestartNoticeByPtyId: nextCodexRestartNoticeByPtyId, - ...(nextRuntimePaneTitlesByTabId !== s.runtimePaneTitlesByTabId - ? { runtimePaneTitlesByTabId: nextRuntimePaneTitlesByTabId } - : {}), - ...removePanesAttention(s, new Set([opts.paneKey])), - lastTerminalInputAtByPaneKey: nextLastTerminalInputAtByPaneKey - } - }) - ) -} diff --git a/src/renderer/src/store/terminals/terminal-pane-hibernation.ts b/src/renderer/src/store/terminals/terminal-pane-hibernation.ts index 35fe21232905..40f0b15f4032 100644 --- a/src/renderer/src/store/terminals/terminal-pane-hibernation.ts +++ b/src/renderer/src/store/terminals/terminal-pane-hibernation.ts @@ -1,4 +1,3 @@ -import { commitHibernatedPane } from './terminal-pane-hibernation-commit' import { isRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id' import { parsePaneKey } from '../../../../shared/stable-pane-id' import { @@ -17,6 +16,8 @@ import type { TerminalSlice, TerminalStoreGet, TerminalStoreSet } from './termin import { equalStringSets, sortedUniquePtyIds } from './terminal-pty-identities' import { resolveTerminalPtyOwner } from '@/lib/terminal-worktree-route' import { resolveTerminalTeardownOwner } from './terminal-teardown-owner' +import { removePanesAttention } from '../slices/workspace-attention/subject-attention-transitions' +import { settleAttentionRemovedBy } from '../slices/workspace-attention/attention-removal-follow-up' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' import { recordPaneSleepThroughLayoutOwner } from './terminal-sleep-layout-owner' @@ -66,22 +67,20 @@ export function createTerminalPaneHibernationActions( ) { throw new Error('agent_hibernation_pane_binding_mismatch') } - const sleepingAgentSessionRecords: ReturnType< - typeof collectSleepingAgentSessionRecordsForWorktree - > = - opts.lifecycle?.preservePane === false - ? {} - : collectSleepingAgentSessionRecordsForWorktree(state, worktreeId, { - paneKeys, - captureMode: 'completed-agent-hibernation' - }) + const sleepingAgentSessionRecords = collectSleepingAgentSessionRecordsForWorktree( + state, + worktreeId, + { + paneKeys, + captureMode: 'completed-agent-hibernation' + } + ) const retainedCompletionEvidence = collectHibernatedCompletionEvidenceForWorktree( state, worktreeId, paneKeys ) - const preservePane = Boolean(sleepingAgentSessionRecords[opts.paneKey]) - if (!opts.lifecycle && !preservePane) { + if (!sleepingAgentSessionRecords[opts.paneKey]) { // Why: killing the PTY with no persisted resume record strands the pane unwakeable; abort instead of hibernating unrecoverably. throw new Error('agent_hibernation_capture_missing') } @@ -103,35 +102,14 @@ export function createTerminalPaneHibernationActions( replacedSleepingRecords[key] = existing } } - const transactionCurrent = (): boolean => { - const current = get() - return ( - current.terminalLayoutsByTabId[opts.tabId]?.ptyIdsByLeafId?.[opts.leafId] === - opts.ptyId && - (!preservePane || - current.sleepingAgentSessionsByPaneKey[opts.paneKey] === - sleepingAgentSessionRecords[opts.paneKey]) - ) - } const rollbackTargetShutdownState = (): void => { set((s) => { const next = { ...s.suppressedPtyExitIds } for (const ptyId of exitGuardPtyIds) { - if ( - !state.suppressedPtyExitIds[ptyId] && - s.terminalLayoutsByTabId[opts.tabId]?.ptyIdsByLeafId?.[opts.leafId] === opts.ptyId && - (!sleepingRecordKeys.length || - s.sleepingAgentSessionsByPaneKey[opts.paneKey] === - sleepingAgentSessionRecords[opts.paneKey]) - ) { - delete next[ptyId] - } + delete next[ptyId] } const nextSleeping = { ...s.sleepingAgentSessionsByPaneKey } for (const key of sleepingRecordKeys) { - if (nextSleeping[key] !== sleepingAgentSessionRecords[key]) { - continue - } const replaced = replacedSleepingRecords[key] if (replaced) { nextSleeping[key] = replaced @@ -202,22 +180,8 @@ export function createTerminalPaneHibernationActions( // Why: pty.kill can flush final data before exit; unregister first so stale handlers can't fire phantom notifications during hibernation. const handlerSnapshots = unregisterPtyDataHandlers(rendererShutdownPtyIds) ?? [] try { - if (opts.lifecycle) { - const proof = await opts.lifecycle.stop(preservePane, transactionCurrent) - if (proof === 'unproven') { - throw new Error('terminal_stop_unproven') - } - if (proof !== 'stopped') { - throw new Error('terminal_stop_still_live') - } - } else { - await window.api.pty.kill(opts.ptyId, { keepHistory: true }) - } + await window.api.pty.kill(opts.ptyId, { keepHistory: true }) } catch (err) { - if (opts.lifecycle && err instanceof Error && err.message === 'terminal_stop_unproven') { - restorePtyDataHandlersAfterFailedShutdown(handlerSnapshots) - throw err - } restorePtyDataHandlersAfterFailedShutdown(handlerSnapshots) rollbackTargetShutdownState() throw err @@ -226,33 +190,74 @@ export function createTerminalPaneHibernationActions( snapshot.commit?.() } } - if (opts.lifecycle) { - if (!transactionCurrent()) { - throw new Error('terminal_sleep_binding_changed') - } - if (!preservePane) { - return - } - } // Switch point: main records the sleep this window decided, once the stop settled. if (ORCA_LAYOUT_OWNER_IS_MAIN) { recordPaneSleepThroughLayoutOwner(get(), worktreeId, sleepingAgentSessionRecords) } - commitHibernatedPane({ - set, - get, - worktreeId, - opts, - state, - rendererShutdownPtyIds, - exitGuardPtyIds - }) - if ( - opts.lifecycle && - get().agentStatusByPaneKey[opts.paneKey] !== state.agentStatusByPaneKey[opts.paneKey] - ) { - return - } + settleAttentionRemovedBy(set, get, () => + set((s) => { + const existingPtyIds = s.ptyIdsByTabId[opts.tabId] ?? [] + const shutdownPtyIdSet = new Set(rendererShutdownPtyIds) + const remainingPtyIds = existingPtyIds.filter((ptyId) => !shutdownPtyIdSet.has(ptyId)) + const nextTabsByWorktree = { ...s.tabsByWorktree } + const tabs = nextTabsByWorktree[worktreeId] ?? [] + const tabIndex = tabs.findIndex((candidate) => candidate.id === opts.tabId) + if (tabIndex !== -1) { + const nextTabs = [...tabs] + nextTabs[tabIndex] = { + ...nextTabs[tabIndex], + ptyId: remainingPtyIds.at(-1) ?? null + } + nextTabsByWorktree[worktreeId] = nextTabs + } + const nextCodexRestartNoticeByPtyId = { ...s.codexRestartNoticeByPtyId } + for (const ptyId of exitGuardPtyIds) { + delete nextCodexRestartNoticeByPtyId[ptyId] + } + const nextLastKnownRelay = + remainingPtyIds.length === 0 + ? { ...s.lastKnownRelayPtyIdByTabId } + : s.lastKnownRelayPtyIdByTabId + if (remainingPtyIds.length === 0) { + delete nextLastKnownRelay[opts.tabId] + } + let nextRuntimePaneTitlesByTabId = s.runtimePaneTitlesByTabId + const numericPaneId = Number(opts.leafId) + if ( + Number.isInteger(numericPaneId) && + s.runtimePaneTitlesByTabId[opts.tabId]?.[numericPaneId] + ) { + const nextByPane = { ...s.runtimePaneTitlesByTabId[opts.tabId] } + delete nextByPane[numericPaneId] + nextRuntimePaneTitlesByTabId = { ...s.runtimePaneTitlesByTabId } + if (Object.keys(nextByPane).length > 0) { + nextRuntimePaneTitlesByTabId[opts.tabId] = nextByPane + } else { + delete nextRuntimePaneTitlesByTabId[opts.tabId] + } + } + const nextLastTerminalInputAtByPaneKey = { ...s.lastTerminalInputAtByPaneKey } + delete nextLastTerminalInputAtByPaneKey[opts.paneKey] + return { + tabsByWorktree: nextTabsByWorktree, + ptyIdsByTabId: { + ...s.ptyIdsByTabId, + [opts.tabId]: remainingPtyIds + }, + lastKnownRelayPtyIdByTabId: nextLastKnownRelay, + suppressedPtyExitIds: { + ...s.suppressedPtyExitIds, + ...Object.fromEntries(exitGuardPtyIds.map((ptyId) => [ptyId, true] as const)) + }, + codexRestartNoticeByPtyId: nextCodexRestartNoticeByPtyId, + ...(nextRuntimePaneTitlesByTabId !== s.runtimePaneTitlesByTabId + ? { runtimePaneTitlesByTabId: nextRuntimePaneTitlesByTabId } + : {}), + ...removePanesAttention(s, new Set([opts.paneKey])), + lastTerminalInputAtByPaneKey: nextLastTerminalInputAtByPaneKey + } + }) + ) get().dropHibernatedAgentStatusPane(worktreeId, opts.paneKey, { retainedCompletionEvidence }) diff --git a/src/shared/automation-terminal-lifecycle.ts b/src/shared/automation-terminal-lifecycle.ts deleted file mode 100644 index bab7ac7b1d4c..000000000000 --- a/src/shared/automation-terminal-lifecycle.ts +++ /dev/null @@ -1,78 +0,0 @@ -/** Local desktop IPC only; resume records stay with the ordinary session owner. */ -export type AutomationTerminalTarget = { - worktreeId: string - tabId: string - leafId: string - paneKey: string -} - -export type AutomationTerminalCorrelation = { - requestId: string - registrationId: string - runId: string - operationId: string - serviceGeneration: string - documentEpoch: string | null -} - -export type AutomationTerminalLifecycleRequest = AutomationTerminalCorrelation & - ( - | { operation: 'arm'; target: AutomationTerminalTarget } - | { operation: 'bind'; ptyId: string; incarnationId: string; hostId: string } - | { operation: 'finalize'; phase: 'prepare'; preservePane: boolean } - | { operation: 'finalize'; phase: 'authorize' } - | { operation: 'finalize'; phase: 'stop-settled'; proof: 'stopped' | 'live' | 'unproven' } - | { operation: 'release' } - ) - -export type AutomationTerminalLifecycleResponse = AutomationTerminalCorrelation & { - disposition: - | 'armed' - | 'bound' - | 'prepared' - | 'authorized' - | 'released' - | 'kept' - | 'closed' - | 'hibernated' - | 'kept-live' - | 'stopped-but-uncommitted' - | 'unproven' -} - -export function automationTerminalLifecycleResponse( - request: AutomationTerminalLifecycleRequest, - documentEpoch: string, - disposition: AutomationTerminalLifecycleResponse['disposition'] -): AutomationTerminalLifecycleResponse { - return { ...request, documentEpoch, disposition } -} - -export function isCurrentAutomationTerminalRequest< - T extends { request: AutomationTerminalCorrelation } ->( - owner: T | undefined, - request: AutomationTerminalLifecycleRequest, - documentEpoch: string -): owner is T { - return ( - !!owner && - (request.documentEpoch === documentEpoch || request.operation === 'release') && - owner.request.runId === request.runId && - owner.request.operationId === request.operationId && - owner.request.serviceGeneration === request.serviceGeneration - ) -} - -export type AutomationTerminalLifecycleOwner = { - request: AutomationTerminalLifecycleRequest - target: AutomationTerminalTarget - ownership: Ownership - ptyId: string | null - prepared: boolean - transactionCurrent?: () => boolean - authorized: boolean - proof?: 'stopped' | 'live' | 'unproven' - settle?: (proof: 'stopped' | 'live' | 'unproven') => void - completion?: Promise -} diff --git a/tests/e2e/automation-terminal-ownership.unit.test.ts b/tests/e2e/automation-terminal-ownership.unit.test.ts deleted file mode 100644 index 2e01dd983e79..000000000000 --- a/tests/e2e/automation-terminal-ownership.unit.test.ts +++ /dev/null @@ -1,805 +0,0 @@ -import { - measureTerminalInventory, - assertTerminalInventorySelection -} from './helpers/automation-terminal-inventory-test-harness' -import * as desktopLifecycle from '../../src/main/automations/desktop-run-terminal-lifecycle' -import { randomUUID } from 'node:crypto' -import { createRuntimeAutomationService } from '../../src/main/automations/runtime-automation-service' -import { runtimeStub } from '../../src/main/runtime/rpc/methods/agent-launch.test-fixture' -import { createQueuedMessageTestRig } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' -import { hostTestAttachParams } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-host-test-data' -import { setStructuredAgentSessionHost } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-registry' -import { readAutomationRunReceipt } from '../../src/main/automations/automation-run-receipt' -import { hostWorktreeTarget } from '../../src/shared/worktree/host-qualified-identity' -import { revealCreatedTerminal } from '../../src/main/runtime/terminal/launch/terminal-create-reveal' -import { OrcaRuntimeWithPublishPtyBackedMobileSessionTerminal } from '../../src/main/runtime/session-tabs/pty-backed-session-publication' -import { OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce } from '../../src/main/runtime/session-tabs/structured-session-tab-restoration' -import type { RuntimeMobileSessionTabsSnapshot } from '../../src/shared/runtime-types' -import { - stopRevokers, - cancelDesktopTerminalRetirement -} from '../../src/main/automations/desktop-run-terminal-stop' -import type * as ChildProcess from 'node:child_process' -import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' -import { AutomationService } from '../../src/main/automations/service' -import { - createStore, - closeTestStores, - testState, - readPersistedStateJson, - writeDataFile -} from '../../src/main/persistence/persistence-test-harness' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { EventEmitter } from 'node:events' -import type { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' -import type { ConnectPanePtySession } from '@/components/terminal-pane/pty-connection/connect-pane-pty-session' -import { buildProfileStateCutoverFixture } from '../../src/main/persistence/profile-state-cutover-fixture' -import type { OwnershipTestStore } from './helpers/automation-terminal-ownership-test-harness' -import { singlePaneLayoutSnapshot } from '@/store/slices/terminal-helpers' -import { - recordTerminalInputActivity, - flushTerminalInputActivity -} from '../../src/renderer/src/lib/terminal-input-activity-coalescing' -import { createAutomationTerminalOwnership } from '../../src/renderer/src/lib/automation-terminal-ownership' -import { - ptyProcesses, - ptyIncarnations, - ptyShutdownOperations, - clearPtyState -} from '../../src/main/providers/local-pty-provider-state' -import { isPtyDataHandlerShutdownPending } from '@/components/terminal-pane/pty-shutdown-data-suspension' -import { installPtyExitHibernate } from '@/components/terminal-pane/pty-connection/pty-exit-hibernate' -import { installSleepingRecordAccess } from '@/components/terminal-pane/pty-connection/sleeping-record-access' - -const mocks = vi.hoisted( - (): { - store: OwnershipTestStore | null - ipc: EventEmitter | null - capture: Mock - prepare: () => Promise - } => ({ - store: null, - ipc: null, - capture: vi.fn(), - prepare: async () => {} - }) -) -vi.mock('electron', async () => { - const { EventEmitter } = await import('node:events') - mocks.ipc = new EventEmitter() - return { - ipcMain: mocks.ipc, - app: { getPath: () => testState.dir }, - safeStorage: { - isEncryptionAvailable: () => true, - encryptString: (s: string) => Buffer.from(s), - decryptString: (b: Buffer) => b.toString() - } - } -}) -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => mocks.store!.getState(), - setState: (...args: Parameters) => - mocks.store!.setState(...args), - subscribe: (...args: Parameters) => - mocks.store!.subscribe(...args) - } -})) -vi.mock('node:child_process', async (importOriginal) => ({ - ...(await importOriginal()), - execFile: ( - _file: string, - _args: string[], - _opts: unknown, - callback: (error: unknown, output: string) => void - ) => { - void mocks.prepare().then(() => callback(null, '4242 1 4242 -1 Mon Jul 13 12:00:00 2026')) - } -})) -vi.mock('sonner', () => ({ - toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } -})) -vi.mock('@/lib/focus-terminal-tab-surface', () => ({ focusTerminalTabSurface: vi.fn() })) - -const state = buildProfileStateCutoverFixture('/fixture') -import { - createAutomationTerminalOwnershipFixture, - OWNERSHIP_WORKSPACE_ID as WT -} from './helpers/automation-terminal-ownership-test-harness' -const noop = () => {} -const cleanups: (() => void)[] = [] -beforeEach(() => { - vi.clearAllMocks() - mocks.prepare = async () => {} - vi.spyOn(process, 'kill').mockImplementation(() => true) -}) -afterEach(() => { - for (const cleanup of cleanups.splice(0).toReversed()) { - cleanup() - } - for (const id of ptyProcesses.keys()) { - clearPtyState(id) - } - flushTerminalInputActivity() - vi.restoreAllMocks() -}) - -function fixture() { - return createAutomationTerminalOwnershipFixture(mocks, cleanups) -} - -describe('desktop completion through local publication and process owner', () => { - it('composes durable service completion with publication, exact stop and local sleep', async () => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-34332-composition-')) - const disk = await createStore() - try { - disk.addRepo({ ...state.repos[0], id: 'r1', path: '/fixture' }) - const automation = disk.createAutomation({ - name: 'Composition', - prompt: 'check', - agentId: 'codex', - projectId: 'r1', - workspaceMode: 'existing', - workspaceId: WT, - timezone: 'UTC', - rrule: 'FREQ=DAILY', - dtstart: 1 - }) - const saved = disk.createAutomationRun(automation, Date.now(), 'manual') - const f = fixture() - const t = f.publish(1, true, true, saved) - const phases: string[] = [] - const service = new AutomationService(disk, { - onRunFinalized: async (run) => { - phases.push('finalize') - expect(disk.listAutomationRuns()[0]).toMatchObject({ - id: saved.id, - status: 'completed', - terminalPtyId: t.run.terminalPtyId - }) - const persisted = JSON.parse( - readPersistedStateJson(join(testState.dir, 'orca-data.json')) - ) - expect(JSON.stringify(persisted)).toContain('completed') - return f.lifecycle.finalize(run) - }, - codexUsage: { - getAutomationRunUsage: async () => { - phases.push('usage') - expect(disk.listAutomationRuns()[0].terminalPtyId).toBeNull() - return null - } - } as never - }) - expect( - await service.markDispatchResult({ - runId: saved.id, - status: 'completed', - workspaceId: WT, - terminalPtyId: t.run.terminalPtyId, - terminalPaneKey: t.paneKey, - terminalSessionId: t.tabId - }) - ).toMatchObject({ terminalPtyId: null, terminalPaneKey: t.paneKey, status: 'completed' }) - expect(f.store.getState().sleepingAgentSessionsByPaneKey[t.paneKey].origin).toBe( - 'worktree-sleep' - ) - expect([...ptyProcesses.keys()]).toEqual(['setup']) - expect(phases).toEqual(['finalize', 'usage']) - service.stop() - } finally { - await closeTestStores() - rmSync(testState.dir, { recursive: true, force: true }) - } - }) - it.each([true, false])( - 'retires only an untouched original, early publication=%s', - async (early) => { - const f = fixture() - const target = f.publish(1, true, early) - const patch = await f.lifecycle.finalize(target.run) - expect(patch).toMatchObject({ terminalPtyId: null }) - expect(f.events.indexOf('arm:')).toBeLessThan( - f.events.indexOf(early ? 'ui:publishAgentLaunchTab' : 'ui:createTerminal') - ) - expect(f.events.indexOf('session:flush')).toBeLessThan(f.events.indexOf('os:exit')) - expect(f.store.getState().ptyIdsByTabId[target.tabId]).toEqual([]) - expect(f.store.getState().ptyIdsByTabId.sibling).toEqual(['setup']) - expect(f.store.getState().sleepingAgentSessionsByPaneKey[target.paneKey]).toMatchObject({ - origin: 'worktree-sleep', - providerSession: { id: 'session-1' } - }) - expect(f.store.getState().activeWorktreeId).toBe('other') - expect(f.web.eventNames()).toEqual([]) - expect(mocks.ipc!.eventNames()).toEqual([]) - expect(ptyShutdownOperations.size).toBe(0) - expect(isPtyDataHandlerShutdownPending(target.run.terminalPtyId)).toBe(false) - } - ) - it.each([false, true])( - 'ordinary wake consumes the captured pane once, reveal racing exit=%s', - async (racing) => { - const f = fixture() - const t = f.publish() - await f.lifecycle.finalize(t.run) - const visible = { current: racing } - let currentPty: string | null = t.run.terminalPtyId - const transport = { getPtyId: () => currentPty } - // SAFETY: pane rendering and physical resume are the boundaries; actual ordinary exit/sleep-record/wake owners execute. - const session = { - pane: { id: 1, leafId: t.leafId }, - paneStartup: {}, - cacheKey: t.paneKey, - disposed: false, - runtimeEnvironmentId: null, - transport, - manager: { setPaneGpuRendering: noop, getActivePane: () => null }, - deps: { - tabId: t.tabId, - worktreeId: WT, - isVisibleRef: visible, - paneTransportsRef: { current: new Map([[1, transport]]) }, - isPtyShutdownPending: isPtyDataHandlerShutdownPending, - consumeSuppressedPtyExit: (id: string) => f.store.getState().consumeSuppressedPtyExit(id), - clearTabPtyId: (tab: string, id: string) => f.store.getState().clearTabPtyId(tab, id), - clearRuntimePaneTitle: noop, - setCacheTimerStartedAt: noop - }, - resetRendererOrderedSeqForPtyExit: noop, - agentCompletionCoordinator: { dispose: noop }, - dropSideEffectFactConsumer: noop, - releaseHiddenRendererPtyDelivery: noop, - clearPanePtyFitBinding: noop, - clearExitedPanePtyLayoutBinding: noop, - writeInputModeGround: noop - } as unknown as ConnectPanePtySession - installSleepingRecordAccess(session) - installPtyExitHibernate(session) - const resume = vi.fn(async () => { - const record = session.getSleepingRecordForPane(f.store.getState()) - expect(record.record.providerSession.id).toBe('session-1') - session.clearSleepingRecordProviderDuplicates(f.store.getState(), record) - currentPty = 'resumed' - f.store.getState().updateTabPtyId(t.tabId, currentPty) - return currentPty - }) - session.wakeHibernatedAgentPane = resume - // A persisted pre-stop record with a live binding does not itself cause another spawn. - expect(resume).not.toHaveBeenCalled() - session.onExit(t.run.terminalPtyId, 0) - await Promise.resolve() - if (!racing) { - expect(resume).not.toHaveBeenCalled() - visible.current = true - session.consumeHibernatedAgentWake() - } - await Promise.resolve() - expect(resume).toHaveBeenCalledOnce() - session.consumeHibernatedAgentWake() - expect(resume).toHaveBeenCalledOnce() - expect(f.store.getState().sleepingAgentSessionsByPaneKey[t.paneKey]).toBeUndefined() - expect(f.store.getState().ptyIdsByTabId.sibling).toEqual(['setup']) - } - ) - it.each(['prepare-persist', 'commit-persist'] as const)( - 'keeps recovery truthful on %s failure', - async (point) => { - const f = fixture() - const t = f.publish() - if (point === 'prepare-persist') { - f.session.flush.mockRejectedValueOnce(new Error('disk unavailable')) - } - if (point === 'commit-persist') { - f.session.flush - .mockResolvedValueOnce(undefined) - .mockRejectedValueOnce(new Error('commit unavailable')) - } - const patch = await f.lifecycle.finalize(t.run) - if (point === 'prepare-persist') { - expect(patch).toBeNull() - expect(f.events).not.toContain('os:exit') - } else { - expect(patch).toMatchObject({ terminalPtyId: null }) - expect(f.store.getState().sleepingAgentSessionsByPaneKey[t.paneKey]).toBeDefined() - } - expect(f.store.getState().tabsByWorktree[WT].some((tab) => tab.id === t.tabId)).toBe(true) - } - ) - it('closes a shared-workspace tab only after exact physical stop', async () => { - const f = fixture() - const t = f.publish(1, false) - f.prepare(async () => - expect(f.store.getState().tabsByWorktree[WT].some((tab) => tab.id === t.tabId)).toBe(true) - ) - expect(await f.lifecycle.finalize(t.run)).toMatchObject({ - terminalPtyId: null, - terminalPaneKey: null, - terminalSessionId: null - }) - expect(f.store.getState().tabsByWorktree[WT].map((tab) => tab.id)).toEqual(['sibling']) - expect(window.api.pty.kill).not.toHaveBeenCalled() - }) - it.each([ - 'view', - 'pending-input', - 'replacement', - 'process', - 'new-record', - 'recreate', - 'move', - 'split', - 'reload', - 'ordinary-stop' - ] as const)('keeps the original on %s during preparation', async (reason) => { - const f = fixture() - const t = f.publish() - f.prepare(async () => { - const s = f.store.getState() - if (reason === 'view') { - f.store.setState({ activeWorktreeId: WT, activeTabId: t.tabId, activeTabType: 'terminal' }) - f.store.setState({ activeWorktreeId: 'other', activeTabId: 'other-tab' }) - } else if (reason === 'pending-input') { - const commit = { insert: () => {}, refreshExisting: () => {} } - f.store.setState({ lastTerminalInputAtByPaneKey: { [t.paneKey]: 100 } }) - recordTerminalInputActivity({ paneKey: t.paneKey, timestamp: 100, commit }) - recordTerminalInputActivity({ paneKey: t.paneKey, timestamp: 101, commit }) - } else if (reason === 'replacement') { - s.updateTabPtyId(t.tabId, 'replacement') - } else if (reason === 'process') { - ptyIncarnations.set(t.run.terminalPtyId, 'replacement') - } else if (reason === 'new-record') { - f.store.setState({ - sleepingAgentSessionsByPaneKey: { - [t.paneKey]: { ...s.sleepingAgentSessionsByPaneKey[t.paneKey], origin: 'live' } - } - }) - } else if (reason === 'recreate') { - const original = s.tabsByWorktree[WT].find((tab) => tab.id === t.tabId)! - f.store.setState({ - tabsByWorktree: { [WT]: s.tabsByWorktree[WT].filter((tab) => tab.id !== t.tabId) } - }) - f.store.setState({ tabsByWorktree: { [WT]: [...s.tabsByWorktree[WT]] } }) - expect(original.createdAt).toBeDefined() - } else if (reason === 'move') { - f.store.setState({ tabsByWorktree: { [WT]: [], elsewhere: s.tabsByWorktree[WT] } }) - } else if (reason === 'split') { - s.setTabLayout(t.tabId, { - ...singlePaneLayoutSnapshot(t.leafId, t.run.terminalPtyId), - root: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', leafId: t.leafId }, - second: { type: 'leaf', leafId: 'second' } - } - }) - } else if (reason === 'reload') { - f.web.emit('did-start-navigation', {}, 'reload', false, true) - } else { - cancelDesktopTerminalRetirement(t.run.terminalPtyId) - } - }) - expect(await f.lifecycle.finalize(t.run)).toBeNull() - expect(f.events).not.toContain('os:exit') - expect(ptyProcesses.has(t.run.terminalPtyId)).toBe(true) - expect(isPtyDataHandlerShutdownPending(t.run.terminalPtyId)).toBe(false) - }) - it.each(['live', 'unproven'] as const)( - 'preserves truthful recovery after a %s stop failure', - async (proof) => { - const f = fixture() - const t = f.publish() - f.failStop(proof) - expect(await f.lifecycle.finalize(t.run)).toBeNull() - expect(f.store.getState().tabsByWorktree[WT].some((tab) => tab.id === t.tabId)).toBe(true) - expect(f.store.getState().sleepingAgentSessionsByPaneKey[t.paneKey]?.origin).toBe( - proof === 'live' ? 'live' : 'worktree-sleep' - ) - expect(isPtyDataHandlerShutdownPending(t.run.terminalPtyId)).toBe(false) - } - ) - it.each(['view', 'input'] as const)( - 'retains synchronous %s takeover before prompt settlement', - async (kind) => { - const f = fixture() - const t = f.publish() - if (kind === 'view') { - f.store.setState({ activeWorktreeId: WT, activeTabId: t.tabId, activeTabType: 'terminal' }) - f.store.setState({ activeWorktreeId: 'other', activeTabId: 'other-tab' }) - } else { - recordTerminalInputActivity({ - paneKey: t.paneKey, - timestamp: Date.now(), - commit: { - insert: (key, stamp) => - f.store.setState({ lastTerminalInputAtByPaneKey: { [key]: stamp } }), - refreshExisting: noop - } - }) - } - expect(await f.lifecycle.finalize(t.run)).toBeNull() - expect(f.events).not.toContain('os:exit') - expect(ptyProcesses.has(t.run.terminalPtyId)).toBe(true) - } - ) - it.each(['generation', 'frame-loss'] as const)( - 'releases unknown eligibility after %s and ignores a late reply', - async (reason) => { - const f = fixture() - const respond = window.api.automations.respondTerminalLifecycle - let late: Parameters[0] | undefined - window.api.automations.respondTerminalLifecycle = (reply) => { - if (reply.disposition !== 'armed') { - return respond(reply) - } - late = reply - if (reason === 'generation') { - respond({ ...reply, serviceGeneration: 'different-service' }) - } else { - mocks.ipc!.emit( - 'automations:terminalLifecycleResponse', - { sender: f.web, senderFrame: {} }, - reply - ) - } - } - const t = f.publish() - if (reason === 'frame-loss') { - f.web.emit('render-process-gone') - } - expect(await f.lifecycle.finalize(t.run)).toBeNull() - if (late) { - respond(late) - } - expect(f.events).not.toContain('os:exit') - expect(mocks.ipc!.eventNames()).toEqual([]) - expect(f.web.eventNames()).toEqual([]) - expect(ptyProcesses.has(t.run.terminalPtyId)).toBe(true) - } - ) - it('never enrolls an already materialized or restarted surface as untouched', () => { - const f = fixture() - const t = f.publish() - const owner = createAutomationTerminalOwnership(f.store, { worktreeId: WT, ...t }) - expect(owner.bind(t.run.terminalPtyId)).toBe(false) - owner.release() - expect( - f.lifecycle.begin({ ...state.automations[0], reuseSession: true }, t.run, 'reuse') - ).toBeNull() - }) -}) - -it.each([5, 50])('bounds actual desktop fallback/Chat/Reuse owners at N=%i', async (count) => { - vi.spyOn(Date, 'now').mockReturnValue(1_800_000_000_000) - const root = mkdtempSync(join(tmpdir(), 'orca-34332-fallback-')) - testState.dir = root - const disk = createStore(), - f = fixture() - const rig = await createQueuedMessageTestRig({ restartable: true }) - setStructuredAgentSessionHost(rig.host) - const timers = vi.spyOn(globalThis, 'setTimeout'), - cleared = vi.spyOn(globalThis, 'clearTimeout') - const tabs = new Map() - const bindings = new Map() - const publisher = Object.assign( - Object.create(OrcaRuntimeWithPublishPtyBackedMobileSessionTerminal.prototype), - { - mobileSessionTabsByWorktree: tabs, - isMobileSessionSurfaceMembershipAllowed: () => true, - getPtyDisplayRecord: (record: unknown) => record, - getPtyManualTitle: () => null, - storeMobileSessionSnapshot: (id: string, snapshot: RuntimeMobileSessionTabsSnapshot) => { - tabs.set(id, snapshot) - return snapshot - }, - notifyMobileSessionTabsChanged: vi.fn() - } - ) - const chatPublisher = Object.assign( - Object.create(OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce.prototype), - { - mobileSessionTabsByWorktree: tabs, - saveWindowlessAgentSessionTab: vi.fn(), - storeMobileSessionSnapshot: publisher.storeMobileSessionSnapshot, - emitMobileSessionTabsSnapshot: vi.fn() - } - ) - let mode = 'unavailable', - currentRun = '', - service: ReturnType | undefined - const trace: string[] = [] - const runtime = { - ...runtimeStub(), - ...f.runtime, - requireStore: () => disk, - setAutomationService: vi.fn(), - notifyAutomationsChanged: vi.fn(), - openAgentSessionRecordStore: async () => rig.store, - showRepo: async () => disk.getRepo('repo1'), - showAutomation: (id: string) => disk.listAutomations().find((a) => a.id === id), - listAutomationRuns: (id: string) => disk.listAutomationRuns(id), - getAgentStatusRowsForPane: () => [], - getTerminalPtyIdForHandle: (handle: string) => bindings.get(handle)?.ptyId ?? null, - getTerminalPaneKey: (handle: string) => bindings.get(handle)?.paneKey ?? null, - getTerminalHandleForPaneKey: (paneKey: string) => - [...bindings].find(([, b]) => b.paneKey === paneKey && ptyProcesses.has(b.ptyId))?.[0] ?? - null, - showManagedWorktree: async () => ({ displayName: 'Fallback' }), - getStructuredAgentSessionCreateSupport: async () => { - trace.push('support') - if (mode === 'unknown') { - throw new Error('support unavailable') - } - return { supported: mode === 'refused' || mode === 'chat', reason: 'chat-program' as const } - }, - resolveStructuredAgentSessionCreateIntent: async () => { - if (mode === 'refused') { - throw new Error('structured_agent_session_unsupported') - } - const { envelope: _, ...params } = hostTestAttachParams(null) - return { ...params, location: { ...params.location, workspaceId: WT } } - }, - publishStructuredAgentSessionTab: - chatPublisher.publishStructuredAgentSessionTab.bind(chatPublisher), - createManagedWorktree: async ( - args: Parameters[0] - ) => { - trace.push('create') - currentRun = args.automationProvenance!.automationRunId - disk.setWorktreeMeta(hostWorktreeTarget({ id: WT, hostId: 'local' }), { - automationProvenance: args.automationProvenance - }) - args.onWorkspaceCreated!(WT) - return { worktree: { id: WT, path: '/repo1/main' } } - }, - createTerminal: async ( - _selector: string, - options: NonNullable[1]> - ) => { - trace.push('terminal') - const tabId = options.tabId ?? randomUUID(), - leafId = options.leafId ?? randomUUID() - const paneKey = `${tabId}:${leafId}` - const ptyId = `actual-${bindings.size}`, - handle = `term-${bindings.size}` - bindings.set(handle, { paneKey, ptyId }) - f.bindProcess(ptyId, paneKey) - publisher.publishPtyBackedMobileSessionTerminal( - WT, - { ptyId, incarnationId: 'original', launchAgent: 'codex' }, - { tabId, leafId, title: 'Codex', activate: false, selectIfNoActiveTab: false } - ) - await revealCreatedTerminal({ - notifier: null, - workspace: { id: WT, path: '/repo1/main' }, - ptyId, - handle, - cwd: '/repo1/main', - launchOpts: options, - opts: options, - tabId, - leafId, - presentation: options.presentation, - adoptedStablePane: false, - effectiveLaunchConfig: undefined, - launchToken: undefined - }) - options.onPtySpawnDispatched?.() - options.onStartupPromptCarry?.(true) - return { handle, paneKey } - }, - deliverStartupFollowup: async () => true, - waitForTerminal: async (_handle: string, options: { signal: AbortSignal }) => - new Promise((_resolve, reject) => { - if (options.signal.aborted) { - reject(new Error('aborted')) - } else { - options.signal.addEventListener('abort', () => reject(new Error('aborted')), { - once: true - }) - } - }), - readTerminal: async () => ({ tail: [] }) - } - try { - disk.addRepo({ ...state.repos[0], id: 'repo1', path: '/repo1/main', connectionId: null }) - // SAFETY: only runtime OS/transport boundaries are scripted; service, common executor, receipt, lifecycle, renderer transaction and stop owner are real. - service = createRuntimeAutomationService({ - store: disk, - runtime: runtime as unknown as OrcaRuntimeService, - headless: false, - createDesktopLifecycle: desktopLifecycle.createDesktopRunTerminalLifecycle - }) - service.setWebContents(f.web) - service.setRendererReady() - let eligible = 0, - retained = 0, - chats = 0 - for (let n = 0; n < count; n++) { - mode = ['unavailable', 'unknown', 'refused', 'chat', 'unavailable'][n % 5] - const reuseSession = n % 5 === 4 - const automation = disk.createAutomation({ - name: 'Fallback', - prompt: 'check', - agentId: 'codex', - projectId: 'repo1', - workspaceMode: reuseSession ? 'existing' : 'new_per_run', - workspaceId: reuseSession ? WT : null, - launchSetupPatch: { surface: reuseSession ? 'terminal' : 'chat' }, - reuseSession, - timezone: 'UTC', - rrule: 'FREQ=DAILY', - dtstart: Date.now() + 86400000, - setupDecision: 'skip' - }) - expect(automation.surface).toBe(reuseSession ? 'terminal' : 'chat') - const start = f.events.length - const run = await service.runNow(automation.id) - expect(run.status).toBe('dispatched') - expect(readAutomationRunReceipt(rig.store, run)?.accepted).toBe(true) - expect(trace.splice(0)).toEqual( - reuseSession - ? ['terminal'] - : mode === 'chat' - ? ['create', 'support'] - : ['create', 'support', 'terminal'] - ) - if (mode === 'chat') { - chats++ - expect(run.sessionKind).toBe('chat') - expect(f.events.slice(start)).toContain('arm:') - expect(f.events.slice(start)).not.toContain('ui:createTerminal') - expect(tabs.get(WT)!.tabs.filter((t) => t.type === 'agent-session')).toHaveLength(chats) - expect(chatPublisher.saveWindowlessAgentSessionTab.mock.lastCall[1].activate).toBe(false) - } else if (reuseSession) { - retained++ - expect(f.events.slice(start).some((e) => e.startsWith('arm:'))).toBe(false) - } else { - eligible++ - expect(f.events.slice(start).filter((e) => e.startsWith('arm:'))).toHaveLength(1) - expect(f.events.slice(start).filter((e) => e.startsWith('bind:'))).toHaveLength(1) - expect(f.events.indexOf('arm:', start)).toBeLessThan( - f.events.indexOf('ui:createTerminal', start) - ) - f.store - .getState() - .setAgentStatus( - run.terminalPaneKey!, - { state: 'done', prompt: 'resume', agentType: 'codex' }, - 'Codex', - { updatedAt: 2000, stateStartedAt: 1000 }, - { tabId: run.terminalSessionId!, worktreeId: WT }, - { providerSession: { key: 'session_id', id: currentRun } } - ) - } - const finalized = await service.markDispatchResult({ runId: run.id, status: 'completed' }) - expect(finalized.terminalPtyId).toBe(reuseSession ? run.terminalPtyId : null) - expect(stopRevokers.size).toBe(0) - expect(f.activeSubscribers()).toBe(0) - expect(ptyShutdownOperations.size).toBe(0) - expect(f.web.eventNames()).toEqual([]) - expect(mocks.ipc!.eventNames()).toEqual([]) - expect(ptyProcesses.size).toBe(1 + retained) - expect(ptyProcesses.has('setup')).toBe(true) - const persisted = JSON.parse(readPersistedStateJson(join(root, 'orca-data.json'))) - expect( - persisted.automationRuns.find((row: { id: string }) => row.id === run.id) - ).toMatchObject({ - status: 'completed', - chatSessionId: run.chatSessionId, - terminalPtyId: finalized.terminalPtyId - }) - } - const sessions = rig.host.collaboratorsForTests().sessions - expect(sessions['observers'].size).toBe(0) - expect(sessions['attachments'].size).toBe(chats + 1) - const protocol = timers.mock.calls.flatMap((args, i) => - args[1] === 20_000 ? [timers.mock.results[i].value] : [] - ) - for (const timer of protocol) { - expect(cleared).toHaveBeenCalledWith(timer) - } - const sleepers = Object.keys(f.store.getState().sleepingAgentSessionsByPaneKey).length - expect(sleepers).toBe(eligible) - expect(f.store.getState().tabsByWorktree[WT]).toHaveLength(1 + eligible) - process.stdout.write( - `${JSON.stringify({ desktopRuns: count, canonicalSources: sessions['attachments'].size, logicalObservers: sessions['observers'].size, eligible, retainedReuse: retained, chats, ptys: ptyProcesses.size, desktopTabs: f.store.getState().tabsByWorktree[WT].length, runtimeTabs: tabs.get(WT)!.tabs.length, sleepers, registrations: stopRevokers.size, subscribers: f.activeSubscribers(), timersCreated: protocol.length, timersCleared: protocol.filter((timer) => cleared.mock.calls.some(([clearedTimer]) => timer === clearedTimer)).length })}\n` - ) - } finally { - service?.stop() - setStructuredAgentSessionHost(null) - await rig.dispose() - await closeTestStores() - rmSync(root, { recursive: true, force: true }) - } -}) - -it.each([ - [5, 100], - [50, 1000] -])('shares one current inventory for %i owners and %i retained rows', async (owners, history) => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-34332-inventory-')) - const seeded = buildProfileStateCutoverFixture('/fixture') - seeded.automations = Array.from({ length: history / 100 }, (_, i) => ({ - ...seeded.automations[0], - id: `inventory-${i}` - })) - seeded.automationRuns = Array.from({ length: history }, (_, i) => ({ - ...seeded.automationRuns[0], - id: `inventory-run-${i}`, - automationId: seeded.automations[Math.floor(i / 100)].id, - status: i < owners ? (['dispatching', 'dispatched', 'completed'] as const)[i % 3] : 'completed', - createdAt: i - })) - writeDataFile(seeded) - const disk = createStore(), - f = fixture() - const create = vi.spyOn(desktopLifecycle, 'createDesktopRunTerminalLifecycle') - const runtime = { - ...runtimeStub(), - ...f.runtime, - setAutomationService: vi.fn(), - notifyAutomationsChanged: vi.fn() - } - // SAFETY: only the OS/window transport is scripted; actual runtime/service/writer/persistence/lifecycle owners execute. - const service = createRuntimeAutomationService({ - store: disk, - runtime: runtime as unknown as OrcaRuntimeService, - headless: false, - createDesktopLifecycle: desktopLifecycle.createDesktopRunTerminalLifecycle - }) - const lifecycle = create.mock.results[0].value! - try { - const runs = disk.listAutomationRuns(), - registered = new Set( - runs.filter((r) => Number(r.id.split('-').at(-1)) < owners).map((r) => r.id) - ) - await service.markDispatchResult({ runId: runs[0].id, status: 'completed' }) - const inventory = measureTerminalInventory(disk, lifecycle, registered) - const { lists } = inventory - lifecycle.reconcile() - expect(lists).not.toHaveBeenCalled() - for (const run of runs.filter((r) => registered.has(r.id))) { - expect( - lifecycle.begin({ ...seeded.automations[0], reuseSession: false }, run, run.id) - ).not.toBeNull() - } - await service.markDispatchResult({ - runId: runs[0].id, - status: 'completed' - }) - expect(inventory.counts()).toEqual({ - inventories: 1, - normalizations: history, - sorts: 1, - rows: history, - statusVisits: history, - linearFinds: 0, - selectedLookups: owners - }) - expect(f.web.listenerCount('render-process-gone')).toBe(1) - process.stdout.write(`${JSON.stringify({ owners, history, ...inventory.counts() })}\n`) - lifecycle.begin( - { ...seeded.automations[0], reuseSession: false }, - { ...runs[0], id: 'missing' }, - 'missing' - ) - lifecycle.reconcile() - expect(stopRevokers.size).toBe(owners) - const failed = runs.find((run) => registered.has(run.id))! - await service.markDispatchResult({ runId: failed.id, status: 'dispatch_failed' }) - expect(stopRevokers.size).toBe(owners - 1) - lifecycle.stop() - lists.mockClear() - lifecycle.reconcile() - expect(lists).not.toHaveBeenCalled() - assertTerminalInventorySelection(runs[0]) - expect(f.web.eventNames()).toEqual([]) - } finally { - service.stop() - await closeTestStores() - rmSync(testState.dir, { 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 index e83c324e3e6b..021b1fcc010d 100644 --- a/tests/e2e/headless-automation-agent-launch.unit.test.ts +++ b/tests/e2e/headless-automation-agent-launch.unit.test.ts @@ -17,8 +17,7 @@ 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 { tokenizeStartupCommand } from '../../src/shared/tui-agent-startup-shell' -import { launchHeadlessAutomationAgent } from '../../src/main/automations/headless-automation-agent-launch' +import { launchAutomationChatAgent } from '../../src/main/automations/automation-chat-agent-launch' const mocks = vi.hoisted(() => ({ actualHost: null as StructuredAgentSessionHost | null, @@ -64,13 +63,14 @@ const automation = { 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: 'terminal', reason: 'requested', detail: 'Terminal' }, + receipt: { mode: 'terminal', preferred: 'structured', reason: 'unsupported', detail: 'Fallback' }, prompt: { delivery: 'submit', outcome: 'handed-to-terminal' } } const chat: AgentLaunchResult = { @@ -131,11 +131,11 @@ beforeEach(() => { }) describe('automations through agent.launch', () => { it.each(['claude', 'codex'] as const)( - 'pins legacy %s runs to Terminal and preserves unattended/background policy', + 'launches explicit Chat for %s through the common entry and keeps its actual fallback', async (agentId) => { const { runtime } = fixture() - const result = await launchHeadlessAutomationAgent(runtime, { - automation: { ...automation, surface: undefined, agentId }, + const result = await launchAutomationChatAgent(runtime, { + automation: { ...automation, agentId }, run, target, runs: [] @@ -143,7 +143,7 @@ describe('automations through agent.launch', () => { expect(mocks.launch).toHaveBeenCalledWith( expect.objectContaining({ agent: agentId, - surface: 'terminal', + surface: 'chat', operationId: automationRunOperationId(run, 'fresh-launch'), prompt: { text: 'Audit', delivery: 'submit' }, presentation: 'background', @@ -151,9 +151,6 @@ describe('automations through agent.launch', () => { }), expect.objectContaining({ runtime }), expect.objectContaining({ - terminalTitle: run.title, - suppressStartupUpdatePrompt: true, - unprovableHost: 'write-unless-shell', onSurfacePublished: expect.any(Function) }) ) @@ -165,57 +162,22 @@ describe('automations through agent.launch', () => { }) } ) - it('merges Terminal extras over the live host defaults, and never applies them to Chat', async () => { + it('does not apply stored Terminal extras to Chat', async () => { const { runtime } = fixture() - await launchHeadlessAutomationAgent(runtime, { + mocks.launch.mockResolvedValue(chat) + await launchAutomationChatAgent(runtime, { automation: { ...automation, extraAgentArgs: '--model opus' }, run, target, runs: [] }) - expect(tokenizeStartupCommand(mocks.launch.mock.calls[0][0].agentArgs, 'posix')).toMatchObject({ - ok: true, - tokens: ['--add-dir', 'docs', '--model', 'opus'] - }) - mocks.launch.mockResolvedValue(chat) - await launchHeadlessAutomationAgent(runtime, { - automation: { ...automation, surface: 'chat', extraAgentArgs: '--model opus' }, - run: { ...run, id: 'chat-run' }, - target, - runs: [] - }) - expect(mocks.launch.mock.calls[1][0].agentArgs).toBeUndefined() - }) - it('retains the actual pane for a reused terminal whose launch result has only a handle', async () => { - const { runtime } = fixture() - mocks.launch.mockResolvedValue({ - ...terminal, - outcome: { kind: 'terminal', handle: 'term-prev' } - }) - const result = await launchHeadlessAutomationAgent(runtime, { - automation: { ...automation, reuseSession: true }, - run, - target, - runs: [ - { - ...run, - id: 'old', - status: 'completed', - workspaceId: 'wt-1', - sessionKind: 'terminal', - terminalPaneKey: 'old:leaf', - terminalPtyId: 'pty-1' - } - ] - }) - expect(result).toMatchObject({ terminalPaneKey: 'tab-1:leaf-1', terminalPtyId: 'pty-1' }) - expect(mocks.launch).toHaveBeenCalledTimes(1) + 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( - launchHeadlessAutomationAgent(runtime, { automation, run, target, runs: [] }) + launchAutomationChatAgent(runtime, { automation, run, target, runs: [] }) ).rejects.toThrow( 'Claude could not start because this run waited too long. Run the automation again.' ) @@ -224,7 +186,7 @@ describe('automations through agent.launch', () => { it('records the actual chat identity and delegates new workspace setup and provenance', async () => { const { runtime } = fixture() mocks.launch.mockResolvedValue(chat) - const result = await launchHeadlessAutomationAgent(runtime, { + const result = await launchAutomationChatAgent(runtime, { automation: { ...automation, surface: 'chat', @@ -263,55 +225,6 @@ describe('automations through agent.launch', () => { terminalPtyId: null }) }) - it('separates a proven no-effect terminal reuse refusal from the fresh launch identity', async () => { - const { runtime, records } = fixture() - records.getOperationRow.mockReturnValue({ outcome: { status: 'failed' } }) - mocks.launch - .mockRejectedValueOnce(new Error('no longer an agent')) - .mockResolvedValueOnce(terminal) - const previous = { - ...run, - id: 'old', - workspaceId: 'wt-1', - status: 'completed' as const, - sessionKind: 'terminal' as const, - terminalPaneKey: 'old:leaf', - terminalPtyId: 'pty-1' - } - await launchHeadlessAutomationAgent(runtime, { - automation: { ...automation, reuseSession: true }, - run, - target, - runs: [previous] - }) - expect(mocks.launch.mock.calls.map(([input]) => input.operationId)).toEqual([ - automationRunOperationId(run, 'reuse-terminal-launch'), - automationRunOperationId(run, 'fresh-launch') - ]) - }) - it('never falls back after an ambiguous reuse launch', async () => { - const { runtime, records } = fixture() - records.getOperationRow.mockReturnValue({ outcome: { status: 'unknown' } }) - mocks.launch.mockRejectedValue(new Error('lost reply')) - await expect( - launchHeadlessAutomationAgent(runtime, { - automation: { ...automation, reuseSession: true }, - run, - target, - runs: [ - { - ...run, - id: 'old', - workspaceId: 'wt-1', - status: 'completed', - terminalPaneKey: 'old:leaf', - terminalPtyId: 'pty-1' - } - ] - }) - ).rejects.toMatchObject({ target: { workspaceId: 'wt-1', sessionKind: 'terminal' } }) - expect(mocks.launch).toHaveBeenCalledTimes(1) - }) it('chooses the newest compatible Chat despite busy work and stale nonfinal history', async () => { const { runtime, records } = fixture() mocks.host.currentWork.mockReturnValue({ working: () => true }) @@ -324,7 +237,7 @@ describe('automations through agent.launch', () => { sessionKind: 'chat' as const, chatSessionId: 'claude_prev' } - const result = await launchHeadlessAutomationAgent(runtime, { + const result = await launchAutomationChatAgent(runtime, { automation: { ...automation, surface: 'chat', reuseSession: true }, run, target, @@ -391,13 +304,11 @@ describe('automations through agent.launch', () => { target, runs } - expect((await launchHeadlessAutomationAgent(runtime, request)).chatSessionId).toBe( - 'claude_prev' - ) + expect((await launchAutomationChatAgent(runtime, request)).chatSessionId).toBe('claude_prev') expect(mocks.launch).not.toHaveBeenCalled() mocks.host.send.mockClear() mocks.launch.mockResolvedValue(chat) - await launchHeadlessAutomationAgent(runtime, { ...request, runs: runs.slice(0, 2) }) + 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( @@ -406,7 +317,7 @@ describe('automations through agent.launch', () => { }) }) -it.each(['terminal', 'chat', 'reuse-terminal'] as const)( +it.each(['terminal', 'chat'] as const)( 'preserves published %s identity for refused, uncertain and throwing settlement', async (kind) => { const { runtime, records } = fixture() @@ -420,11 +331,7 @@ it.each(['terminal', 'chat', 'reuse-terminal'] as const)( policy.onSurfacePublished(published) if (outcome === 'accepted-throw') { records.getOperationRow.mockImplementation((_caller, id) => - id === - automationRunOperationId( - run, - kind === 'reuse-terminal' ? 'reuse-terminal-launch' : 'fresh-launch' - ) + id === automationRunOperationId(run, 'fresh-launch') ? { outcome: { status: 'succeeded', launch: published } } : undefined ) @@ -435,28 +342,14 @@ it.each(['terminal', 'chat', 'reuse-terminal'] as const)( } return { ...published, prompt: { delivery: 'submit', outcome } } }) - const result = await launchHeadlessAutomationAgent(runtime, { + const result = await launchAutomationChatAgent(runtime, { automation: { ...automation, - surface: kind === 'chat' ? 'chat' : 'terminal', - reuseSession: kind === 'reuse-terminal' + surface: 'chat' }, run, target, - runs: - kind === 'reuse-terminal' - ? [ - { - ...run, - id: 'old', - status: 'completed', - workspaceId: 'wt-1', - sessionKind: 'terminal', - terminalPaneKey: 'old:leaf', - terminalPtyId: 'pty-1' - } - ] - : [] + runs: [] }).catch((error) => error) expect(outcome === 'accepted-throw' ? { target: result } : result).toMatchObject({ target: { @@ -522,7 +415,7 @@ it('retains a known identity when record/host preparation cannot prove availabil ) } await expect( - launchHeadlessAutomationAgent(runtime, { + launchAutomationChatAgent(runtime, { automation: { ...automation, surface: 'chat', reuseSession: true }, run, target, @@ -574,7 +467,7 @@ it.each(['before-admission', 'accepted-reply', 'accepted-lost-reply'] as const)( return reply }) mocks.launch.mockResolvedValue(chat) - const attempt = launchHeadlessAutomationAgent(runtime, { + const attempt = launchAutomationChatAgent(runtime, { automation: { ...automation, agentId: 'codex', @@ -639,7 +532,7 @@ it.each(['unknown', 'refused', 'conflict', 'failed-row'] as const)( acceptance === 'failed-row' ? { outcome: { status: 'failed' } } : undefined ) await expect( - launchHeadlessAutomationAgent(runtime, { + launchAutomationChatAgent(runtime, { automation: { ...automation, surface: 'chat', reuseSession: true }, run, target, diff --git a/tests/e2e/helpers/automation-chat-reuse-test-harness.ts b/tests/e2e/helpers/automation-chat-reuse-test-harness.ts index 465091e74d15..80a7faf643ad 100644 --- a/tests/e2e/helpers/automation-chat-reuse-test-harness.ts +++ b/tests/e2e/helpers/automation-chat-reuse-test-harness.ts @@ -6,11 +6,7 @@ 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 { runHeadlessAutomationDispatch } from '../../../src/main/automations/headless-dispatch-runner' -import { - launchHeadlessAutomationAgent, - type AutomationAgentLaunchRequest -} from '../../../src/main/automations/headless-automation-agent-launch' +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' @@ -36,8 +32,8 @@ export type ChatReuseMode = 'normal' | 'lost-reply' | 'restart' export async function exerciseBusyChatReuse( mode: ChatReuseMode, - automation: AutomationAgentLaunchRequest['automation'], - target: AutomationAgentLaunchRequest['target'], + automation: AutomationChatLaunchRequest['automation'], + target: AutomationChatLaunchRequest['target'], controls: { setHost: (host: StructuredAgentSessionHost | null) => void openChat: Mock @@ -103,28 +99,15 @@ export async function exerciseBusyChatReuse( const runtime = { ensureStructuredAgentSessionHost: async () => {}, openAgentSessionRecordStore: async () => rig.store, + openedAgentSessionRecordStore: () => rig.store, setAutomationService: vi.fn(), notifyAutomationsChanged: vi.fn(), showManagedWorktree: async () => { throw new Error('optional display unavailable') } } as unknown as OrcaRuntimeService - const dispatched = await runHeadlessAutomationDispatch({ - automation: saved, - run: current, - target, - runs: writer, - dispatcher: () => - launchHeadlessAutomationAgent(runtime, { - automation: saved, - run: current, - target, - runs: disk.listAutomationRuns(saved.id) - }), - runPrecheck: async () => null, - markDispatchResult: writer.updateRun, - watchRun: () => {} - }) + service = createRuntimeAutomationService({ store: disk, runtime, headless: true }) + const dispatched = await service.runNow(saved.id) expect(dispatched).toMatchObject({ status: 'dispatched', sessionKind: 'chat', @@ -134,7 +117,6 @@ export async function exerciseBusyChatReuse( expect(await rig.drafts()).toEqual([{ messageId: q, state: 'waiting' }]) expect(await rig.handoff(q)).toBeUndefined() expect(send).toHaveBeenCalledOnce() - service = createRuntimeAutomationService({ store: disk, runtime, headless: true }) service.start() await eventually(() => expect(rig.host.collaboratorsForTests().sessions['observers'].size).toBe(1) diff --git a/tests/e2e/helpers/automation-terminal-inventory-test-harness.ts b/tests/e2e/helpers/automation-terminal-inventory-test-harness.ts deleted file mode 100644 index b1c157755258..000000000000 --- a/tests/e2e/helpers/automation-terminal-inventory-test-harness.ts +++ /dev/null @@ -1,119 +0,0 @@ -import type { AutomationRun } from '../../../src/shared/automations-types' -import { reconcileDesktopRunTerminals } from '../../../src/main/automations/desktop-run-terminal-reconciliation' -import { expect, vi } from 'vitest' -import type { Store } from '../../../src/main/persistence' -import type { createDesktopRunTerminalLifecycle } from '../../../src/main/automations/desktop-run-terminal-lifecycle' -import * as runNormalization from '../../../src/main/persistence/scheduling-automations/automation-context-migration' -import { compareAutomationRunsNewestFirst } from '../../../src/shared/automation-run-cursor' - -export function measureTerminalInventory( - disk: Store, - lifecycle: ReturnType, - registered: ReadonlySet -) { - const list = disk.listAutomationRuns.bind(disk) - let rows = 0, - statusVisits = 0, - linearFinds = 0, - measuring = false - const lists = vi.spyOn(disk, 'listAutomationRuns').mockImplementation((...args) => { - const result = list(...args) - if (!measuring) { - return result - } - return new Proxy(result, { - get(target, key, receiver) { - if (key === 'find') { - linearFinds++ - } - // 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. - const value = Reflect.get(target, key, receiver) - if (typeof key !== 'string' || !/^(0|[1-9][0-9]*)$/.test(key)) { - return value - } - rows++ - return new Proxy(value, { - get(run, field, rowReceiver) { - if (field === 'status') { - statusVisits++ - } - // 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(run, field, rowReceiver) - } - }) - } - }) - }) - const normalized = vi.spyOn(runNormalization, 'normalizeAutomationPrecheckResult') - const sorts = vi.spyOn(Array.prototype, 'sort') - const lookups = vi.spyOn(Map.prototype, 'get') - let inventories = 0, - normalizations = 0, - fullSorts = 0, - selectedLookups = 0 - const reconcile = lifecycle.reconcile - vi.spyOn(lifecycle, 'reconcile').mockImplementation(() => { - const before = [ - lists.mock.calls.length, - normalized.mock.calls.length, - sorts.mock.calls.length, - lookups.mock.calls.length - ] - measuring = true - try { - reconcile() - } finally { - measuring = false - } - inventories += lists.mock.calls.length - before[0] - normalizations += normalized.mock.calls.length - before[1] - fullSorts += sorts.mock.calls - .slice(before[2]) - .filter(([compare]) => compare === compareAutomationRunsNewestFirst).length - selectedLookups += lookups.mock.calls - .slice(before[3]) - .filter( - ([key], i) => - typeof key === 'string' && - registered.has(key) && - typeof lookups.mock.results[before[3] + i].value === 'string' - ).length - }) - return { - lists, - counts: () => ({ - inventories, - normalizations, - sorts: fullSorts, - rows, - statusVisits, - linearFinds, - selectedLookups - }) - } -} - -export function assertTerminalInventorySelection(run: AutomationRun): void { - const released = vi.fn(), - kept = vi.fn() - const registrations = new Map([ - ['missing', { release: released }], - ['failed', { release: released }], - ['duplicate', { release: kept }], - ...(['dispatching', 'dispatched', 'completed'] as const).map( - (status) => [status, { release: kept }] as const - ) - ]) - reconcileDesktopRunTerminals(registrations, () => [ - { ...run, id: 'duplicate', status: 'completed' }, - { ...run, id: 'duplicate', status: 'dispatch_failed' }, - { ...run, id: 'failed', status: 'dispatch_failed' }, - ...(['dispatching', 'dispatched', 'completed'] as const).map((status) => ({ - ...run, - id: status, - status - })) - ]) - expect(released).toHaveBeenCalledTimes(2) - expect(kept).not.toHaveBeenCalled() -} diff --git a/tests/e2e/helpers/automation-terminal-ownership-test-harness.ts b/tests/e2e/helpers/automation-terminal-ownership-test-harness.ts deleted file mode 100644 index 6424ed0e6c77..000000000000 --- a/tests/e2e/helpers/automation-terminal-ownership-test-harness.ts +++ /dev/null @@ -1,304 +0,0 @@ -import { EventEmitter } from 'node:events' -import type * as pty from 'node-pty' -import { expect, vi } from 'vitest' -import type { StoreApi, UseBoundStore } from 'zustand' -import type { AppState } from '../../../src/renderer/src/store/types' -import { buildProfileStateCutoverFixture } from '../../../src/main/persistence/profile-state-cutover-fixture' -import { - createTestStore, - makeTab, - makeWorktree, - seedStore -} from '../../../src/renderer/src/store/slices/store-test-helpers' -import { createStoreSessionMockApi } from '@/store/slices/store-session-test-harness' -import type { OrcaRuntimeService } from '../../../src/main/runtime/orca-runtime' -import type { Store } from '../../../src/main/persistence' -import type { PtyShutdownOptions } from '../../../src/main/providers/pty-provider-contract' -import { OrcaRuntimeWithStopExactTerminalsForWorktree } from '../../../src/main/runtime/terminal/stop/worktree-terminal-stop-targets' -import { registerTerminalPresentationIpcBridge } from '@/hooks/ipc-events/terminal-presentation-ipc-bridge' -import { registerAgentLaunchTabIpcBridge } from '@/hooks/ipc-events/agent-launch-tab-ipc-bridge' -import { createDesktopRunTerminalLifecycle } from '../../../src/main/automations/desktop-run-terminal-lifecycle' -import { - shutdownLocalPty, - createPtyPhysicalExit -} from '../../../src/main/providers/local-pty-termination' -import { - ptyProcesses, - ptyIncarnations, - ptyPhysicalExits, - clearPtyState -} from '../../../src/main/providers/local-pty-provider-state' - -export type OwnershipTestStore = UseBoundStore> - -export const OWNERSHIP_WORKSPACE_ID = 'repo1::/repo1/main' -const WT = OWNERSHIP_WORKSPACE_ID -const state = buildProfileStateCutoverFixture('/fixture') -const noop = () => {} -export function createAutomationTerminalOwnershipFixture( - mocks: { - store: OwnershipTestStore | null - ipc: EventEmitter | null - prepare: () => Promise - }, - cleanups: (() => void)[] -) { - const store: OwnershipTestStore = createTestStore() - let subscribers = 0 - const subscribe = store.subscribe - vi.spyOn(store, 'subscribe').mockImplementation((listener) => { - const release = subscribe(listener) - subscribers++ - return () => { - subscribers-- - release() - } - }) - mocks.store = store - const api = createStoreSessionMockApi() - const listeners = new EventEmitter() - const events: string[] = [] - const web = Object.assign(new EventEmitter(), { - mainFrame: {}, - isDestroyed: () => false, - send: (channel: string, payload: unknown) => { - let label = channel - if (channel === 'automations:terminalLifecycleRequest') { - if ( - typeof payload !== 'object' || - payload === null || - !('operation' in payload) || - typeof payload.operation !== 'string' - ) { - throw new Error('Lifecycle test transport requires a string operation') - } - if ('phase' in payload && typeof payload.phase !== 'string') { - throw new Error('Lifecycle test transport requires a string phase when present') - } - label = `${payload.operation}:${'phase' in payload ? payload.phase : ''}` - } - events.push(label) - listeners.emit(channel, payload) - } - }) - const win = Object.assign(new EventEmitter(), { webContents: web, isDestroyed: () => false }) - const on = (channel: string) => (listener: (...payload: unknown[]) => void) => { - listeners.on(channel, listener) - return () => { - listeners.off(channel, listener) - } - } - const session = { - set: vi.fn(async () => { - events.push('session:set') - }), - flush: vi.fn(async () => { - events.push('session:flush') - }) - } - vi.stubGlobal('window', { - dispatchEvent: vi.fn(), - api: { - ...api, - session, - automations: { - onTerminalLifecycleRequest: on('automations:terminalLifecycleRequest'), - respondTerminalLifecycle: (reply: unknown) => - mocks.ipc!.emit( - 'automations:terminalLifecycleResponse', - { sender: web, senderFrame: web.mainFrame }, - reply - ) - }, - ui: { - onLaunchRecipe: on('recipe'), - onCreateTerminal: on('ui:createTerminal'), - onRequestTerminalTabMount: on('mount'), - onPublishAgentLaunchTab: on('ui:publishAgentLaunchTab'), - onAgentLaunchPaneVerdict: on('verdict'), - replyAgentLaunchTabPublish: vi.fn(), - replyTerminalCreate: vi.fn() - } - } - }) - seedStore(store, { - worktreesByRepo: { repo1: [makeWorktree({ id: WT, repoId: 'repo1', path: '/repo1/main' })] }, - activeWorktreeId: 'other', - activeTabId: 'other-tab', - activeTabType: 'terminal', - tabsByWorktree: { [WT]: [makeTab({ id: 'sibling', worktreeId: WT, ptyId: 'setup' })] }, - ptyIdsByTabId: { sibling: ['setup'] } - }) - const unsubs: (() => void)[] = [] - registerTerminalPresentationIpcBridge(unsubs) - registerAgentLaunchTabIpcBridge(unsubs) - cleanups.push(() => unsubs.forEach((release) => release())) - // SAFETY: the sibling has a fake physical process; every exercised stop owner must leave it live. - ptyProcesses.set('setup', { - pid: 4343, - kill: () => { - throw new Error('sibling stopped') - } - } as unknown as pty.IPty) - ptyIncarnations.set('setup', 'setup') - let expectedPty = '' - let expectedPane = '' - let provenance: string | undefined - let stopFailure: 'live' | 'unproven' | null = null - const runtime = { - getAuthoritativeWindow: () => win, - getTerminalPtyIdForHandle: () => expectedPty, - getTerminalHandleForPaneKey: () => 'term-current', - getPtyExecutionHostMetadata: () => ({ incarnationId: 'original', executionHostId: 'local' }), - terminalRunFacts: { readLastDrivingInputAt: () => null }, - stopExactTerminalsForWorktree: vi.fn( - async ( - _selector: string, - ids: string[], - opts: NonNullable[2]> - ) => { - if (stopFailure) { - expect(await opts.authorizeStop!()).toBe(true) - if (stopFailure === 'unproven') { - ptyProcesses.delete(expectedPty) - throw new Error('lost reply') - } - throw new Error('still alive') - } - // Actual exact-stop owner proves the target exited while retaining the live sibling. - const inventory = new Map([ - [ids[0], { worktreeId: WT, ptyId: ids[0], connected: true, incarnationId: 'original' }], - ['setup', { worktreeId: WT, ptyId: 'setup', connected: true, incarnationId: 'setup' }] - ]) - const exact = Object.assign( - Object.create(OrcaRuntimeWithStopExactTerminalsForWorktree.prototype), - { - captureReadyGraphEpoch: noop, - assertStableReadyGraph: noop, - resolveWorktreeSelector: async () => ({ id: WT }), - getResolvedWorktreeMap: async () => new Map(), - refreshPtyWorktreeRecordsFromController: async () => - new Set([...ptyProcesses.keys(), 'setup']), - leaves: new Map(), - ptysById: inventory, - intentionalPtyStops: { mark: () => noop }, - ptyController: { - stopAndWait: async (id: string, options: PtyShutdownOptions) => { - events.push('provider:prepare') - await shutdownLocalPty(id, { ...options, immediate: true }) - events.push('provider:stopped') - return true - } - } - } - ) - return exact.stopExactTerminalsForWorktree(_selector, ids, opts) - } - ), - listTerminals: async () => ({ - terminals: [...ptyProcesses.keys()].map((ptyId) => ({ - ptyId, - connected: true, - incarnationId: 'original' - })) - }) - } - // SAFETY: transport/window and OS doubles implement the exercised runtime/store boundaries; lifecycle and local stop are real. - const lifecycle = createDesktopRunTerminalLifecycle( - runtime as unknown as OrcaRuntimeService, - { - getWorktreeMeta: () => ({ automationProvenance: { automationRunId: provenance } }), - listAutomationRuns: () => [] - } as unknown as Store, - async (_id, operation) => operation() - ) - cleanups.push(lifecycle.stop) - function bindProcess(ptyId: string, paneKey: string) { - expectedPty = ptyId - expectedPane = paneKey - // SAFETY: node-pty's destructive OS boundary is a fake; exit and exact process maps are the real owner state. - ptyProcesses.set(expectedPty, { - pid: 4242, - kill: () => { - events.push('os:exit') - ptyPhysicalExits.get(ptyId)?.markExited() - clearPtyState(ptyId) - } - } as unknown as pty.IPty) - ptyIncarnations.set(expectedPty, 'original') - createPtyPhysicalExit(expectedPty) - } - function publish( - index = 1, - preserve = true, - early = true, - saved?: (typeof state.automationRuns)[number] - ) { - const run = { - ...state.automationRuns[0], - id: `run-${index}`, - ...saved, - workspaceId: WT, - terminalPtyId: `pty-${index}`, - status: 'completed' as const - } - provenance = preserve ? run.id : undefined - const owner = lifecycle.begin( - { ...state.automations[0], reuseSession: false }, - run, - `operation-${index}` - )! - expectedPty = run.terminalPtyId - expectedPane = owner.paneKey - const [tabId, leafId] = expectedPane.split(':') - if (early) { - owner.reserve(WT) - } else { - owner.policy.onWorkspaceCreated!(WT) - } - if (early) { - web.send('ui:publishAgentLaunchTab', { - requestId: 'publish', - worktreeId: WT, - tabId, - leafId, - viewer: 'background', - launchAgent: 'codex' - }) - } - bindProcess(expectedPty, expectedPane) - owner.policy.onSurfacePublished!({ - worktreeId: WT, - outcome: { kind: 'terminal', paneKey: expectedPane, handle: 'term-original' } - } as never) - store - .getState() - .setAgentStatus( - expectedPane, - { state: 'done', prompt: 'resume', agentType: 'codex' }, - 'Codex', - { updatedAt: 2000, stateStartedAt: 1000 }, - { tabId, worktreeId: WT }, - { providerSession: { key: 'session_id', id: `session-${index}` } } - ) - return { run, owner, tabId, leafId, paneKey: expectedPane } - } - return { - store, - bindProcess, - activeSubscribers: () => subscribers, - session, - runtime, - lifecycle, - publish, - events, - web, - listeners, - prepare: (fn: () => Promise) => { - mocks.prepare = fn - }, - failStop: (kind: typeof stopFailure) => { - stopFailure = kind - } - } -} From 7b51df32cd81421c36a6813f9f306a3b8afae93d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:55:27 -0700 Subject: [PATCH 12/23] Preserve Chat automation intent while support loads --- .../AutomationSurfaceField.test.tsx | 102 ++++- ...utomationsPage.create-destination.test.tsx | 414 +++++++++++++++--- .../automations/automation-launch-surface.ts | 4 +- 3 files changed, 461 insertions(+), 59 deletions(-) diff --git a/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx index 82a202552971..c1a303168b16 100644 --- a/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx +++ b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx @@ -1,13 +1,38 @@ // @vitest-environment happy-dom -import { afterEach, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import type { AutomationDraft } from './AutomationEditorDialog' +import { AutomationEditorDialog, type AutomationDraft } from './AutomationEditorDialog' +import { makeStoreState } from './automations-page-fixtures' +import { setLocalRuntimeCapabilitiesForTests } from '@/runtime/local-runtime-capabilities' +import { + AUTOMATION_SURFACE_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY +} from '../../../../shared/protocol-version' import type { GlobalSettings } from '../../../../shared/global-settings-types' import { AutomationSurfaceField } from './AutomationSurfaceField' import { automationDraftSurface } from './automation-launch-surface' import { buildAutomationEditDraft } from './automation-edit-draft' import { buildProfileStateCutoverFixture } from '../../../../main/persistence/profile-state-cutover-fixture' +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: () => null +})) +vi.mock('./AutomationEditorDialogHeader', () => ({ AutomationEditorDialogHeader: () => null })) + +let routeState = makeStoreState().state +beforeEach(() => { + routeState = makeStoreState().state +}) +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. @@ -45,6 +70,79 @@ it('reserves disabled controls until host support is known and hides Chat on uns const props = { draft, settings, groupClassName: '', itemClassName: '', 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') + 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 dialog footer withholds an unchosen native Chat save until support resolves', () => { + 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: 'claude' as const }, + onProjectChange: vi.fn(), + onOpenChange: vi.fn(), + onDraftChange: vi.fn(), + onSetupDecisionTouched: vi.fn(), + onApplyTemplate: vi.fn(), + onSave + } + setLocalRuntimeCapabilitiesForTests(null) + const view = render() + const button = screen.getByRole('button', { name: 'Create', exact: true }) + expect(button.hasAttribute('disabled')).toBe(true) + fireEvent.click(button) + expect(onSave).not.toHaveBeenCalled() + setLocalRuntimeCapabilitiesForTests([ + AUTOMATION_SURFACE_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY + ]) + 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) +}) 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 7a16d1ba1d0e..9b6cbbe0b1e5 100644 --- a/src/renderer/src/components/automations/AutomationsPage.create-destination.test.tsx +++ b/src/renderer/src/components/automations/AutomationsPage.create-destination.test.tsx @@ -3,6 +3,17 @@ /** 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 { getDefaultSettings } from '../../../../shared/constants' +import { + AUTOMATION_SURFACE_RUNTIME_CAPABILITY, + AUTOMATION_EXTRA_AGENT_ARGS_RUNTIME_CAPABILITY, + AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY, + AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY, + AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY +} from '../../../../shared/protocol-version' +import type { HookCheckResult } from '@/runtime/runtime-hooks-client' import { describe, expect, it, vi } from 'vitest' import type { Automation } from '../../../../shared/automations-types' import { hostStableKey } from '../../../../shared/automation-owner-key' @@ -27,6 +38,34 @@ import type { Repo } from '../../../../shared/repo-types' installAutomationsPageHarness() +const CHAT_CAPABILITIES = [ + AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY, + AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY, + AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY, + AUTOMATION_SURFACE_RUNTIME_CAPABILITY, + AUTOMATION_EXTRA_AGENT_ARGS_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY +] + +function draftRecord(current: unknown): object { + if (current === null || typeof current !== 'object') { + throw new Error('Missing editor draft') + } + return current +} + +function observeRuntimeChat(capabilities: string[] | null): void { + mocks.state.runtimeStatusByEnvironmentId = new Map( + capabilities === null ? [] : [[RUNTIME_ID, { status: { capabilities } }]] + ) +} + +function capableChatDestination(): void { + observeRuntimeChat(CHAT_CAPABILITIES) + mocks.getRuntimeEnvironmentStatus.mockResolvedValue({ capabilities: CHAT_CAPABILITIES }) +} + const SSH_TARGET_ID = 'ssh-target-1' const SSH_REPO_ID = 'repo-ssh' const SSH_HOST_KEY = hostStableKey({ @@ -150,31 +189,163 @@ function createRpcCalls(): unknown[][] { } describe('AutomationsPage create destination', () => { - it('creates Terminal on the selected runtime while Chat capability observation is unavailable', async () => { + 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 } + } + 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' } } + }) + } + ) + + 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) + const page = await renderPage() + await settleHostQueries() + await openCreateDialogFor(RUNTIME_REPO_ID, RUNTIME_WORKSPACE_ID) + await act(async () => { + mocks.editorDialog?.onDraftChange((current) => ({ + ...draftRecord(current), + 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 + })) + }) + + capableChatDestination() + 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' }) + } + } + ) + + 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' })) - mocks.state.runtimeStatusByEnvironmentId = new Map() addRuntimeProject() + capableChatDestination() + mocks.state.settings = { ...getDefaultSettings('/tmp'), experimentalNativeChat: true } mocks.state.automationHostFilter = RUNTIME_SELF_FILTER - - await renderPage() - await settleHostQueries() - await openCreateDialogFor(RUNTIME_REPO_ID, RUNTIME_WORKSPACE_ID) - 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' } } - }) + 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 + }) + } }) it('refuses a desktop project for a runtime destination instead of sending its id', async () => { @@ -379,6 +550,10 @@ describe('AutomationsPage edit fencing', () => { 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]) @@ -390,6 +565,12 @@ describe('AutomationsPage edit fencing', () => { 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('refuses the save when nothing names the record’s host', async () => { @@ -456,43 +637,146 @@ describe('AutomationsPage edit destination', () => { 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 })) + 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) + }) - 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() - 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() - 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')) + } + ) - 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.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' }) @@ -579,13 +863,25 @@ describe('AutomationsPage edit destination', () => { 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' }) + 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() - runtimeCreateReturns(makeAutomation({ id: 'a-moved', projectId: RUNTIME_REPO_ID })) + 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() @@ -607,6 +903,12 @@ describe('AutomationsPage edit destination', () => { 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() diff --git a/src/renderer/src/components/automations/automation-launch-surface.ts b/src/renderer/src/components/automations/automation-launch-surface.ts index 8ba7753af7f7..d65e66ace1da 100644 --- a/src/renderer/src/components/automations/automation-launch-surface.ts +++ b/src/renderer/src/components/automations/automation-launch-surface.ts @@ -58,7 +58,9 @@ export function automationDraftSurface( ): 'chat' | 'terminal' { return ( draft.surface ?? - (chatSupported && isNativeChatDefaultFor(settings, draft.agentId) ? 'chat' : 'terminal') + (chatSupported !== false && isNativeChatDefaultFor(settings, draft.agentId) + ? 'chat' + : 'terminal') ) } From 9c4c175189dc3d771dc47d6e6b62895b277dc1ec Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 29 Oct 2026 03:37:51 -0700 Subject: [PATCH 13/23] Resolve automation Chat validation diagnostics --- .../runtime-chat-run-observer.test.ts | 26 +++++++++++-------- .../AutomationSurfaceField.test.tsx | 2 +- .../automations/AutomationSurfaceField.tsx | 2 ++ ...dless-automation-agent-launch.unit.test.ts | 19 ++++++++------ .../automation-chat-reuse-test-harness.ts | 14 +++++----- 5 files changed, 37 insertions(+), 26 deletions(-) diff --git a/src/main/automations/runtime-chat-run-observer.test.ts b/src/main/automations/runtime-chat-run-observer.test.ts index 155522e94c6b..cb04c2922db6 100644 --- a/src/main/automations/runtime-chat-run-observer.test.ts +++ b/src/main/automations/runtime-chat-run-observer.test.ts @@ -26,14 +26,17 @@ import { import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types' import { automationRunOperationId } from './automation-run-operation' -const mocks = vi.hoisted(() => ({ - actualHost: null as StructuredAgentSessionHost | null, - host: { - journalSnapshot: vi.fn(), - observeConversationPublications: vi.fn(), - queuedSendAnswer: vi.fn(async () => null) +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 })) @@ -400,8 +403,7 @@ describe('real host queue publication and operation bounds', () => { const beforeBaseline = measure() await tokenBurst() const baselineWork = difference(beforeBaseline) - // SAFETY: only receipt acquisition is a transport stand-in; the observer uses the actual host below. - const runtime = { + const runtimeFacade = { ensureStructuredAgentSessionHost: async () => {}, openAgentSessionRecordStore: async () => ({ getOperationRow: (_caller: string, id: string) => @@ -413,7 +415,9 @@ describe('real host queue publication and operation bounds', () => { location: { workspaceId: 'workspace-1' } }) }) - } as unknown as OrcaRuntimeService + } + // 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(() => {}) @@ -612,7 +616,7 @@ describe('real host queue publication and operation bounds', () => { getConversation: () => ({ provider: 'codex', location: { workspaceId: 'workspace-1' } }) }) } - // SAFETY: only receipt transport is scripted; all observation and queue lifecycle owners are real. + // 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( diff --git a/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx index c1a303168b16..6638cf2fd5c4 100644 --- a/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx +++ b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx @@ -123,7 +123,7 @@ it('the real dialog footer withholds an unchosen native Chat save until support } setLocalRuntimeCapabilitiesForTests(null) const view = render() - const button = screen.getByRole('button', { name: 'Create', exact: true }) + const button = screen.getByRole('button', { name: 'Create' }) expect(button.hasAttribute('disabled')).toBe(true) fireEvent.click(button) expect(onSave).not.toHaveBeenCalled() diff --git a/src/renderer/src/components/automations/AutomationSurfaceField.tsx b/src/renderer/src/components/automations/AutomationSurfaceField.tsx index 3b9f69329120..5fa465f90492 100644 --- a/src/renderer/src/components/automations/AutomationSurfaceField.tsx +++ b/src/renderer/src/components/automations/AutomationSurfaceField.tsx @@ -39,6 +39,7 @@ export function AutomationSurfaceField({ type="single" spacing={1} size="sm" + // oxlint-disable-next-line shadcn/require-static-classes -- Temporary: forwards the editor's existing segmented group styles unchanged; shared picker replacement tracked in #34728. className={groupClassName} value={automationDraftSurface(draft, settings, supported)} disabled={supported === null} @@ -54,6 +55,7 @@ export function AutomationSurfaceField({ aria-checked={automationDraftSurface(draft, settings, supported) === surface} key={surface} value={surface} + // oxlint-disable-next-line shadcn/require-static-classes -- Temporary: forwards the editor's existing segmented item styles unchanged; shared picker replacement tracked in #34728. className={itemClassName} disabled={surface === 'chat' && supported !== true} > diff --git a/tests/e2e/headless-automation-agent-launch.unit.test.ts b/tests/e2e/headless-automation-agent-launch.unit.test.ts index 021b1fcc010d..8c03573ea7ec 100644 --- a/tests/e2e/headless-automation-agent-launch.unit.test.ts +++ b/tests/e2e/headless-automation-agent-launch.unit.test.ts @@ -19,14 +19,17 @@ 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(() => ({ - actualHost: null as StructuredAgentSessionHost | null, - hostAvailable: true, - openChat: vi.fn(), - readChat: vi.fn().mockResolvedValue({}), - launch: vi.fn(), - host: { journalSnapshot: vi.fn(), currentWork: vi.fn(), send: vi.fn() } -})) +const mocks = vi.hoisted(() => { + const hostState: { actualHost: StructuredAgentSessionHost | null } = { actualHost: null } + return { + ...hostState, + hostAvailable: true, + openChat: vi.fn(), + 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 })) diff --git a/tests/e2e/helpers/automation-chat-reuse-test-harness.ts b/tests/e2e/helpers/automation-chat-reuse-test-harness.ts index 80a7faf643ad..78447577e2e3 100644 --- a/tests/e2e/helpers/automation-chat-reuse-test-harness.ts +++ b/tests/e2e/helpers/automation-chat-reuse-test-harness.ts @@ -95,8 +95,7 @@ export async function exerciseBusyChatReuse( } return answer }) - // SAFETY: only runtime transport/metadata is scripted; service, send, receipts, queue, writer and observer are real. - const runtime = { + const runtimeFacade = { ensureStructuredAgentSessionHost: async () => {}, openAgentSessionRecordStore: async () => rig.store, openedAgentSessionRecordStore: () => rig.store, @@ -105,7 +104,9 @@ export async function exerciseBusyChatReuse( showManagedWorktree: async () => { throw new Error('optional display unavailable') } - } as unknown as OrcaRuntimeService + } + // 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({ @@ -226,14 +227,15 @@ export async function exerciseBusyChatReuse( status: 'completed', outputSnapshot: { content: 'Exact automation output' } }) - // SAFETY: page context alone is scripted; the ordinary Details action executes. - const context = { + const pageContext = { store: { repoForRow: () => undefined, worktreeForRow: () => ({ id: saved.workspaceId, hostId: 'local' }) }, list: { selectedRow: { key: 'row' } } - } as unknown as AutomationsPageActionContext + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: selectedRow/repoForRow/worktreeForRow are scripted; the ordinary Details action and actual Chat opener execute. + const context = pageContext as unknown as AutomationsPageActionContext createAutomationRunWorkspaceAction(context)(readCurrent()) await eventually(() => expect(controls.openChat).toHaveBeenCalledWith( From ace256e787d2b1e458c44e4d8159fc968ad9fce2 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 29 Oct 2026 04:34:05 -0700 Subject: [PATCH 14/23] Remove unused automation style directives --- .../src/components/automations/AutomationSurfaceField.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/renderer/src/components/automations/AutomationSurfaceField.tsx b/src/renderer/src/components/automations/AutomationSurfaceField.tsx index 5fa465f90492..3b9f69329120 100644 --- a/src/renderer/src/components/automations/AutomationSurfaceField.tsx +++ b/src/renderer/src/components/automations/AutomationSurfaceField.tsx @@ -39,7 +39,6 @@ export function AutomationSurfaceField({ type="single" spacing={1} size="sm" - // oxlint-disable-next-line shadcn/require-static-classes -- Temporary: forwards the editor's existing segmented group styles unchanged; shared picker replacement tracked in #34728. className={groupClassName} value={automationDraftSurface(draft, settings, supported)} disabled={supported === null} @@ -55,7 +54,6 @@ export function AutomationSurfaceField({ aria-checked={automationDraftSurface(draft, settings, supported) === surface} key={surface} value={surface} - // oxlint-disable-next-line shadcn/require-static-classes -- Temporary: forwards the editor's existing segmented item styles unchanged; shared picker replacement tracked in #34728. className={itemClassName} disabled={surface === 'chat' && supported !== true} > From 2d391e4b385e37a4c38ef81f83ecae746d683fa7 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 29 Oct 2026 04:45:43 -0700 Subject: [PATCH 15/23] Make automation surface classes statically inspectable --- .../automations/AutomationEditorSettingsSidebar.tsx | 2 -- .../automations/AutomationSurfaceField.test.tsx | 11 ++--------- .../components/automations/AutomationSurfaceField.tsx | 8 ++------ 3 files changed, 4 insertions(+), 17 deletions(-) diff --git a/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.tsx b/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.tsx index 0a88618ab20c..956ff9e8aa6d 100644 --- a/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.tsx +++ b/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.tsx @@ -91,8 +91,6 @@ export function AutomationEditorSettingsSidebar({ draft={draft} settings={settings} supported={chatSupported} - groupClassName={segmentedGroupClassName} - itemClassName={segmentedItemClassName} onDraftChange={onDraftChange} /> {surface === 'terminal' ? ( diff --git a/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx index 6638cf2fd5c4..4c5ba9cba706 100644 --- a/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx +++ b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx @@ -41,14 +41,7 @@ afterEach(cleanup) it('places the current default on the right, highlights it, and preserves arguments through toggles', () => { const change = vi.fn() render( - + ) const radios = screen.getAllByRole('radio') expect(radios.map((radio) => radio.textContent)).toEqual(['Terminal', 'Chat']) @@ -67,7 +60,7 @@ it('keeps legacy automations Terminal when the current default is Chat', () => { 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, groupClassName: '', itemClassName: '', onDraftChange: vi.fn() } + 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([ diff --git a/src/renderer/src/components/automations/AutomationSurfaceField.tsx b/src/renderer/src/components/automations/AutomationSurfaceField.tsx index 3b9f69329120..4c27edecc082 100644 --- a/src/renderer/src/components/automations/AutomationSurfaceField.tsx +++ b/src/renderer/src/components/automations/AutomationSurfaceField.tsx @@ -10,15 +10,11 @@ export function AutomationSurfaceField({ draft, settings, supported, - groupClassName, - itemClassName, onDraftChange }: { draft: AutomationDraft settings: GlobalSettings | null supported: boolean | null - groupClassName: string - itemClassName: string onDraftChange: (updater: (current: AutomationDraft) => AutomationDraft) => void }): React.JSX.Element | null { if (supported === false && draft.surface !== 'chat') { @@ -39,7 +35,7 @@ export function AutomationSurfaceField({ type="single" spacing={1} size="sm" - className={groupClassName} + className="grid w-full grid-cols-2 rounded-md bg-muted p-0.5" value={automationDraftSurface(draft, settings, supported)} disabled={supported === null} onValueChange={(surface) => { @@ -54,7 +50,7 @@ export function AutomationSurfaceField({ aria-checked={automationDraftSurface(draft, settings, supported) === surface} key={surface} value={surface} - className={itemClassName} + className="h-7 rounded-sm border-0 bg-transparent shadow-none hover:bg-card/70 data-[state=on]:bg-card data-[state=on]:text-card-foreground data-[state=on]:shadow-xs" disabled={surface === 'chat' && supported !== true} > {surface === 'chat' From 1224cf64314ebf645a4def92f65ad61c6b650dd4 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 29 Oct 2026 05:06:57 -0700 Subject: [PATCH 16/23] Move automation surface styling into a toggle group variant --- .../AutomationSurfaceField.test.tsx | 43 ++++++++++++++++++- .../automations/AutomationSurfaceField.tsx | 3 +- .../src/components/ui/toggle-group.tsx | 18 +++++--- 3 files changed, 55 insertions(+), 9 deletions(-) diff --git a/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx index 4c5ba9cba706..a0b090a75329 100644 --- a/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx +++ b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx @@ -1,7 +1,13 @@ // @vitest-environment happy-dom import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { AutomationEditorDialog, type AutomationDraft } from './AutomationEditorDialog' +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 { setLocalRuntimeCapabilitiesForTests } from '@/runtime/local-runtime-capabilities' import { @@ -40,9 +46,42 @@ const draft = { agentId: 'claude', extraAgentArgs: '--model opus' } as Automatio afterEach(cleanup) it('places the current default on the right, highlights it, and preserves arguments through toggles', () => { const change = vi.fn() - render( + 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') diff --git a/src/renderer/src/components/automations/AutomationSurfaceField.tsx b/src/renderer/src/components/automations/AutomationSurfaceField.tsx index 4c27edecc082..ccad8bff5e3f 100644 --- a/src/renderer/src/components/automations/AutomationSurfaceField.tsx +++ b/src/renderer/src/components/automations/AutomationSurfaceField.tsx @@ -35,7 +35,7 @@ export function AutomationSurfaceField({ type="single" spacing={1} size="sm" - className="grid w-full grid-cols-2 rounded-md bg-muted p-0.5" + variant="segmented-card" value={automationDraftSurface(draft, settings, supported)} disabled={supported === null} onValueChange={(surface) => { @@ -50,7 +50,6 @@ export function AutomationSurfaceField({ aria-checked={automationDraftSurface(draft, settings, supported) === surface} key={surface} value={surface} - className="h-7 rounded-sm border-0 bg-transparent shadow-none hover:bg-card/70 data-[state=on]:bg-card data-[state=on]:text-card-foreground data-[state=on]:shadow-xs" disabled={surface === 'chat' && supported !== true} > {surface === 'chat' 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 ( Date: Thu, 29 Oct 2026 05:33:58 -0700 Subject: [PATCH 17/23] Correct automation launch test receipt and output fixtures --- tests/e2e/headless-automation-agent-launch.unit.test.ts | 7 ++++++- tests/e2e/helpers/automation-chat-reuse-test-harness.ts | 7 +++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/e2e/headless-automation-agent-launch.unit.test.ts b/tests/e2e/headless-automation-agent-launch.unit.test.ts index 8c03573ea7ec..077014a83831 100644 --- a/tests/e2e/headless-automation-agent-launch.unit.test.ts +++ b/tests/e2e/headless-automation-agent-launch.unit.test.ts @@ -73,7 +73,12 @@ 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: 'unsupported', detail: 'Fallback' }, + receipt: { + mode: 'terminal', + preferred: 'structured', + reason: 'structured_unsupported_on_host', + detail: 'Fallback' + }, prompt: { delivery: 'submit', outcome: 'handed-to-terminal' } } const chat: AgentLaunchResult = { diff --git a/tests/e2e/helpers/automation-chat-reuse-test-harness.ts b/tests/e2e/helpers/automation-chat-reuse-test-harness.ts index 78447577e2e3..c59fe6a56ad9 100644 --- a/tests/e2e/helpers/automation-chat-reuse-test-harness.ts +++ b/tests/e2e/helpers/automation-chat-reuse-test-harness.ts @@ -72,11 +72,18 @@ export async function exerciseBusyChatReuse( 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, From 9a4ac5bf3c1b33837eee53ebc9664cfbc99bc7ef Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 29 Oct 2026 06:33:43 -0700 Subject: [PATCH 18/23] Account for pane and prompt journal reads in delivery test --- ...ured-agent-session-append-delivery.test.ts | 80 ++++++++++++++++++- 1 file changed, 76 insertions(+), 4 deletions(-) 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 () => { From cad434492d2a8d04f7df0ae9a3ed1d5ef79e2360 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:25:26 -0700 Subject: [PATCH 19/23] Preserve admitted automation surface across save effects --- .../AutomationRunDetailsPage.test.tsx | 48 +++++- .../AutomationSurfaceField.test.tsx | 146 ++++++++++++++++-- ...utomationsPage.create-destination.test.tsx | 126 +++++++++++++-- .../AutomationsPage.edit-destination.test.tsx | 48 ++++++ .../automations/automation-launch-surface.ts | 32 +++- .../automations/automation-orca-save.ts | 14 +- .../automations/automation-run-view-state.ts | 4 +- .../automations/automation-save-action.ts | 2 +- .../automations-page-destination-fixtures.ts | 112 +++++++++++++- .../automations-page-test-harness.tsx | 3 + .../e2e/automation-save-fallback.unit.test.ts | 81 ++++++++++ 11 files changed, 572 insertions(+), 44 deletions(-) create mode 100644 tests/e2e/automation-save-fallback.unit.test.ts 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 index a0b090a75329..c68a5d627856 100644 --- a/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx +++ b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx @@ -12,14 +12,18 @@ import { makeStoreState } from './automations-page-fixtures' import { setLocalRuntimeCapabilitiesForTests } from '@/runtime/local-runtime-capabilities' import { AUTOMATION_SURFACE_RUNTIME_CAPABILITY, - STRUCTURED_AGENT_SESSION_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 { automationDraftSurface } from './automation-launch-surface' +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) })) @@ -27,13 +31,37 @@ vi.mock('@/lib/host-chat-program-acquisition', () => ({ useChatProgramFacts: () vi.mock('./AutomationEditorPromptEditor', () => ({ getAutomationPromptEditorRoot: () => null })) vi.mock('./AutomationEditorPromptSection', () => ({ AutomationEditorPromptSection: () => null })) vi.mock('./AutomationEditorSettingsSidebar', () => ({ - AutomationEditorSettingsSidebar: () => null + 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' + let routeState = makeStoreState().state beforeEach(() => { routeState = makeStoreState().state + resetHostStructuredAgentsForTests() + registryRpc.mockReset() }) afterEach(() => { setLocalRuntimeCapabilitiesForTests(null) @@ -119,6 +147,33 @@ it('rederives unknown native preference for the current agent while explicit and 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' @@ -127,7 +182,7 @@ it('rederives unknown native preference for the current agent while explicit and expect(automationDraftSurface({ ...draft, surface: 'chat' }, settings, false)).toBe('chat') }) -it('the real dialog footer withholds an unchosen native Chat save until support resolves', () => { +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] @@ -145,7 +200,7 @@ it('the real dialog footer withholds an unchosen native Chat save until support repoMap: fixtures.repoMap, worktrees: [...fixtures.worktreeMap.values()], settings, - draft: { ...newDraft, agentId: 'claude' as const }, + draft: { ...newDraft, agentId: 'pi' as const }, onProjectChange: vi.fn(), onOpenChange: vi.fn(), onDraftChange: vi.fn(), @@ -153,16 +208,19 @@ it('the real dialog footer withholds an unchosen native Chat save until support onApplyTemplate: vi.fn(), onSave } - setLocalRuntimeCapabilitiesForTests(null) + 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() - setLocalRuntimeCapabilitiesForTests([ - AUTOMATION_SURFACE_RUNTIME_CAPABILITY, - STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY + 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) @@ -178,3 +236,73 @@ it('the real dialog footer withholds an unchosen native Chat save until support 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' } + routeState.runtimeStatusByEnvironmentId = new Map([ + ['paired', { status: { runtimeId: 'A', capabilities: registeredCapabilities } }] + ]) + registryRpc.mockResolvedValue({ agents: [{ agent: 'pi', capabilities: {} }] }) + await loadHostStructuredAgents('runtime:paired', registeredCapabilities, 'A') + expect(automationChatSupport(routeState, pi, paired)).toBe(true) + routeState.runtimeStatusByEnvironmentId = new Map([ + ['paired', { status: { runtimeId: 'B', capabilities: registeredCapabilities } }] + ]) + expect(automationChatSupport(routeState, pi, paired)).toBeNull() + routeState.runtimeStatusByEnvironmentId = new Map([ + [ + 'paired', + { + status: { + 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/AutomationsPage.create-destination.test.tsx b/src/renderer/src/components/automations/AutomationsPage.create-destination.test.tsx index d0e96fd50341..e610c60d8060 100644 --- a/src/renderer/src/components/automations/AutomationsPage.create-destination.test.tsx +++ b/src/renderer/src/components/automations/AutomationsPage.create-destination.test.tsx @@ -22,6 +22,10 @@ import { settleHostQueries } from './automations-page-test-harness' import { + openCreateDialogFor, + holdRuntimeSave, + observeRuntimeIncarnation, + learnRuntimeAgents, addSshHost, addSshProject, capableChatDestination, @@ -40,22 +44,6 @@ import { makeAutomation, REPO_ID, WORKSPACE_ID } from './automations-page-fixtur installAutomationsPageHarness() -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 - })) - }) -} - describe('AutomationsPage create destination', () => { it.each(['default-off', 'explicit'] as const)( 'creates %s Terminal on the selected runtime while Chat observation is unavailable', @@ -109,12 +97,16 @@ describe('AutomationsPage create destination', () => { 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 })) @@ -139,6 +131,10 @@ describe('AutomationsPage create destination', () => { }) capableChatDestination() + if (supported) { + observeRuntimeIncarnation('A') + await learnRuntimeAgents('A', ['pi']) + } if (!supported) { observeRuntimeChat( CHAT_CAPABILITIES.filter( @@ -216,6 +212,104 @@ describe('AutomationsPage create destination', () => { } }) + 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() + } + ) + + 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-destination-fixtures') + await loadHostStructuredAgents(`runtime:${RUNTIME_ID}`, REGISTERED_CHAT_CAPABILITIES, 'B') + await held.page.rerender() + await held.release() + expect(createRpcCalls()).toHaveLength(1) + expect(createRpcCalls()[0]?.[2]).toMatchObject({ + 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 () => { // Reject desktop repo IDs before sending them to a runtime that cannot resolve them (repo_not_found). api.automations.list.mockResolvedValue([]) diff --git a/src/renderer/src/components/automations/AutomationsPage.edit-destination.test.tsx b/src/renderer/src/components/automations/AutomationsPage.edit-destination.test.tsx index f11595afb74e..0e2a68aac41b 100644 --- a/src/renderer/src/components/automations/AutomationsPage.edit-destination.test.tsx +++ b/src/renderer/src/components/automations/AutomationsPage.edit-destination.test.tsx @@ -34,6 +34,7 @@ import { 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' @@ -113,6 +114,53 @@ describe('AutomationsPage edit fencing', () => { ) }) + 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. diff --git a/src/renderer/src/components/automations/automation-launch-surface.ts b/src/renderer/src/components/automations/automation-launch-surface.ts index d65e66ace1da..8847248590f8 100644 --- a/src/renderer/src/components/automations/automation-launch-surface.ts +++ b/src/renderer/src/components/automations/automation-launch-surface.ts @@ -1,7 +1,12 @@ 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 } from '../../../../shared/automation-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 { isNativeChatDefaultFor } from '../../../../shared/structured-native-chat-launch-route' import { buildAgentLaunchRouteInput, @@ -42,13 +47,30 @@ export function automationChatSupport( workspace: ProspectiveWorkspace ): boolean | null { const input = buildAgentLaunchRouteInput(state, { agent: draft.agentId, workspace }) - if (input.hostCapabilities === null) { - return null + if ( + input.hostCapabilities !== null && + !input.hostCapabilities.includes(AUTOMATION_SURFACE_RUNTIME_CAPABILITY) + ) { + return false } - if (!input.hostCapabilities.includes(AUTOMATION_SURFACE_RUNTIME_CAPABILITY)) { + // 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 structuredAgentLaunchSupport(input).supported + return input.hostCapabilities === null + ? null + : structuredAgentLaunchSupport(input).supported + ? true + : null } export function automationDraftSurface( diff --git a/src/renderer/src/components/automations/automation-orca-save.ts b/src/renderer/src/components/automations/automation-orca-save.ts index 27d822520d5d..a74f1513ea38 100644 --- a/src/renderer/src/components/automations/automation-orca-save.ts +++ b/src/renderer/src/components/automations/automation-orca-save.ts @@ -1,7 +1,6 @@ import { automationChatSupport, automationDraftLaunchSetup, - automationDraftSurface, automationLaunchWorkspace } from './automation-launch-surface' import { toast } from 'sonner' @@ -34,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 @@ -157,15 +156,16 @@ export async function saveOrcaAutomation( currentAutomation = (reread.ok ? reread.value : null) ?? currentAutomation } - const surface = automationDraftSurface( - draft, - store.settings, + 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, 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 dfcc3d11f6e2..812906fe3bd7 100644 --- a/src/renderer/src/components/automations/automation-run-view-state.ts +++ b/src/renderer/src/components/automations/automation-run-view-state.ts @@ -69,8 +69,8 @@ export function getAutomationRunViewState({ if (run.sessionKind === 'chat' && run.chatSessionId && run.workspaceId && workspaceExists) { return { availability: 'chat', - actionLabel: 'View run', - statusLabel: 'Open run chat', + actionLabel: translate('auto.components.automations.runViewState.viewRun', 'View run'), + statusLabel: translate('auto.components.automations.runViewState.runOpen', 'Run is open'), canOpen: true } } diff --git a/src/renderer/src/components/automations/automation-save-action.ts b/src/renderer/src/components/automations/automation-save-action.ts index e7d07692977b..1d3438b99d84 100644 --- a/src/renderer/src/components/automations/automation-save-action.ts +++ b/src/renderer/src/components/automations/automation-save-action.ts @@ -119,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/automations-page-destination-fixtures.ts b/src/renderer/src/components/automations/automations-page-destination-fixtures.ts index 9f3132db6c1d..954e09819a9d 100644 --- a/src/renderer/src/components/automations/automations-page-destination-fixtures.ts +++ b/src/renderer/src/components/automations/automations-page-destination-fixtures.ts @@ -1,4 +1,8 @@ import { act } from 'react' +import { expect, vi } from 'vitest' +import type { HookCheckResult } from '@/runtime/runtime-hooks-client' +import { checkRuntimeHooks } from '@/runtime/runtime-hooks-client' +import { loadHostStructuredAgents } from '@/runtime/host-structured-agents' import type { Automation } from '../../../../shared/automations-types' import type { Repo } from '../../../../shared/repo-types' import { hostStableKey } from '../../../../shared/automation-owner-key' @@ -9,9 +13,25 @@ import { 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_CLIENT_LAUNCH_MODE_CAPABILITY, + STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' -import { mocks, RUNTIME_ID } from './automations-page-test-harness' +import { + api, + addRuntimeProject, + mocks, + renderPage, + runtimeHost, + RUNTIME_ID, + RUNTIME_REPO_ID, + RUNTIME_WORKSPACE_ID, + RUNTIME_SELF_FILTER, + scopedList, + settleHostQueries +} from './automations-page-test-harness' +import { getDefaultSettings } from '../../../../shared/constants' +import { makeAutomation } from './automations-page-fixtures' +import type { AutomationDraft } from './AutomationEditorDialog' export const CHAT_CAPABILITIES = [ LIST_HOST_SCOPE, @@ -20,7 +40,8 @@ export const CHAT_CAPABILITIES = [ 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_CLIENT_LAUNCH_MODE_CAPABILITY, + STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY ] export function draftRecord(current: unknown): object { @@ -117,3 +138,88 @@ export async function save(): Promise { 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-test-harness.tsx b/src/renderer/src/components/automations/automations-page-test-harness.tsx index 716e76c23129..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,4 @@ +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. */ @@ -74,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 @@ -397,6 +399,7 @@ export function installAutomationsPageHarness(): void { 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) 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..a3105336b808 --- /dev/null +++ b/tests/e2e/automation-save-fallback.unit.test.ts @@ -0,0 +1,81 @@ +// @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-destination-fixtures' +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, + ...input + } = AutomationCreate.parse(payload) + expect(repo).toBe(`id:${RUNTIME_REPO_ID}`) + return { automation: disk.createAutomation({ ...input, projectId: RUNTIME_REPO_ID }) } + }) + await held.page.rerender() + await held.release() + expect(createRpcCalls()).toHaveLength(1) + expect(createRpcCalls()[0]?.[2]).not.toHaveProperty('launchSetupPatch') + 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 }) + } +}) From cb6f08b1f25c0ab7f95f65410f1fcdbdde61f93e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:11:19 -0700 Subject: [PATCH 20/23] Separate automation page test actions from their lifecycle owner --- .../AutomationSurfaceField.test.tsx | 33 +++- ...utomationsPage.create-destination.test.tsx | 28 +-- .../AutomationsPage.edit-destination.test.tsx | 24 +-- .../automations-page-actions-test-harness.ts | 157 +++++++++++++++++ .../automations-page-destination-fixtures.ts | 160 +----------------- .../e2e/automation-save-fallback.unit.test.ts | 20 ++- 6 files changed, 234 insertions(+), 188 deletions(-) create mode 100644 src/renderer/src/components/automations/automations-page-actions-test-harness.ts diff --git a/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx index c68a5d627856..44b8a43ecdf9 100644 --- a/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx +++ b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx @@ -9,6 +9,9 @@ import { } 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, @@ -57,9 +60,20 @@ import { resetHostStructuredAgentsForTests } from '@/runtime/host-structured-agents' -let routeState = makeStoreState().state +function makeRouteState(): AgentLaunchRouteStore { + return { + ...makeStoreState().state, + projects: [], + activeRepoId: null, + activeWorktreeId: null, + settings: getDefaultSettings('/tmp'), + runtimeStatusByEnvironmentId: new Map() + } +} + +let routeState = makeRouteState() beforeEach(() => { - routeState = makeStoreState().state + routeState = makeRouteState() resetHostStructuredAgentsForTests() registryRpc.mockReset() }) @@ -281,21 +295,32 @@ it('observes only established current-runtime facts and retains independent defi 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', { status: { runtimeId: 'A', capabilities: registeredCapabilities } }] + ['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', { status: { runtimeId: 'B', capabilities: registeredCapabilities } }] + ['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 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 e610c60d8060..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 { 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 { addRuntimeProject, api, @@ -22,21 +17,28 @@ import { settleHostQueries } from './automations-page-test-harness' import { - openCreateDialogFor, + CHAT_CAPABILITIES, + createRpcCalls, + draftRecord, holdRuntimeSave, - observeRuntimeIncarnation, 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, - CHAT_CAPABILITIES, - createRpcCalls, DESKTOP_SELF_KEY, - draftRecord, observeRuntimeChat, - runtimeCreateReturns, RUNTIME_SELF_KEY, - save, SSH_HOST_KEY, SSH_REPO_ID } from './automations-page-destination-fixtures' @@ -294,7 +296,7 @@ describe('AutomationsPage create destination', () => { return await previous?.(target, method, params, options) }) const { loadHostStructuredAgents } = await import('@/runtime/host-structured-agents') - const { REGISTERED_CHAT_CAPABILITIES } = await import('./automations-page-destination-fixtures') + 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() diff --git a/src/renderer/src/components/automations/AutomationsPage.edit-destination.test.tsx b/src/renderer/src/components/automations/AutomationsPage.edit-destination.test.tsx index 0e2a68aac41b..ac7bbdd60ea3 100644 --- a/src/renderer/src/components/automations/AutomationsPage.edit-destination.test.tsx +++ b/src/renderer/src/components/automations/AutomationsPage.edit-destination.test.tsx @@ -1,11 +1,5 @@ // @vitest-environment happy-dom -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 { addRuntimeProject, api, @@ -20,16 +14,24 @@ import { settleHostQueries } from './automations-page-test-harness' import { - addSshHost, - addSshProject, - capableChatDestination, CHAT_CAPABILITIES, createRpcCalls, - DESKTOP_SELF_KEY, 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, - save, SSH_HOST_KEY, SSH_REPO_ID, SSH_TARGET_ID 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 index 954e09819a9d..9cca5aa784ea 100644 --- a/src/renderer/src/components/automations/automations-page-destination-fixtures.ts +++ b/src/renderer/src/components/automations/automations-page-destination-fixtures.ts @@ -1,55 +1,7 @@ -import { act } from 'react' -import { expect, vi } from 'vitest' -import type { HookCheckResult } from '@/runtime/runtime-hooks-client' -import { checkRuntimeHooks } from '@/runtime/runtime-hooks-client' -import { loadHostStructuredAgents } from '@/runtime/host-structured-agents' -import type { Automation } from '../../../../shared/automations-types' +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' -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 { - api, - addRuntimeProject, - mocks, - renderPage, - runtimeHost, - RUNTIME_ID, - RUNTIME_REPO_ID, - RUNTIME_WORKSPACE_ID, - RUNTIME_SELF_FILTER, - scopedList, - settleHostQueries -} from './automations-page-test-harness' -import { getDefaultSettings } from '../../../../shared/constants' -import { makeAutomation } from './automations-page-fixtures' -import type { AutomationDraft } from './AutomationEditorDialog' - -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 -} export function observeRuntimeChat(capabilities: string[] | null): void { mocks.state.runtimeStatusByEnvironmentId = new Map( @@ -115,111 +67,3 @@ export function addSshProject(): void { } ] } - -/** 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/tests/e2e/automation-save-fallback.unit.test.ts b/tests/e2e/automation-save-fallback.unit.test.ts index a3105336b808..7dfb8fae889c 100644 --- a/tests/e2e/automation-save-fallback.unit.test.ts +++ b/tests/e2e/automation-save-fallback.unit.test.ts @@ -10,7 +10,7 @@ import { holdRuntimeSave, observeRuntimeIncarnation, REGISTERED_CHAT_CAPABILITIES -} from '../../src/renderer/src/components/automations/automations-page-destination-fixtures' +} from '../../src/renderer/src/components/automations/automations-page-actions-test-harness' import { closeTestStores, createStore, @@ -53,15 +53,31 @@ it('settles the actual implicit late-false save with real final-store refusal of repo, workspace: _workspace, destination: _destination, + workspaceMode, + timezone, ...input } = AutomationCreate.parse(payload) expect(repo).toBe(`id:${RUNTIME_REPO_ID}`) - return { automation: disk.createAutomation({ ...input, projectId: 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) From 2ea2e05afef68ad03bdc2b1fdc5ace33825b9dc0 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:44:14 -0700 Subject: [PATCH 21/23] Complete automation route test fixture input --- .../src/components/automations/AutomationSurfaceField.test.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx index 44b8a43ecdf9..88f1d1162d04 100644 --- a/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx +++ b/src/renderer/src/components/automations/AutomationSurfaceField.test.tsx @@ -64,6 +64,8 @@ function makeRouteState(): AgentLaunchRouteStore { return { ...makeStoreState().state, projects: [], + projectGroups: [], + folderWorkspaces: [], activeRepoId: null, activeWorktreeId: null, settings: getDefaultSettings('/tmp'), From c5f3c9493c977a822094fef26fd563afa1cfde35 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 30 Oct 2026 01:26:13 -0700 Subject: [PATCH 22/23] Reopen saved automation chats through the existing record owner --- ...run-workspace-action.paired-server.test.ts | 98 ++++++-- .../automation-run-workspace-action.ts | 44 ++-- .../ai-vault-original-pane-actions.test.ts | 40 ++- .../ai-vault-session-launch-actions.test.ts | 75 +++++- ...e-ai-vault-structured-session-host.test.ts | 107 ++++++++ ...ai-vault-structured-session-reveal.test.ts | 35 ++- .../activate-ai-vault-structured-session.ts | 234 +++--------------- .../lib/open-existing-structured-session.ts | 221 +++++++++++++++++ tests/e2e/automation-chat-reopen.unit.test.ts | 109 ++++++++ ...dless-automation-agent-launch.unit.test.ts | 43 +++- .../automation-chat-renderer-test-harness.ts | 169 +++++++++++++ .../automation-chat-reopen-test-harness.ts | 158 ++++++++++++ .../automation-chat-reuse-test-harness.ts | 38 +-- 13 files changed, 1086 insertions(+), 285 deletions(-) create mode 100644 src/renderer/src/lib/open-existing-structured-session.ts create mode 100644 tests/e2e/automation-chat-reopen.unit.test.ts create mode 100644 tests/e2e/helpers/automation-chat-renderer-test-harness.ts create mode 100644 tests/e2e/helpers/automation-chat-reopen-test-harness.ts 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 73948da0b5de..544edac41454 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,15 +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 { 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, - openChat: vi.fn(), - readChat: vi.fn(async () => ({})), + chatTabs, + activateTab: vi.fn(), + rpc: vi.fn(), toastError: vi.fn(), toastMessage: vi.fn(), activateAndRevealWorktree: vi.fn(() => true), @@ -18,11 +22,9 @@ const mocks = vi.hoisted(() => { } }) -vi.mock('@/runtime/structured-agent-session-client', () => ({ - callStructuredAgentSession: mocks.readChat -})) -vi.mock('@/lib/structured-agent-session-launch-surface', () => ({ - openStructuredAgentSessionProvisionalTab: mocks.openChat +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 } })) @@ -90,7 +92,9 @@ function storeState(mirrored: boolean): Record { } : {}, ptyIdsByTabId: mirrored ? { [MIRRORED_TAB]: [MIRRORED_PTY] } : {}, - unifiedTabsByWorktree: {}, + unifiedTabsByWorktree: { [WT]: mocks.chatTabs }, + activateTab: mocks.activateTab, + focusGroup: vi.fn(), groupsByWorktree: {}, activeGroupIdByWorktree: {}, setTabLayout: vi.fn(), @@ -108,11 +112,26 @@ 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', + 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) @@ -177,24 +196,20 @@ it('opens the recorded Chat on its owning paired server without creating a sessi terminalPtyId: null }) await vi.waitFor(() => - expect(mocks.openChat).toHaveBeenCalledWith({ - worktreeId: WT, - executionHostId: `runtime:${ENV}`, - sessionId: 'codex_recorded_chat', - agent: 'codex' - }) + expect(mocks.activateTab).toHaveBeenCalledWith('recorded-chat', { worktreeId: WT }) ) - expect(mocks.readChat).toHaveBeenCalledWith( + expect(mocks.rpc).toHaveBeenCalledWith( { kind: 'environment', environmentId: ENV }, - 'agentSession.history', - { sessionId: 'codex_recorded_chat', direction: 'tail', limit: 1 } + '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.openChat.mockClear() + mocks.activateTab.mockClear() Object.assign(mocks.state, storeState(false)) - mocks.readChat.mockRejectedValueOnce(new Error('gone')) + 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 }, @@ -211,14 +226,14 @@ it('keeps Run Details output and opens the workspace when the recorded chat is g await vi.waitFor(() => expect(mocks.toastMessage).toHaveBeenCalledWith(expect.stringContaining('saved output remains')) ) - expect(mocks.openChat).not.toHaveBeenCalled() + 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.openChat.mockClear() + mocks.activateTab.mockClear() mocks.activateWebRuntimeSessionTab.mockClear() const failed = { ...run, @@ -237,9 +252,42 @@ it.each(['terminal', 'chat'] as const)( openRun(failed) await vi.waitFor(() => expect( - kind === 'chat' ? mocks.openChat : mocks.activateWebRuntimeSessionTab + 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', + 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 b5e518dfb242..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,6 +1,4 @@ -import { callStructuredAgentSession } from '@/runtime/structured-agent-session-client' -import { openStructuredAgentSessionProvisionalTab } from '@/lib/structured-agent-session-launch-surface' -import type { TuiAgent } from '../../../../shared/tui-agent' +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' @@ -63,7 +61,7 @@ export function createAutomationRunWorkspaceAction({ store, list }: AutomationsP toast.error(workspaceUnavailableMessage()) return } - void openRunChat(run.workspaceId, run.chatSessionId, agent, ownerEnvironmentId) + void openRunChat(run.workspaceId, run.chatSessionId, ownerEnvironmentId) return } const paneRef = parsePaneKey(run.terminalPaneKey ?? '') @@ -103,31 +101,35 @@ export function createAutomationRunWorkspaceAction({ store, list }: AutomationsP async function openRunChat( worktreeId: string, sessionId: string, - agent: TuiAgent, environmentId: string | null ): Promise { try { - await callStructuredAgentSession( - environmentId ? { kind: 'environment', environmentId } : { kind: 'local' }, - 'agentSession.history', - { sessionId, direction: 'tail', limit: 1 } + await openExistingStructuredSession( + { workspaceId: worktreeId, sessionId }, + { + target: environmentId ? { kind: 'environment', environmentId } : { kind: 'local' }, + present: (outcome) => { + if (outcome !== 'activated') { + runChatUnavailable() + } + }, + onError: runChatUnavailable + } ) - openStructuredAgentSessionProvisionalTab({ - worktreeId, - executionHostId: environmentId ? `runtime:${environmentId}` : 'local', - sessionId, - agent - }) } catch { - toast.message( - translate( - 'components.automations.runChatUnavailable', - 'Run chat is unavailable. Showing its workspace; any saved output remains in Run Details.' - ) - ) + // 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/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..b9c66a38e4a2 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 type { AiVaultSession } from '../../../../shared/ai-vault-types' import { renderHook } from '@testing-library/react' import { 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', () => { @@ -83,3 +86,36 @@ 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.activateAndRevealWorkspace.mockClear() + 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..cbef2d2b6955 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,6 +1,9 @@ +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 { render, fireEvent, renderHook, waitFor } from '@testing-library/react' import { 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 } })) @@ -246,3 +254,68 @@ 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.toastError.mockClear() + mocks.launchAiVaultSessionInNewTab.mockClear() + 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)) + 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() + rect.mockRestore() + } +}) diff --git a/src/renderer/src/lib/activate-ai-vault-structured-session-host.test.ts b/src/renderer/src/lib/activate-ai-vault-structured-session-host.test.ts index 27b001732e45..b78d101534fd 100644 --- a/src/renderer/src/lib/activate-ai-vault-structured-session-host.test.ts +++ b/src/renderer/src/lib/activate-ai-vault-structured-session-host.test.ts @@ -4,6 +4,8 @@ import type { Tab } from '../../../shared/tab-types' const mocks = vi.hoisted(() => { 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/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/headless-automation-agent-launch.unit.test.ts b/tests/e2e/headless-automation-agent-launch.unit.test.ts index 077014a83831..7a5485f05694 100644 --- a/tests/e2e/headless-automation-agent-launch.unit.test.ts +++ b/tests/e2e/headless-automation-agent-launch.unit.test.ts @@ -1,3 +1,5 @@ +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 { @@ -20,11 +22,13 @@ import { buildProfileStateCutoverFixture } from '../../src/main/persistence/prof import { launchAutomationChatAgent } from '../../src/main/automations/automation-chat-agent-launch' const mocks = vi.hoisted(() => { - const hostState: { actualHost: StructuredAgentSessionHost | null } = { actualHost: null } + const hostState: { + actualHost: StructuredAgentSessionHost | null + renderer: Awaited> | null + } = { actualHost: null, renderer: null } return { ...hostState, hostAvailable: true, - openChat: vi.fn(), readChat: vi.fn().mockResolvedValue({}), launch: vi.fn(), host: { journalSnapshot: vi.fn(), currentWork: vi.fn(), send: vi.fn() } @@ -40,20 +44,31 @@ vi.mock('@/runtime/structured-agent-session-client', () => ({ callStructuredAgentSession: (...args: Parameters) => mocks.readChat(...args) })) -vi.mock('@/lib/structured-agent-session-launch-surface', () => ({ - openStructuredAgentSessionProvisionalTab: (...args: unknown[]) => mocks.openChat(...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: () => ({ - settings: {}, - repos: [], - worktreesByRepo: {}, - getTab: () => undefined, - terminalLayoutsByTabId: {}, - ptyIdsByTabId: {} - }) + getState: () => + mocks.renderer?.store.getState() ?? { + settings: {}, + repos: [], + worktreesByRepo: {}, + getTab: () => undefined, + terminalLayoutsByTabId: {}, + ptyIdsByTabId: {} + } } })) vi.mock('sonner', () => ({ toast: { error: vi.fn(), message: vi.fn() } })) @@ -385,7 +400,9 @@ it.each(['normal', 'lost-reply', 'restart'] as const)( setHost: (host) => { mocks.actualHost = host }, - openChat: mocks.openChat, + bindRenderer: (renderer) => { + mocks.renderer = renderer + }, launch: mocks.launch }) ) 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 index c59fe6a56ad9..0450dc6ca3e9 100644 --- a/tests/e2e/helpers/automation-chat-reuse-test-harness.ts +++ b/tests/e2e/helpers/automation-chat-reuse-test-harness.ts @@ -1,3 +1,8 @@ +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' @@ -25,8 +30,6 @@ import { testState, readPersistedStateJson } from '../../../src/main/persistence/persistence-test-harness' -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' export type ChatReuseMode = 'normal' | 'lost-reply' | 'restart' @@ -36,7 +39,7 @@ export async function exerciseBusyChatReuse( target: AutomationChatLaunchRequest['target'], controls: { setHost: (host: StructuredAgentSessionHost | null) => void - openChat: Mock + bindRenderer: (renderer: Awaited> | null) => void launch: Mock } ): Promise { @@ -234,21 +237,22 @@ export async function exerciseBusyChatReuse( status: 'completed', outputSnapshot: { content: 'Exact automation output' } }) - const pageContext = { - store: { - repoForRow: () => undefined, - worktreeForRow: () => ({ id: saved.workspaceId, hostId: 'local' }) - }, - list: { selectedRow: { key: 'row' } } + 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) } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: selectedRow/repoForRow/worktreeForRow are scripted; the ordinary Details action and actual Chat opener execute. - const context = pageContext as unknown as AutomationsPageActionContext - createAutomationRunWorkspaceAction(context)(readCurrent()) - await eventually(() => - expect(controls.openChat).toHaveBeenCalledWith( - expect.objectContaining({ sessionId: sessionId, agent: 'codex' }) - ) - ) + 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() From 72fe71a8832d598c52b9e26c886ab5dcd0d2aa91 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 30 Oct 2026 03:02:33 -0700 Subject: [PATCH 23/23] test: isolate session action fixtures and complete tab groups --- .../agent-session-journal/journal-store.ts | 35 +++---- ...run-workspace-action.paired-server.test.ts | 22 ++++- .../ai-vault-original-pane-actions.test.ts | 19 ++-- .../ai-vault-session-launch-actions.test.ts | 95 ++++++++++--------- 4 files changed, 94 insertions(+), 77 deletions(-) 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 3fbb0c82b428..53432c789e29 100644 --- a/src/main/native-chat/agent-session-journal/journal-store.ts +++ b/src/main/native-chat/agent-session-journal/journal-store.ts @@ -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'] @@ -270,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( @@ -338,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 { @@ -375,7 +370,7 @@ export class AgentSessionJournal { } replaceEpochItems( - ...args: Parameters + ...args: Parameters ): Promise { return this.epochController.replace(...args) } 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 544edac41454..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,6 +1,6 @@ /** 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 { makeUnifiedTab } from '@/store/slices/store-test-helpers' +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' @@ -43,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) @@ -95,8 +96,20 @@ function storeState(mirrored: boolean): Record { unifiedTabsByWorktree: { [WT]: mocks.chatTabs }, activateTab: mocks.activateTab, focusGroup: vi.fn(), - groupsByWorktree: {}, - activeGroupIdByWorktree: {}, + 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() @@ -120,6 +133,7 @@ beforeEach(() => { mocks.chatTabs.push( makeUnifiedTab({ id: 'recorded-chat', + groupId: GROUP, entityId: params.sessionId, worktreeId: WT, executionHostId: `runtime:${ENV}`, @@ -198,6 +212,7 @@ it('opens the recorded Chat on its owning paired server without creating a sessi 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', @@ -264,6 +279,7 @@ it('presents one automation fallback when duplicate exact activation clicks reje mocks.chatTabs.push( makeUnifiedTab({ id: 'recorded-chat', + groupId: GROUP, entityId: 'claude_published', worktreeId: WT, executionHostId: `runtime:${ENV}`, 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 b9c66a38e4a2..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,7 +1,7 @@ // @vitest-environment happy-dom import type { AiVaultSession } from '../../../../shared/ai-vault-types' -import { renderHook } from '@testing-library/react' -import { beforeEach, describe, expect, it, vi } from 'vitest' +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), @@ -47,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()) @@ -111,7 +115,6 @@ it('keeps the original-pane handled boolean used by the History dialog close cal subagent: null, structuredSession: { workspaceId: 'workspace', sessionId: 'claude_saved' } } - mocks.activateAndRevealWorkspace.mockClear() mocks.findStructured.mockReturnValue({}) mocks.structured.mockResolvedValue(true) const { result } = renderHook(() => useAiVaultOriginalPaneActions()) 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 cbef2d2b6955..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 @@ -3,8 +3,8 @@ 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 { render, fireEvent, 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' @@ -107,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'], @@ -238,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" @@ -265,8 +267,6 @@ it('intercepts an ordinary structured Resume and actual pane drop on handled ref projectGroups: [], unifiedTabsByWorktree: {} }) - mocks.toastError.mockClear() - mocks.launchAiVaultSessionInNewTab.mockClear() mocks.rpc.mockImplementation(async (_target, method) => { if (method === 'session.tabs.list') { throw new Error('advisory inventory unavailable') @@ -283,39 +283,42 @@ it('intercepts an ordinary structured Resume and actual pane drop on handled ref const rect = vi .spyOn(HTMLElement.prototype, 'getBoundingClientRect') .mockReturnValue(new DOMRect(0, 0, 100, 100)) - 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 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() } - 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() rect.mockRestore() } })