Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions src/main/automations/dispatch-refusal.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { Automation, AutomationRun } from '../../shared/automations-types'
import type { AutomationRunWriter } from './automation-run-writer'
import { UNEVALUABLE_SCHEDULE, recordUnevaluableAutomation } from './dispatch-refusal'

const brokenAutomation: Automation = {
id: 'a1',
name: 'Broken schedule',
prompt: 'Check the repo',
precheck: null,
agentId: 'claude',
projectId: 'r1',
executionTargetType: 'local',
executionTargetId: 'local',
schedulerOwner: 'local_host_service',
workspaceMode: 'existing',
workspaceId: 'wt1',
baseBranch: null,
reuseSession: false,
timezone: 'UTC',
rrule: '0 9 32 * *',
dtstart: 0,
enabled: true,
nextRunAt: 1000,
missedRunPolicy: 'run_once_within_grace',
missedRunGraceMinutes: 720,
createdAt: 0,
updatedAt: 0
}

const makeRun = (id: string): AutomationRun => ({
id,
automationId: brokenAutomation.id,
title: 'Broken schedule run',
scheduledFor: brokenAutomation.nextRunAt,
status: 'pending',
trigger: 'scheduled',
workspaceId: brokenAutomation.workspaceId,
sessionKind: 'terminal',
chatSessionId: null,
terminalSessionId: null,
terminalPaneKey: null,
terminalPtyId: null,
outputSnapshot: null,
precheckResult: null,
usage: null,
error: null,
startedAt: null,
dispatchedAt: null,
createdAt: 0
})

/** Records what the writer was asked to do, with `repeatSkip` standing in for a fold or not. */
function makeRunWriter(foldsRepeat: boolean): {
writer: AutomationRunWriter
created: string[]
updated: { status: string; error?: string | null }[]
} {
const created: string[] = []
const updated: { status: string; error?: string | null }[] = []
const writer: AutomationRunWriter = {
repeatSkip: () => (foldsRepeat ? makeRun('folded') : null),
createRun: () => {
const run = makeRun(`run-${created.length + 1}`)
created.push(run.id)
return run
},
updateRun: (args) => {
updated.push({ status: args.status, error: args.error })
return { ...makeRun(args.runId), status: args.status, error: args.error ?? null }
}
}
return { writer, created, updated }
}

describe('recordUnevaluableAutomation', () => {
afterEach(() => {
vi.restoreAllMocks()
})

it('writes one run and logs once when the record is newly broken', () => {
const logged = vi.spyOn(console, 'error').mockImplementation(() => {})
const { writer, created, updated } = makeRunWriter(false)

recordUnevaluableAutomation({
runs: writer,
automation: brokenAutomation,
error: new Error('Invalid cron day of month.')
})

expect(created).toEqual(['run-1'])
expect(updated).toEqual([{ status: 'skipped_unavailable', error: UNEVALUABLE_SCHEDULE }])
expect(logged).toHaveBeenCalledTimes(1)
})

// The record is retried every tick on purpose, so a repaired schedule resumes on its own.
// The fold is what keeps that from writing a row, and logging, once per tick forever.
it('stays silent on a record it has already reported', () => {
const logged = vi.spyOn(console, 'error').mockImplementation(() => {})
const { writer, created } = makeRunWriter(true)

for (let tick = 0; tick < 5; tick += 1) {
recordUnevaluableAutomation({
runs: writer,
automation: brokenAutomation,
error: new Error('Invalid cron day of month.')
})
}

expect(created).toEqual([])
expect(logged).not.toHaveBeenCalled()
})
})
40 changes: 40 additions & 0 deletions src/main/automations/dispatch-refusal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ import type { AutomationRunWriter } from './automation-run-writer'

export const NO_DISPATCH_HOST = 'No Orca window was available to launch the automation.'

/** A record the tick could not evaluate at all — its schedule no longer resolves (#16303). */
export const UNEVALUABLE_SCHEDULE =
'Orca could not evaluate this automation and skipped the occurrence.'

