diff --git a/skills/orca-cli/SKILL.md b/skills/orca-cli/SKILL.md index 9474e3d19..8bf298804 100644 --- a/skills/orca-cli/SKILL.md +++ b/skills/orca-cli/SKILL.md @@ -174,7 +174,8 @@ orca automations list --json orca automations show --json orca automations create --name "Daily review" --trigger daily --time 09:00 --prompt "Review open changes" --provider codex --repo id: --json orca automations create --name "Weekday triage" --trigger "0 9 * * 1-5" --prompt "Triage issues" --provider claude --repo path:/abs/repo --disabled --json -orca automations edit --name "Weekday review" --trigger weekdays --time 09:30 --json +orca automations create --name "Inbox digest" --trigger hourly --prompt "Summarize unread mail" --provider codex --workspace active --reuse-session --json +orca automations edit --name "Weekday review" --trigger weekdays --time 09:30 --fresh-session --json orca automations run --json orca automations runs --id --json orca automations remove --json @@ -184,6 +185,8 @@ Automation schedules accept `hourly`, `daily`, `weekdays`, `weekly`, a 5-field c Use `--repo ` for a new worktree per run, or `--workspace ` / `--workspace-mode existing` when the automation should run in an existing Orca worktree. `--repo` and `--workspace` are mutually exclusive. +Use `--reuse-session` only for existing-workspace automations when later runs should submit into the previous live automation terminal. Use `--fresh-session` to turn reuse back off. If the previous live terminal is gone, Orca falls back to a fresh session. + Why: automations are persisted through the running Orca runtime, so use the CLI instead of editing automation storage files directly. Prefer `--disabled` when creating an automation during tests or setup so it cannot run before the user reviews it. ### Terminal diff --git a/src/cli/format.ts b/src/cli/format.ts index e40a22906..1ce69469d 100644 --- a/src/cli/format.ts +++ b/src/cli/format.ts @@ -310,6 +310,7 @@ export function formatAutomationShow(result: { automation: Automation }): string `workspaceMode: ${automation.workspaceMode}`, `workspaceId: ${automation.workspaceId ?? 'null'}`, `baseBranch: ${automation.baseBranch ?? 'null'}`, + `reuseSession: ${automation.reuseSession}`, `target: ${automation.executionTargetType}:${automation.executionTargetId}`, `prompt: ${automation.prompt}` ].join('\n') diff --git a/src/cli/handlers/automations.ts b/src/cli/handlers/automations.ts index f5c0fcfc0..8c7ec60d3 100644 --- a/src/cli/handlers/automations.ts +++ b/src/cli/handlers/automations.ts @@ -208,6 +208,32 @@ function getEnabledFlag(flags: Map): boolean | undefin return undefined } +function getReuseSessionFlag(flags: Map): boolean | undefined { + const reuseFlag = flags.get('reuse-session') + const freshFlag = flags.get('fresh-session') + if (typeof reuseFlag === 'string') { + throw new RuntimeClientError('invalid_argument', '--reuse-session does not take a value') + } + if (typeof freshFlag === 'string') { + throw new RuntimeClientError('invalid_argument', '--fresh-session does not take a value') + } + const reuse = reuseFlag === true + const fresh = freshFlag === true + if (reuse && fresh) { + throw new RuntimeClientError( + 'invalid_argument', + 'Use either --reuse-session or --fresh-session, not both.' + ) + } + if (reuse) { + return true + } + if (fresh) { + return false + } + return undefined +} + function getWorkspaceModeFlag( flags: Map ): 'existing' | 'new_per_run' | undefined { @@ -290,6 +316,7 @@ export const AUTOMATION_HANDLERS: Record = { workspace: target.workspace, workspaceMode, baseBranch: getOptionalStringFlag(flags, 'base-branch'), + reuseSession: getReuseSessionFlag(flags), timezone: getOptionalStringFlag(flags, 'timezone'), enabled: getEnabledFlag(flags), missedRunGraceMinutes: getOptionalPositiveIntegerFlag(flags, 'missed-run-grace-minutes'), @@ -310,6 +337,7 @@ export const AUTOMATION_HANDLERS: Record = { workspace: target.workspace, workspaceMode: getWorkspaceModeFlag(flags), baseBranch: getOptionalStringFlag(flags, 'base-branch'), + reuseSession: getReuseSessionFlag(flags), timezone: getOptionalStringFlag(flags, 'timezone'), enabled: getEnabledFlag(flags), missedRunGraceMinutes: getOptionalPositiveIntegerFlag(flags, 'missed-run-grace-minutes'), diff --git a/src/cli/help.ts b/src/cli/help.ts index 0de9f17f4..2a2c80793 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -386,6 +386,9 @@ export function formatFlagHelp(flag: string): string { timezone: '--timezone IANA timezone for the automation', enabled: '--enabled Enable the automation', disabled: '--disabled Disable the automation', + 'reuse-session': + '--reuse-session Reuse the previous live session for existing-workspace runs', + 'fresh-session': '--fresh-session Disable session reuse for future runs', 'workspace-mode': '--workspace-mode existing or new-per-run', 'missed-run-grace-minutes': '--missed-run-grace-minutes Missed-run grace window', 'value-stdin': '--value-stdin Read set-value payload from stdin', diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index f6a85c94b..6349d5648 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1498,6 +1498,7 @@ describe('orca cli worktree awareness', () => { workspace: `path:${path.resolve('/tmp/repo/feature')}`, workspaceMode: 'existing', baseBranch: undefined, + reuseSession: undefined, timezone: undefined, enabled: undefined, missedRunGraceMinutes: undefined, @@ -1672,6 +1673,71 @@ describe('orca cli worktree awareness', () => { process.exitCode = priorExitCode }) + it('passes automation session reuse flags through create and edit', async () => { + queueFixtures( + callMock, + worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo', 'abc', 'repo-1')]), + okFixture('req_create', { automation: { id: 'auto-1', name: 'Daily review' } }), + okFixture('req_edit', { automation: { id: 'auto-1', name: 'Daily review' } }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main( + [ + 'automations', + 'create', + '--name', + 'Daily review', + '--trigger', + 'daily', + '--prompt', + 'Review open changes', + '--provider', + 'codex', + '--workspace', + 'current', + '--reuse-session', + '--json' + ], + '/tmp/repo/feature/src' + ) + await main(['automations', 'edit', 'auto-1', '--fresh-session', '--json'], '/tmp/repo') + + expect(callMock).toHaveBeenNthCalledWith(1, 'worktree.list', { limit: 10_000 }) + expect(callMock).toHaveBeenNthCalledWith( + 2, + 'automation.create', + expect.objectContaining({ + workspace: `path:${path.resolve('/tmp/repo/feature')}`, + workspaceMode: 'existing', + reuseSession: true + }) + ) + expect(callMock).toHaveBeenNthCalledWith(3, 'automation.update', { + id: 'auto-1', + updates: expect.objectContaining({ reuseSession: false }) + }) + }) + + it('rejects conflicting automation session reuse flags', async () => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const priorExitCode = process.exitCode + + await main( + ['automations', 'edit', 'auto-1', '--reuse-session', '--fresh-session', '--json'], + '/tmp/repo' + ) + + expect(callMock).not.toHaveBeenCalled() + expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain( + 'Use either --reuse-session or --fresh-session, not both.' + ) + expect(process.exitCode).toBe(1) + + process.exitCode = priorExitCode + }) + it('rejects automation edit with both repo and workspace targets', async () => { const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) @@ -1804,6 +1870,7 @@ describe('orca cli worktree awareness', () => { workspace: `path:${path.resolve('/tmp/repo/feature')}`, workspaceMode: undefined, baseBranch: undefined, + reuseSession: undefined, timezone: undefined, enabled: true, missedRunGraceMinutes: undefined diff --git a/src/cli/specs/automations.ts b/src/cli/specs/automations.ts index 5f71d137f..250329427 100644 --- a/src/cli/specs/automations.ts +++ b/src/cli/specs/automations.ts @@ -3,7 +3,13 @@ import { GLOBAL_FLAGS } from '../args' const AUTOMATION_TARGET_FLAGS = ['repo', 'workspace', 'workspace-mode', 'base-branch'] const AUTOMATION_SCHEDULE_FLAGS = ['trigger', 'schedule', 'time', 'day', 'timezone'] -const AUTOMATION_STATE_FLAGS = ['enabled', 'disabled', 'missed-run-grace-minutes'] +const AUTOMATION_STATE_FLAGS = [ + 'enabled', + 'disabled', + 'missed-run-grace-minutes', + 'reuse-session', + 'fresh-session' +] export const AUTOMATION_COMMAND_SPECS: CommandSpec[] = [ { @@ -38,7 +44,8 @@ export const AUTOMATION_COMMAND_SPECS: CommandSpec[] = [ notes: [ 'Trigger accepts hourly, daily, weekdays, weekly, a 5-field cron expression, or an RRULE string.', 'When --repo is omitted, the CLI uses the enclosing Orca worktree when one can be resolved from cwd.', - 'Use --workspace to run in an existing worktree; otherwise the automation creates a new worktree per run.' + 'Use --workspace to run in an existing worktree; otherwise the automation creates a new worktree per run.', + 'Use --reuse-session only with existing-workspace automations to submit later runs to the previous live automation session when it is still available. Use --fresh-session to disable reuse.' ], examples: [ 'orca automations create --name "Daily review" --trigger daily --prompt "Review open changes" --provider codex', diff --git a/src/main/persistence.test.ts b/src/main/persistence.test.ts index b3f837580..ac4b7ffd4 100644 --- a/src/main/persistence.test.ts +++ b/src/main/persistence.test.ts @@ -457,6 +457,47 @@ describe('Store', () => { expect(persisted.automations[0].baseBranch).toBeNull() }) + it('persists session reuse only for existing-workspace automations', async () => { + const store = await createStore() + store.addRepo(makeRepo()) + + const existingWorkspace = store.createAutomation({ + name: 'Digest', + prompt: 'Summarize changes', + agentId: 'claude', + projectId: 'r1', + workspaceMode: 'existing', + workspaceId: 'wt1', + reuseSession: true, + timezone: 'UTC', + rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', + dtstart: new Date('2026-05-13T00:00:00Z').getTime() + }) + const newPerRun = store.createAutomation({ + name: 'Fresh', + prompt: 'Run checks', + agentId: 'claude', + projectId: 'r1', + workspaceMode: 'new_per_run', + reuseSession: true, + timezone: 'UTC', + rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', + dtstart: new Date('2026-05-13T00:00:00Z').getTime() + }) + + expect(existingWorkspace.reuseSession).toBe(true) + expect(newPerRun.reuseSession).toBe(false) + expect( + store.updateAutomation(existingWorkspace.id, { workspaceMode: 'new_per_run' }).reuseSession + ).toBe(false) + + const persisted = readDataFile() as { automations: Record[] } + delete persisted.automations[0].reuseSession + writeDataFile(persisted) + const reloaded = await createStore() + expect(reloaded.listAutomations()[0].reuseSession).toBe(false) + }) + it('numbers automation run titles per automation', async () => { const store = await createStore() store.addRepo(makeRepo()) diff --git a/src/main/persistence.ts b/src/main/persistence.ts index f093f5151..8f5e4a1f2 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -209,6 +209,13 @@ function normalizeAutomationRunOutputSnapshot( } } +function normalizeAutomationSessionReuse(automation: Automation): Automation { + return { + ...automation, + reuseSession: automation.workspaceMode === 'existing' && automation.reuseSession === true + } +} + // Why: old persisted targets predate configHost. Default to label-based lookup // so imported SSH aliases keep resolving through ssh -G after upgrade. function normalizeSshTarget(t: SshTarget): SshTarget { @@ -1834,9 +1841,9 @@ export class Store { // ── Automations ─────────────────────────────────────────────────── listAutomations(): Automation[] { - return [...(this.state.automations ?? [])].sort((left, right) => - left.name.localeCompare(right.name) - ) + return (this.state.automations ?? []) + .map((automation) => normalizeAutomationSessionReuse(automation)) + .sort((left, right) => left.name.localeCompare(right.name)) } listAutomationRuns(automationId?: string): AutomationRun[] { @@ -1862,6 +1869,7 @@ export class Store { workspaceMode: input.workspaceMode, workspaceId: input.workspaceMode === 'existing' ? (input.workspaceId ?? null) : null, baseBranch: input.workspaceMode === 'new_per_run' ? (input.baseBranch ?? null) : null, + reuseSession: input.workspaceMode === 'existing' ? (input.reuseSession ?? false) : false, timezone: input.timezone, rrule: input.rrule, dtstart: input.dtstart, @@ -1912,6 +1920,10 @@ export class Store { ? (updates.baseBranch ?? null) : (current.baseBranch ?? null) : null, + reuseSession: + workspaceMode === 'existing' + ? (updates.reuseSession ?? current.reuseSession ?? false) + : false, rrule, dtstart, nextRunAt: scheduleChanged diff --git a/src/main/runtime/orca-runtime-automations.test.ts b/src/main/runtime/orca-runtime-automations.test.ts index 59435f49e..28746f115 100644 --- a/src/main/runtime/orca-runtime-automations.test.ts +++ b/src/main/runtime/orca-runtime-automations.test.ts @@ -57,6 +57,7 @@ const existingAutomation = { workspaceMode: 'new_per_run', workspaceId: null, baseBranch: 'main', + reuseSession: false, timezone: 'UTC', rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', dtstart: 1, @@ -123,6 +124,67 @@ describe('OrcaRuntimeService automation methods', () => { expect(store.updateAutomation).toHaveBeenCalledWith('auto-1', { baseBranch: null }) }) + it('passes session reuse updates for existing-workspace automations', async () => { + const existing = { + ...existingAutomation, + workspaceMode: 'existing', + workspaceId: 'repo-1::/tmp/orca', + baseBranch: null + } satisfies Automation + const store = makeStore([existing]) + const runtime = new OrcaRuntimeService(store as never) + + await runtime.updateAutomation('auto-1', { reuseSession: true }) + + expect(store.updateAutomation).toHaveBeenCalledWith('auto-1', { reuseSession: true }) + }) + + it('clears session reuse when retargeting to new-per-run', async () => { + const existing = { + ...existingAutomation, + workspaceMode: 'existing', + workspaceId: 'repo-1::/tmp/orca', + baseBranch: null, + reuseSession: true + } satisfies Automation + const store = makeStore([existing]) + const runtime = new OrcaRuntimeService(store as never) + + await runtime.updateAutomation('auto-1', { + repo: 'repo-1', + workspaceMode: 'new_per_run' + }) + + expect(store.updateAutomation).toHaveBeenCalledWith( + 'auto-1', + expect.objectContaining({ + projectId: 'repo-1', + workspaceMode: 'new_per_run', + workspaceId: null, + reuseSession: false + }) + ) + }) + + it('rejects session reuse for new-per-run automations', async () => { + const store = makeStore() + const runtime = new OrcaRuntimeService(store as never) + + await expect( + runtime.createAutomation({ + name: 'Fresh', + prompt: 'Run checks', + agentId: 'codex', + repo: 'repo-1', + workspaceMode: 'new_per_run', + reuseSession: true, + rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', + dtstart: 1 + }) + ).rejects.toThrow('Session reuse requires an existing workspace target.') + expect(store.createAutomation).not.toHaveBeenCalled() + }) + it('rejects repo-only updates for existing-workspace automations', async () => { const existing = { ...existingAutomation, diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 871990493..3ac993ef5 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -1045,6 +1045,9 @@ export class OrcaRuntimeService { throw new Error('runtime_unavailable') } const target = await this.resolveAutomationTarget(input) + if (input.reuseSession && target.workspaceMode !== 'existing') { + throw new Error('Session reuse requires an existing workspace target.') + } return this.store.createAutomation({ name: input.name, prompt: input.prompt, @@ -1053,6 +1056,7 @@ export class OrcaRuntimeService { workspaceMode: target.workspaceMode, workspaceId: target.workspaceId, baseBranch: input.baseBranch, + reuseSession: input.reuseSession, timezone: input.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone, rrule: input.rrule, dtstart: input.dtstart, @@ -1079,6 +1083,9 @@ export class OrcaRuntimeService { if (hasRuntimeAutomationUpdateValue(updates, 'baseBranch')) { patch.baseBranch = updates.baseBranch } + if (hasRuntimeAutomationUpdateValue(updates, 'reuseSession')) { + patch.reuseSession = updates.reuseSession + } if (hasRuntimeAutomationUpdateValue(updates, 'timezone')) { patch.timezone = updates.timezone } @@ -1100,9 +1107,18 @@ export class OrcaRuntimeService { hasRuntimeAutomationUpdateValue(updates, 'workspaceMode') if (targetChanged) { const target = await this.resolveAutomationTarget(updates, current) + if (patch.reuseSession === true && target.workspaceMode !== 'existing') { + throw new Error('Session reuse requires an existing workspace target.') + } patch.projectId = target.projectId patch.workspaceMode = target.workspaceMode patch.workspaceId = target.workspaceId + if (target.workspaceMode !== 'existing') { + patch.reuseSession = false + } + } + if (!targetChanged && patch.reuseSession && current.workspaceMode !== 'existing') { + throw new Error('Session reuse requires an existing workspace target.') } return this.store.updateAutomation(id, patch) } diff --git a/src/main/runtime/rpc/methods/automations.test.ts b/src/main/runtime/rpc/methods/automations.test.ts index f2c8dce99..b0bb15a7f 100644 --- a/src/main/runtime/rpc/methods/automations.test.ts +++ b/src/main/runtime/rpc/methods/automations.test.ts @@ -30,6 +30,7 @@ describe('automation RPC methods', () => { prompt: 'Review changes', agentId: 'codex', repo: 'repo-1', + reuseSession: true, rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', dtstart: 1 }) @@ -39,6 +40,7 @@ describe('automation RPC methods', () => { id: 'auto-1', updates: { enabled: false, + reuseSession: false, rrule: '0 9 * * 1-5', dtstart: 2 } @@ -55,12 +57,13 @@ describe('automation RPC methods', () => { name: 'New review', prompt: 'Review changes', agentId: 'codex', - repo: 'repo-1' + repo: 'repo-1', + reuseSession: true }) ) expect(runtime.updateAutomation).toHaveBeenCalledWith( 'auto-1', - expect.objectContaining({ enabled: false, rrule: '0 9 * * 1-5' }) + expect.objectContaining({ enabled: false, reuseSession: false, rrule: '0 9 * * 1-5' }) ) expect(runtime.deleteAutomation).toHaveBeenCalledWith('auto-1') expect(runtime.runAutomationNow).toHaveBeenCalledWith('auto-1') diff --git a/src/main/runtime/rpc/methods/automations.ts b/src/main/runtime/rpc/methods/automations.ts index 97bd301ea..f2d13e04b 100644 --- a/src/main/runtime/rpc/methods/automations.ts +++ b/src/main/runtime/rpc/methods/automations.ts @@ -43,6 +43,7 @@ const AutomationCreate = z.object({ workspace: OptionalString, workspaceMode: AutomationWorkspaceMode, baseBranch: OptionalPlainString, + reuseSession: OptionalBoolean, timezone: OptionalString, rrule: AutomationSchedule, dtstart: requiredNumber('Missing trigger start time'), @@ -59,6 +60,7 @@ const AutomationUpdateFields = z.object({ workspaceMode: AutomationWorkspaceMode, // Why: update patches distinguish omitted from null so callers can clear a saved base branch. baseBranch: OptionalNullablePlainString, + reuseSession: OptionalBoolean, timezone: OptionalString, rrule: AutomationSchedule.optional(), dtstart: requiredNumber('Missing trigger start time').optional(), diff --git a/src/renderer/src/components/agent/AgentCombobox.tsx b/src/renderer/src/components/agent/AgentCombobox.tsx index 9c22089a0..2eaa4137d 100644 --- a/src/renderer/src/components/agent/AgentCombobox.tsx +++ b/src/renderer/src/components/agent/AgentCombobox.tsx @@ -39,6 +39,7 @@ type AgentComboboxProps = { * instead of opening the popover — lets the parent form treat the Agent * field as the last keyboard-submit step. */ onTriggerEnter?: () => void + allowNarrowTrigger?: boolean } const BLANK_VALUE = '__none__' @@ -127,7 +128,8 @@ export default function AgentCombobox({ defaultAgent, onSetDefault, triggerClassName, - onTriggerEnter + onTriggerEnter, + allowNarrowTrigger = false }: AgentComboboxProps): React.JSX.Element { const [open, setOpen] = useState(false) const [query, setQuery] = useState('') @@ -244,7 +246,7 @@ export default function AgentCombobox({ // the compact trigger still needs room for "GitHub Copilot". 'h-8 justify-between px-3 text-xs font-normal', triggerClassName, - TRIGGER_MIN_WIDTH_CLASS + !allowNarrowTrigger && TRIGGER_MIN_WIDTH_CLASS )} data-agent-combobox-root="true" > @@ -264,7 +266,10 @@ export default function AgentCombobox({ event.preventDefault()} > diff --git a/src/renderer/src/components/automations/AutomationDetail.tsx b/src/renderer/src/components/automations/AutomationDetail.tsx index 9d2f9bcda..9de06100f 100644 --- a/src/renderer/src/components/automations/AutomationDetail.tsx +++ b/src/renderer/src/components/automations/AutomationDetail.tsx @@ -194,6 +194,10 @@ export function AutomationDetail({ : workspaceName } /> +
Prompt

