Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
39 changes: 39 additions & 0 deletions src/main/automations/automation-run-precheck.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import type { Store } from '../persistence'
import type { Automation, AutomationPrecheckResult } from '../../shared/automations-types'
import type { AutomationRunTargetResult } from './run-target-resolution'
import { failedPrecheckResult, runAutomationPrecheck } from './precheck-runner'

export async function runStoredAutomationPrecheck({
store,
automationId,
runId,
resolveTarget
}: {
store: Store
automationId: string
runId: string
resolveTarget: (automation: Automation) => AutomationRunTargetResult
}): Promise<AutomationPrecheckResult | null> {
const automation = store.listAutomations().find((entry) => entry.id === automationId)
if (!automation) {
throw new Error('Automation not found.')
}
const run = store.listAutomationRuns(automationId).find((entry) => entry.id === runId)
if (!run) {
throw new Error('Automation run not found.')
}
if (run.trigger !== 'scheduled' || !automation.precheck) {
return null
}
const target = resolveTarget(automation)
if (!target.ok) {
return failedPrecheckResult(automation.precheck, Date.now(), target.error)
}
return await runAutomationPrecheck({
precheck: automation.precheck,
target:
automation.executionTargetType === 'ssh'
? { type: 'ssh', cwd: target.cwd, connectionId: automation.executionTargetId }
: { type: 'local', cwd: target.cwd }
})
}
21 changes: 21 additions & 0 deletions src/main/automations/automation-run-writer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,27 @@ describe('automation run writer publications', () => {
expect(publish).not.toHaveBeenCalled()
})

it('persists webhook deliveries before publishing the run', async () => {
const { store, writer, publish } = writerWith(SSH_SELECTOR)
const delivery = {
body: '{"event":"push"}',
contentType: 'application/json',
truncated: false,
receivedAt: 1
}
const acknowledgement = Promise.withResolvers<void>()
store.flushPendingOrThrowAsync.mockReturnValue(acknowledgement.promise)
const settled = vi.fn()
const pending = writer.createRun(automation, 1, 'webhook', delivery).then(settled)
await Promise.resolve()
expect(store.createAutomationRun).toHaveBeenCalledWith(automation, 1, 'webhook', delivery)
expect(publish).not.toHaveBeenCalled()
expect(settled).not.toHaveBeenCalled()
acknowledgement.resolve()
await pending
expect(publish).toHaveBeenCalledOnce()
})

