Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(trigger): delivery — sendText paste path, idle gate, deliver-on-idle queue (#493 phase 3)
enes6cb12088fd52
diff --git a/CLAUDE.md b/CLAUDE.mdindex 77b55c463..5e62257c7 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -138,10 +138,17 @@ group transforms (`groupSelectedNodes`, `ungroupNodes`, `duplicateNode`), and th`src/shared/types.ts`): `terminal | sticky | group | editor | diff | video | web | browser |subagent | loop | dino | trigger` — `subagent` and `loop` are render-only (ephemeral hook-drivenviz) and never persisted. `trigger` (issue #493, landing in phases — schema + the core-scheduler so far: `core/trigger-scheduler.ts`, booted by BOTH shells, sweep-service shape,-fire-time `TriggerArmStore.isArmed` re-ask, no catch-up for missed slots, cron matched by the-dependency-free `@shared/cron` with the vixie dom/dow OR rule; delivery + renderer still to come)-is a first-class PERSISTED kind: its spec (`CanvasNodeState.trigger`,+scheduler + DELIVERY so far; the renderer/arming UI is the remaining phase, so nothing can arm a+trigger yet and nothing fires in production) is a first-class PERSISTED kind. The whole host-side+machine is composed ONCE in `core/trigger-service.ts` (`startTriggerService`) and booted+identically by BOTH shells: `core/trigger-scheduler.ts` (sweep-service shape, no catch-up for+missed slots, cron via the dependency-free `@shared/cron` with the vixie dom/dow OR rule) decides+WHEN, and `core/trigger-delivery.ts` decides WHETHER — the `sendText` paste path, an agent target+only on a mirror-verified idle `done` (busy/blocked/unknown → the messaging `DeliveryQueue`, own+instance, flushed by the mirror's `done` edge via `onNodeStateChange`, with FULL flush-time+re-validation: a trigger disarmed or spec-edited while queued is dropped), a plain-terminal target+only into a SHELL pane and never queued, a dead target an honest `missed` and never a cold start.+Fire-time `TriggerArmStore.isArmed` re-ask everywhere; every rule test-pinned. The kind's spec: its spec (`CanvasNodeState.trigger`,@shared/trigger) is git-shared CONTENT sanitized as hostile input on every load path(`sanitizeNodeTriggers`), and the definition alone never fires — execution consent is themachine-local, content-bound `core/trigger-arm-store.ts` (a spec that arrives or CHANGES via gitdiff --git a/src/core/trigger-delivery.test.ts b/src/core/trigger-delivery.test.tsnew file mode 100644index 000000000..467104329--- /dev/null+++ b/src/core/trigger-delivery.test.ts@@ -0,0 +1,201 @@+import { describe, expect, it, vi } from 'vitest'+import type { CanvasNodeState } from '../shared/types'+import type { TriggerSpec } from '../shared/trigger'+import { createTriggerDelivery, type TriggerDeliveryDeps } from './trigger-delivery'+import type { TriggerRow, TriggerRun } from './trigger-scheduler'++const spec = (payload = 'npm run report'): TriggerSpec => ({+ schedule: { kind: 'cron', expr: '0 9 * * *' },+ payload,+ target: 'term-tgt-1'+})++const row = (payload?: string): TriggerRow => ({+ projectId: 'project-1',+ nodeId: 'trigger-a-1',+ spec: spec(payload)+})++interface World {+ nodes: Map<string, Partial<CanvasNodeState>>+ state: string | undefined+ pane: string | null+ sent: Array<{ nodeId: string; text: string }>+ sendOk: boolean+ armed: boolean+ triggerSpec: TriggerSpec | undefined+ runs: Array<{ nodeId: string; run: TriggerRun }>+ timers: Array<{ ms: number; fn: () => void }>+ delivery: ReturnType<typeof createTriggerDelivery>+ deps: TriggerDeliveryDeps+}++function world(overrides: Partial<TriggerDeliveryDeps> = {}): World {+ const w = {+ nodes: new Map<string, Partial<CanvasNodeState>>([+ ['term-tgt-1', { agentId: 'claude' }]+ ]),+ state: 'done' as string | undefined,+ pane: null as string | null,+ sent: [] as Array<{ nodeId: string; text: string }>,+ sendOk: true,+ armed: true,+ triggerSpec: spec() as TriggerSpec | undefined,+ runs: [] as Array<{ nodeId: string; run: TriggerRun }>,+ timers: [] as Array<{ ms: number; fn: () => void }>+ }+ const deps: TriggerDeliveryDeps = {+ sendText: vi.fn(async (nodeId: string, text: string) => {+ if (w.sendOk) w.sent.push({ nodeId, text })+ return w.sendOk+ }),+ paneCommand: async () => w.pane,+ agentState: () => (w.state === undefined ? undefined : { state: w.state }),+ targetNode: (nodeId) => w.nodes.get(nodeId) as CanvasNodeState | undefined,+ currentSpec: () => w.triggerSpec,+ isArmed: () => w.armed,+ schedule: (ms, fn) => {+ const t = { ms, fn }+ w.timers.push(t)+ return () => {+ const i = w.timers.indexOf(t)+ if (i >= 0) w.timers.splice(i, 1)+ }+ },+ ...overrides+ }+ const delivery = createTriggerDelivery(deps)+ delivery.setRunSink((_p, nodeId, run) => w.runs.push({ nodeId, run }))+ // Attach onto the SAME object the dep closures capture — a spread copy would let a test mutate+ // fields the delivery never reads.+ return Object.assign(w, { delivery, deps })+}++describe('trigger delivery — immediate outcomes', () => {+ it('delivers into an idle (done) agent target', async () => {+ const w = world()+ const r = await w.delivery.fire(row())+ expect(r.outcome).toBe('fired')+ expect(w.sent).toEqual([{ nodeId: 'term-tgt-1', text: 'npm run report' }])+ })++ it('a gone target is missed — nothing sent', async () => {+ const w = world()+ w.nodes.clear()+ const r = await w.delivery.fire(row())+ expect(r.outcome).toBe('missed')+ expect(r.detail).toMatch(/no longer exists/)+ expect(w.sent).toHaveLength(0)+ })++ it('a dead session is missed (sendText false)', async () => {+ const w = world()+ w.sendOk = false+ const r = await w.delivery.fire(row())+ expect(r.outcome).toBe('missed')+ expect(r.detail).toMatch(/not running/)+ })++ it('a plain terminal delivers only into a SHELL pane, and is never queued', async () => {+ const w = world()+ w.nodes.set('term-tgt-1', {}) // no agentId+ w.pane = 'zsh'+ expect((await w.delivery.fire(row())).outcome).toBe('fired')++ w.pane = 'vim'+ const busy = await w.delivery.fire(row())+ expect(busy.outcome).toBe('missed')+ expect(busy.detail).toContain("running 'vim'")++ w.pane = null+ expect((await w.delivery.fire(row())).outcome).toBe('missed')+ // One successful send total — the vim and null-pane attempts typed nothing.+ expect(w.sent).toHaveLength(1)+ })++ it('a busy agent target queues; an unknown agent state queues too', async () => {+ const w = world()+ w.state = 'working'+ const busy = await w.delivery.fire(row())+ expect(busy.outcome).toBe('queued')+ expect(busy.detail).toContain('working')++ w.state = undefined+ const unknown = await w.delivery.fire(row('second payload'))+ expect(unknown.outcome).toBe('queued')+ expect(w.sent).toHaveLength(0)+ })+})++describe('trigger delivery — the deliver-on-idle queue', () => {+ it('flushes on the idle edge and reports delivered-late', async () => {+ const w = world()+ w.state = 'working'+ expect((await w.delivery.fire(row())).outcome).toBe('queued')+ w.state = 'done'+ await w.delivery.onTargetIdle('term-tgt-1')+ expect(w.sent).toEqual([{ nodeId: 'term-tgt-1', text: 'npm run report' }])+ expect(w.runs.map((r) => r.run.outcome)).toEqual(['delivered-late'])+ expect(w.runs[0].nodeId).toBe('trigger-a-1')+ })++ it('FLUSH-TIME RE-VALIDATION: disarmed while queued is dropped, never delivered', async () => {+ const w = world()+ w.state = 'working'+ await w.delivery.fire(row())+ w.armed = false // the user disarmed the trigger while its payload waited+ w.state = 'done'+ await w.delivery.onTargetIdle('term-tgt-1')+ expect(w.sent).toHaveLength(0)+ expect(w.runs.map((r) => r.run.outcome)).toEqual(['missed'])+ expect(w.runs[0].run.detail).toMatch(/disarmed or edited/)+ })++ it('FLUSH-TIME RE-VALIDATION: a spec edited while queued is dropped', async () => {+ const w = world()+ w.state = 'working'+ await w.delivery.fire(row())+ w.triggerSpec = spec('some new payload') // git pull rewrote the trigger+ w.state = 'done'+ await w.delivery.onTargetIdle('term-tgt-1')+ expect(w.sent).toHaveLength(0)+ expect(w.runs.map((r) => r.run.outcome)).toEqual(['missed'])+ })++ it('a target still busy at flush is re-queued, then delivered on the next idle', async () => {+ const w = world()+ w.state = 'working'+ await w.delivery.fire(row())+ // The idle edge fires but the target picked up new work before the flush ran.+ await w.delivery.onTargetIdle('term-tgt-1')+ expect(w.sent).toHaveLength(0)+ w.state = 'done'+ await w.delivery.onTargetIdle('term-tgt-1')+ expect(w.sent).toHaveLength(1)+ expect(w.runs.map((r) => r.run.outcome)).toEqual(['delivered-late'])+ })++ it('a queued payload that waits out its TTL expires with a run record, nothing sent', async () => {+ const w = world()+ w.state = 'working'+ await w.delivery.fire(row())+ expect(w.timers).toHaveLength(1)+ w.timers[0].fn() // the TTL timer fires+ await Promise.resolve()+ expect(w.sent).toHaveLength(0)+ expect(w.runs.map((r) => r.run.outcome)).toEqual(['expired'])+ expect(w.runs[0].run.detail).toMatch(/never went idle/)+ })++ it('a target that disappears while queued is a missed run at flush', async () => {+ const w = world()+ w.state = 'working'+ await w.delivery.fire(row())+ w.nodes.clear()+ w.state = 'done'+ await w.delivery.onTargetIdle('term-tgt-1')+ expect(w.sent).toHaveLength(0)+ expect(w.runs.map((r) => r.run.outcome)).toEqual(['missed'])+ expect(w.runs[0].run.detail).toMatch(/went away/)+ })+})diff --git a/src/core/trigger-delivery.ts b/src/core/trigger-delivery.tsnew file mode 100644index 000000000..99c77c22f--- /dev/null+++ b/src/core/trigger-delivery.ts@@ -0,0 +1,183 @@+/**+ * Trigger DELIVERY (issue #493, phase 3) — the real implementation behind the scheduler's `fire`+ * seam: put the armed payload into the target's pane, or say honestly why not.+ *+ * The delivery path is the existing `sendText` (`paste-buffer -p` — tmux frames from the pane's+ * REAL bracketed-paste state, and the payload travels by stdin, never argv). This module only+ * decides WHETHER to send, and the rules mirror the ones agent messaging already measured:+ *+ * - **An agent target delivers only on a verified-idle turn boundary** (`mirrorEntry.state ===+ * 'done'`). A `working` target is mid-turn; a `blocked`/`waiting` one is sitting on a+ * permission prompt or a question, where a pasted payload would ANSWER it (the agent-restart+ * lesson). An UNKNOWN state — no hook event this app run, common right after a restart — is+ * not evidence of idleness either. All of those go to the deliver-on-idle QUEUE.+ * - **The queue is the messaging `DeliveryQueue`, own instance** — same TTL/capacity/flush+ * machinery, same load-bearing property: the flush re-runs the WHOLE decision against live+ * state (arm gate included), caching nothing. A trigger disarmed — or spec-edited — while its+ * payload waited is DROPPED at flush, never delivered; pinned by test. The idle signal is the+ * core mirror's own `done` edge (`onNodeStateChange`), which BOTH shells feed, so there is no+ * per-shell listener to drift.+ * - **A plain-terminal target delivers only into a SHELL-owned pane** (`isShellCommand`) — the+ * payload executing is the trigger's purpose, consented at arm time — and is never queued: the+ * DECSET-2004 measurement behind the queue says a non-agent pane is the ONE unsafe surface for+ * an unattended paste, and a plain terminal emits no idle event to flush on anyway. A pane+ * running something else (vim, a dev server) is an honest `missed`, with the command named.+ * - **A dead target is a `missed`, never a cold start** (v1 decision from the design thread):+ * a session that does not exist (`sendText` → false, `paneCommand` → null) records why and the+ * schedule moves on. Auto-launching a node from a timer is a larger consent surface, deferred.+ */++import { randomUUID } from 'node:crypto'+import { hasHooks, type AgentId } from '../shared/agents/config'+import { isShellCommand } from '../shared/agents/pane'+import { canonicalTriggerSpec, sanitizeTriggerSpec, type TriggerSpec } from '../shared/trigger'+import type { AgentMessageOutcome } from './agents/agent-message-decide'+import { DeliveryQueue, type CancelTimer, type QueuedDeliveryRequest } from './agents/delivery-queue'+import type { TriggerFireResult, TriggerRow, TriggerRun } from './trigger-scheduler'++export interface TriggerDeliveryDeps {+ /** `PtyManager.sendText` — the paste path; false = tmux unavailable / session doesn't exist. */+ sendText(nodeId: string, text: string): Promise<boolean>+ /** `PtyManager.paneCommand` — null = no live session / unreadable, never evidence of a command. */+ paneCommand(nodeId: string): Promise<string | null>+ /** The mirror's live view of the target (`mirrorEntry`) — state undefined = unknown. */+ agentState(nodeId: string): { state?: string } | undefined+ /** The persisted target node (`WorkspaceStore.getNode`) — undefined = gone from every canvas. */+ targetNode(nodeId: string): { agentId?: string } | undefined+ /**+ * The TRIGGER node's own current spec, re-resolved for the flush-time re-validation — never the+ * queued copy. Undefined = the trigger node (or its spec) is gone.+ */+ currentSpec(projectId: string, nodeId: string): TriggerSpec | undefined+ /** The machine-local, content-bound arm gate — re-asked at flush exactly as at fire. */+ isArmed(projectId: string, nodeId: string, spec: TriggerSpec): boolean+ now?(): number+ /** Timer seam for the queue's TTL (tests); defaults to setTimeout. */+ schedule?(ms: number, fn: () => void): CancelTimer+}++/** What one attempt decided. `queue` is only ever produced for an agent target (see module doc). */+type Attempt =+ | { act: 'fired' }+ | { act: 'missed'; detail: string }+ | { act: 'queue'; reason: string }++export interface TriggerDelivery {+ /** The scheduler's `fire` dep. */+ fire(row: TriggerRow): Promise<TriggerFireResult>+ /** Flush the target's queued payloads — wired to the mirror's `done` edges by the service. */+ onTargetIdle(nodeId: string): Promise<void>+ /** Where the queue's LATE outcomes land (`scheduler.recordExternalRun`); set once at boot. */+ setRunSink(sink: (projectId: string, nodeId: string, run: TriggerRun) => void): void+}++export function createTriggerDelivery(deps: TriggerDeliveryDeps): TriggerDelivery {+ const now = deps.now ?? Date.now+ let sink: ((projectId: string, nodeId: string, run: TriggerRun) => void) | undefined++ const attempt = async (row: TriggerRow): Promise<Attempt> => {+ const node = deps.targetNode(row.spec.target)+ if (!node) return { act: 'missed', detail: 'target node no longer exists' }+ if (node.agentId && hasHooks(node.agentId as AgentId)) {+ const state = deps.agentState(row.spec.target)?.state+ if (state !== 'done') {+ // Unknown is not idle: right after an app restart an agent sitting at its prompt has no+ // live state, and pasting into what MIGHT be a permission prompt is the failure this+ // gate exists for. The queue waits for the next real `done` edge instead.+ return {+ act: 'queue',+ reason: state ? `target is ${state}` : 'no live agent state for the target yet'+ }+ }+ } else {+ const pane = await deps.paneCommand(row.spec.target)+ if (pane === null)+ return { act: 'missed', detail: 'target session is not running (or its pane is unreadable)' }+ if (!isShellCommand(pane))+ // Never queued: a non-agent pane is the one surface the deliver-on-idle measurement+ // calls unsafe for an unattended paste, and nothing would ever flush it anyway.+ return { act: 'missed', detail: `target pane is running '${pane}' — refusing to type into it` }+ }+ const sent = await deps.sendText(row.spec.target, row.spec.payload)+ return sent ? { act: 'fired' } : { act: 'missed', detail: 'target session is not running' }+ }++ /**+ * The queue's `deliver` — the FULL re-validated attempt, expressed in the messaging outcome+ * vocabulary the queue's requeue set understands. Only the `kind` matters to the queue+ * (REQUEUE_ON membership → wait for the next idle; anything else is terminal); the run the+ * user sees is derived in `onFlushed` below, so no messaging trace/receipt semantics leak in.+ */+ const flushDeliver = async (req: QueuedDeliveryRequest): Promise<AgentMessageOutcome> => {+ const projectId = req.projectId as string+ const triggerNodeId = req.sourceNodeId+ // Flush-time re-validation, against live state and never the queued copy: the trigger must+ // still exist, still carry the SAME content it was queued for, and still be armed for it.+ const current = deps.currentSpec(projectId, triggerNodeId)+ const safe = current && sanitizeTriggerSpec(current)+ if (!safe || canonicalTriggerSpec(safe) !== (req.canon as string))+ return { kind: 'notPermitted', reason: 'switch-off' } // terminal: spec gone or edited while queued+ if (!deps.isArmed(projectId, triggerNodeId, safe))+ return { kind: 'notPermitted', reason: 'switch-off' } // terminal: disarmed while queued+ const a = await attempt({ projectId, nodeId: triggerNodeId, spec: safe })+ if (a.act === 'fired')+ // The extra fields are the messaging receipt contract; the queue never reads them, and the+ // run recorded for the card comes from `onFlushed`, keyed on the kind alone.+ return { kind: 'delivered', traceId: randomUUID(), traced: 'memory', receipt: 'observed', signal: 'newTurn' }+ if (a.act === 'queue') return { kind: 'targetBusy', state: a.reason } // requeued, TTL keeps counting+ return { kind: 'targetGone' } // terminal miss — the target left while the payload waited+ }++ const queue = new DeliveryQueue({+ now,+ ...(deps.schedule ? { schedule: deps.schedule } : {}),+ deliver: flushDeliver,+ // Trigger runs are recorded in the trigger's own run ring (below), not the board log — a+ // scheduled fire is not an agent-to-agent message. The queue only needs an id back.+ trace: async () => ({ traceId: randomUUID(), traced: 'memory' as const }),+ onFlushed: (req, outcome) => {+ const run: TriggerRun =+ outcome.kind === 'delivered'+ ? { at: now(), outcome: 'delivered-late' }+ : outcome.kind === 'notPermitted'+ ? { at: now(), outcome: 'missed', detail: 'disarmed or edited while queued — dropped' }+ : { at: now(), outcome: 'missed', detail: 'target went away while queued' }+ sink?.(req.projectId as string, req.sourceNodeId, run)+ },+ onExpired: (req, info) => {+ sink?.(req.projectId as string, req.sourceNodeId, {+ at: now(),+ outcome: 'expired',+ detail: `target never went idle (queued ${Math.round(info.queuedForMs / 1000)}s)`+ })+ }+ })++ return {+ async fire(row) {+ const a = await attempt(row)+ if (a.act === 'fired') return { outcome: 'fired' }+ if (a.act === 'missed') return { outcome: 'missed', detail: a.detail }+ const queued = await queue.enqueue({+ sourceNodeId: row.nodeId,+ targetNodeId: row.spec.target,+ sourceTitle: 'trigger',+ body: row.spec.payload,+ projectId: row.projectId,+ // The content binding rides the queue entry so the flush can tell "same trigger, edited+ // spec" from "the spec I was queued for".+ canon: canonicalTriggerSpec(row.spec)+ })+ if (queued.kind === 'queueFull')+ return { outcome: 'failed', detail: `deliver-on-idle queue is full (${queued.capacity})` }+ return {+ outcome: 'queued',+ detail: `${a.reason} — will deliver when it goes idle (waits up to ${Math.round(queued.ttlMs / 60_000)} min)`+ }+ },+ onTargetIdle: (nodeId) => queue.onTargetIdle(nodeId),+ setRunSink(s) {+ sink = s+ }+ }+}diff --git a/src/core/trigger-scheduler.test.ts b/src/core/trigger-scheduler.test.tsindex 0c1ae310b..e762c4186 100644--- a/src/core/trigger-scheduler.test.ts+++ b/src/core/trigger-scheduler.test.ts@@ -36,7 +36,7 @@ function harness(fireImpl?: (row: TriggerRow) => Promise<TriggerFireResult>): HafireImpl ??(async (row: TriggerRow) => {fires.push(row)- return { ok: true }+ return { outcome: 'fired' as const }}))const scheduler = createTriggerScheduler({@@ -178,7 +178,7 @@ describe('createTriggerScheduler', () => {let call = 0const h = harness(async () => {call++- if (call === 1) return { ok: false, detail: 'target not running' }+ if (call === 1) return { outcome: 'missed' as const, detail: 'target not running' }throw new Error('boom')})h.armed.add('project-1/trigger-a-1')@@ -189,7 +189,7 @@ describe('createTriggerScheduler', () => {h.clock.t = T0 + 10 * MINawait h.scheduler.sweepOnce()const runs = h.scheduler.runsFor('project-1', 'trigger-a-1')- expect(runs.map((r) => r.outcome)).toEqual(['failed', 'failed'])+ expect(runs.map((r) => r.outcome)).toEqual(['missed', 'failed'])expect(runs[0].detail).toBe('target not running')expect(runs[1].detail).toBe('boom')expect(h.scheduler.nextFireAt('project-1', 'trigger-a-1')).toBe(T0 + 15 * MIN)@@ -200,7 +200,7 @@ describe('createTriggerScheduler', () => {const h = harness(() =>new Promise<TriggerFireResult>((resolve) => {- release = () => resolve({ ok: true })+ release = () => resolve({ outcome: 'fired' })}))h.armed.add('project-1/trigger-a-1')@@ -245,7 +245,7 @@ describe('createTriggerScheduler', () => {return rows},isArmed: () => true,- fire: async () => ({ ok: true }),+ fire: async () => ({ outcome: 'fired' as const }),now: () => clock.t})await scheduler.sweepOnce()diff --git a/src/core/trigger-scheduler.ts b/src/core/trigger-scheduler.tsindex 338451011..6de73bc4a 100644--- a/src/core/trigger-scheduler.ts+++ b/src/core/trigger-scheduler.ts@@ -65,7 +65,19 @@ export function triggerRowsFromCanvases(return rows}-export type TriggerRunOutcome = 'fired' | 'failed' | 'missed'+/**+ * `fired`/`missed`/`failed` come straight back from a fire attempt; `queued` means the target was+ * busy and the payload waits in the deliver-on-idle queue, whose LATE outcomes —+ * `delivered-late` / `expired` (plus a `missed` for a target that went away, or a trigger+ * disarmed/edited while queued) — arrive through `recordExternalRun`.+ */+export type TriggerRunOutcome =+ | 'fired'+ | 'failed'+ | 'missed'+ | 'queued'+ | 'delivered-late'+ | 'expired'export interface TriggerRun {at: number@@ -73,8 +85,10 @@ export interface TriggerRun {detail?: string}+/** What one fire attempt reports back, recorded verbatim as the run. `queued` is not `fired`:+ * the bytes have not reached the pane yet — the queue's flush/expiry reports the ending. */export interface TriggerFireResult {- ok: boolean+ outcome: 'fired' | 'missed' | 'failed' | 'queued'detail?: string}@@ -126,6 +140,12 @@ export interface TriggerScheduler {runsFor: (projectId: string, nodeId: string) => TriggerRun[]/** The computed next due time, or null — phase 4's card reads this for its countdown. */nextFireAt: (projectId: string, nodeId: string) => number | null+ /**+ * Record a run that ended OUTSIDE a fire attempt — the deliver-on-idle queue's late outcomes+ * (`delivered-late`, `expired`, a flush-time drop). Same ring, same `onRun`, so the card shows+ * one history however the run ended.+ */+ recordExternalRun: (projectId: string, nodeId: string, run: TriggerRun) => void}export function createTriggerScheduler(deps: TriggerSchedulerDeps): TriggerScheduler {@@ -201,7 +221,7 @@ export function createTriggerScheduler(deps: TriggerSchedulerDeps): TriggerSchedconst result = await deps.fire(row)record(row.projectId, row.nodeId, {at: now(),- outcome: result.ok ? 'fired' : 'failed',+ outcome: result.outcome,...(result.detail ? { detail: result.detail } : {})})} catch (e) {@@ -234,6 +254,7 @@ export function createTriggerScheduler(deps: TriggerSchedulerDeps): TriggerSched},sweepOnce,runsFor: (projectId, nodeId) => [...(runs.get(keyOf(projectId, nodeId)) ?? [])],- nextFireAt: (projectId, nodeId) => states.get(keyOf(projectId, nodeId))?.nextAt ?? null+ nextFireAt: (projectId, nodeId) => states.get(keyOf(projectId, nodeId))?.nextAt ?? null,+ recordExternalRun: record}}diff --git a/src/core/trigger-service.test.ts b/src/core/trigger-service.test.tsnew file mode 100644index 000000000..134e15360--- /dev/null+++ b/src/core/trigger-service.test.ts@@ -0,0 +1,93 @@+import { promises as fs } from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import type { CanvasNodeState } from '../shared/types'+import type { TriggerSpec } from '../shared/trigger'+import { startTriggerService, type TriggerService } from './trigger-service'++const MIN = 60_000+const T0 = new Date(2026, 8, 2, 12, 0).getTime()++const spec = (): TriggerSpec => ({+ schedule: { kind: 'interval', everyMinutes: 5 },+ payload: 'npm test',+ target: 'term-tgt-1'+})++const node = (partial: Partial<CanvasNodeState> & { id: string }): CanvasNodeState => ({+ kind: 'terminal',+ position: { x: 0, y: 0 },+ size: { width: 1, height: 1 },+ title: '',+ color: '',+ group: null,+ ...partial+})++describe('startTriggerService (end to end over fakes)', () => {+ let dir: string+ let service: TriggerService+ let clock: { t: number }+ let sent: string[]+ let nodes: CanvasNodeState[]++ beforeEach(async () => {+ dir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-trigger-svc-'))+ clock = { t: T0 }+ sent = []+ // A trigger node and its PLAIN-TERMINAL target (shell pane ⇒ deliverable without any+ // agent-status mirror state, which this test deliberately leaves untouched).+ nodes = [+ node({ id: 'trigger-a-1', kind: 'trigger', trigger: spec() }),+ node({ id: 'term-tgt-1' })+ ]+ service = startTriggerService({+ userDataDir: dir,+ listCanvases: () => [{ id: 'project-1', nodes }],+ getNode: (id) => nodes.find((n) => n.id === id),+ sendText: async (_id, text) => {+ sent.push(text)+ return true+ },+ paneCommand: async () => 'bash',+ now: () => clock.t+ })+ })++ afterEach(async () => {+ service.stop()+ await fs.rm(dir, { recursive: true, force: true })+ })++ it('an armed trigger fires end to end; a disarmed one never does', async () => {+ await service.scheduler.sweepOnce() // anchor+ clock.t = T0 + 5 * MIN+ await service.scheduler.sweepOnce() // due, but DISARMED (nothing ever armed it)+ expect(sent).toHaveLength(0)++ expect(await service.armStore.arm('project-1', 'trigger-a-1', spec())).toBe(true)+ clock.t = T0 + 10 * MIN+ await service.scheduler.sweepOnce()+ expect(sent).toEqual(['npm test'])+ const runs = service.scheduler.runsFor('project-1', 'trigger-a-1')+ expect(runs.map((r) => r.outcome)).toEqual(['fired'])+ })++ it('the arm binds to content across the whole service: an edited spec stops firing', async () => {+ await service.armStore.arm('project-1', 'trigger-a-1', spec())+ await service.scheduler.sweepOnce()+ // A git pull rewrites the payload. The next sweep re-anchors (spec changed) and every+ // due check re-asks the content-bound arm gate, which now says no.+ nodes[0] = node({+ id: 'trigger-a-1',+ kind: 'trigger',+ trigger: { ...spec(), payload: 'rm -rf /' }+ })+ clock.t = T0 + 5 * MIN+ await service.scheduler.sweepOnce() // re-anchor on the new content+ clock.t = T0 + 15 * MIN+ await service.scheduler.sweepOnce() // due — disarmed for THIS content+ expect(sent).toHaveLength(0)+ })+})diff --git a/src/core/trigger-service.ts b/src/core/trigger-service.tsnew file mode 100644index 000000000..b77d883d0--- /dev/null+++ b/src/core/trigger-service.ts@@ -0,0 +1,94 @@+/**+ * The trigger node's whole host-side machine, composed ONCE (issue #493, phase 3): the+ * machine-local arm store + the scheduler + the delivery (with its deliver-on-idle queue) + the+ * idle signal, wired together here so BOTH shells boot the identical thing with a one-call+ * `startTriggerService(...)`. This is the duplicated-wiring lesson applied preemptively — phase 2+ * had each shell assemble the pieces inline, and every extra piece phase 3 adds is one more line+ * for the two copies to disagree about.+ *+ * The idle signal is the core mirror's own `done` edge (`onNodeStateChange`), which both shells+ * already feed through their raw hook listeners — so the queue flush needs NO per-shell listener+ * branch, and there is nothing here for the hook-parity discipline to chase.+ */++import { mirrorEntry, onNodeStateChange } from './agent-status-mirror'+import { TriggerArmStore } from './trigger-arm-store'+import { createTriggerDelivery, type TriggerDeliveryDeps } from './trigger-delivery'+import {+ createTriggerScheduler,+ triggerRowsFromCanvases,+ type TriggerScheduler+} from './trigger-scheduler'+import { sanitizeTriggerSpec } from '../shared/trigger'+import type { CanvasNodeState } from '../shared/types'++export interface TriggerServiceDeps {+ /** Where the arm store persists (`app.getPath('userData')` / `config.dataDir`). */+ userDataDir: string+ /** `WorkspaceStore.persistedCanvases` — the trigger list's raw material. */+ listCanvases(): Array<{ id: string; nodes: CanvasNodeState[] }>+ /** `WorkspaceStore.getNode` — target resolution + the flush-time current-spec re-read. */+ getNode(nodeId: string): CanvasNodeState | undefined+ /** `PtyManager.sendText` / `PtyManager.paneCommand`. */+ sendText(nodeId: string, text: string): Promise<boolean>+ paneCommand(nodeId: string): Promise<string | null>+ /** Test seams; production passes none. */+ now?(): number+ schedulerIntervalMs?: number+ schedule?: TriggerDeliveryDeps['schedule']+}++export interface TriggerService {+ scheduler: TriggerScheduler+ armStore: TriggerArmStore+ stop(): void+}++export function startTriggerService(deps: TriggerServiceDeps): TriggerService {+ const armStore = new TriggerArmStore(deps.userDataDir)+ const isArmed = (projectId: string, nodeId: string, spec: Parameters<TriggerArmStore['isArmed']>[2]) =>+ armStore.isArmed(projectId, nodeId, spec)++ const delivery = createTriggerDelivery({+ sendText: deps.sendText,+ paneCommand: deps.paneCommand,+ agentState: (nodeId) => mirrorEntry(nodeId),+ targetNode: (nodeId) => deps.getNode(nodeId),+ // The trigger's OWN node, freshly resolved — what the queue's flush re-validates against.+ // getNode scans by node id; the projectId key is already bound into the arm record.+ currentSpec: (_projectId, nodeId) => {+ const node = deps.getNode(nodeId)+ if (!node || node.kind !== 'trigger') return undefined+ return sanitizeTriggerSpec(node.trigger)+ },+ isArmed,+ ...(deps.now ? { now: deps.now } : {}),+ ...(deps.schedule ? { schedule: deps.schedule } : {})+ })++ const scheduler = createTriggerScheduler({+ listTriggers: () => triggerRowsFromCanvases(deps.listCanvases()),+ isArmed,+ fire: (row) => delivery.fire(row),+ ...(deps.now ? { now: deps.now } : {}),+ ...(deps.schedulerIntervalMs ? { intervalMs: deps.schedulerIntervalMs } : {})+ })+ delivery.setRunSink(scheduler.recordExternalRun)++ // The queue's flush trigger: a target finished a turn, so it is idle NOW — the same edge+ // messaging flushes on, read from core instead of each shell's listener.+ const unsubscribe = onNodeStateChange((change) => {+ if (change.state === 'done') void delivery.onTargetIdle(change.nodeId)+ })++ void armStore.load().finally(() => scheduler.start())++ return {+ scheduler,+ armStore,+ stop() {+ unsubscribe()+ scheduler.stop()+ }+ }+}diff --git a/src/main/index.ts b/src/main/index.tsindex b0c67e740..1a0cc0006 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,7 +1,6 @@import { join, resolve, posix } from 'path'import { startSessionNameSweep, displayNodeTitle } from '../core/session-name-sweep'-import { TriggerArmStore } from '../core/trigger-arm-store'-import { createTriggerScheduler, triggerRowsFromCanvases } from '../core/trigger-scheduler'+import { startTriggerService } from '../core/trigger-service'import { readAgentSessionName, type AgentSessionNameDeps } from '../core/agent-session-name'import { readFile, realpath as fsRealpath, lstat as fsLstat, writeFile as fsWriteFile } from 'fs/promises'import { existsSync, statSync, openSync, fstatSync, readFileSync, closeSync } from 'fs'@@ -1779,19 +1778,17 @@ app.whenReady().then(async () => {// get it wrong, and getting it wrong is invisible — the wrong list silently skips an agent's// nodes with every test still green.})- // Trigger nodes (issue #493, phase 2): the host-side scheduler. Same wiring as the Server- // Edition's (src/server/index.ts) — the trigger list, the arm gate and the sweep all live in- // core; this shell only supplies the seams. `fire` is a stub until the delivery phase lands,- // and since nothing can ARM a trigger yet (no arm IPC/UI), a production trigger cannot reach- // it — the stub exists so a due+armed trigger in a dev build records an honest failure- // instead of pretending to run.- const triggerArms = new TriggerArmStore(app.getPath('userData'))- const triggerScheduler = createTriggerScheduler({- listTriggers: () => triggerRowsFromCanvases(workspaceStore.persistedCanvases()),- isArmed: (projectId, nodeId, spec) => triggerArms.isArmed(projectId, nodeId, spec),- fire: async () => ({ ok: false, detail: 'delivery not wired yet (trigger phase 3)' })- })- void triggerArms.load().finally(() => triggerScheduler.start())+ // Trigger nodes (issue #493): the whole host-side machine — arm store, scheduler, delivery with+ // its deliver-on-idle queue, and the mirror's idle signal — composed ONCE in core+ // (`startTriggerService`); this shell only supplies its seams. Identical call in+ // src/server/index.ts. Arming still has no IPC/UI (phase 4), so nothing fires in production yet.+ startTriggerService({+ userDataDir: app.getPath('userData'),+ listCanvases: () => workspaceStore.persistedCanvases(),+ getNode: (nodeId) => workspaceStore.getNode(nodeId),+ sendText: (nodeId, text) => ptyManager.sendText(nodeId, text),+ paneCommand: (nodeId) => ptyManager.paneCommand(nodeId)+ })// macOS Notch HUD (docs/notch-hud.md): walking agent mascots by the notch. darwin + setting only;// reads the same agent-status seams the mirror does. Live-toggled via settings below.//diff --git a/src/server/index.ts b/src/server/index.tsindex 14ba015f3..8ba054950 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -1,8 +1,7 @@import fs from 'fs'import { readAgentSessionName } from '../core/agent-session-name'import { startSessionNameSweep, displayNodeTitle } from '../core/session-name-sweep'-import { TriggerArmStore } from '../core/trigger-arm-store'-import { createTriggerScheduler, triggerRowsFromCanvases } from '../core/trigger-scheduler'+import { startTriggerService } from '../core/trigger-service'import path from 'path'import http from 'http'@@ -379,17 +378,18 @@ export async function startServer(// No `supports`: core's `supportsTitleRead` (TITLE_READ_CAPABLE) is the rule, and duplicating// it here is how the two shells drift — see the note in core/session-name-sweep.ts.})- // Trigger nodes (issue #493, phase 2): the host-side scheduler — the reason it lives in core is- // exactly this shell: a headless Server Edition with no browser tab open must still fire. Same- // wiring as desktop main's; `fire` is a stub until the delivery phase, and with no arm IPC/UI- // yet nothing can arm a trigger, so the stub is unreachable in production.- const triggerArms = new TriggerArmStore(config.dataDir)- const triggerScheduler = createTriggerScheduler({- listTriggers: () => triggerRowsFromCanvases(workspaceStore.persistedCanvases()),- isArmed: (projectId, nodeId, spec) => triggerArms.isArmed(projectId, nodeId, spec),- fire: async () => ({ ok: false, detail: 'delivery not wired yet (trigger phase 3)' })+ // Trigger nodes (issue #493): the whole host-side machine — arm store, scheduler, delivery with+ // its deliver-on-idle queue, and the mirror's idle signal — composed ONCE in core+ // (`startTriggerService`); the reason it lives in core is exactly this shell: a headless Server+ // Edition with no browser tab open must still fire. Identical call in src/main/index.ts. Arming+ // still has no IPC/UI (phase 4), so nothing fires in production yet.+ startTriggerService({+ userDataDir: config.dataDir,+ listCanvases: () => workspaceStore.persistedCanvases(),+ getNode: (nodeId) => workspaceStore.getNode(nodeId),+ sendText: (nodeId, text) => ptyManager.sendText(nodeId, text),+ paneCommand: (nodeId) => ptyManager.paneCommand(nodeId)})- void triggerArms.load().finally(() => triggerScheduler.start())// Advertise launch settings to the mobile companion through the mirror (same provider the// desktop wires in src/main/index.ts). No SSH push exists server-side, so only the local// provider applies. The provider is consulted at every flush (heartbeat ≤60s), so a settings