/** A record the authority refuses to execute at all, with no target diagnosis of its own. */
export const NO_RUNNABLE_HOST = 'This automation has no host to run on.'

Expand Down Expand Up @@ -51,3 +55,39 @@ export function recordRefusedAutomationRun(input: {
error: target.ok ? NO_RUNNABLE_HOST : target.error
})
}

/**
* Marks the poison record the scheduler tick just stepped over, so the user sees why it
* stalled. Folds on the fixed sentence and the unchanged nextRunAt, so a record that stays
* broken writes one row rather than one per tick, and never throws back into the tick.
*/
export function recordUnevaluableAutomation(input: {
runs: AutomationRunWriter
automation: Automation
error: unknown
}): void {
const { automation } = input
try {
// nextRunAt deliberately stays put: the record is retried so a repaired schedule resumes
// on its own. The fold is what keeps that from writing a row — and logging — every tick.
if (input.runs.repeatSkip(automation.id, UNEVALUABLE_SCHEDULE, automation.nextRunAt)) {
return
}
console.error('[automations] failed to evaluate automation:', automation.id, input.error)
const run = input.runs.createRun(automation, automation.nextRunAt)
input.runs.updateRun({
runId: run.id,
status: 'skipped_unavailable',
workspaceId: automation.workspaceId,
error: UNEVALUABLE_SCHEDULE
})
} catch (writeError) {
// The original failure has not been reported yet on this path, so carry it too.
console.error(
'[automations] failed to record unevaluable automation:',
automation.id,
input.error,
writeError
)
}
}
32 changes: 32 additions & 0 deletions src/main/automations/run-usage-collection.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { Automation, AutomationRun, AutomationRunUsage } from '../../shared/automations-types'
import type { Store } from '../persistence'
import type { AutomationRunWriter } from './automation-run-writer'
import type { ClaudeUsageStore } from '../claude-usage/store'
import type { CodexUsageStore } from '../codex-usage/store'

Expand Down Expand Up @@ -97,3 +99,33 @@ export async function collectAutomationRunUsage({
}
return unavailable(null, 'provider_unsupported', 'This agent does not report usage to Orca yet.')
}

/** Collects and writes the usage a just-finalized run earned, returning the row to answer with. */
export async function writeAutomationRunUsage(input: {
store: Store
runs: AutomationRunWriter
run: AutomationRun
claudeUsage: ClaudeUsageStore | null
codexUsage: CodexUsageStore | null
}): Promise<AutomationRun> {
const { store, run } = input
const usage = await collectAutomationRunUsage({
automation: store.listAutomations().find((entry) => entry.id === run.automationId),
run,
claudeUsage: input.claudeUsage,
codexUsage: input.codexUsage
})
// Why: the run is final during the await above, so a concurrent create-time
// retention prune may have evicted it — the usage write must not throw then.
if (!store.listAutomationRuns(run.automationId).some((entry) => entry.id === run.id)) {
return run
}
return input.runs.updateRun({
runId: run.id,
status: run.status,
workspaceId: run.workspaceId,
terminalSessionId: run.terminalSessionId,
usage,
error: run.error
})
}
115 changes: 115 additions & 0 deletions src/main/automations/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -647,4 +647,119 @@ describe('AutomationService', () => {
expect(updated.usage?.status).toBe('unavailable')
expect(updated.usage?.unavailableReason).toBe('provider_unsupported')
})

