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): TriggerNode UI, arm/disarm IPC, consent UX, Run-now, run history (#493 phase 4)
enes43db1169c5f3
diff --git a/CLAUDE.md b/CLAUDE.mdindex 5e62257c7..cf11f7021 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -132,14 +132,14 @@ separate store mirroring node state — earlier dual-source designs caused sync`src/renderer/state/workspace.ts` holds only pure helpers: the color palette, the nodefactories (`createTerminalNode`, `createSshTerminalNode`, `createAgentNode(agentId, …)`,`createAccountLoginNode`, `createStickyNode`, `createGroupNode`, `createEditorNode`,-`createDiffNode`, `createVideoNode`, `createWebNode`, `createBrowserNode`, `createDinoNode`), the+`createDiffNode`, `createVideoNode`, `createWebNode`, `createBrowserNode`, `createDinoNode`,+`createTriggerNode`), thegroup transforms (`groupSelectedNodes`, `ungroupNodes`, `duplicateNode`), and the`nodeStatesToFlow` / `flowToNodeStates` serializers. Node kinds (`NodeKind` in`src/shared/types.ts`): `terminal | sticky | group | editor | diff | video | web | browser |subagent | loop | dino | trigger` — `subagent` and `loop` are render-only (ephemeral hook-driven-viz) and never persisted. `trigger` (issue #493, landing in phases — schema + the core-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+viz) and never persisted. `trigger` (issue #493, all four+phases landed) is a first-class PERSISTED kind. The whole host-sidemachine is composed ONCE in `core/trigger-service.ts` (`startTriggerService`) and bootedidentically by BOTH shells: `core/trigger-scheduler.ts` (sweep-service shape, no catch-up formissed slots, cron via the dependency-free `@shared/cron` with the vixie dom/dow OR rule) decides@@ -741,6 +741,18 @@ session.surface backs the kanban card modal's browser popup.- **dino** (`DinoNode.tsx`) — a small self-contained T-Rex-style runner on a canvas (no PTY);high score persists via `data.highScore`.+- **trigger** (`TriggerNode.tsx`) — a canvas-owned schedule (cron / interval / once) that+ delivers a payload into a connected terminal/agent node when due (issue #493 — the inverse of+ the ephemeral loop/cron cards, which visualize AGENT-initiated recurrence). The card shows the+ schedule + next-run countdown, the target (a derived, never-persisted edge — same rule as the+ pending-launch dep edges), the payload, an honest ARMED/DISARMED/CHANGED/SET-UP chip with the+ "definitions travel with the repo, consent never does" narrative, Run-now, and the last runs+ (fired / delivered-late / queued / missed / failed / expired). Arming passes a ConfirmDialog+ showing the exact schedule+payload+target being consented to; all decisions are the pure,+ tested `lib/triggerCard.ts`, all state is host-side over `window.nodeTerminal.triggers`+ (arm/disarm/status/runNow — `startTriggerService` registers the handlers in BOTH shells;+ `runNow` deliberately takes no spec: a caller chooses WHEN, never WHAT). The relay stub+ refuses and the card says triggers are managed on the host. Mobile: N/A (no canvas).- **subagent** / **loop** (`SubagentNode.tsx` / `LoopNode.tsx`) — render-only, hook-driven viznodes, **never persisted**. `subagent` visualizes a subagent the Claude session spawned (type +task + live timer, expand for its live transcript — subagents have no PTY); `loop` shows adiff --git a/docs/trigger-node.md b/docs/trigger-node.mdnew file mode 100644index 000000000..c19248203--- /dev/null+++ b/docs/trigger-node.md@@ -0,0 +1,77 @@+# Trigger nodes (issue #493)++A **trigger** is a first-class canvas node that fires a payload into a connected terminal/agent+node on a schedule — the *canvas* owns the schedule, unlike the ephemeral `/loop` `/schedule`+`/cron` cards, which visualize recurrence an *agent* set up inside its own process. Landed in four+phases: schema + arm store (#502), scheduler (#523), delivery (#595), UI (this one).++## Trust model (the part everything else follows from)++The trigger's **definition** (schedule `cron | interval | once`, payload, target node id, note)+lives on the node in `.nodeterm/project.json` — git-shared on purpose, and therefore HOSTILE+input: sanitized on every load path (`sanitizeNodeTriggers`, `@shared/trigger`), rebuilt+known-fields-only, malformed ⇒ an inert node.++The **consent** to fire is machine-local and content-bound: `core/trigger-arm-store.ts` records+`canonicalTriggerSpec` of the exact content the user armed, and `isArmed` answers true only while+the node's current spec canonicalizes to the same string. Consequences, all test-pinned:++- a trigger arriving via `git clone`/`pull` is **disarmed** until someone on this machine arms it;+- editing the schedule/payload/target — locally or via a pull — lands an armed trigger back in+ disarmed (`CHANGED` on the card), never runs the new content under the old consent;+- disarming (or editing) while a payload waits in the deliver-on-idle queue drops it at flush.++## The machine (all core, both shells)++`startTriggerService` (`core/trigger-service.ts`) composes everything once; desktop main and the+Server Edition boot the identical call — a headless SE fires with no browser tab open.++- **Scheduler** (`core/trigger-scheduler.ts`): 30 s sweep, fire-time `isArmed` re-ask, **no+ catch-up** (a host that slept through three slots fires once, from *now*; a spent `once` logs a+ single honest `missed`), exactly-once per slot. Cron is the dependency-free `@shared/cron`+ (five fields, names, steps, vixie dom/dow OR rule, local wall-clock; parse failure schedules+ nothing).+- **Delivery** (`core/trigger-delivery.ts`): the `sendText` paste path (`paste-buffer -p`,+ payload by stdin). An agent target delivers only on the mirror's idle `done`;+ working/blocked/unknown queue in a trigger-local `DeliveryQueue` instance (TTL 5 min) flushed+ by the mirror's `done` edge, with full flush-time re-validation. A plain-terminal target+ delivers only into a shell-owned pane and never queues. A dead target is a `missed`, never a+ cold start.+- **IPC** (`triggers:arm/disarm/status/run-now`, registered inside the service): `arm` binds the+ spec the renderer displayed (consent = what was seen); `run-now` takes **no** spec — the payload+ is resolved core-side from the node's persisted content, so a caller chooses *when*, never+ *what*. All inputs re-validated at the boundary.++## The card (`renderer/nodes/TriggerNode.tsx`, decisions in `renderer/lib/triggerCard.ts`)++Schedule line + live next-run countdown, target (plus a derived, never-persisted edge), payload+preview, note, and an honest state chip: `ARMED` / `DISARMED` (with the "definitions travel with+the project; arming is always a local decision" narrative) / `CHANGED` (armed for other content)+/ `SET UP` (no valid spec — the editor opens). Arming passes a ConfirmDialog whose body shows the+exact schedule + payload + target being consented to; Run-now on a disarmed trigger confirms the+same way. The last runs render from the core's ring: `fired`, `delivered-late`, `queued`,+`missed`, `failed`, `expired`.++## Surfaces++- **Desktop + Server Edition**: identical (core service + real ws-bridge namespace).+- **Relay tabs**: the stub refuses — the arm store and sessions live on the host, and arming from+ a guest would write another machine's execution consent. The card says so.+- **Mobile**: N/A (no canvas). The kanban board deliberately shows no trigger cards in v1: a+ trigger is configuration, not work-in-flight, and its *target* session already has a card —+ made as a conscious three-surfaces call, revisit if boards grow a configuration lane.+- **Host-alive v1** (the #493 design decision): nothing fires while the app is closed, and missed+ fires are logged, never retroactively run. The durable answer is a Server Edition host;+ OS-level scheduling (crontab/launchd/Task Scheduler) is a possible v2 as an explicit,+ reversible per-trigger opt-in — the #490 consent invariant applies in full.++## Device checklist (owed — written where it could not be run)++1. macOS: create → edit → arm → scheduled fire into an idle claude node; verify the payload+ arrives framed (no submit-per-line) and the run ring shows `fired`.+2. macOS: fire while the target is mid-turn → `queued`, then `delivered-late` on turn end;+ disarm while queued → dropped.+3. Server Edition (browser): same arm/fire round trip; then close the tab and verify a scheduled+ fire still lands (headless firing).+4. Relay tab: the card shows the managed-on-host notice, no dead buttons.+5. Fall-back DST hour + spring-forward hour behavior of a cron trigger (documented edges).diff --git a/src/core/trigger-scheduler.ts b/src/core/trigger-scheduler.tsindex 6de73bc4a..a99e69a36 100644--- a/src/core/trigger-scheduler.ts+++ b/src/core/trigger-scheduler.ts@@ -37,9 +37,18 @@*/import type { CanvasNodeState } from '../shared/types'-import { sanitizeTriggerSpec, type TriggerSpec } from '../shared/trigger'+import {+ sanitizeTriggerSpec,+ type TriggerRun,+ type TriggerRunOutcome,+ type TriggerSpec+} from '../shared/trigger'import { nextCronFire, parseCron } from '../shared/cron'+// The run types moved to @shared/trigger (the card renders what the core records); re-exported so+// every phase-2/3 import path keeps working.+export type { TriggerRun, TriggerRunOutcome }+export interface TriggerRow {projectId: stringnodeId: string@@ -65,26 +74,6 @@ export function triggerRowsFromCanvases(return rows}-/**- * `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- outcome: TriggerRunOutcome- 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 {diff --git a/src/core/trigger-service.test.ts b/src/core/trigger-service.test.tsindex 134e15360..d2adfa569 100644--- a/src/core/trigger-service.test.ts+++ b/src/core/trigger-service.test.ts@@ -31,11 +31,13 @@ describe('startTriggerService (end to end over fakes)', () => {let clock: { t: number }let sent: string[]let nodes: CanvasNodeState[]+ let handlers: Map<string, (...args: unknown[]) => unknown>beforeEach(async () => {dir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-trigger-svc-'))clock = { t: T0 }sent = []+ handlers = new Map()// A trigger node and its PLAIN-TERMINAL target (shell pane ⇒ deliverable without any// agent-status mirror state, which this test deliberately leaves untouched).nodes = [@@ -51,6 +53,7 @@ describe('startTriggerService (end to end over fakes)', () => {return true},paneCommand: async () => 'bash',+ handle: (channel, handler) => handlers.set(channel, handler),now: () => clock.t})})@@ -74,6 +77,82 @@ describe('startTriggerService (end to end over fakes)', () => {expect(runs.map((r) => r.outcome)).toEqual(['fired'])})+ const invoke = <T,>(channel: string, payload: unknown): Promise<T> => {+ const h = handlers.get(channel)+ if (!h) throw new Error(`no handler registered for ${channel}`)+ return Promise.resolve(h(payload)) as Promise<T>+ }++ it('registers the card IPC surface: arm → status → run-now → disarm round trip', async () => {+ const armed = await invoke<boolean>('triggers:arm', {+ projectId: 'project-1',+ nodeId: 'trigger-a-1',+ spec: spec()+ })+ expect(armed).toBe(true)++ const status = await invoke<{ armed: boolean; nextFireAt: number | null; runs: unknown[] }>(+ 'triggers:status',+ { projectId: 'project-1', nodeId: 'trigger-a-1' }+ )+ expect(status.armed).toBe(true)+ // The sweep has not anchored yet — the status computes a countdown from the spec itself.+ expect(status.nextFireAt).toBe(T0 + 5 * MIN)++ // Run-now resolves the payload CORE-side (the caller chooses when, never what) and records+ // the run in the same ring the scheduler uses.+ const result = await invoke<{ outcome: string }>('triggers:run-now', {+ projectId: 'project-1',+ nodeId: 'trigger-a-1'+ })+ expect(result.outcome).toBe('fired')+ expect(sent).toEqual(['npm test'])+ expect(service.scheduler.runsFor('project-1', 'trigger-a-1').map((r) => r.outcome)).toEqual([+ 'fired'+ ])++ await invoke('triggers:disarm', { projectId: 'project-1', nodeId: 'trigger-a-1' })+ const after = await invoke<{ armed: boolean }>('triggers:status', {+ projectId: 'project-1',+ nodeId: 'trigger-a-1'+ })+ expect(after.armed).toBe(false)+ })++ it('the IPC boundary re-validates: bad keys and a smuggled spec are refused', async () => {+ expect(+ await invoke<boolean>('triggers:arm', { projectId: 'p;rm', nodeId: 'trigger-a-1', spec: spec() })+ ).toBe(false)+ expect(+ await invoke<boolean>('triggers:arm', {+ projectId: 'project-1',+ nodeId: 'trigger-a-1',+ spec: { ...spec(), payload: '' }+ })+ ).toBe(false)+ const r = await invoke<{ outcome: string }>('triggers:run-now', {+ projectId: 'project-1',+ nodeId: 'term-tgt-1' // not a trigger node+ })+ expect(r.outcome).toBe('failed')+ expect(sent).toHaveLength(0)+ })++ it('status reports armed-for-other-content after the spec changes', async () => {+ await invoke('triggers:arm', { projectId: 'project-1', nodeId: 'trigger-a-1', spec: spec() })+ nodes[0] = node({+ id: 'trigger-a-1',+ kind: 'trigger',+ trigger: { ...spec(), payload: 'something else' }+ })+ const status = await invoke<{ armed: boolean; armedForOtherContent: boolean }>(+ 'triggers:status',+ { projectId: 'project-1', nodeId: 'trigger-a-1' }+ )+ expect(status.armed).toBe(false)+ expect(status.armedForOtherContent).toBe(true)+ })+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()diff --git a/src/core/trigger-service.ts b/src/core/trigger-service.tsindex b77d883d0..436887502 100644--- a/src/core/trigger-service.ts+++ b/src/core/trigger-service.ts@@ -11,6 +11,8 @@* branch, and there is nothing here for the hook-parity discipline to chase.*/+import { IPC } from '../shared/ipc'+import { isSafeNodeId } from '../shared/safe-id'import { mirrorEntry, onNodeStateChange } from './agent-status-mirror'import { TriggerArmStore } from './trigger-arm-store'import { createTriggerDelivery, type TriggerDeliveryDeps } from './trigger-delivery'@@ -19,7 +21,14 @@ import {triggerRowsFromCanvases,type TriggerScheduler} from './trigger-scheduler'-import { sanitizeTriggerSpec } from '../shared/trigger'+import {+ computeNextFire,+} from './trigger-scheduler'+import {+ sanitizeTriggerSpec,+ type TriggerNodeStatus,+ type TriggerSpec+} from '../shared/trigger'import type { CanvasNodeState } from '../shared/types'export interface TriggerServiceDeps {@@ -32,6 +41,12 @@ export interface TriggerServiceDeps {/** `PtyManager.sendText` / `PtyManager.paneCommand`. */sendText(nodeId: string, text: string): Promise<boolean>paneCommand(nodeId: string): Promise<string | null>+ /**+ * Register one request/response IPC handler — both shells pass `platform().handle`. REQUIRED+ * (not defaulted inside core) so a shell that forgets it is a compile error rather than a+ * surface that silently has no arm/disarm; tests pass a recorder.+ */+ handle(channel: string, handler: (...args: unknown[]) => unknown): void/** Test seams; production passes none. */now?(): numberschedulerIntervalMs?: number@@ -81,6 +96,82 @@ export function startTriggerService(deps: TriggerServiceDeps): TriggerService {if (change.state === 'done') void delivery.onTargetIdle(change.nodeId)})+ // ── The card's IPC surface (issue #493, phase 4) ────────────────────────────────────────────+ // Everything here re-validates its inputs at this boundary (the values crossed a process/WS+ // boundary), and `run-now` deliberately takes NO spec from the caller: the payload that runs is+ // always the node's CURRENT persisted content, resolved core-side — a caller can choose WHEN,+ // never WHAT. `arm` DOES take the spec: consent must bind to the exact content the user was+ // shown, and the renderer's live copy can be ahead of the debounced save; `TriggerArmStore.arm`+ // re-sanitizes and canonicalizes it, so a binding for content that never lands simply reads as+ // disarmed. The keys are checked with the same predicate the store uses.+ const safeKeys = (projectId: unknown, nodeId: unknown): projectId is string =>+ typeof projectId === 'string' && typeof nodeId === 'string' &&+ isSafeNodeId(projectId) && isSafeNodeId(nodeId)++ const currentSpecOf = (nodeId: string): TriggerSpec | undefined => {+ const node = deps.getNode(nodeId)+ if (!node || node.kind !== 'trigger') return undefined+ return sanitizeTriggerSpec(node.trigger)+ }++ deps.handle(IPC.triggersArm, async (payload) => {+ const p = (payload ?? {}) as { projectId?: unknown; nodeId?: unknown; spec?: unknown }+ if (!safeKeys(p.projectId, p.nodeId)) return false+ const spec = sanitizeTriggerSpec(p.spec)+ if (!spec) return false+ return armStore.arm(p.projectId as string, p.nodeId as string, spec)+ })++ deps.handle(IPC.triggersDisarm, async (payload) => {+ const p = (payload ?? {}) as { projectId?: unknown; nodeId?: unknown }+ if (!safeKeys(p.projectId, p.nodeId)) return+ await armStore.disarm(p.projectId as string, p.nodeId as string)+ })++ deps.handle(IPC.triggersStatus, async (payload): Promise<TriggerNodeStatus> => {+ const p = (payload ?? {}) as { projectId?: unknown; nodeId?: unknown }+ const empty: TriggerNodeStatus = {+ armed: false, armedForOtherContent: false, nextFireAt: null, runs: []+ }+ if (!safeKeys(p.projectId, p.nodeId)) return empty+ const projectId = p.projectId as string+ const nodeId = p.nodeId as string+ const spec = currentSpecOf(nodeId)+ const armed = spec ? armStore.isArmed(projectId, nodeId, spec) : false+ const record = armStore.armedRecord(projectId, nodeId)+ // The scheduler's own nextFireAt is the sweep's anchored value; a fresh/edited trigger the+ // sweep has not seen yet still deserves a countdown, so fall back to a pure computation.+ const scheduled = scheduler.nextFireAt(projectId, nodeId)+ const nextFireAt =+ scheduled ?? (spec ? computeNextFire(spec, (deps.now ?? Date.now)()) : null)+ return {+ armed,+ armedForOtherContent: !armed && !!record,+ nextFireAt,+ runs: scheduler.runsFor(projectId, nodeId)+ }+ })++ deps.handle(IPC.triggersRunNow, async (payload) => {+ const p = (payload ?? {}) as { projectId?: unknown; nodeId?: unknown }+ if (!safeKeys(p.projectId, p.nodeId))+ return { outcome: 'failed', detail: 'invalid trigger reference' }+ const projectId = p.projectId as string+ const nodeId = p.nodeId as string+ const spec = currentSpecOf(nodeId)+ if (!spec) return { outcome: 'failed', detail: 'the trigger has no valid definition' }+ // An explicit user click, delivered through the SAME gates as a scheduled fire (idle gate,+ // queue, missed-when-dead) — the only thing bypassed is the schedule. Recorded in the same+ // ring so the card shows one history.+ const result = await delivery.fire({ projectId, nodeId, spec })+ scheduler.recordExternalRun(projectId, nodeId, {+ at: (deps.now ?? Date.now)(),+ outcome: result.outcome,+ ...(result.detail ? { detail: result.detail } : {})+ })+ return result+ })+void armStore.load().finally(() => scheduler.start())return {diff --git a/src/main/index.ts b/src/main/index.tsindex 907e44ff4..f46ee41a5 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -274,7 +274,7 @@ import {allowMediaPath,writeAgentHtml} from './media-protocol'-import { initPlatform } from '../core/platform'+import { initPlatform, platform } from '../core/platform'import { electronPlatform } from './platform-electron'import { wirePeerRegistry } from './peer-registry'import { WEBGL_CONTEXT_CAP_DESKTOP } from '../shared/webgl'@@ -1787,7 +1787,8 @@ app.whenReady().then(async () => {listCanvases: () => workspaceStore.persistedCanvases(),getNode: (nodeId) => workspaceStore.getNode(nodeId),sendText: (nodeId, text) => ptyManager.sendText(nodeId, text),- paneCommand: (nodeId) => ptyManager.paneCommand(nodeId)+ paneCommand: (nodeId) => ptyManager.paneCommand(nodeId),+ handle: (channel, handler) => platform().handle(channel, handler)})// 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/preload/index.ts b/src/preload/index.tsindex b6e285dc4..e0594574a 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -476,6 +476,12 @@ const api: NodeTerminalApi = {read: (q?: SessionMemoryQuery) => ipcRenderer.invoke(IPC.sessionMemory, q),host: (q?: SessionMemoryQuery) => ipcRenderer.invoke(IPC.sessionMemoryHost, q)},+ triggers: {+ arm: (projectId, nodeId, spec) => ipcRenderer.invoke(IPC.triggersArm, { projectId, nodeId, spec }),+ disarm: (projectId, nodeId) => ipcRenderer.invoke(IPC.triggersDisarm, { projectId, nodeId }),+ status: (projectId, nodeId) => ipcRenderer.invoke(IPC.triggersStatus, { projectId, nodeId }),+ runNow: (projectId, nodeId) => ipcRenderer.invoke(IPC.triggersRunNow, { projectId, nodeId })+ },context: {onUpdate: (listener) => {const handler = (_e: unknown, payload: Parameters<typeof listener>[0]) => listener(payload)diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex c912525c0..37f0fe689 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -273,6 +273,17 @@ export function buildStubApi(): Omit<read: () => Promise.resolve({ ok: false, rows: [], mem: null }),host: () => Promise.resolve(null)},+ triggers: {+ // Superseded by the real WS-backed namespace in ws-bridge (startTriggerService registers the+ // handlers in the server shell). On the RELAY tab this stub stays in force and REFUSES: the+ // arm store, the scheduler and the sessions all live on the host — arming from the guest+ // would write another machine's execution consent. The card catches the rejection and says+ // triggers are managed on the host machine.+ arm: U('triggers.arm'),+ disarm: U('triggers.disarm'),+ status: U('triggers.status'),+ runNow: U('triggers.runNow')+ },codex: {// Overridden by the real WS-backed namespace in ws-bridge. The stub's answer is the same// one the Server Edition gives on purpose (see server/handlers/index.ts): no shareddiff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 695c6e14c..2758fe068 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -763,6 +763,33 @@ function buildUsageApi(client: RpcClient): Pick<NodeTerminalApi, 'usage'> {* which are the service's own words for "the sweep could not run" and "RAM unreadable". The panel* shows a failed request as a failed request.*/+/**+ * The `triggers` namespace over an RpcClient — REAL on the Server Edition: the arm store, the+ * scheduler and the delivery all run in the server shell (`startTriggerService` registers these+ * handlers there exactly as desktop main does), so arming a trigger from the browser arms it on+ * the machine that will fire it. The relay deliberately keeps the refusing stub (stubs.ts):+ * another machine's arm store is not the guest's to write.+ */+export function buildTriggersApi(client: RpcClient): Pick<NodeTerminalApi, 'triggers'> {+ return {+ triggers: {+ arm: (projectId, nodeId, spec) =>+ client.request(IPC.triggersArm, { projectId, nodeId, spec }) as Promise<boolean>,+ disarm: (projectId, nodeId) =>+ client.request(IPC.triggersDisarm, { projectId, nodeId }) as Promise<void>,+ status: (projectId, nodeId) =>+ client.request(IPC.triggersStatus, { projectId, nodeId }) as Promise<+ import('@shared/trigger').TriggerNodeStatus+ >,+ runNow: (projectId, nodeId) =>+ client.request(IPC.triggersRunNow, { projectId, nodeId }) as Promise<{+ outcome: 'fired' | 'missed' | 'failed' | 'queued'+ detail?: string+ }>+ }+ }+}+export function buildSessionMemoryApi(client: RpcClient): Pick<NodeTerminalApi, 'sessionMemory'> {return {sessionMemory: {@@ -995,6 +1022,7 @@ export async function installWsBridge(): Promise<boolean> {...buildSpeechApi(client),...buildUsageApi(client),...buildSessionMemoryApi(client),+ ...buildTriggersApi(client),...buildGitHubApi(client),...buildClaudeAccountsApi(client),codex: buildCodexApi(client),diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 236cbbf64..06e40e8db 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -76,6 +76,7 @@ import { StickyNode } from '../nodes/StickyNode'import { GroupNode, setWorktreeActionHandler } from '../nodes/GroupNode'import { LazyEditorNode, LazyDiffNode } from '../nodes/lazyMonacoNodes'import { DinoNode } from '../nodes/DinoNode'+import { TriggerNode } from '../nodes/TriggerNode'import BrowserNode from '../nodes/BrowserNode'import { normalizeAddress } from '../nodes/browserUrl'import VideoNode from '../nodes/VideoNode'@@ -385,6 +386,7 @@ import {} from '../session/relay-tab'import { buildBackgroundLinkMaps, buildContextLinkNote, buildLinkMap, buildNotePushMessage, classifyLink, hiddenLinkIds, linkIdsCoveredByRopes, pairKey, planBridges, type LinkEndpoint } from '../lib/noteLink'import { dependencyEdges, launchesToFire, unmetDeps, type ArmedNode } from '../lib/pendingLaunch'+import { triggerEdges } from '../lib/triggerCard'import { freeSpot } from '../lib/placement'import { pushSessionRename } from '../lib/sessionRename'import { useReopenHistory } from '../state/reopenHistory'@@ -455,6 +457,7 @@ import {createAgentNode,createBrowserNode,createDinoNode,+ createTriggerNode,createDiffNode,createEditorNode,createGroupNode,@@ -1458,6 +1461,7 @@ export function Canvas() {subagent: withNodeBoundary(SubagentNode),loop: withNodeBoundary(LoopNode),dino: withNodeBoundary(DinoNode),+ trigger: withNodeBoundary(TriggerNode),video: withNodeBoundary(VideoNode),web: withNodeBoundary(WebNode),browser: withNodeBoundary(BrowserNode)@@ -1768,6 +1772,24 @@ export function Canvas() {// eslint-disable-next-line react-hooks/exhaustive-deps -- depEdgeSig IS the ref's signature[depEdgeSig])+ // Trigger→target edges (issue #493) — derived, never persisted, same signature discipline as+ // depEdges: the per-frame pass reduces `nodes` to a signature (which trigger points where), and+ // the styled objects only rebuild when that set actually changes, not on every drag frame.+ const trigPairsRef = useRef<ReturnType<typeof triggerEdges>>([])+ const trigEdgeSig = useMemo(() => {+ if (!nodes.some((n) => n.type === 'trigger')) {+ trigPairsRef.current = []+ return ''+ }+ const pairs = triggerEdges(nodes as never, accent)+ trigPairsRef.current = pairs+ return pairs.map((e) => `${e.source}>${e.target}`).join('|')+ }, [nodes, accent])+ const trigEdges = useMemo(+ () => trigPairsRef.current,+ // eslint-disable-next-line react-hooks/exhaustive-deps -- trigEdgeSig IS the ref's signature+ [trigEdgeSig]+ )// Which browser nodes are being DRIVEN (Task 6.2) — for the rope highlight only. Membership comes// from the ownership-backed lease store; a rope whose target is NOT here is never highlighted, so a// hostile pre-declared rope (a cloned project.json can ship one) lights up nothing. Rendering-only:@@ -1841,11 +1863,11 @@ export function Canvas() {// durable relation and stays. Built above (depEdges), keyed on the dependency signature so a// drag frame does not rebuild it.const extra =- ephemeralEdges.length || ropes.length || depEdges.length- ? [...ephemeralEdges, ...ropes, ...depEdges]+ ephemeralEdges.length || ropes.length || depEdges.length || trigEdges.length+ ? [...ephemeralEdges, ...ropes, ...depEdges, ...trigEdges]: []return extra.length ? [...decorated, ...extra] : decorated- }, [linkEdges, ephemeralEdges, controlEdges, accent, stickySig, depEdges, drivenLeaseEntries])+ }, [linkEdges, ephemeralEdges, controlEdges, accent, stickySig, depEdges, trigEdges, drivenLeaseEntries])// Header pin button (and ⌘⇧L): toggle the persisted pin preference. Clears the transient// dismiss so (re)pinning shows the docked panel; unpinning collapses it to hover-peek.@@ -3953,6 +3975,14 @@ export function Canvas() {[setNodes, markDirty, viewCenter, activeProjectId])+ const addTrigger = useCallback(+ (center?: { x: number; y: number }) => {+ setNodes((ns) => [...ns, createTriggerNode(ns.length, center ?? viewCenter())])+ markDirty()+ },+ [setNodes, markDirty, viewCenter]+ )+const addWebView = useCallback(async (center?: { x: number; y: number }) => {const input = await promptDialog({ message: 'Open web view — enter a URL:' })@@ -7320,6 +7350,7 @@ export function Canvas() {web: (at) => void addWebView(at),sticky: (at) => addSticky(at),dino: (at) => addDino(at),+ trigger: (at) => addTrigger(at),openFile: (at) => void openFileDialog(at),newFile: (at) => void newProjectFile(at),spawnTeam: (at) => setSpawnTeamDialog({ at }),@@ -7332,6 +7363,7 @@ export function Canvas() {addWebView,addSticky,addDino,+ addTrigger,openFileDialog,newProjectFile,openWorktreeDialog@@ -12091,6 +12123,7 @@ export function Canvas() {onAddSticky={addSticky}onSpawnTeam={() => setSpawnTeamDialog({})}onAddDino={addDino}+ onAddTrigger={addTrigger}onAddAgent={(aid, accountId) => addAgentNode(aid, undefined, undefined, accountId)}onOpenFile={() => void openFileDialog()}onAddRemote={() => openRemotePicker({ x: window.innerWidth / 2, y: window.innerHeight / 2 })}diff --git a/src/renderer/components/Dock.tsx b/src/renderer/components/Dock.tsxindex ff2f909c8..51cc6214b 100644--- a/src/renderer/components/Dock.tsx+++ b/src/renderer/components/Dock.tsx@@ -24,6 +24,7 @@ interface DockProps {/** Opens the Spawn-a-team dialog (issue #78) — the conductor lands at the Dock's default spot. */onSpawnTeam: () => voidonAddDino: () => void+ onAddTrigger: () => voidonAddAgent: (agentId: AgentId, accountId?: string) => voidonOpenFile: () => voidonAddRemote: () => void@@ -61,6 +62,7 @@ export function Dock({onAddSticky,onSpawnTeam,onAddDino,+ onAddTrigger,onAddAgent,onOpenFile,onAddRemote,@@ -142,6 +144,7 @@ export function Dock({sticky: onAddSticky,spawnTeam: onSpawnTeam,dino: onAddDino,+ trigger: onAddTrigger,openFile: onOpenFile,newFile: onNewFile,worktree: onAddWorktreediff --git a/src/renderer/lib/addMenuSpec.test.tsx b/src/renderer/lib/addMenuSpec.test.tsxindex 78c68090d..c11d4d19d 100644--- a/src/renderer/lib/addMenuSpec.test.tsx+++ b/src/renderer/lib/addMenuSpec.test.tsx@@ -15,6 +15,7 @@ const handlers = (overrides: Partial<AddHandlers> = {}): AddHandlers => ({web: noop,sticky: noop,dino: noop,+ trigger: noop,openFile: noop,newFile: noop,spawnTeam: noop,@@ -29,6 +30,7 @@ const allKinds: AddItem['kind'][] = ['web','sticky','dino',+ 'trigger','open-file','new-file','spawn-team',@@ -56,6 +58,7 @@ describe('contentAddItemsToMenuItems', () => {'New web view…','New sticky note','New dino game',+ 'New trigger…','Open file…','New file…','Spawn a team…',@@ -117,6 +120,7 @@ describe('contentAddItemsToDockRows', () => {'web','sticky','dino',+ 'trigger','open-file','new-file','spawn-team',diff --git a/src/renderer/lib/addMenuSpec.tsx b/src/renderer/lib/addMenuSpec.tsxindex 028695dd5..c5f4737a5 100644--- a/src/renderer/lib/addMenuSpec.tsx+++ b/src/renderer/lib/addMenuSpec.tsx@@ -28,7 +28,8 @@ import {IconNote,IconRemote,IconTerminal,- IconWeb+ IconWeb,+ IconBellFilled} from '../components/icons'/** A flow-space position; `undefined` means "wherever the surface's default is". */@@ -46,6 +47,7 @@ export type AddItem =| { kind: 'web' }| { kind: 'sticky' }| { kind: 'dino' }+ | { kind: 'trigger' }| { kind: 'open-file' }| { kind: 'new-file' } // requiresCwd| { kind: 'spawn-team' }@@ -65,6 +67,7 @@ export const CONTENT_ADD_ITEMS: readonly AddItem[] = [{ kind: 'web' },{ kind: 'sticky' },{ kind: 'dino' },+ { kind: 'trigger' },{ kind: 'open-file' },{ kind: 'new-file' },{ kind: 'spawn-team' },@@ -94,6 +97,8 @@ export interface AddHandlers {web: (at?: AddPos) => voidsticky: (at?: AddPos) => voiddino: (at?: AddPos) => void+ /** Adds a trigger node (issue #493) — a canvas-owned schedule that fires into another node. */+ trigger: (at?: AddPos) => voidopenFile: (at?: AddPos) => voidnewFile: (at?: AddPos) => void/** Opens the Spawn-a-team dialog (issue #78); `at` is where the conductor node will land. */@@ -144,6 +149,9 @@ export function contentAddItemsToMenuItems(case 'dino':out.push({ label: 'New dino game', icon: <IconDino />, onClick: () => handlers.dino(at) })break+ case 'trigger':+ out.push({ label: 'New trigger…', icon: <IconBellFilled />, onClick: () => handlers.trigger(at) })+ breakcase 'open-file':out.push({ label: 'Open file…', icon: <IconEditor />, onClick: () => void handlers.openFile(at) })break@@ -219,6 +227,9 @@ export function contentAddItemsToDockRows(case 'dino':out.push({ kind: 'dino', label: 'Dino Game', icon: <IconDino />, onClick: () => handlers.dino() })break+ case 'trigger':+ out.push({ kind: 'trigger', label: 'Trigger', icon: <IconBellFilled />, onClick: () => handlers.trigger() })+ breakcase 'open-file':out.push({ kind: 'open-file', label: 'Open file…', icon: <IconEditor />, onClick: () => void handlers.openFile() })breakdiff --git a/src/renderer/lib/triggerCard.test.ts b/src/renderer/lib/triggerCard.test.tsnew file mode 100644index 000000000..9740e50c1--- /dev/null+++ b/src/renderer/lib/triggerCard.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from 'vitest'+import type { TriggerSpec } from '@shared/trigger'+import {+ RUN_OUTCOME_LABEL,+ TRIGGER_STATE_LINES,+ armConfirmMessage,+ formatCountdown,+ triggerCardState,+ triggerEdges+} from './triggerCard'++const spec = (): TriggerSpec => ({+ schedule: { kind: 'interval', everyMinutes: 30 },+ payload: 'npm test',+ target: 'term-tgt-1'+})++describe('triggerCardState', () => {+ it('precedence: invalid > armed > changed > disarmed', () => {+ expect(triggerCardState(undefined, { armed: true, armedForOtherContent: false })).toBe('invalid')+ expect(+ triggerCardState({ schedule: { kind: 'weekly' } } as never, undefined)+ ).toBe('invalid')+ expect(triggerCardState(spec(), { armed: true, armedForOtherContent: false })).toBe('armed')+ expect(triggerCardState(spec(), { armed: false, armedForOtherContent: true })).toBe('changed')+ expect(triggerCardState(spec(), { armed: false, armedForOtherContent: false })).toBe('disarmed')+ expect(triggerCardState(spec(), undefined)).toBe('disarmed')+ })++ it('every state has a line, and the disarmed line carries the trust narrative', () => {+ for (const state of ['invalid', 'armed', 'changed', 'disarmed'] as const)+ expect(TRIGGER_STATE_LINES[state].length).toBeGreaterThan(0)+ expect(TRIGGER_STATE_LINES.disarmed).toMatch(/arming is always a local decision/i)+ })+})++describe('armConfirmMessage', () => {+ it('says the payload runs, names the content binding, and the local scope of consent', () => {+ const msg = armConfirmMessage(spec(), 'Build box')+ expect(msg).toMatch(/automatically deliver/i)+ expect(msg).toContain('Build box')+ expect(msg).toMatch(/exactly this content/i)+ expect(msg).toMatch(/git pull/i)+ expect(msg).toMatch(/never leaves this machine/i)+ })+})++describe('formatCountdown', () => {+ const now = 1_000_000_000+ it('formats seconds, minutes, hours, days, due-now and null', () => {+ expect(formatCountdown(null, now)).toBeNull()+ expect(formatCountdown(now - 5, now)).toBe('due now')+ expect(formatCountdown(now + 30_000, now)).toBe('in 30s')+ expect(formatCountdown(now + 5 * 60_000, now)).toBe('in 5m 0s')+ expect(formatCountdown(now + 3 * 3_600_000 + 12 * 60_000, now)).toBe('in 3h 12m')+ expect(formatCountdown(now + 60 * 3_600_000, now)).toBe('in 2d')+ })+})++describe('run outcome labels', () => {+ it('covers every outcome the core can record', () => {+ for (const k of ['fired', 'delivered-late', 'queued', 'missed', 'failed', 'expired'] as const)+ expect(RUN_OUTCOME_LABEL[k].label.length).toBeGreaterThan(0)+ })+})++describe('triggerEdges', () => {+ const trig = (id: string, target: string) => ({+ id,+ type: 'trigger',+ data: { trigger: { ...spec(), target } }+ })++ it('draws an edge only for a valid spec whose target exists', () => {+ const nodes = [+ trig('trigger-a-1', 'term-tgt-1'),+ trig('trigger-b-1', 'term-gone-1'), // target not on canvas+ { id: 'trigger-c-1', type: 'trigger', data: { trigger: { bad: true } } }, // invalid spec+ { id: 'term-tgt-1', type: 'terminal', data: {} }+ ]+ const edges = triggerEdges(nodes as never, '#fff')+ expect(edges.map((e) => `${e.source}>${e.target}`)).toEqual(['trigger-a-1>term-tgt-1'])+ expect(edges[0].selectable).toBe(false)+ })++ it('non-trigger nodes never draw', () => {+ const nodes = [+ { id: 'term-a-1', type: 'terminal', data: { trigger: spec() } },+ { id: 'term-tgt-1', type: 'terminal', data: {} }+ ]+ expect(triggerEdges(nodes as never, '#fff')).toEqual([])+ })+})diff --git a/src/renderer/lib/triggerCard.ts b/src/renderer/lib/triggerCard.tsnew file mode 100644index 000000000..39a714b6b--- /dev/null+++ b/src/renderer/lib/triggerCard.ts@@ -0,0 +1,123 @@+/**+ * Pure decision + formatting logic for the trigger node's card (issue #493, phase 4) — kept out+ * of TriggerNode.tsx so the states the card can be in, and the honest wording for each, are+ * unit-tested rather than implied by JSX.+ */++import type { Edge } from '@xyflow/react'+import {+ sanitizeTriggerSpec,+ type TriggerNodeStatus,+ type TriggerRun,+ type TriggerSpec+} from '@shared/trigger'++/**+ * The card's headline state. Order of precedence matters and is test-pinned:+ * - `invalid` — no valid spec (fresh node, or a malformed/hand-mangled one): nothing can be+ * armed or scheduled; the card opens its editor.+ * - `armed` — armed on THIS machine for exactly this content.+ * - `changed` — an arm record exists but for DIFFERENT content: the spec was edited (locally or+ * via git pull) after arming. Honest wording, not "disarmed": the user armed *something* and+ * should see that the content moved out from under it.+ * - `disarmed` — never armed here. The narrative names the reason a trigger can arrive this way+ * (the definition travels with the repo; consent never does).+ */+export type TriggerCardState = 'invalid' | 'armed' | 'changed' | 'disarmed'++export function triggerCardState(+ spec: TriggerSpec | undefined,+ status: Pick<TriggerNodeStatus, 'armed' | 'armedForOtherContent'> | undefined+): TriggerCardState {+ if (!spec || !sanitizeTriggerSpec(spec)) return 'invalid'+ if (status?.armed) return 'armed'+ if (status?.armedForOtherContent) return 'changed'+ return 'disarmed'+}++/** One line under the armed/disarmed chip, per state. The `disarmed` line carries the trust+ * model's user-facing half: the definition is shared, the consent is this machine's. */+export const TRIGGER_STATE_LINES: Record<TriggerCardState, string> = {+ invalid: 'Set a schedule, payload and target to finish this trigger.',+ armed: 'Runs automatically on this machine while armed.',+ changed: 'The definition changed since it was armed — review it and arm again to resume.',+ disarmed:+ 'Not armed on this machine. Trigger definitions travel with the project (including via git); arming is always a local decision.'+}++/**+ * The arm confirmation copy — the CapabilityNotice register: say exactly what arming means+ * (scheduled, unattended delivery of this payload), name the guardrails that make it revocable+ * and content-bound, and stop. No scare quotes, no burying the fact that the payload will RUN.+ */+export function armConfirmMessage(spec: TriggerSpec, targetTitle: string): string {+ return (+ `Arm this trigger on this machine?\n\n` ++ `While armed, nodeterm will automatically deliver the payload below into “${targetTitle}” ` ++ `on the schedule shown — including while you are not looking, and (for a command target) it will run.\n\n` ++ `Arming applies to exactly this content: if the schedule, payload or target changes — by an ` ++ `edit here or a git pull — the trigger returns to disarmed until someone arms the new ` ++ `content. You can disarm at any time, and this consent never leaves this machine.`+ )+}++/** Run-now on a DISARMED trigger is still an explicit click, but it deserves the same honesty. */+export function runNowConfirmMessage(targetTitle: string): string {+ return (+ `Run this trigger once, now?\n\n` ++ `The payload below is delivered into “${targetTitle}” immediately (through the same idle ` ++ `checks a scheduled run uses). This does not arm the trigger — the schedule stays off.`+ )+}++/** "in 4h 12m" / "in 3m 20s" / "due now" — the card ticks this locally off `nextFireAt`. */+export function formatCountdown(nextFireAt: number | null, now: number): string | null {+ if (nextFireAt === null) return null+ const ms = nextFireAt - now+ if (ms <= 0) return 'due now'+ const s = Math.ceil(ms / 1000)+ if (s < 60) return `in ${s}s`+ const m = Math.floor(s / 60)+ if (m < 60) return `in ${m}m ${s % 60}s`+ const h = Math.floor(m / 60)+ if (h < 48) return `in ${h}h ${m % 60}m`+ return `in ${Math.floor(h / 24)}d`+}++/** Chip label + tone per run outcome — one place, so history rows and toasts agree. */+export const RUN_OUTCOME_LABEL: Record<TriggerRun['outcome'], { label: string; tone: 'ok' | 'warn' | 'muted' }> = {+ fired: { label: 'fired', tone: 'ok' },+ 'delivered-late': { label: 'delivered late', tone: 'ok' },+ queued: { label: 'queued', tone: 'muted' },+ missed: { label: 'missed', tone: 'warn' },+ failed: { label: 'failed', tone: 'warn' },+ expired: { label: 'expired', tone: 'warn' }+}++/**+ * The derived trigger→target edges — drawn, never persisted, exactly like the pending-launch+ * dependency edges: the durable relation is the spec's `target` field itself. Only a node whose+ * spec survives sanitization draws one, and only when the target exists on this canvas.+ */+export function triggerEdges(+ nodes: Array<{ id: string; type?: string; data: { trigger?: TriggerSpec } }>,+ accent: string+): Edge[] {+ const ids = new Set(nodes.map((n) => n.id))+ const out: Edge[] = []+ for (const n of nodes) {+ if (n.type !== 'trigger') continue+ const spec = sanitizeTriggerSpec(n.data.trigger)+ if (!spec || !ids.has(spec.target)) continue+ out.push({+ id: `trigger-edge-${n.id}`,+ source: n.id,+ target: spec.target,+ type: 'smoothstep',+ style: { stroke: accent, strokeDasharray: '6 4', opacity: 0.55 },+ selectable: false,+ focusable: false+ })+ }+ return out+}diff --git a/src/renderer/nodes/TriggerNode.tsx b/src/renderer/nodes/TriggerNode.tsxnew file mode 100644index 000000000..55f9f95a1--- /dev/null+++ b/src/renderer/nodes/TriggerNode.tsx@@ -0,0 +1,385 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { NodeResizer, useReactFlow, type NodeProps } from '@xyflow/react'+import {+ canonicalTriggerSpec,+ describeTriggerSchedule,+ sanitizeTriggerSpec,+ type TriggerNodeStatus,+ type TriggerSchedule,+ type TriggerSpec+} from '@shared/trigger'+import { NODE_MIN_SIZES } from '../lib/nodeSizing'+import {+ RUN_OUTCOME_LABEL,+ TRIGGER_STATE_LINES,+ armConfirmMessage,+ formatCountdown,+ runNowConfirmMessage,+ triggerCardState+} from '../lib/triggerCard'+import { useProjects } from '../state/projects'+import { type CanvasNode } from '../state/workspace'+import { ConfirmDialog } from '../components/ConfirmDialog'++/** Poll cadence for `triggers.status` while the node is mounted — the read is in-memory core+ * state, and a canvas holds few trigger nodes, so this stays cheap. */+const STATUS_POLL_MS = 5_000++/** How many history rows the card shows (the core ring holds 20). */+const RUNS_SHOWN = 5++interface DraftSpec {+ kind: TriggerSchedule['kind']+ expr: string+ everyMinutes: string+ at: string+ payload: string+ target: string+ note: string+}++const draftFrom = (spec: TriggerSpec | undefined): DraftSpec => ({+ kind: spec?.schedule.kind ?? 'interval',+ expr: spec?.schedule.kind === 'cron' ? spec.schedule.expr : '0 9 * * 1-5',+ everyMinutes: spec?.schedule.kind === 'interval' ? String(spec.schedule.everyMinutes) : '30',+ at: spec?.schedule.kind === 'once' ? spec.schedule.at : '',+ payload: spec?.payload ?? '',+ target: spec?.target ?? '',+ note: spec?.note ?? ''+})++function specFromDraft(d: DraftSpec): TriggerSpec | undefined {+ const schedule: unknown =+ d.kind === 'cron'+ ? { kind: 'cron', expr: d.expr }+ : d.kind === 'interval'+ ? { kind: 'interval', everyMinutes: Number(d.everyMinutes) }+ : // datetime-local yields a LOCAL wall time with no zone; Date.parse reads it as local,+ // and the ISO form keeps the schema's "parseable" rule happy on every machine.+ { kind: 'once', at: d.at ? new Date(d.at).toISOString() : '' }+ return sanitizeTriggerSpec({+ schedule,+ payload: d.payload,+ target: d.target,+ ...(d.note ? { note: d.note } : {})+ })+}++/**+ * The trigger node's card (issue #493, phase 4). All decisions the card renders are the pure+ * `lib/triggerCard.ts`; everything scheduled/armed/fired lives host-side — this component only+ * shows status and forwards explicit clicks over `window.nodeTerminal.triggers`.+ *+ * The honest-state rules the JSX must keep: DISARMED is a first-class visible state with the+ * "definitions travel, consent doesn't" narrative (never a bare grey nothing); CHANGED (armed for+ * other content) is distinct from disarmed; arming always passes a ConfirmDialog whose body shows+ * the exact schedule + payload + target being consented to; Run-now on a disarmed trigger+ * confirms the same way. On a relay tab the API stub refuses — the card says triggers are managed+ * on the host machine instead of showing dead buttons.+ */+export function TriggerNode({ id, data, selected }: NodeProps<CanvasNode>) {+ const { updateNodeData, deleteElements, getNodes } = useReactFlow()+ const projectId = useProjects((s) => s.activeProjectId)++ const spec = useMemo(() => sanitizeTriggerSpec(data.trigger), [data.trigger])+ const specCanon = spec ? canonicalTriggerSpec(spec) : ''++ const [status, setStatus] = useState<TriggerNodeStatus | null>(null)+ const [unavailable, setUnavailable] = useState(false)+ const [now, setNow] = useState(() => Date.now())+ const [editing, setEditing] = useState(!spec)+ const [draft, setDraft] = useState<DraftSpec>(() => draftFrom(spec))+ const [draftError, setDraftError] = useState<string | null>(null)+ const [confirm, setConfirm] = useState<null | 'arm' | 'run'>(null)+ const [busy, setBusy] = useState(false)+ const [runNote, setRunNote] = useState<string | null>(null)+ const aliveRef = useRef(true)++ const refreshStatus = useCallback(async () => {+ try {+ const s = await window.nodeTerminal.triggers.status(projectId, id)+ if (!aliveRef.current) return+ setStatus(s)+ setUnavailable(false)+ } catch {+ if (aliveRef.current) setUnavailable(true) // the relay stub's refusal, or a dead bridge+ }+ }, [projectId, id])++ useEffect(() => {+ aliveRef.current = true+ void refreshStatus()+ const t = setInterval(() => void refreshStatus(), STATUS_POLL_MS)+ return () => {+ aliveRef.current = false+ clearInterval(t)+ }+ // specCanon: an edit re-reads immediately so the armed chip flips without waiting a poll.+ }, [refreshStatus, specCanon])++ // Local countdown tick — cheap, and only while there is something to count down to.+ useEffect(() => {+ if (status?.nextFireAt === null || status === null) return+ const t = setInterval(() => setNow(Date.now()), 1_000)+ return () => clearInterval(t)+ }, [status])++ const state = triggerCardState(spec, status ?? undefined)+ const nodes = getNodes()+ const targetNode = spec ? nodes.find((n) => n.id === spec.target) : undefined+ const targetTitle = targetNode ? String(targetNode.data.title || spec?.target) : spec?.target ?? ''+ const countdown =+ state === 'armed' ? formatCountdown(status?.nextFireAt ?? null, now) : null++ const doArm = useCallback(async () => {+ if (!spec) return+ setBusy(true)+ try {+ const ok = await window.nodeTerminal.triggers.arm(projectId, id, spec)+ if (!ok) setRunNote('Arming was refused (invalid definition).')+ await refreshStatus()+ } catch {+ setUnavailable(true)+ } finally {+ setBusy(false)+ setConfirm(null)+ }+ }, [projectId, id, spec, refreshStatus])++ const doDisarm = useCallback(async () => {+ setBusy(true)+ try {+ await window.nodeTerminal.triggers.disarm(projectId, id)+ await refreshStatus()+ } catch {+ setUnavailable(true)+ } finally {+ setBusy(false)+ }+ }, [projectId, id, refreshStatus])++ const doRunNow = useCallback(async () => {+ setBusy(true)+ setConfirm(null)+ try {+ const r = await window.nodeTerminal.triggers.runNow(projectId, id)+ const chip = RUN_OUTCOME_LABEL[r.outcome]?.label ?? r.outcome+ setRunNote(r.detail ? `${chip} — ${r.detail}` : chip)+ await refreshStatus()+ } catch {+ setUnavailable(true)+ } finally {+ setBusy(false)+ }+ }, [projectId, id, refreshStatus])++ const saveDraft = useCallback(() => {+ const next = specFromDraft(draft)+ if (!next) {+ setDraftError(+ 'Not a valid trigger yet — check the schedule, a non-empty payload, and pick a target node.'+ )+ return+ }+ setDraftError(null)+ // Persisted as git-shared content; an armed trigger is disarmed by this edit by construction+ // (the arm binds to the previous content), which the CHANGED state then explains.+ updateNodeData(id, { trigger: next })+ setEditing(false)+ }, [draft, id, updateNodeData])++ const targetOptions = nodes.filter((n) => n.type === 'terminal' && n.id !== id)+ const runs = (status?.runs ?? []).slice(-RUNS_SHOWN).reverse()++ const confirmBody = spec ? (+ <div className="trigger-node__confirm">+ <div><b>Schedule:</b> {describeTriggerSchedule(spec.schedule)}</div>+ <div><b>Target:</b> {targetTitle}</div>+ <pre className="trigger-node__payload">{spec.payload}</pre>+ </div>+ ) : null++ return (+ <div className={`trigger-node${selected ? ' selected' : ''}`} style={{ borderColor: data.color }}>+ <NodeResizer+ minWidth={NODE_MIN_SIZES.trigger.width}+ minHeight={NODE_MIN_SIZES.trigger.height}+ isVisible={selected}+ color={data.color}+ />+ <div className="trigger-node__header" style={{ background: `${data.color}33` }}>+ <span className="term-node__color" style={{ background: data.color }} />+ <input+ className="term-node__title nodrag"+ value={data.title}+ spellCheck={false}+ onChange={(e) => updateNodeData(id, { title: e.target.value })}+ />+ <span className={`trigger-node__chip trigger-node__chip--${state}`}>+ {state === 'armed' ? 'ARMED' : state === 'changed' ? 'CHANGED' : state === 'invalid' ? 'SET UP' : 'DISARMED'}+ </span>+ <button className="term-node__close" title="Close" onClick={() => deleteElements({ nodes: [{ id }] })}>+ ×+ </button>+ </div>++ <div className="trigger-node__body nodrag">+ {unavailable ? (+ <div className="trigger-node__note">+ Triggers are managed on the machine that runs the sessions — not available from this+ view.+ </div>+ ) : editing ? (+ <div className="trigger-node__form">+ <label>+ Schedule+ <select+ value={draft.kind}+ onChange={(e) => setDraft({ ...draft, kind: e.target.value as DraftSpec['kind'] })}+ >+ <option value="interval">every N minutes</option>+ <option value="cron">cron expression</option>+ <option value="once">once, at a time</option>+ </select>+ </label>+ {draft.kind === 'interval' && (+ <input+ type="number"+ min={1}+ value={draft.everyMinutes}+ onChange={(e) => setDraft({ ...draft, everyMinutes: e.target.value })}+ />+ )}+ {draft.kind === 'cron' && (+ <input+ placeholder="0 9 * * 1-5"+ value={draft.expr}+ onChange={(e) => setDraft({ ...draft, expr: e.target.value })}+ />+ )}+ {draft.kind === 'once' && (+ <input+ type="datetime-local"+ value={draft.at.includes('T') && !draft.at.endsWith('Z') ? draft.at : ''}+ onChange={(e) => setDraft({ ...draft, at: e.target.value })}+ />+ )}+ <label>+ Target+ <select value={draft.target} onChange={(e) => setDraft({ ...draft, target: e.target.value })}>+ <option value="">— pick a terminal / agent node —</option>+ {targetOptions.map((n) => (+ <option key={n.id} value={n.id}>+ {String(n.data.title || n.id)}+ </option>+ ))}+ </select>+ </label>+ <label>+ Payload (delivered into the target when the trigger fires)+ <textarea+ rows={3}+ value={draft.payload}+ spellCheck={false}+ onChange={(e) => setDraft({ ...draft, payload: e.target.value })}+ />+ </label>+ <input+ placeholder="Note (optional)"+ value={draft.note}+ onChange={(e) => setDraft({ ...draft, note: e.target.value })}+ />+ {draftError && <div className="trigger-node__error">{draftError}</div>}+ <div className="trigger-node__row">+ <button onClick={saveDraft}>Save</button>+ {spec && (+ <button+ onClick={() => {+ setDraft(draftFrom(spec))+ setDraftError(null)+ setEditing(false)+ }}+ >+ Cancel+ </button>+ )}+ </div>+ </div>+ ) : spec ? (+ <>+ <div className="trigger-node__schedule">+ {describeTriggerSchedule(spec.schedule)}+ {countdown && <span className="trigger-node__countdown"> · {countdown}</span>}+ </div>+ <div className="trigger-node__target">+ → {targetTitle}+ {spec && !targetNode && <span className="trigger-node__error"> (missing)</span>}+ </div>+ <pre className="trigger-node__payload">{spec.payload}</pre>+ {spec.note && <div className="trigger-node__note">{spec.note}</div>}+ <div className="trigger-node__state-line">{TRIGGER_STATE_LINES[state]}</div>+ <div className="trigger-node__row">+ {state === 'armed' ? (+ <button disabled={busy} onClick={() => void doDisarm()}>+ Disarm+ </button>+ ) : (+ <button disabled={busy || state === 'invalid'} onClick={() => setConfirm('arm')}>+ Arm…+ </button>+ )}+ <button+ disabled={busy || state === 'invalid'}+ onClick={() => (state === 'armed' ? void doRunNow() : setConfirm('run'))}+ >+ Run now+ </button>+ <button disabled={busy} onClick={() => { setDraft(draftFrom(spec)); setEditing(true) }}>+ Edit+ </button>+ </div>+ {runNote && <div className="trigger-node__note">Last run: {runNote}</div>}+ {runs.length > 0 && (+ <div className="trigger-node__runs">+ {runs.map((r, i) => {+ const meta = RUN_OUTCOME_LABEL[r.outcome] ?? { label: r.outcome, tone: 'muted' as const }+ return (+ <div key={`${r.at}-${i}`} className="trigger-node__run" title={r.detail}>+ <span className={`trigger-node__run-chip trigger-node__run-chip--${meta.tone}`}>+ {meta.label}+ </span>+ <span className="trigger-node__run-time">{new Date(r.at).toLocaleTimeString()}</span>+ </div>+ )+ })}+ </div>+ )}+ </>+ ) : (+ <div className="trigger-node__note">{TRIGGER_STATE_LINES.invalid}</div>+ )}+ </div>++ {confirm === 'arm' && spec && (+ <ConfirmDialog+ message={armConfirmMessage(spec, targetTitle)}+ body={confirmBody}+ confirmLabel="Arm on this machine"+ danger={false}+ onConfirm={() => void doArm()}+ onCancel={() => setConfirm(null)}+ />+ )}+ {confirm === 'run' && spec && (+ <ConfirmDialog+ message={runNowConfirmMessage(targetTitle)}+ body={confirmBody}+ confirmLabel="Run once now"+ danger={false}+ onConfirm={() => void doRunNow()}+ onCancel={() => setConfirm(null)}+ />+ )}+ </div>+ )+}diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex b999f795d..5d79f765d 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -983,6 +983,27 @@ export function createStickyNode(index: number, center?: { x: number; y: number}}+/**+ * Creates a new trigger node (issue #493). Born with NO spec — `data.trigger` stays undefined+ * until the card's editor saves a valid one, so a fresh trigger is inert by construction (an+ * invalid/absent spec schedules nothing and cannot be armed).+ */+export function createTriggerNode(index: number, center?: { x: number; y: number }): CanvasNode {+ return {+ id: nextId('trigger'),+ type: 'trigger',+ position: placeAt(center, index, TRIGGER_SIZE.width, TRIGGER_SIZE.height),+ width: TRIGGER_SIZE.width,+ height: TRIGGER_SIZE.height,+ style: { width: TRIGGER_SIZE.width, height: TRIGGER_SIZE.height },+ data: {+ title: 'Trigger',+ color: '#e6a23c',+ group: null+ }+ }+}+/** Creates a new dino (T-Rex Runner) game node, seeded with the project's record. */export function createDinoNode(index: number,diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 7859f558e..8f6742d55 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -11391,3 +11391,109 @@ body.focus-mode .dock:hover {border: 1px solid var(--warn);background: transparent;}++/* ── Trigger node (issue #493) ──────────────────────────────────────────────────────────────── */+.trigger-node {+ width: 100%;+ height: 100%;+ display: flex;+ flex-direction: column;+ background: var(--surface-black);+ border: 1px solid var(--border);+ border-radius: 10px;+ overflow: hidden;+ font-size: 12px;+ color: rgba(255, 255, 255, 0.85);+}+.trigger-node.selected {+ box-shadow: 0 0 0 2px var(--accent);+}+.trigger-node__header {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 4px 6px;+ flex: 0 0 auto;+}+.trigger-node__chip {+ flex: 0 0 auto;+ font-size: 9px;+ font-weight: 700;+ letter-spacing: 0.06em;+ padding: 2px 6px;+ border-radius: 999px;+ border: 1px solid transparent;+}+.trigger-node__chip--armed { color: #30d158; border-color: rgba(48, 209, 88, 0.5); }+.trigger-node__chip--disarmed { color: #8e8e93; border-color: rgba(142, 142, 147, 0.5); }+.trigger-node__chip--changed { color: #ff9f0a; border-color: rgba(255, 159, 10, 0.5); }+.trigger-node__chip--invalid { color: #ff9f0a; border-color: rgba(255, 159, 10, 0.5); }+.trigger-node__body {+ flex: 1 1 auto;+ overflow-y: auto;+ padding: 8px;+ display: flex;+ flex-direction: column;+ gap: 6px;+ cursor: default;+}+.trigger-node__schedule { font-weight: 600; }+.trigger-node__countdown { color: var(--accent); font-weight: 500; }+.trigger-node__target { color: rgba(255, 255, 255, 0.65); }+.trigger-node__payload {+ margin: 0;+ padding: 6px;+ background: rgba(0, 0, 0, 0.35);+ border-radius: 6px;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11px;+ white-space: pre-wrap;+ word-break: break-word;+ max-height: 72px;+ overflow-y: auto;+}+.trigger-node__state-line,+.trigger-node__note { color: rgba(255, 255, 255, 0.55); font-size: 11px; }+.trigger-node__error { color: #ff9f0a; font-size: 11px; }+.trigger-node__row { display: flex; gap: 6px; }+.trigger-node__row button {+ background: rgba(255, 255, 255, 0.08);+ color: inherit;+ border: 1px solid rgba(255, 255, 255, 0.16);+ border-radius: 6px;+ padding: 3px 10px;+ font-size: 11px;+ cursor: pointer;+}+.trigger-node__row button:hover:not(:disabled) { background: rgba(255, 255, 255, 0.14); }+.trigger-node__row button:disabled { opacity: 0.45; cursor: default; }+.trigger-node__form { display: flex; flex-direction: column; gap: 6px; }+.trigger-node__form label { display: flex; flex-direction: column; gap: 3px; color: rgba(255, 255, 255, 0.65); }+.trigger-node__form input,+.trigger-node__form select,+.trigger-node__form textarea {+ background: rgba(0, 0, 0, 0.35);+ color: inherit;+ border: 1px solid rgba(255, 255, 255, 0.16);+ border-radius: 6px;+ padding: 4px 6px;+ font-size: 11px;+}+.trigger-node__form textarea { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; resize: vertical; }+.trigger-node__runs { display: flex; flex-direction: column; gap: 3px; }+.trigger-node__run { display: flex; align-items: center; gap: 6px; }+.trigger-node__run-chip {+ font-size: 9px;+ font-weight: 700;+ letter-spacing: 0.05em;+ padding: 1px 6px;+ border-radius: 999px;+ border: 1px solid transparent;+ text-transform: uppercase;+}+.trigger-node__run-chip--ok { color: #30d158; border-color: rgba(48, 209, 88, 0.5); }+.trigger-node__run-chip--warn { color: #ff9f0a; border-color: rgba(255, 159, 10, 0.5); }+.trigger-node__run-chip--muted { color: #8e8e93; border-color: rgba(142, 142, 147, 0.5); }+.trigger-node__run-time { color: rgba(255, 255, 255, 0.45); font-size: 10px; }+.trigger-node__confirm { display: flex; flex-direction: column; gap: 6px; text-align: left; font-size: 12px; }+.trigger-node__confirm .trigger-node__payload { max-height: 140px; }diff --git a/src/server/index.ts b/src/server/index.tsindex 8ba054950..0c6766653 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -388,7 +388,9 @@ export async function startServer(listCanvases: () => workspaceStore.persistedCanvases(),getNode: (nodeId) => workspaceStore.getNode(nodeId),sendText: (nodeId, text) => ptyManager.sendText(nodeId, text),- paneCommand: (nodeId) => ptyManager.paneCommand(nodeId)+ paneCommand: (nodeId) => ptyManager.paneCommand(nodeId),+ // The shell's own CorePlatform instance (`platform` is this file's ServerPlatform local).+ handle: (channel, handler) => platform.handle(channel, handler)})// 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 localdiff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 9c7f50b3f..23db9dd77 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -229,6 +229,11 @@ export const IPC = {/** The scoped machine's RAM (available/total) — the cheap read behind the system-resource* pill. Safe to poll locally; NOT polled for an SSH scope. */sessionMemoryHost: 'session-memory:host',+ // Trigger nodes (issue #493): machine-local arm/disarm + the card's status/run-now.+ triggersArm: 'triggers:arm',+ triggersDisarm: 'triggers:disarm',+ triggersStatus: 'triggers:status',+ triggersRunNow: 'triggers:run-now',contextUpdate: 'context:update',contextEnsure: 'context:ensure',// Team presence (docs/team-presence.md). `presence:hello` is a REQUEST: its response tells thediff --git a/src/shared/trigger.ts b/src/shared/trigger.tsindex 446b2cf9e..3716e6c6c 100644--- a/src/shared/trigger.ts+++ b/src/shared/trigger.ts@@ -125,6 +125,54 @@ export function sanitizeTriggerSpec(value: unknown): TriggerSpec | undefined {* must only ever be fed a spec that went through `sanitizeTriggerSpec` — enforce that at the* call site rather than re-validating here.*/+/**+ * `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 are+ * `delivered-late` / `expired` (plus a `missed` for a target that went away, or a trigger+ * disarmed/edited while queued). Shared because the card renders the history the core records.+ */+export type TriggerRunOutcome =+ | 'fired'+ | 'failed'+ | 'missed'+ | 'queued'+ | 'delivered-late'+ | 'expired'++export interface TriggerRun {+ at: number+ outcome: TriggerRunOutcome+ detail?: string+}++/** What `triggers:status` answers — everything the card needs in one read. */+export interface TriggerNodeStatus {+ /** Armed on THIS machine for the node's CURRENT content. */+ armed: boolean+ /** An arm record exists but for DIFFERENT content — "changed since armed", not "never armed". */+ armedForOtherContent: boolean+ /** Next due time (epoch ms), or null (disarmed schedules still compute; invalid/spent = null). */+ nextFireAt: number | null+ runs: TriggerRun[]+}++/** Human-readable schedule line for the card ("every 30 min", "once at …", the cron expr). */+export function describeTriggerSchedule(schedule: TriggerSchedule): string {+ if (schedule.kind === 'interval') {+ const m = schedule.everyMinutes+ if (m % 60 === 0) {+ const h = m / 60+ return h === 1 ? 'every hour' : `every ${h} hours`+ }+ return m === 1 ? 'every minute' : `every ${m} minutes`+ }+ if (schedule.kind === 'once') {+ const at = Date.parse(schedule.at)+ return Number.isFinite(at) ? `once at ${new Date(at).toLocaleString()}` : 'once (invalid time)'+ }+ return `cron ${schedule.expr}`+}+export function canonicalTriggerSpec(spec: TriggerSpec): string {const s = spec.scheduleconst schedule =diff --git a/src/shared/types.ts b/src/shared/types.tsindex 24e8c5f6f..9fb8dc069 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -2847,6 +2847,23 @@ export interface ShortcutsApi {setTerminalFocused(focused: boolean): void}+/**+ * Trigger nodes (issue #493): the card's IPC surface. `arm` binds this machine's consent to the+ * exact spec the user was shown (content-bound — see @shared/trigger); `runNow` chooses only WHEN,+ * never WHAT (the payload is resolved core-side from the node's persisted content). Real on+ * desktop and the Server Edition; the relay stub refuses (another machine's arm store is not ours+ * to write).+ */+export interface TriggersApi {+ arm(projectId: string, nodeId: string, spec: import('./trigger').TriggerSpec): Promise<boolean>+ disarm(projectId: string, nodeId: string): Promise<void>+ status(projectId: string, nodeId: string): Promise<import('./trigger').TriggerNodeStatus>+ runNow(+ projectId: string,+ nodeId: string+ ): Promise<{ outcome: 'fired' | 'missed' | 'failed' | 'queued'; detail?: string }>+}+export interface NodeTerminalApi {pty: PtyApiworkspace: WorkspaceApi@@ -2876,6 +2893,7 @@ export interface NodeTerminalApi {githubControl: import('./github-issues').GitHubControlApiusage: UsageApisessionMemory: SessionMemoryApi+ triggers: TriggersApicontext: ContextApicanvas: CanvasApicodex: CodexApi