diff --git a/src/renderer/src/components/automations/AutomationEditorDialog.tsx b/src/renderer/src/components/automations/AutomationEditorDialog.tsx index 481ffe5d6..76915590b 100644 --- a/src/renderer/src/components/automations/AutomationEditorDialog.tsx +++ b/src/renderer/src/components/automations/AutomationEditorDialog.tsx @@ -23,6 +23,7 @@ import type { import type { GlobalSettings, Repo, TuiAgent, Worktree } from '../../../../shared/types' import { Field } from './automation-page-parts' import { AutomationSchedulePicker } from './AutomationSchedulePicker' +import { AutomationSessionField } from './AutomationSessionField' import { AUTOMATION_TEMPLATES, type AutomationTemplate } from './automation-templates' import { CreateFromPicker } from './CreateFromPicker' import { WorkspaceCombobox } from './WorkspaceCombobox' @@ -40,6 +41,7 @@ export type AutomationDraft = { workspaceMode: AutomationWorkspaceMode workspaceId: string baseBranch: string + reuseSession: boolean preset: AutomationSchedulePreset time: string dayOfWeek: string @@ -213,8 +215,8 @@ export function AutomationEditorDialog({

@@ -229,37 +231,28 @@ export function AutomationEditorDialog({ + Workspace + + + + + + Worktree runs in the selected workspace. New run creates a fresh workspace + from the selected branch each time. + + + } + className={isHermesCreate ? undefined : 'sm:col-span-2 lg:col-span-3'} > - {isHermesCreate ? null : ( - - workspaceMode && - onDraftChange((current) => ({ - ...current, - workspaceMode: workspaceMode as AutomationWorkspaceMode - })) - } - variant="outline" - size="sm" - className="mb-2 grid w-full grid-cols-2" - > - - worktree - - - New run - - - )} - {draft.workspaceMode === 'existing' || isHermesCreate ? ( + {isHermesCreate ? ( ) : ( - - onDraftChange((current) => ({ ...current, baseBranch })) - } - /> +
+ + workspaceMode && + onDraftChange((current) => ({ + ...current, + workspaceMode: workspaceMode as AutomationWorkspaceMode, + reuseSession: workspaceMode === 'existing' ? current.reuseSession : false + })) + } + variant="outline" + size="sm" + className="grid w-full grid-cols-2" + > + + Worktree + + + New run + + + {draft.workspaceMode === 'existing' ? ( + + onDraftChange((current) => ({ ...current, workspaceId })) + } + /> + ) : ( + + onDraftChange((current) => ({ ...current, baseBranch })) + } + /> + )} +
)}
{isHermesCreate ? null : ( @@ -291,9 +319,17 @@ export function AutomationEditorDialog({ } defaultAgent={settings?.defaultTuiAgent ?? null} triggerClassName={`h-9 w-full min-w-0 ${PICKER_TRIGGER_CLASS}`} + allowNarrowTrigger /> )} + {isHermesCreate ? null : ( + + )} AutomationDraft) => void +} + +export function AutomationSessionField({ + draft, + toggleItemClassName, + onDraftChange +}: AutomationSessionFieldProps): React.JSX.Element { + return ( + + Session + + + + + + Reuse sends future runs to the previous live automation session. If that session is + gone, Orca starts a fresh one. + + + + } + > + { + if (!value) { + return + } + onDraftChange((current) => ({ + ...current, + reuseSession: value === 'reuse', + workspaceMode: value === 'reuse' ? 'existing' : current.workspaceMode + })) + }} + variant="outline" + size="sm" + className="grid w-full grid-cols-2" + > + + Fresh + + + Reuse + + + + ) +} diff --git a/src/renderer/src/components/automations/AutomationsPage.tsx b/src/renderer/src/components/automations/AutomationsPage.tsx index dba33b8a4..3fdef61a9 100644 --- a/src/renderer/src/components/automations/AutomationsPage.tsx +++ b/src/renderer/src/components/automations/AutomationsPage.tsx @@ -291,6 +291,7 @@ export default function AutomationsPage(): React.JSX.Element { workspaceMode: 'existing', workspaceId: '', baseBranch: '', + reuseSession: false, preset: 'weekdays', time: DEFAULT_TIME, dayOfWeek: '1', @@ -556,16 +557,25 @@ export default function AutomationsPage(): React.JSX.Element { if (inFlight.has(run.id)) { return false } + const dispatchedAt = run.dispatchedAt ?? null + if (dispatchedAt === null) { + return false + } const paneKeyPrefix = `${run.terminalSessionId}:` const liveDone = Object.entries(agentStatusByPaneKey).some( - ([paneKey, entry]) => paneKey.startsWith(paneKeyPrefix) && entry.state === 'done' + ([paneKey, entry]) => + paneKey.startsWith(paneKeyPrefix) && + entry.state === 'done' && + entry.updatedAt >= dispatchedAt ) if (liveDone) { return true } return Object.entries(retainedAgentsByPaneKey).some( ([paneKey, retained]) => - paneKey.startsWith(paneKeyPrefix) && retained.entry.state === 'done' + paneKey.startsWith(paneKeyPrefix) && + retained.entry.state === 'done' && + retained.entry.updatedAt >= dispatchedAt ) }) if (completedRuns.length === 0) { @@ -642,7 +652,8 @@ export default function AutomationsPage(): React.JSX.Element { setDraft((current) => ({ ...current, agentId: 'hermes', - workspaceMode: 'existing' + workspaceMode: 'existing', + reuseSession: false })) } }, []) @@ -661,6 +672,7 @@ export default function AutomationsPage(): React.JSX.Element { workspaceMode: 'existing', workspaceId: target.workspaceId, baseBranch: '', + reuseSession: false, preset: 'weekdays', time: DEFAULT_TIME, dayOfWeek: '1', @@ -712,6 +724,7 @@ export default function AutomationsPage(): React.JSX.Element { workspaceMode: latest.workspaceMode, workspaceId: latest.workspaceId ?? '', baseBranch: latest.baseBranch ?? '', + reuseSession: latest.workspaceMode === 'existing' && latest.reuseSession, preset: schedule?.preset ?? (hasCustomSchedule ? 'custom' : 'weekdays'), time: schedule ? formatTimeInput(schedule.hour, schedule.minute) : DEFAULT_TIME, dayOfWeek: String(schedule?.dayOfWeek ?? 1), @@ -756,6 +769,7 @@ export default function AutomationsPage(): React.JSX.Element { workspaceMode: 'existing', workspaceId, baseBranch: '', + reuseSession: false, preset: hasCustomSchedule ? 'custom' : 'weekdays', time: DEFAULT_TIME, dayOfWeek: '1', @@ -915,6 +929,7 @@ export default function AutomationsPage(): React.JSX.Element { workspaceMode: draft.workspaceMode, workspaceId: draft.workspaceId, baseBranch: draft.baseBranch.trim() || null, + reuseSession: draft.workspaceMode === 'existing' && draft.reuseSession, timezone, missedRunGraceMinutes } @@ -936,6 +951,7 @@ export default function AutomationsPage(): React.JSX.Element { workspaceMode: draft.workspaceMode, workspaceId: draft.workspaceId, baseBranch: draft.baseBranch.trim() || null, + reuseSession: draft.workspaceMode === 'existing' && draft.reuseSession, timezone, rrule, dtstart: now, diff --git a/src/renderer/src/components/automations/automation-page-parts.tsx b/src/renderer/src/components/automations/automation-page-parts.tsx index 2097ba795..b492b1ccf 100644 --- a/src/renderer/src/components/automations/automation-page-parts.tsx +++ b/src/renderer/src/components/automations/automation-page-parts.tsx @@ -99,7 +99,7 @@ export function Field({ className?: string }): React.JSX.Element { return ( -
+
{label}
{children}
diff --git a/src/renderer/src/components/terminal-pane/pty-connection.test.ts b/src/renderer/src/components/terminal-pane/pty-connection.test.ts index e405225b5..c828beb83 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.test.ts @@ -1872,7 +1872,6 @@ describe('connectPanePty', () => { '\x1b[?1004hrestored snapshot', expect.any(Function) ) - expect(pane.terminal.write).toHaveBeenCalledWith('\r\n', expect.any(Function)) expect(pane.terminal.write).toHaveBeenCalledWith( POST_REPLAY_FOCUS_REPORTING_RESET, expect.any(Function) @@ -3065,7 +3064,6 @@ describe('connectPanePty', () => { // content already in the terminal from a prior session. expect(pane.terminal.write).toHaveBeenCalledWith('\x1b[2J\x1b[3J\x1b[H', expect.any(Function)) expect(pane.terminal.write).toHaveBeenCalledWith('restored-ssh-output', expect.any(Function)) - expect(pane.terminal.write).toHaveBeenCalledWith('\r\n', expect.any(Function)) expect(pane.terminal.write).toHaveBeenCalledWith( POST_REPLAY_FOCUS_REPORTING_RESET, expect.any(Function) diff --git a/src/renderer/src/hooks/useAutomationDispatchEvents.ts b/src/renderer/src/hooks/useAutomationDispatchEvents.ts index 6fd48a4c5..2963e9392 100644 --- a/src/renderer/src/hooks/useAutomationDispatchEvents.ts +++ b/src/renderer/src/hooks/useAutomationDispatchEvents.ts @@ -1,5 +1,11 @@ +/* eslint-disable max-lines -- Why: automation dispatch is a single renderer lifecycle + * coordinator spanning workspace creation, SSH readiness, terminal launch/reuse, + * completion bookkeeping, and focus restoration. */ import { useEffect } from 'react' import { launchAgentBackgroundSession } from '@/lib/launch-agent-background-session' +import { submitPromptToAgentTab } from '@/lib/agent-paste-draft' +import { findReusableAutomationSession } from '@/lib/automation-session-reuse' +import { observeExistingAutomationSession } from '@/lib/automation-session-observer' import { useAppStore } from '@/store' import type { AutomationDispatchResult } from '../../../shared/automations-types' import { parsePaneKey } from '../../../shared/stable-pane-id' @@ -9,6 +15,15 @@ import { } from '@/components/automations/automation-run-output-snapshot' const AUTOMATIONS_CHANGED_EVENT = 'orca:automations-changed' +const activeReuseDispatchTabIds = new Set() + +function acquireReuseDispatchTab(tabId: string): (() => void) | null { + if (activeReuseDispatchTabIds.has(tabId)) { + return null + } + activeReuseDispatchTabIds.add(tabId) + return () => activeReuseDispatchTabIds.delete(tabId) +} function buildAutomationWorkspaceName(runTitle: string, scheduledFor: number): string { const slug = runTitle @@ -133,12 +148,22 @@ export function useAutomationDispatchEvents(): void { let pendingDone = false let completionMarked = 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 - unsubscribeAgentStatus() + cleanupRunObservers() await markDispatchResult({ runId: run.id, status: 'completed', @@ -149,7 +174,7 @@ export function useAutomationDispatchEvents(): void { }) } const markExitResult = (code: number): Promise => { - unsubscribeAgentStatus() + cleanupRunObservers() return markDispatchResult({ runId: run.id, status: code === 0 ? 'completed' : 'dispatch_failed', @@ -169,12 +194,26 @@ export function useAutomationDispatchEvents(): void { } void markCompletionResult() } - const observeAgentStatus = (tabId: string): void => { + const observeAgentStatus = ( + tabId: string, + startedAfter: number, + options?: { requireWorkingAfterStart?: boolean } + ): void => { + let sawWorkingAfterStart = false const checkCurrentStatus = (): void => { const { agentStatusByPaneKey } = useAppStore.getState() for (const [paneKey, entry] of Object.entries(agentStatusByPaneKey)) { const parsed = parsePaneKey(paneKey) - if (parsed?.tabId === tabId && entry.state === 'done') { + if (parsed?.tabId !== tabId || entry.updatedAt < startedAfter) { + continue + } + if (entry.state === 'working') { + sawWorkingAfterStart = true + } + if ( + entry.state === 'done' && + (!options?.requireWorkingAfterStart || sawWorkingAfterStart) + ) { latestAssistantMessage = entry.lastAssistantMessage?.trim() || latestAssistantMessage handleAgentDone() @@ -187,6 +226,88 @@ export function useAutomationDispatchEvents(): void { unsubscribeAgentStatus = useAppStore.subscribe(checkCurrentStatus) checkCurrentStatus() } + const dispatchStartedAt = Date.now() + if (automation.reuseSession) { + const reusableSession = findReusableAutomationSession({ + automationId: automation.id, + agentId: automation.agentId, + worktreeId: worktree.id, + currentRunId: run.id, + runs: await window.api.automations.listRuns({ automationId: automation.id }), + state: useAppStore.getState() + }) + if (reusableSession) { + const releaseTab = acquireReuseDispatchTab(reusableSession.tabId) + if (releaseTab) { + releaseReuseDispatchTab = releaseTab + try { + const submitted = await submitPromptToAgentTab({ + tabId: reusableSession.tabId, + content: automation.prompt + }) + if (!submitted) { + cleanupRunObservers() + } else { + let reuseSawWorking = false + const handleReusableAgentStatus = (payload: { state: string }): void => { + if (payload.state === 'working') { + reuseSawWorking = true + return + } + if (payload.state === 'done' && reuseSawWorking) { + handleAgentDone() + } + } + const reuseCompletionStartedAt = Date.now() + unsubscribeSessionObserver = await observeExistingAutomationSession({ + ptyId: reusableSession.ptyId, + paneKey: reusableSession.paneKey, + runId: run.id, + onData: (chunk) => { + outputSnapshotBuffer.append(chunk) + }, + onAgentStatus: (payload) => { + latestAssistantMessage = + payload.lastAssistantMessage?.trim() || latestAssistantMessage + handleReusableAgentStatus(payload) + }, + onExit: (code) => { + if (completionMarked) { + return + } + if (!dispatchMarked) { + pendingExitCode = code + return + } + void markExitResult(code) + } + }) + observeAgentStatus(reusableSession.tabId, reuseCompletionStartedAt, { + requireWorkingAfterStart: true + }) + await markDispatchResult({ + runId: run.id, + status: 'dispatched', + workspaceId: worktree.id, + workspaceDisplayName: worktree.displayName, + terminalSessionId: reusableSession.tabId, + error: null + }) + dispatchMarked = true + if (pendingDone) { + await markCompletionResult() + } else if (pendingExitCode !== null) { + await markExitResult(pendingExitCode) + } + return + } + } catch (error) { + cleanupRunObservers() + throw error + } + } + } + } const result = await launchAgentBackgroundSession({ agent: automation.agentId, worktreeId: worktree.id, @@ -217,7 +338,7 @@ export function useAutomationDispatchEvents(): void { if (!result) { throw new Error('Unable to build an agent launch plan.') } - observeAgentStatus(result.tabId) + observeAgentStatus(result.tabId, dispatchStartedAt) try { await markDispatchResult({ runId: run.id, @@ -234,7 +355,7 @@ export function useAutomationDispatchEvents(): void { await markExitResult(pendingExitCode) } } catch (error) { - unsubscribeAgentStatus() + cleanupRunObservers() throw error } const currentState = useAppStore.getState() diff --git a/src/renderer/src/lib/agent-paste-draft.ts b/src/renderer/src/lib/agent-paste-draft.ts index 37f4f30ae..b133c3591 100644 --- a/src/renderer/src/lib/agent-paste-draft.ts +++ b/src/renderer/src/lib/agent-paste-draft.ts @@ -2,7 +2,11 @@ import type { TuiAgent } from '../../../shared/types' import { TUI_AGENT_CONFIG, type DraftPasteReadySignal } from '../../../shared/tui-agent-config' import { useAppStore } from '@/store' import { subscribeToPtyData } from '@/components/terminal-pane/pty-dispatcher' -import { isRemoteRuntimePtyId, sendRuntimePtyInput } from '@/runtime/runtime-terminal-inspection' +import { + isRemoteRuntimePtyId, + sendRuntimePtyInput, + sendRuntimePtyInputVerified +} from '@/runtime/runtime-terminal-inspection' import { subscribeToRuntimeTerminalData } from '@/runtime/runtime-terminal-stream' // Why: bracketed paste markers let modern TUIs (Claude Code / Codex / Pi / @@ -99,6 +103,23 @@ export async function pasteDraftWhenAgentReady(args: { return true } +export async function submitPromptToAgentTab(args: { + tabId: string + content: string + timeoutMs?: number +}): Promise { + const { tabId, content, timeoutMs } = args + const ptyId = await waitForPtyId(tabId, timeoutMs ?? READINESS_TIMEOUT_MS) + if (!ptyId) { + return false + } + return await sendRuntimePtyInputVerified( + useAppStore.getState().settings, + ptyId, + `${BRACKETED_PASTE_BEGIN}${content}${BRACKETED_PASTE_END}\r` + ) +} + /** * Tap the PTY data stream as a side-channel observer (does NOT take over * the primary handler that feeds xterm) and resolve `true` once we see diff --git a/src/renderer/src/lib/automation-session-observer.ts b/src/renderer/src/lib/automation-session-observer.ts new file mode 100644 index 000000000..1553ee3e4 --- /dev/null +++ b/src/renderer/src/lib/automation-session-observer.ts @@ -0,0 +1,76 @@ +import { createAgentStatusOscProcessor } from '@/components/terminal-pane/agent-status-osc' +import { subscribeToPtyData, subscribeToPtyExit } from '@/components/terminal-pane/pty-dispatcher' +import { callRuntimeRpc, getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client' +import { getRemoteRuntimeTerminalMultiplexer } from '@/runtime/remote-runtime-terminal-multiplexer' +import { isRemoteRuntimePtyId } from '@/runtime/runtime-terminal-inspection' +import { + getRemoteRuntimePtyEnvironmentId, + getRemoteRuntimeTerminalHandle +} from '@/runtime/runtime-terminal-stream' +import { useAppStore } from '@/store' +import type { ParsedAgentStatusPayload } from '../../../shared/agent-status-types' + +export async function observeExistingAutomationSession(args: { + ptyId: string + paneKey: string + runId: string + onData: (chunk: string) => void + onAgentStatus: (payload: ParsedAgentStatusPayload) => void + onExit: (code: number) => void +}): Promise<() => void> { + const { ptyId, paneKey, runId, onData, onExit } = args + const processAgentStatus = createAgentStatusOscProcessor() + const handleData = (data: string): void => { + onData(data) + const processed = processAgentStatus(data) + for (const payload of processed.payloads) { + useAppStore.getState().setAgentStatus(paneKey, payload, undefined) + args.onAgentStatus(payload) + } + } + + if (isRemoteRuntimePtyId(ptyId)) { + let disposed = false + const ownerEnvironmentId = getRemoteRuntimePtyEnvironmentId(ptyId) + const runtimeTarget = ownerEnvironmentId + ? ({ kind: 'environment', environmentId: ownerEnvironmentId } as const) + : getActiveRuntimeTarget(useAppStore.getState().settings) + const terminal = getRemoteRuntimeTerminalHandle(ptyId) + if (runtimeTarget.kind !== 'environment' || !terminal) { + return () => {} + } + const stream = await getRemoteRuntimeTerminalMultiplexer( + runtimeTarget.environmentId + ).subscribeTerminal({ + terminal, + client: { id: `desktop:automation-reuse:${runId}`, type: 'desktop' }, + callbacks: { + onData: handleData, + onSnapshot: () => {} + } + }) + void callRuntimeRpc<{ wait: { exitCode?: number | null } }>( + runtimeTarget, + 'terminal.wait', + { terminal, for: 'exit' }, + { timeoutMs: 24 * 60 * 60 * 1000 } + ) + .then((result) => { + if (!disposed) { + onExit(result.wait.exitCode ?? 0) + } + }) + .catch(() => {}) + return () => { + disposed = true + stream.close() + } + } + + const unsubscribeData = subscribeToPtyData(ptyId, handleData) + const unsubscribeExit = subscribeToPtyExit(ptyId, onExit) + return () => { + unsubscribeData() + unsubscribeExit() + } +} diff --git a/src/renderer/src/lib/automation-session-reuse.test.ts b/src/renderer/src/lib/automation-session-reuse.test.ts new file mode 100644 index 000000000..fca5efe02 --- /dev/null +++ b/src/renderer/src/lib/automation-session-reuse.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from 'vitest' +import type { AgentStatusEntry } from '../../../shared/agent-status-types' +import type { AutomationRun } from '../../../shared/automations-types' +import { findReusableAutomationSession } from './automation-session-reuse' + +const leafId = '11111111-1111-4111-8111-111111111111' +const paneKey = `tab-1:${leafId}` + +function run(overrides: Partial): AutomationRun { + return { + id: 'run-1', + automationId: 'auto-1', + title: 'Run 1', + scheduledFor: 1, + status: 'completed', + trigger: 'manual', + workspaceId: 'wt-1', + workspaceDisplayName: 'Workspace', + sessionKind: 'terminal', + chatSessionId: null, + terminalSessionId: 'tab-1', + outputSnapshot: null, + usage: null, + error: null, + startedAt: 1, + dispatchedAt: 1, + createdAt: 1, + ...overrides + } +} + +function status(overrides: Partial = {}): AgentStatusEntry { + return { + state: 'done', + prompt: 'previous', + updatedAt: 10, + stateStartedAt: 10, + paneKey, + stateHistory: [], + agentType: 'claude', + ...overrides + } +} + +describe('automation session reuse', () => { + it('selects the latest completed live session for the same automation and workspace', () => { + const session = findReusableAutomationSession({ + automationId: 'auto-1', + agentId: 'claude', + worktreeId: 'wt-1', + currentRunId: 'run-current', + runs: [ + run({ id: 'run-old', terminalSessionId: 'tab-old', createdAt: 1 }), + run({ id: 'run-new', terminalSessionId: 'tab-1', createdAt: 2 }) + ], + state: { + agentStatusByPaneKey: { [paneKey]: status() }, + ptyIdsByTabId: { 'tab-1': ['pty-1'], 'tab-old': ['pty-old'] }, + unifiedTabsByWorktree: { + 'wt-1': [ + { contentType: 'terminal', entityId: 'tab-1' }, + { contentType: 'terminal', entityId: 'tab-old' } + ] + } + } as never + }) + + expect(session).toEqual({ tabId: 'tab-1', ptyId: 'pty-1', paneKey }) + }) + + it('rejects sessions that are not idle in a live agent pane', () => { + const session = findReusableAutomationSession({ + automationId: 'auto-1', + agentId: 'claude', + worktreeId: 'wt-1', + currentRunId: 'run-current', + runs: [run({ id: 'run-new', terminalSessionId: 'tab-1', createdAt: 2 })], + state: { + agentStatusByPaneKey: { [paneKey]: status({ state: 'working' }) }, + ptyIdsByTabId: { 'tab-1': ['pty-1'] }, + unifiedTabsByWorktree: { + 'wt-1': [{ contentType: 'terminal', entityId: 'tab-1' }] + } + } as never + }) + + expect(session).toBeNull() + }) +}) diff --git a/src/renderer/src/lib/automation-session-reuse.ts b/src/renderer/src/lib/automation-session-reuse.ts new file mode 100644 index 000000000..70d618c51 --- /dev/null +++ b/src/renderer/src/lib/automation-session-reuse.ts @@ -0,0 +1,72 @@ +import type { AgentStatusEntry } from '../../../shared/agent-status-types' +import type { AutomationRun } from '../../../shared/automations-types' +import type { TuiAgent } from '../../../shared/types' +import { parsePaneKey } from '../../../shared/stable-pane-id' +import type { AppState } from '@/store/types' + +export type ReusableAutomationSession = { + tabId: string + ptyId: string + paneKey: string +} + +export function findReusableAutomationSession(args: { + automationId: string + agentId: TuiAgent + worktreeId: string + currentRunId: string + runs: AutomationRun[] + state: Pick +}): ReusableAutomationSession | null { + const { automationId, agentId, worktreeId, currentRunId, runs, state } = args + const worktreeTabs = state.unifiedTabsByWorktree[worktreeId] ?? [] + const terminalTabIds = new Set( + worktreeTabs.filter((tab) => tab.contentType === 'terminal').map((tab) => tab.entityId) + ) + const candidates = runs + .filter( + (run) => + run.id !== currentRunId && + run.automationId === automationId && + run.workspaceId === worktreeId && + run.status === 'completed' && + run.terminalSessionId && + terminalTabIds.has(run.terminalSessionId) + ) + .sort((left, right) => right.createdAt - left.createdAt) + + for (const run of candidates) { + const tabId = run.terminalSessionId + if (!tabId) { + continue + } + const ptyId = state.ptyIdsByTabId[tabId]?.[0] + if (!ptyId) { + continue + } + const paneKey = findReusablePaneKey(state.agentStatusByPaneKey, tabId, agentId) + if (!paneKey) { + continue + } + return { tabId, ptyId, paneKey } + } + return null +} + +function findReusablePaneKey( + entries: Record, + tabId: string, + agentId: TuiAgent +): string | null { + for (const [paneKey, entry] of Object.entries(entries)) { + const parsed = parsePaneKey(paneKey) + if (parsed?.tabId !== tabId || entry.state !== 'done') { + continue + } + if (entry.agentType && entry.agentType !== 'unknown' && entry.agentType !== agentId) { + continue + } + return paneKey + } + return null +} diff --git a/src/renderer/src/lib/launch-agent-background-session.test.ts b/src/renderer/src/lib/launch-agent-background-session.test.ts index f3dd61a63..6ca936d91 100644 --- a/src/renderer/src/lib/launch-agent-background-session.test.ts +++ b/src/renderer/src/lib/launch-agent-background-session.test.ts @@ -18,6 +18,7 @@ const mockRegisterEagerPtyBuffer = vi.fn() const mockSubscribeToPtyData = vi.fn() const mockSubscribeToPtyExit = vi.fn() const mockPasteDraftWhenAgentReady = vi.fn() +const mockMarkTrusted = vi.fn() const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ function expectStablePaneSpawn(): string { @@ -96,6 +97,9 @@ describe('launchAgentBackgroundSession', () => { pty: { spawn: mockSpawn }, + agentTrust: { + markTrusted: mockMarkTrusted + }, runtime: { call: vi.fn() }, @@ -150,6 +154,22 @@ describe('launchAgentBackgroundSession', () => { expect(result).toMatchObject({ tabId: 'tab-1', ptyId: 'pty-1' }) }) + it('pre-marks trust for agents with first-launch trust prompts', async () => { + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'codex', + worktreeId: 'wt-1', + prompt: 'run the automation' + }) + + expect(mockMarkTrusted).toHaveBeenCalledWith({ + preset: 'codex', + workspacePath: '/repo/worktree' + }) + expect(mockSpawn).toHaveBeenCalled() + }) + it('parses agent status from hidden PTY output', async () => { const onAgentStatus = vi.fn() const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') diff --git a/src/renderer/src/lib/launch-agent-background-session.ts b/src/renderer/src/lib/launch-agent-background-session.ts index f2903b314..9aa471ea7 100644 --- a/src/renderer/src/lib/launch-agent-background-session.ts +++ b/src/renderer/src/lib/launch-agent-background-session.ts @@ -51,6 +51,17 @@ export async function launchAgentBackgroundSession( if (!worktree) { throw new Error('The target workspace is no longer available.') } + const preflight = TUI_AGENT_CONFIG[agent].preflightTrust + if (preflight && worktree.path && window.api.agentTrust?.markTrusted) { + try { + await window.api.agentTrust.markTrusted({ + preset: preflight, + workspacePath: worktree.path + }) + } catch { + // Best-effort: continue with launch. The user can still accept the trust menu. + } + } const cmdOverrides = store.settings?.agentCmdOverrides ?? {} const trimmedPrompt = prompt?.trim() ?? '' const hasPrompt = trimmedPrompt.length > 0 diff --git a/src/renderer/src/runtime/runtime-terminal-inspection.ts b/src/renderer/src/runtime/runtime-terminal-inspection.ts index e3040fb14..18d87ec4a 100644 --- a/src/renderer/src/runtime/runtime-terminal-inspection.ts +++ b/src/renderer/src/runtime/runtime-terminal-inspection.ts @@ -94,3 +94,29 @@ export function sendRuntimePtyInput( }) return true } + +export async function sendRuntimePtyInputVerified( + settings: Pick | null | undefined, + ptyId: string, + data: string +): Promise { + const ownerEnvironmentId = getRemoteRuntimePtyEnvironmentId(ptyId) + const target = ownerEnvironmentId + ? ({ kind: 'environment', environmentId: ownerEnvironmentId } as const) + : getActiveRuntimeTarget(settings) + const terminal = getRemoteRuntimeTerminalHandle(ptyId) + if (target.kind !== 'environment' || !terminal) { + window.api.pty.write(ptyId, data) + return true + } + + try { + await callRuntimeRpc(target, 'terminal.send', { terminal, text: data }, { timeoutMs: 15_000 }) + return true + } catch (error) { + if (isTerminalGoneError(error)) { + return false + } + throw error + } +} diff --git a/src/shared/automations-types.ts b/src/shared/automations-types.ts index 5bd6b1ce5..369604b7b 100644 --- a/src/shared/automations-types.ts +++ b/src/shared/automations-types.ts @@ -66,6 +66,7 @@ export type Automation = { workspaceMode: AutomationWorkspaceMode workspaceId: string | null baseBranch: string | null + reuseSession: boolean timezone: string rrule: string dtstart: number @@ -108,6 +109,7 @@ export type AutomationCreateInput = { workspaceMode: AutomationWorkspaceMode workspaceId?: string | null baseBranch?: string | null + reuseSession?: boolean timezone: string rrule: string dtstart: number @@ -125,6 +127,7 @@ export type AutomationUpdateInput = Partial< | 'workspaceMode' | 'workspaceId' | 'baseBranch' + | 'reuseSession' | 'timezone' | 'rrule' | 'dtstart'