// #16303: listAutomations sorts by name, so 'A ...' is evaluated before 'B ...'.
it('keeps evaluating later due automations after an unreadable schedule throws', async () => {
vi.setSystemTime(new Date('2026-05-13T08:59:00'))
const store = await createStore()
store.addRepo(makeRepo())
const poison = store.createAutomation({
name: 'A poison schedule',
prompt: 'Check the repo',
agentId: 'claude',
projectId: 'r1',
workspaceMode: 'existing',
workspaceId: 'wt1',
timezone: 'UTC',
rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0',
dtstart: new Date('2026-05-12T00:00:00').getTime()
})
const healthy = store.createAutomation({
name: 'B healthy schedule',
prompt: 'Check the repo',
agentId: 'claude',
projectId: 'r1',
workspaceMode: 'existing',
workspaceId: 'wt1',
timezone: 'UTC',
rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0',
dtstart: new Date('2026-05-12T00:00:00').getTime()
})
// Persisted by an older build, or hand-edited: WEEKLY with no BYDAY cannot resolve a day.
mutateDataFile((state) => {
const entry = state.automations.find((automation) => automation.id === poison.id)!
entry.rrule = 'FREQ=WEEKLY;BYHOUR=9;BYMINUTE=0'
})
const reloaded = await createStore()
const logged = vi.spyOn(console, 'error').mockImplementation(() => {})

vi.setSystemTime(new Date('2026-05-13T09:01:00'))
const send = vi.fn()
const service = new AutomationService(reloaded, { tickMs: 60_000 })
service.setWebContents({ isDestroyed: () => false, send })

service.start()
service.setRendererReady()
await vi.waitFor(() =>
expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.any(Object))
)
service.stop()

const [, payload] = send.mock.calls[0]
expect(payload.automation.id).toBe(healthy.id)
expect(reloaded.listAutomationRuns(healthy.id)[0]?.status).toBe('dispatching')
const poisonRun = reloaded.listAutomationRuns(poison.id)[0]
expect(poisonRun?.status).toBe('skipped_unavailable')
expect(poisonRun?.error).toBe(
'Orca could not evaluate this automation and skipped the occurrence.'
)
expect(logged).toHaveBeenCalled()
})

// Same isolation, reached through the cron parser rather than the RRULE one, because that
// is the path all four cron repairs run on.
it('keeps evaluating later due automations after an unreadable cron schedule throws', async () => {
vi.setSystemTime(new Date('2026-05-13T08:59:00'))
const store = await createStore()
store.addRepo(makeRepo())
const poison = store.createAutomation({
name: 'A poison cron',
prompt: 'Check the repo',
agentId: 'claude',
projectId: 'r1',
workspaceMode: 'existing',
workspaceId: 'wt1',
timezone: 'UTC',
rrule: '0 9 * * *',
dtstart: new Date('2026-05-12T00:00:00').getTime()
})
const healthy = store.createAutomation({
name: 'B healthy cron',
prompt: 'Check the repo',
agentId: 'claude',
projectId: 'r1',
workspaceMode: 'existing',
workspaceId: 'wt1',
timezone: 'UTC',
rrule: '0 9 * * *',
dtstart: new Date('2026-05-12T00:00:00').getTime()
})
// Day of month 32 never validates at input; only a hand-edited or older-build row has it.
mutateDataFile((state) => {
const entry = state.automations.find((automation) => automation.id === poison.id)!
entry.rrule = '0 9 32 * *'
})
const reloaded = await createStore()
const logged = vi.spyOn(console, 'error').mockImplementation(() => {})

vi.setSystemTime(new Date('2026-05-13T09:01:00'))
const send = vi.fn()
const service = new AutomationService(reloaded, { tickMs: 60_000 })
service.setWebContents({ isDestroyed: () => false, send })

service.start()
service.setRendererReady()
await vi.waitFor(() =>
expect(send).toHaveBeenCalledWith('automations:dispatchRequested', expect.any(Object))
)
service.stop()

const [, payload] = send.mock.calls[0]
expect(payload.automation.id).toBe(healthy.id)
expect(reloaded.listAutomationRuns(healthy.id)[0]?.status).toBe('dispatching')
expect(reloaded.listAutomationRuns(poison.id)[0]?.error).toBe(
'Orca could not evaluate this automation and skipped the occurrence.'
)
expect(logged).toHaveBeenCalled()
})
})
Loading