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
63 changes: 63 additions & 0 deletions src/main/automations/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,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 } as never)
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
36 changes: 23 additions & 13 deletions src/main/automations/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import type {
AutomationDispatchResult,
AutomationPrecheckResult,
AutomationRun,
AutomationRunStatus
AutomationWebhookDelivery
} from '../../shared/automations-types'
import { isWebhookTriggerEnabled } from '../../shared/automation-webhook'
import { isFinalAutomationRunStatus } from '../../shared/automation-run-status'
import type { ClaudeUsageStore } from '../claude-usage/store'
import type { CodexUsageStore } from '../codex-usage/store'
import { runAutomationPrecheck } from './precheck-runner'
Expand Down Expand Up @@ -90,6 +92,25 @@ export class AutomationService {
return await this.requestDispatch(automation, run)
}

/** Trigger a run from an inbound webhook. The HTTP receiver has already
* verified the secret; here we re-check the trigger is enabled (config may
* have changed) and attach the captured delivery so its body is appended to
* the agent prompt. */
async triggerWebhook(
automationId: string,
delivery: AutomationWebhookDelivery
): Promise<AutomationRun> {
const automation = this.store.listAutomations().find((entry) => entry.id === automationId)
if (!automation) {
throw new Error('Automation not found.')
}
if (!isWebhookTriggerEnabled(automation)) {
throw new Error('Webhook trigger is not enabled for this automation.')
}
const run = this.store.createAutomationRun(automation, Date.now(), 'webhook', delivery)
return await this.requestDispatch(automation, run)
}

