Add automation session reuse (#2329)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo Hong
2026-05-19 20:03:06 -07:00
committed by GitHub
co-authored by Orca
parent 5486bd2740
commit 3299635013
28 changed files with 876 additions and 65 deletions
+4 -1
View File
@@ -174,7 +174,8 @@ orca automations list --json
orca automations show <automationId> --json
orca automations create --name "Daily review" --trigger daily --time 09:00 --prompt "Review open changes" --provider codex --repo id:<repoId> --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 <automationId> --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 <automationId> --name "Weekday review" --trigger weekdays --time 09:30 --fresh-session --json
orca automations run <automationId> --json
orca automations runs --id <automationId> --json
orca automations remove <automationId> --json
@@ -184,6 +185,8 @@ Automation schedules accept `hourly`, `daily`, `weekdays`, `weekly`, a 5-field c
Use `--repo <selector>` for a new worktree per run, or `--workspace <selector>` / `--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
+1
View File
@@ -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')
+28
View File
@@ -208,6 +208,32 @@ function getEnabledFlag(flags: Map<string, string | boolean>): boolean | undefin
return undefined
}
function getReuseSessionFlag(flags: Map<string, string | boolean>): 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<string, string | boolean>
): 'existing' | 'new_per_run' | undefined {
@@ -290,6 +316,7 @@ export const AUTOMATION_HANDLERS: Record<string, CommandHandler> = {
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<string, CommandHandler> = {
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'),
+3
View File
@@ -386,6 +386,9 @@ export function formatFlagHelp(flag: string): string {
timezone: '--timezone <tz> 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 <mode> existing or new-per-run',
'missed-run-grace-minutes': '--missed-run-grace-minutes <n> Missed-run grace window',
'value-stdin': '--value-stdin Read set-value payload from stdin',
+67
View File
@@ -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
+9 -2
View File
@@ -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',
+41
View File
@@ -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<string, unknown>[] }
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())
+15 -3
View File
@@ -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
@@ -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,
+16
View File
@@ -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)
}
@@ -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')
@@ -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(),
@@ -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({
</PopoverTrigger>
<PopoverContent
align="start"
className="w-[var(--radix-popover-trigger-width)] min-w-[18rem] p-0"
className={cn(
'w-[var(--radix-popover-trigger-width)] p-0',
!allowNarrowTrigger && 'min-w-[18rem]'
)}
data-agent-combobox-root="true"
onOpenAutoFocus={(event) => event.preventDefault()}
>
@@ -194,6 +194,10 @@ export function AutomationDetail({
: workspaceName
}
/>
<DetailMetric
label="Session"
value={automation.reuseSession ? 'Reuse live session' : 'Fresh each run'}
/>
<div className="min-w-0">
<div className="text-[11px] font-medium uppercase text-muted-foreground">Prompt</div>
<p className="mt-1 line-clamp-4 whitespace-pre-wrap text-sm text-foreground">
@@ -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({
<div
className={
isHermesCreate
? 'grid gap-3 lg:grid-cols-[minmax(9rem,1.1fr)_minmax(14rem,1.4fr)_minmax(12rem,1.2fr)]'
: 'grid gap-3 lg:grid-cols-[minmax(9rem,1.1fr)_minmax(14rem,1.4fr)_minmax(12rem,1.2fr)_minmax(8rem,0.8fr)_minmax(9rem,1fr)]'
? 'grid gap-3 md:grid-cols-3'
: 'grid gap-3 sm:grid-cols-2 lg:grid-cols-4'
}
>
<Field label="Project">
@@ -229,37 +231,28 @@ export function AutomationEditorDialog({
</Field>
<Field
label={
isHermesCreate
? 'Workspace'
: draft.workspaceMode === 'new_per_run'
? 'Start branch'
: 'Workspace'
<span className="inline-flex items-center gap-1">
Workspace
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
aria-label="Workspace mode help"
className="rounded-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50"
>
<Info className="size-3.5" />
</button>
</TooltipTrigger>
<TooltipContent side="top" sideOffset={6} className="max-w-72">
Worktree runs in the selected workspace. New run creates a fresh workspace
from the selected branch each time.
</TooltipContent>
</Tooltip>
</span>
}
className={isHermesCreate ? undefined : 'sm:col-span-2 lg:col-span-3'}
>
{isHermesCreate ? null : (
<ToggleGroup
type="single"
value={draft.workspaceMode}
onValueChange={(workspaceMode) =>
workspaceMode &&
onDraftChange((current) => ({
...current,
workspaceMode: workspaceMode as AutomationWorkspaceMode
}))
}
variant="outline"
size="sm"
className="mb-2 grid w-full grid-cols-2"
>
<ToggleGroupItem value="existing" className={MODE_TOGGLE_ITEM_CLASS}>
worktree
</ToggleGroupItem>
<ToggleGroupItem value="new_per_run" className={MODE_TOGGLE_ITEM_CLASS}>
New run
</ToggleGroupItem>
</ToggleGroup>
)}
{draft.workspaceMode === 'existing' || isHermesCreate ? (
{isHermesCreate ? (
<WorkspaceCombobox
worktrees={worktrees}
value={draft.workspaceId}
@@ -269,16 +262,51 @@ export function AutomationEditorDialog({
}
/>
) : (
<CreateFromPicker
repoId={draft.projectId}
repoMap={repoMap}
worktrees={worktrees}
value={draft.baseBranch}
triggerClassName={PICKER_TRIGGER_CLASS}
onValueChange={(baseBranch) =>
onDraftChange((current) => ({ ...current, baseBranch }))
}
/>
<div className="grid gap-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,2fr)]">
<ToggleGroup
type="single"
value={draft.workspaceMode}
onValueChange={(workspaceMode) =>
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"
>
<ToggleGroupItem value="existing" className={MODE_TOGGLE_ITEM_CLASS}>
Worktree
</ToggleGroupItem>
<ToggleGroupItem value="new_per_run" className={MODE_TOGGLE_ITEM_CLASS}>
New run
</ToggleGroupItem>
</ToggleGroup>
{draft.workspaceMode === 'existing' ? (
<WorkspaceCombobox
worktrees={worktrees}
value={draft.workspaceId}
triggerClassName={`min-w-0 ${PICKER_TRIGGER_CLASS}`}
onValueChange={(workspaceId) =>
onDraftChange((current) => ({ ...current, workspaceId }))
}
/>
) : (
<CreateFromPicker
repoId={draft.projectId}
repoMap={repoMap}
worktrees={worktrees}
value={draft.baseBranch}
triggerClassName={`min-w-0 ${PICKER_TRIGGER_CLASS}`}
onValueChange={(baseBranch) =>
onDraftChange((current) => ({ ...current, baseBranch }))
}
/>
)}
</div>
)}
</Field>
{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
/>
</Field>
)}
{isHermesCreate ? null : (
<AutomationSessionField
draft={draft}
toggleItemClassName={MODE_TOGGLE_ITEM_CLASS}
onDraftChange={onDraftChange}
/>
)}
<Field label="Schedule">
<AutomationSchedulePicker
draft={draft}
@@ -0,0 +1,68 @@
import React from 'react'
import { Info } from 'lucide-react'
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { Field } from './automation-page-parts'
import type { AutomationDraft } from './AutomationEditorDialog'
type AutomationSessionFieldProps = {
draft: AutomationDraft
toggleItemClassName: string
onDraftChange: (updater: (current: AutomationDraft) => AutomationDraft) => void
}
export function AutomationSessionField({
draft,
toggleItemClassName,
onDraftChange
}: AutomationSessionFieldProps): React.JSX.Element {
return (
<Field
label={
<span className="inline-flex items-center gap-1">
Session
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
aria-label="Session reuse help"
className="rounded-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50"
>
<Info className="size-3.5" />
</button>
</TooltipTrigger>
<TooltipContent side="top" sideOffset={6} className="max-w-72">
Reuse sends future runs to the previous live automation session. If that session is
gone, Orca starts a fresh one.
</TooltipContent>
</Tooltip>
</span>
}
>
<ToggleGroup
type="single"
value={draft.workspaceMode === 'existing' && draft.reuseSession ? 'reuse' : 'fresh'}
onValueChange={(value) => {
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"
>
<ToggleGroupItem value="fresh" className={toggleItemClassName}>
Fresh
</ToggleGroupItem>
<ToggleGroupItem value="reuse" className={toggleItemClassName}>
Reuse
</ToggleGroupItem>
</ToggleGroup>
</Field>
)
}
@@ -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,
@@ -99,7 +99,7 @@ export function Field({
className?: string
}): React.JSX.Element {
return (
<div className={cn('space-y-1.5', className)}>
<div className={cn('min-w-0 space-y-1.5', className)}>
<div className="text-xs text-muted-foreground">{label}</div>
{children}
</div>
@@ -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)
@@ -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<string>()
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<void> => {
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<void> => {
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()
+22 -1
View File
@@ -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<boolean> {
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
@@ -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()
}
}
@@ -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>): 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> = {}): 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()
})
})
@@ -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<AppState, 'agentStatusByPaneKey' | 'ptyIdsByTabId' | 'unifiedTabsByWorktree'>
}): 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<string, AgentStatusEntry>,
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
}
@@ -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')
@@ -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
@@ -94,3 +94,29 @@ export function sendRuntimePtyInput(
})
return true
}
export async function sendRuntimePtyInputVerified(
settings: Pick<GlobalSettings, 'activeRuntimeEnvironmentId'> | null | undefined,
ptyId: string,
data: string
): Promise<boolean> {
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
}
}
+3
View File
@@ -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'