it('names the host a created run belongs to', async () => {
const { writer, publish } = writerWith(SSH_SELECTOR)
await writer.createRun(automation, 0, 'scheduled')
Expand Down
9 changes: 7 additions & 2 deletions src/main/automations/automation-run-writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,13 @@ export function createAutomationRunWriter(
await store.flushPendingOrThrowAsync({ drainToStableGeneration: false })
return automation
},
createRun: async (automation, scheduledFor, trigger): Promise<AutomationRun> => {
const run = store.createAutomationRun(automation, scheduledFor, trigger)
createRun: async (
automation,
scheduledFor,
trigger,
webhookDelivery
): Promise<AutomationRun> => {
const run = store.createAutomationRun(automation, scheduledFor, trigger, webhookDelivery)
await store.flushPendingOrThrowAsync({ drainToStableGeneration: false })
announce(automation.id, 'run')
return run
Expand Down
5 changes: 3 additions & 2 deletions src/main/automations/headless-automation-agent-launch.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { composeAutomationDispatchPrompt } from '../../shared/automation-webhook'
// Automations observe PTYs, so launch terminal agents regardless of the chat default.

import type {
Expand Down Expand Up @@ -31,14 +32,14 @@ export async function launchHeadlessAutomationAgent(
runtime: OrcaRuntimeService,
request: {
automation: Automation
run: Pick<AutomationRun, 'id' | 'title' | 'scheduledFor'>
run: Pick<AutomationRun, 'id' | 'title' | 'scheduledFor' | 'webhookDelivery'>
target: Extract<AutomationRunTargetResult, { ok: true }>
runs: readonly AutomationRun[]
}
): Promise<HeadlessAutomationAgentLaunch> {
const { automation, run, target } = request
const agent = automation.agentId
const text = automation.prompt?.trim()
const text = composeAutomationDispatchPrompt(automation, run)?.trim()
if (automation.reuseSession && automation.workspaceMode === 'existing' && text) {
const reused = await sendToReusableSession(runtime, { ...request, text })
if (reused) {
Expand Down
8 changes: 6 additions & 2 deletions src/main/automations/headless-workspace-create.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { composeAutomationDispatchPrompt } from '../../shared/automation-webhook'
import type { Automation, AutomationRun } from '../../shared/automations-types'
import { buildAutomationWorkspaceProvenance } from '../../shared/automation-workspace-provenance'
import type { Repo } from '../../shared/repo-types'
import type { OrcaRuntimeService } from '../runtime/orca-runtime'

type HeadlessAutomationRunForWorkspace = Pick<AutomationRun, 'id' | 'title' | 'scheduledFor'>
type HeadlessAutomationRunForWorkspace = Pick<
AutomationRun,
'id' | 'title' | 'scheduledFor' | 'webhookDelivery'
>
type RuntimeCreateManagedWorktreeArgs = Parameters<OrcaRuntimeService['createManagedWorktree']>[0]

export function buildHeadlessAutomationWorkspaceName(
Expand Down Expand Up @@ -39,7 +43,7 @@ export function buildHeadlessAutomationWorktreeCreateArgs({
activate: false,
createdWithAgent: automation.agentId,
startupAgent: automation.agentId,
startupPrompt: automation.prompt,
startupPrompt: composeAutomationDispatchPrompt(automation, run),
startupSuppressUpdatePrompt: true,
...(automation.extraAgentArgs ? { startupExtraAgentArgs: automation.extraAgentArgs } : {}),
telemetrySource: 'unknown',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ function build(headless: boolean) {
)
}
const store = {
onSettingsChanged: vi.fn(() => vi.fn()),
getSettings: () => ({
webhookServer: { enabled: false, bindAddress: '127.0.0.1', port: 8473 }
}),
listAutomationRuns: vi.fn(() => finishedRuns(5)),
listAutomations: () => [],
getWorktreeMeta: vi.fn(
Expand Down
3 changes: 3 additions & 0 deletions src/main/automations/runtime-automation-service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { bindAutomationWebhookLifecycle } from '../webhooks/automation-webhook-lifecycle'

import type { ClaudeUsageStore } from '../claude-usage/store'
import type { CodexUsageStore } from '../codex-usage/store'
import type { Store } from '../persistence'
Expand Down Expand Up @@ -60,6 +62,7 @@ export function createRuntimeAutomationService(input: {
}
: undefined
})
bindAutomationWebhookLifecycle(service, store)
runtime.setAutomationService(service)
if (input.headless) {
bindHeadlessRunTerminalRetention(service, store, runtime)
Expand Down
71 changes: 71 additions & 0 deletions src/main/automations/service-webhook-legacy-target.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { mkdtempSync, rmSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import {
closeTestStores,
createStore,
testState,
readPersistedStateJson,
writePersistedStateJson
} from '../persistence/persistence-test-harness'
import { AutomationService } from './service'

vi.mock('electron', () => ({
app: { getPath: () => testState.dir },
safeStorage: {
isEncryptionAvailable: () => true,
encryptString: (text: string) => Buffer.from(`encrypted:${text}`),
decryptString: (data: Buffer) => data.toString().slice('encrypted:'.length)
}
}))

beforeEach(() => {
testState.dir = mkdtempSync(join(tmpdir(), 'orca-webhook-legacy-'))
})

afterEach(async () => {
await closeTestStores()
rmSync(testState.dir, { recursive: true, force: true })
})

it('captures a legacy webhook target before publishing the dispatch snapshot', async () => {
const store = await createStore()
store.addRepo({ id: 'r1', path: '/repo', displayName: 'test', badgeColor: '#fff', addedAt: 1 })
const created = store.createAutomation({
name: 'Legacy webhook',
prompt: 'Review delivery',
agentId: 'claude',
projectId: 'r1',
workspaceMode: 'new_per_run',
timezone: 'UTC',
rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0',
dtstart: Date.now() + 86_400_000,
webhook: { enabled: true, secretMode: 'none', secret: null }
})
const file = join(testState.dir, 'orca-data.json')
const persisted = JSON.parse(readPersistedStateJson(file))
persisted.automations[0].runContext = null
writePersistedStateJson(file, JSON.stringify(persisted))
const reloaded = await createStore()
expect(reloaded.listAutomations()[0].runContext).toBeNull()
const send = vi.fn()
const service = new AutomationService(reloaded)
service.setWebContents({ isDestroyed: () => false, send })
service.setRendererReady()
const run = await service.triggerWebhook(created.id, {
body: '{}',
contentType: 'application/json',
truncated: false,
receivedAt: Date.now()
})
const context = reloaded.listAutomations()[0].runContext
expect(context).toMatchObject({ hostId: 'local', repoId: 'r1', path: '/repo' })
expect(send).toHaveBeenCalledWith(
'automations:dispatchRequested',
expect.objectContaining({
automation: expect.objectContaining({ runContext: context }),
run: expect.objectContaining({ id: run.id, trigger: 'webhook' })
})
)
})
63 changes: 63 additions & 0 deletions src/main/automations/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,69 @@ describe('AutomationService', () => {
)
})

it('dispatches a webhook-triggered run carrying the delivery body', async () => {
vi.setSystemTime(new Date('2026-05-13T08:00:00Z'))
const store = await createStore()
store.addRepo(makeRepo())
const automation = store.createAutomation({
name: 'MR review',
prompt: 'Review the merge request',
agentId: 'claude',
projectId: 'r1',
workspaceMode: 'existing',
workspaceId: 'wt1',
timezone: 'UTC',
rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0',
dtstart: new Date('2026-05-14T00:00:00Z').getTime(),
webhook: { enabled: true, secretMode: 'none', secret: null }
})
const send = vi.fn()
const service = new AutomationService(store, { tickMs: 60_000 })
service.setWebContents({ isDestroyed: () => false, send })
service.setRendererReady()

const run = await service.triggerWebhook(automation.id, {
body: '{"object_kind":"merge_request"}',
contentType: 'application/json',
truncated: false,
receivedAt: 1
})

expect(run.trigger).toBe('webhook')
expect(run.webhookDelivery?.body).toBe('{"object_kind":"merge_request"}')
expect(send).toHaveBeenCalledWith(
'automations:dispatchRequested',
expect.objectContaining({
run: expect.objectContaining({ id: run.id })
})
)
})

it('rejects a webhook trigger when the automation has no webhook enabled', async () => {
const store = await createStore()
store.addRepo(makeRepo())
const automation = store.createAutomation({
name: 'No webhook',
prompt: 'x',
agentId: 'claude',
projectId: 'r1',
workspaceMode: 'existing',
workspaceId: 'wt1',
timezone: 'UTC',
rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0',
dtstart: new Date('2026-05-14T00:00:00Z').getTime()
})
const service = new AutomationService(store, { tickMs: 60_000 })
await expect(
service.triggerWebhook(automation.id, {
body: '{}',
contentType: null,
truncated: false,
receivedAt: 1
})
).rejects.toThrow(/not enabled/i)
})

it('skips dispatch when the selected project host setup is gone', async () => {
vi.setSystemTime(new Date('2026-05-13T08:00:00Z'))
const store = await createStore()
Expand Down
57 changes: 29 additions & 28 deletions src/main/automations/service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getWebhookAutomationForDispatch } from './webhook-run-target'
import {
AutomationDispatchCancelledError,
requestAutomationDispatch,
Expand All @@ -10,16 +11,15 @@ import {
type Automation,
type AutomationDispatchResult,
type AutomationPrecheckResult,
type AutomationRun
type AutomationRun,
type AutomationWebhookDelivery,
type WebhookServerEndpoint
} from '../../shared/automations-types'
import type { ClaudeUsageStore } from '../claude-usage/store'
import type { CodexUsageStore } from '../codex-usage/store'
import { failedPrecheckResult, runAutomationPrecheck } from './precheck-runner'
import {
captureLegacyRunTarget,
resolveAutomationRunTarget,
type AutomationRunTargetResult
} from './run-target-resolution'
import { runStoredAutomationPrecheck } from './automation-run-precheck'
import { captureLegacyRunTarget, resolveAutomationRunTarget } from './run-target-resolution'
import type { AutomationRunTargetResult } from './run-target-resolution'
import { writeAutomationRunUsage } from './run-usage-collection'
import type { HeadlessAutomationDispatcher } from './headless-dispatch'
import { runKeyedSerializedOperation } from '../cli/keyed-promise-queue'
Expand Down Expand Up @@ -142,6 +142,23 @@ export class AutomationService {
this.timer = null
}

getWebhookEndpoint: (() => WebhookServerEndpoint) | null = null

async triggerWebhook(
automationId: string,
delivery: AutomationWebhookDelivery
): Promise<AutomationRun> {
const generation = this.dispatchGeneration
const automation = getWebhookAutomationForDispatch(
this.store,
automationId,
this.allowRemoteHostScheduling
)
const target = this.resolveTarget(automation)
const run = await this.runs.createRun(automation, Date.now(), 'webhook', delivery)
return await this.requestDispatch(automation, run, target, generation)
}

async runNow(automationId: string): Promise<AutomationRun> {
const generation = this.dispatchGeneration
const listed = this.store.listAutomations().find((entry) => entry.id === automationId)
Expand All @@ -167,27 +184,11 @@ export class AutomationService {
}

async runPrecheck(automationId: string, runId: string): Promise<AutomationPrecheckResult | null> {
const automation = this.store.listAutomations().find((entry) => entry.id === automationId)
if (!automation) {
throw new Error('Automation not found.')
}
const run = this.store.listAutomationRuns(automationId).find((entry) => entry.id === runId)
if (!run) {
throw new Error('Automation run not found.')
}
if (run.trigger !== 'scheduled' || !automation.precheck) {
return null
}
const target = this.resolveTarget(automation)
if (!target.ok) {
return failedPrecheckResult(automation.precheck, Date.now(), target.error)
}
return await runAutomationPrecheck({
precheck: automation.precheck,
target:
automation.executionTargetType === 'ssh'
? { type: 'ssh', cwd: target.cwd, connectionId: automation.executionTargetId }
: { type: 'local', cwd: target.cwd }
return await runStoredAutomationPrecheck({
store: this.store,
automationId,
runId,
resolveTarget: (automation) => this.resolveTarget(automation)
})
}

Expand Down
Loading