async runPrecheck(automationId: string, runId: string): Promise<AutomationPrecheckResult | null> {
const automation = this.store.listAutomations().find((entry) => entry.id === automationId)
if (!automation) {
Expand Down Expand Up @@ -131,7 +152,7 @@ export class AutomationService {

async markDispatchResult(result: AutomationDispatchResult): Promise<AutomationRun> {
const run = this.store.updateAutomationRun(result)
if (!isFinalRunStatus(run.status)) {
if (!isFinalAutomationRunStatus(run.status)) {
return run
}
// Why: the renderer's mark-completed effect can re-fire for the same run
Expand Down Expand Up @@ -300,14 +321,3 @@ export class AutomationService {
}
}
}

function isFinalRunStatus(status: AutomationRunStatus): boolean {
return (
status === 'completed' ||
status === 'dispatch_failed' ||
status === 'skipped_precheck' ||
status === 'skipped_missed' ||
status === 'skipped_unavailable' ||
status === 'skipped_needs_interactive_auth'
)
}
35 changes: 33 additions & 2 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@ import { initializeBrowserSessionsForApp } from './browser/browser-session-start
import { setUnreadDockBadgeCount } from './dock/unread-badge'
import { AutomationService } from './automations/service'
import { createHeadlessAutomationOutputSnapshotBuffer } from './automations/headless-dispatch'
import { composeAutomationDispatchPrompt } from '../shared/automation-webhook'
import { WebhookServer } from './webhooks/webhook-server'
import { generateWebhookSecret } from './webhooks/webhook-secret'
import { getDefaultWebhookServerSettings } from '../shared/constants'
import { AgentAwakeService } from './agent-awake-service'
import {
getCrashBreadcrumbSnapshot,
Expand Down Expand Up @@ -178,6 +182,8 @@ let unsubscribeAgentAwakeStatusChanges: (() => void) | null = null
let watcherShutdownPromise: Promise<void> | null = null
let watcherShutdownDone = false
let automations: AutomationService | null = null
let webhookServer: WebhookServer | null = null
let unsubscribeWebhookSettings: (() => void) | null = null
let keybindings: KeybindingService | null = null
let expectedRendererReload: { webContentsId: number; until: number } | null = null
let firstWindowStartupServicesReady: Promise<void> = Promise.resolve()
Expand Down Expand Up @@ -1354,6 +1360,9 @@ app.whenReady().then(async () => {
let terminalSessionId: string | null = null
let workspaceId: string
let workspaceDisplayName: string | null = null
// Why: webhook-triggered runs append the request body to the prompt;
// keep this in sync with the renderer dispatch path.
const dispatchPrompt = composeAutomationDispatchPrompt(automation, run)

if (automation.workspaceMode === 'new_per_run') {
const created = await runtimeService.createManagedWorktree({
Expand All @@ -1364,7 +1373,7 @@ app.whenReady().then(async () => {
activate: false,
createdWithAgent: automation.agentId,
startupAgent: automation.agentId,
startupPrompt: automation.prompt,
startupPrompt: dispatchPrompt,
telemetrySource: 'unknown'
})
terminalHandle = created.startupTerminal?.handle ?? ''
Expand All @@ -1385,7 +1394,7 @@ app.whenReady().then(async () => {
`id:${automation.workspaceId}`,
{
agent: automation.agentId,
prompt: automation.prompt,
prompt: dispatchPrompt,
title: run.title
}
)
Expand Down Expand Up @@ -1431,6 +1440,25 @@ app.whenReady().then(async () => {
: undefined
})
runtimeService.setAutomationService(automations)
// Why: inbound-webhook listener (issue #2). The bind interface/port live in
// settings; apply() starts/stops/rebinds to match, and the settings
// subscription keeps it in sync when the user changes the config live.
const automationsService = automations
webhookServer = new WebhookServer({
getAutomation: (id) => store!.listAutomations().find((entry) => entry.id === id),
triggerWebhook: (id, delivery) => automationsService.triggerWebhook(id, delivery)
})
void webhookServer.apply(store!.getSettings().webhookServer ?? getDefaultWebhookServerSettings())
unsubscribeWebhookSettings?.()
unsubscribeWebhookSettings = store!.onSettingsChanged((updates) => {
if ('webhookServer' in updates) {
void webhookServer?.apply(
store!.getSettings().webhookServer ?? getDefaultWebhookServerSettings()
)
}
})
ipcMain.handle('automations:webhookEndpoint', () => webhookServer?.getEndpoint() ?? null)
ipcMain.handle('automations:generateWebhookSecret', () => generateWebhookSecret())
runtimeService.setAccountServices({ claudeAccounts, codexAccounts, rateLimits })
runtimeService.setCommitMessageAgentEnvironmentResolvers({
// Why: local Codex hooks and auth now live in Orca's managed runtime home
Expand Down Expand Up @@ -1679,6 +1707,9 @@ app.on('will-quit', (e) => {
// agent_start events with no matching stops.
starNag?.stop()
automations?.stop()
unsubscribeWebhookSettings?.()
unsubscribeWebhookSettings = null
webhookServer?.stop()
setUnreadDockBadgeCount(0)
agentHookServer.stop()
stats?.flush()
Expand Down
56 changes: 56 additions & 0 deletions src/main/persistence.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1162,6 +1162,62 @@ describe('Store', () => {
expect(persisted.automations[0].baseBranch).toBeNull()
})

it('persists and normalizes a webhook trigger config', async () => {
const store = await createStore()
store.addRepo(makeRepo())

const automation = store.createAutomation({
name: 'MR review',
prompt: 'Review the merge request',
agentId: 'claude',
projectId: 'r1',
workspaceMode: 'new_per_run',
timezone: 'UTC',
rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0',
dtstart: new Date('2026-05-13T00:00:00Z').getTime(),
webhook: { enabled: true, secretMode: 'token', secret: ' s3cret ' }
})

expect(automation.webhook).toEqual({ enabled: true, secretMode: 'token', secret: 's3cret' })

// A 'none' mode update drops the secret.
const cleared = store.updateAutomation(automation.id, {
webhook: { enabled: true, secretMode: 'none', secret: 'ignored' }
})
expect(cleared.webhook).toEqual({ enabled: true, secretMode: 'none', secret: null })
store.flush()
const persisted = readDataFile() as {
automations: { webhook: { secret: string | null } }[]
}
expect(persisted.automations[0].webhook.secret).toBeNull()
})

it('stores the captured webhook delivery on a webhook-triggered run', async () => {
const store = await createStore()
store.addRepo(makeRepo())
const automation = store.createAutomation({
name: 'MR review',
prompt: 'Review the merge request',
agentId: 'claude',
projectId: 'r1',
workspaceMode: 'new_per_run',
timezone: 'UTC',
rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0',
dtstart: new Date('2026-05-13T00:00:00Z').getTime(),
webhook: { enabled: true, secretMode: 'none', secret: null }
})

const run = store.createAutomationRun(automation, Date.now(), 'webhook', {
body: '{"object_kind":"merge_request"}',
contentType: 'application/json',
truncated: false,
receivedAt: 123
})

expect(run.trigger).toBe('webhook')
expect(run.webhookDelivery?.body).toBe('{"object_kind":"merge_request"}')
})

it('persists session reuse only for existing-workspace automations', async () => {
const store = await createStore()
store.addRepo(makeRepo())
Expand Down
19 changes: 17 additions & 2 deletions src/main/persistence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,16 @@ import type {
AutomationRun,
AutomationSchedulerOwner,
AutomationRunTrigger,
AutomationUpdateInput
AutomationUpdateInput,
AutomationWebhookDelivery
} from '../shared/automations-types'
import {
latestAutomationOccurrenceAtOrBefore,
nextAutomationOccurrenceAfter
} from '../shared/automation-schedules'
import { getAutomationLegacyRepoId } from '../shared/automation-run-identity'
import { normalizeAutomationPrecheck } from '../shared/automation-precheck'
import { normalizeAutomationWebhookConfig } from '../shared/automation-webhook'
import type {
PersistedState,
Project,
Expand Down Expand Up @@ -86,6 +88,7 @@ import {
getDefaultWorkspaceSession,
normalizeAgentActivityDisplayMode,
normalizeWorktreeCardProperties,
normalizeWebhookServerSettings,
ONBOARDING_FLOW_VERSION,
ONBOARDING_FINAL_STEP
} from '../shared/constants'
Expand Down Expand Up @@ -3885,6 +3888,7 @@ export class Store {
nextRunAt: nextAutomationOccurrenceAfter(input.rrule, input.dtstart, now),
missedRunPolicy: 'run_once_within_grace',
missedRunGraceMinutes: input.missedRunGraceMinutes ?? 720,
webhook: normalizeAutomationWebhookConfig(input.webhook ?? null),
createdAt: now,
updatedAt: now
}
Expand Down Expand Up @@ -3917,6 +3921,9 @@ export class Store {
precheck: Object.hasOwn(updates, 'precheck')
? normalizeAutomationPrecheck(updates.precheck)
: normalizeAutomationPrecheck(current.precheck),
webhook: Object.hasOwn(updates, 'webhook')
? normalizeAutomationWebhookConfig(updates.webhook)
: normalizeAutomationWebhookConfig(current.webhook ?? null),
projectId: repoId,
runContext: Object.hasOwn(updates, 'runContext')
? (updates.runContext ?? null)
Expand Down Expand Up @@ -3971,7 +3978,8 @@ export class Store {
createAutomationRun(
automation: Automation,
scheduledFor: number,
trigger: AutomationRunTrigger = 'scheduled'
trigger: AutomationRunTrigger = 'scheduled',
webhookDelivery: AutomationWebhookDelivery | null = null
): AutomationRun {
const existing = (this.state.automationRuns ?? []).find(
(run) => run.automationId === automation.id && run.scheduledFor === scheduledFor
Expand Down Expand Up @@ -4000,6 +4008,7 @@ export class Store {
outputSnapshot: null,
precheckResult: null,
usage: null,
webhookDelivery,
error: null,
startedAt: null,
dispatchedAt: null,
Expand Down Expand Up @@ -4471,6 +4480,12 @@ export class Store {
if ('appIcon' in updates) {
sanitizedUpdates.appIcon = normalizeAppIconId(updates.appIcon)
}
if ('webhookServer' in updates) {
sanitizedUpdates.webhookServer = normalizeWebhookServerSettings(
updates.webhookServer,
this.state.settings.webhookServer
)
}
if ('uiLanguage' in updates) {
sanitizedUpdates.uiLanguage = normalizeUiLanguage(updates.uiLanguage)
}
Expand Down
6 changes: 5 additions & 1 deletion src/main/runtime/orca-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2127,7 +2127,8 @@ export class OrcaRuntimeService {
rrule: input.rrule,
dtstart: input.dtstart,
enabled: input.enabled,
missedRunGraceMinutes: input.missedRunGraceMinutes
missedRunGraceMinutes: input.missedRunGraceMinutes,
webhook: input.webhook
})
}

Expand Down Expand Up @@ -2176,6 +2177,9 @@ export class OrcaRuntimeService {
if (hasRuntimeAutomationUpdateValue(updates, 'missedRunGraceMinutes')) {
patch.missedRunGraceMinutes = updates.missedRunGraceMinutes
}
if (hasRuntimeAutomationUpdateValue(updates, 'webhook')) {
patch.webhook = updates.webhook
}
const targetChanged =
hasRuntimeAutomationUpdateValue(updates, 'repo') ||
hasRuntimeAutomationUpdateValue(updates, 'workspace') ||
Expand Down
Loading
Loading